Current Stable Version

2.41.0

What's new in 2.41.0

Version 2.41.0 launched on 05/11/2016. Here is what's new:

  • improvement (#446) Adds fatal category to log filters
  • improvement (#448) Removes unused status categories for charts
  • improvement (#388) Keep Exceptions for replaceExisting=false
  • fix (#395) On the List View of executed test cases with dashboard is enabled, user is unable to scroll the list till the end
  • fix (#397) Formatting causes status to shift
  • new ExtentReports can now use the ExtentX report server, to connect, see this section
  • new (#315) Enhancement to be able to show/hide log depending on status
  • new (#384) ExtentTest has AddBase64ScreenCapture method to add the screen shot image as base64 string

Basic Usage

This section demonstrates basic methods that you will be using with this library.

Initializing Report

To initialize the report, you must create an instance of ExtentReports. It is possible to initialize in the following different ways:


var extent = ExtentReports(string filePath)
var extent = ExtentReports(string filePath, bool replaceExisting)
var extent = ExtentReports(string filePath, DisplayOrder displayOrder)
var extent = ExtentReports(string filePath, DisplayOrder displayOrder, bool replaceExisting)
  • filePath - path of the file, in .htm or .html format
  • replaceExisting - Setting to overwrite (TRUE) the existing file or append to it
    • True (default): the file will be replaced with brand new markup, and all existing data will be lost. Use this option to create a brand new report
    • False: existing data will remain, new tests will be appended to the existing report. If the the supplied path does not exist, a new file will be created.
  • displayOrder
    • OLDEST_FIRST (default) - oldest test at the top, newest at the end
    • NEWEST_FIRST - newest test at the top, oldest at the end

Specifying Locale

To use a localized version (see supported localized versions here), use:


Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("es-ES");
// or
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("es");    

Writing to Report

Once your session is complete and you are ready to write all logs to the report, simply call the flush() method.


// writing everything to document
extent.Flush();

It is recommended to call flush only once at the end of your session because calling it multiple times will reduce the performance as the log file will be written/updated multiple times.

Appending to an Existing Report

To append to a report you had previously created, simply mark replaceExisting = false and new tests will be appended to the same report.


ExtentReports extent = new ExtentReports(file-path, false);

Starting and Ending Tests

To start tests, a new instance of ExtentTest must be created. To end, simply call endTest(testInstance).


// new instance
var extent = new ExtentReports(file-path);

// starting test
var test = extent.StartTest("Test Name", "Sample description");

// step log
test.Log(LogStatus.PASS, "Step details");

// ending test
extent.EndTest(test);

// writing everything to document
extent.Flush();

Creating Step Logs

There are 2 ways logs can be created: one that creates 3 columns and other that creates 4. Always use only 1 type of log for the test otherwise the table will become malformed.


// creates 3 columns in table: TimeStamp, Status, Details
Log(LogStatus, Details);
Log(LogStatus, Exception);

// creates 4 columns in table: TimeStamp, Status, StepName, Details
Log(LogStatus, StepName, Details);
Log(LogStatus, StepName, Exception);

Getting Current RunStatus of Test

You can know the current status of the test during execution by calling the GetRunStatus() method.


LogStatus status = test.GetCurrentStatus();

Assign Test Categories

You can assign categories to tests using AssignCategory(String... params) method:


test.AssignCategory("Regression");
test.AssignCategory("Regression", "ExtentAPI");
test.AssignCategory("Regression", "ExtentAPI", "category-3", "cagegory-4", ..);

Or simply assign them when you start your test:


var test = extent
    .StartTest("Categories")
    .AssignCategory("Regression", "ExtentAPI");

Assign Test Author(s)

Assign the author of the test (similar to AssignCategory above):


test.AssignAuthor("Anshoo");
test.AssignAuthor("Anshoo", "Viren");

Adding Child Tests

To add a test node as a child of another test, use the appendChild method.


var parent = extent.StartTest("Parent");

var child1 = extent.StartTest("Child 1");
child1.Log(LogStatus.Info, "Info");

var child2 = extent.StartTest("Child 2");
child2.Log(LogStatus.Pass, "Pass");

parent
    .AppendChild(child1)
    .AppendChild(child2);
    
extent.EndTest(parent);

Inserting custom HTML

Simply insert any custom HTML in the logs by using an HTML tag:


extent.Log(LogStatus.Info, "HTML", "Usage: BOLD TEXT");

Insert Snapshots

To add a screen-shot, simply call addScreenCapture. This method returns the HTML with tag which can be used anywhere in the log details. Calling addScreenCapture will also add the image to the ImageCollectionView from where you can see all images used by your tests.


test.Log(LogStatus.Info, "Snapshot below: " + test.addScreenCapture("screenshot-path"));

Relative paths starting with . and / are supported. If you using an absolute path, file:/// will be automatically be appended for the image to load.

Insert Screencast

To add a screencast/recording of your test run, use the addScreencast method anywhere in the log details:


test.Log(LogStatus.Info, "Screencast below: " + test.addScreencast("screencast-path"));

Relative paths starting with . and / are supported. If you using an absolute path, file:/// will be automatically be appended for the screencst to load.

Adding System Info

It is possible to add system or environment info for your using using the AddSystemInfo method.


extent.addSystemInfo("Selenium Version", "2.46");
extent.addSystemInfo("Environment", "Prod");

Dictionary si = new Dictionary()
{
    {"Selenium Version", "2.46"},
    {"Environment", "Prod"}
};

extent.AddSystemInfo(si);

Clear all resources

Call close() at the very end of your session to clear all resources. If any of your test ended abruptly causing any side-affects (not all logs sent to ExtentReports, information missing), this method will ensure that the test is still appended to the report with a warning message.

You should call close() only once, at the very end (in @AfterSuite for example) as it closes the underlying stream. Once this method is called, calling any Extent method will throw an error.

Internally, this method does everything that flush() does by writing to the text file. Here are a few differences between close and flush::

  • If you fail to end any of your tests safely (by calling endTest), close will still show them in the report with a warning sign. Calling Flush will only write tests to the report once they are ended
  • Close does not write SystemInfo to the report (flush does)
  • You can call flush any number of times for a report session but close only once, because:
  • Close closes the underlying stream and destroys the source references so no other Extent commands can be used

extent.Close();

Connect to ExtentX

If you are using ExtentX as the report server, it will be required to provide the host & port of MongoDB to connect:


// if MongoDB on localhost, port: 27017
extent.X();

// Connect using connection string
// mongodb://host:27017,host2:27017/?replicaSet=rs0
extent.X(connectionString);

// connect using MongoUrl
// https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/MongoUrl.cs
extent.X(MongoUrl url);

// use MongoClientSettings
// https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/MongoClientSettings.cs
extent.X(MongoClientSettings settings);

Extent uses the same way to connect to MongoDB as used by MongoClient class. To see additional connection options, see MongoClient docs. The MongoClient connect options are used in x() the same way.

Examples

This section shows basic examples to get started.

Basic Usage Example

A simple example with a static method.


namespace RelevantCodes.ExtentReports
{
    class Program
    {
        static void Main(string[] args)
        {
            var extent = new ExtentReports("file-path", true);

            // creates a toggle for the given test, adds all log events under it    
            var test = extent.StartTest("My First Test", "Sample description");

            // log(LogStatus, details)
            test.Log(LogStatus.Info, "This step shows usage of log(logStatus, details)");

            // report with snapshot
            String img = test.AddScreenCapture("img-path");
            test.Log(LogStatus.Info, "Image example: " + img);
            
            // end test
            extent.EndTest(test);
            
            // calling Flush writes everything to the log file
            extent.Flush();
        }
    }
}

NUnit Example

Below is a quick example showing a base class containing TearDown which manages automatic failure messages so you only have to create your tests as you normally do. If an assert causes a failure, it will be caught and reported to Extent here.


internal class ExtentManager
{
    private static readonly ExtentReports _instance = 
        new ExtentReports("Extent.Net.html", DisplayOrder.OldestFirst);

    static ExtentManager() { }

    private ExtentManager() { }

    public static ExtentReports Instance
    {
        get
        {
            return _instance;
        }
    }
}

public abstract class ExtentBase
{
    protected ExtentReports extent;
    protected ExtentTest test;

    [OneTimeSetUp]
    public void FixtureInit()
    {
        extent = ExtentManager.Instance;
    }

    [TearDown]
    public void TearDown()
    {
        var status = TestContext.CurrentContext.Result.Outcome.Status;
        var stacktrace = string.IsNullOrEmpty(TestContext.CurrentContext.Result.StackTrace)
                ? ""
                : string.Format("<pre>{0}</pre>", TestContext.CurrentContext.Result.StackTrace);
        LogStatus logstatus;

        switch (status)
        {
            case TestStatus.Failed:
                logstatus = LogStatus.Fail;
                break;
            case TestStatus.Inconclusive:
                logstatus = LogStatus.Warning;
                break;
            case TestStatus.Skipped:
                logstatus = LogStatus.Skip;
                break;
            default:
                logstatus = LogStatus.Pass;
                break;
        }

        test.Log(logstatus, "Test ended with " + logstatus + stacktrace);

        extent.EndTest(test);
        extent.Flush();
    }
}

[TestFixture]
public class SingleLogTests : ExtentBase
{
    [Test]
    public void IntentionalFailure()
    {
        test = extent.StartTest("PassTest");
        test.Log(LogStatus.Pass, "Pass");

        // intentional failure 
        Assert.True(test.GetCurrentStatus() == LogStatus.Fail);
    }
}

Localized Versions

Extent currently supports the following localized versions of the document:

  • English ("en")
  • Spanish ("es")

Configuration

New configuration items are added in most new versions, so be sure to use the latest config.xml for your report.


<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
  <configuration>
    <!-- report theme -->
    <!-- standard, dark -->
    <theme>standard</theme>
  
    <!-- document encoding -->
    <!-- defaults to UTF-8 -->
    <encoding>UTF-8</encoding>
    
    <!-- protocol for script and stylesheets -->
    <!-- defaults to https -->
    <protocol>https</protocol>
    
    <!-- title of the document -->
    <documentTitle>ExtentReports 2.0</documentTitle>
    
    <!-- report name - displayed at top-nav -->
    <reportName>Automation Report</reportName>
    
    <!-- report headline - displayed at top-nav, after reportHeadline -->
    <reportHeadline></reportHeadline>
    
    <!-- global date format override -->
    <!-- defaults to yyyy-MM-dd -->
    <dateFormat>yyyy-MM-dd</dateFormat>
    
    <!-- global time format override -->
    <!-- defaults to HH:mm:ss -->
    <timeFormat>HH:mm:ss</timeFormat>
    
    <!-- custom javascript -->
    <scripts>
      <![CDATA[
        $(document).ready(function() {
          
        });
      ]]>
    </scripts>
    
    <!-- custom styles -->
    <styles>
      <![CDATA[
        
      ]]>
    </styles>
  </configuration>
</extentreports>


<extentreports>
  <configuration>
    <!-- document encoding -->
    <!-- defaults to UTF-8 -->
    <encoding>UTF-8</encoding>

    <!-- protocol for script and stylesheets -->
    <!-- defaults to https -->
    <protocol>https</protocol>
    
    <!-- title of the document -->
    <documentTitle>ExtentReports 2.0</documentTitle>
        
    <!-- report name - displayed at top-nav -->
    <reportName>Automation Report</reportName>
        
    <!-- report headline - displayed at top-nav, after reportHeadline -->
    <reportHeadline></reportHeadline>

    <!-- global date format override -->
    <!-- defaults to yyyy-MM-dd -->
    <dateFormat>yyyy-MM-dd</dateFormat>

    <!-- global time format override -->
    <!-- defaults to HH:mm:ss -->
    <timeFormat>HH:mm:ss</timeFormat>
      
    <!-- custom javascript -->
    <scripts>
      <![CDATA[
      $(document).ready(function() {

      });
      ]]>
    </scripts>
        
    <!-- custom styles -->
    <styles>
      <![CDATA[
                
      ]]>
    </styles>
  </configuration>
</extentreports>

The configuration file can be saved as one of your project resources of kept externally.

To use this configuration, in your code, call LoadConfig:


LoadConfig(string ConfigFile);

// file location: "C:\HelloWorld\extent-config.xml"
LoadConfig(@"C:\HelloWorld\extent-config.xml");

License

Extent - Reporting API and Server Copyright (C) 2016 Anshoo Arora, RelevantCodes.com All rights reserved

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESSOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER ORCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.