Python Selenium Extent Report Guide

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
12 Min Read

Welcome to this simple yet effective step-by-step guide. It explains how to use Extent reports in Selenium Python scripts. By the end of this tutorial, you shall be able to add Extent reporting to your test suites.

Simple Steps to Add Extent Report in Python

Automated testing is essential for ensuring that software works reliably. Today, we’ll teach you how to use Selenium and Extent Report with Python. You can then generate intuitive test reports using the steps given below.

Setup and Installation

Installing Python

This guide requires that you have Python set up on your system before starting with Selenium and Extent Report. Get the latest Python version directly from the official website. Use pip to install packages or if you don’t have it, then first install pip.

Installing Selenium

It is very easy to get Selenium running on your system. Launch the console and write the below command:

pip install selenium

Setting up a WebDriver

To run Selenium, you need a WebDriver that talks to the web browsers. For example, a web driver is the ChromeDriver for Google Chrome, GeckoDriver (for Firefox), and EdgeDriver for Microsoft. So, choose the one that is good for you and add its location to your system’s PATH.

Installing Extent Report

To work with Extent Report in Python, you need to install the extentreports library. Run the following command:

pip install extentreports

Now that the initial setup is complete, let’s move on to creating your first Selenium script.

Creating Your First Selenium Script

Importing Necessary Modules

Create a new Python file and start by importing the necessary modules:

from selenium import webdriver

Initializing the WebDriver

Initialize the WebDriver of your choice. For example, using Chrome:

driver = webdriver.Chrome()

Navigating to a Website

Navigate to a website of your choice:

driver.get("https://www.example.com")

Writing a Basic Test Case

Write a basic test case to verify the page title:

expected_title = "Example Domain"
actual_title = driver.title

assert expected_title == actual_title, f"Expected title: {expected_title}, Actual title: {actual_title}"

print("Test passed successfully!")

Run the script to ensure everything is set up correctly. If the test passes, you’re ready to move on to enhancing your test scripts with Selenium.

Enhancing Your Test Scripts with Selenium

Locating Web Elements

Selenium provides various methods to locate web elements, such as find_element_by_id, find_element_by_name, find_element_by_xpath, etc. Choose the appropriate method based on the structure of the web page.

# Example: Locating an element by ID
element = driver.find_element_by_id("username")

Interacting with Different Types of Web Elements

Perform actions on web elements using methods like click(), send_keys(), clear(), etc.

# Example: Entering text into a text box
element = driver.find_element_by_id("username")
element.send_keys("your_username")

Handling Dynamic Elements

Use techniques like XPath or CSS selectors to handle dynamic elements.

# Example: Using XPath for dynamic elements
element = driver.find_element_by_xpath("//input[contains(@id, 'dynamic_id')]")

Waits in Selenium

Implement explicit waits to ensure the web page has loaded or to handle delays caused by dynamic content.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Example: Wait for an element to be clickable
element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "submit_button"))
)
element.click()

With these enhancements, your Selenium scripts are now more robust and capable of handling various scenarios. In the next section, we’ll introduce Extent Report and explore its integration with Selenium.

Introduction to Extent Report

Overview of Extent Report

Extent Report is a reporting library for creating interactive and detailed test reports. It supports multiple programming languages, including Python, and is widely used in the testing community for its rich features.

Benefits of using Extent Report

  • Interactive and visually appealing reports
  • Detailed information about test execution
  • Categorization of test cases
  • Easy integration with various test frameworks

Integrating Extent Report with Selenium

To use Extent Report with Selenium in Python, follow these steps:

Setting Up Extent Report in Python

Installing the Extent Report Python Library

Install the Extent Report Python library using the following command:

pip install extentreports

Configuring Extent Report

Create a new Python file for your test script and configure Extent Report at the beginning of your script:

from extentreports import ExtentReports, LogStatus

# Initialize Extent Report
extent = ExtentReports("path/to/extent_report.html", True)
extent.start_test("Test Name", "Test Description")

Replace “path/to/extent_report.html” with the desired location and name for your report.

With the Extent Report configured, let’s proceed to creating and managing test reports.

Creating and Managing Test Reports with Extent Report

Initializing the Extent Report Instance

Begin each test script by initializing the Extent Report instance:

from extentreports import ExtentReports, LogStatus

# Initialize Extent Report
extent = ExtentReports("path/to/extent_report.html", True)
extent.start_test("Test Name", "Test Description")

Adding test information to the report

Add information about the test, such as the author, category, and description:

extent.test.set_author("Your Name")
extent.test.assign_category("Category Name")
extent.test.assign_device("Device Info")

Logging test steps

Log each step of the test using log functions provided by Extent Report:

extent.test.log(LogStatus.INFO, "Step 1: Perform an action")
extent.test.log(LogStatus.PASS, "Step 2: Verify the result")
extent.test.log(LogStatus.FAIL, "Step 3: Test case failed")

Capturing screenshots

Take screenshots during the test and add them to the report:

extent.test.log(LogStatus.INFO, "Screenshot: " + extent.test.add_screen_capture("path/to/screenshot.png"))

Managing test logs and status

Handle test logs and set the final status of the test:

# Example: Set the final status as Pass
extent.test.log(LogStatus.PASS, "Test case passed")
extent.end_test()
extent.end()

With these steps, you’ve successfully created a basic Extent Report. In the next section, we’ll explore customizing the report for more detailed insights.

Customizing Extent Report

Adding custom information to the report

Enhance the report by adding custom information such as environment details, build version, or additional metadata:

extent.add_system_info("Environment", "Production")
extent.add_system_info("Build Version", "1.0.0")

Creating categorized tests

Categorize tests for better organization:

extent.start_test("Login Test").assign_category("Smoke Test")
extent.start_test("Registration Test").assign_category("Regression Test")

Adding additional information to test steps

Include additional details for each test step:

extent.test.log(LogStatus.INFO, "Step 1: Perform an action", "Additional information for step 1")

Customizing Report Appearance

Customize the appearance of the report, including themes and styles:

extent.load_config("path/to/extent-config.xml")

Create an XML configuration file with your desired settings and provide its path.

Now that you’ve customized the report, let’s move on to handling test suites with Extent Report.

Handling Test Suites with Extent Report

Running multiple test cases

For running multiple test cases as part of a test suite, create a test suite and add individual test cases:

suite = extent.create_test_suite("Test Suite Name")
suite.add_child_test("Test Case 1")
suite.add_child_test("Test Case 2")

Generating a consolidated report for a test suite

Generate a consolidated report for the entire test suite:

extent.end_test()
extent.end()

This concludes the section on handling test suites. In the next section, we’ll explore integrating Extent Report with popular Python test frameworks.

Integrating Extent Report with Test Frameworks

Integrating with Pytest

For Pytest integration, use the pytest-parallel plugin along with the Extent Report. Install the plugin:

pip install pytest-parallel

Create a Pytest fixture for Extent Report:

import pytest
from extentreports import ExtentReports

@pytest.fixture(scope="session")
def extent_report():
    extent = ExtentReports("path/to/extent_report.html", True)
    yield extent
    extent.end()

Use the fixture in your Pytest test cases:

def test_example(extent_report):
    extent_report.start_test("Test Name", "Test Description")
    extent_report.test.log(LogStatus.PASS, "Test passed")
    extent_report.end_test()

Integrating with Unittest

For Unittest integration, extend the unittest.TestCase class and use Extent Report within your test methods:

import unittest
from extentreports import ExtentReports

class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.extent = ExtentReports("path/to/extent_report.html", True)

    @classmethod
    def tearDownClass(cls):
        cls.extent.end()

    def test_example(self):
        self.extent.start_test("Test Name", "Test Description")
        self.extent.test.log(LogStatus.PASS, "Test passed")
        self.extent.end_test()

This section covers integrating Extent Report with popular Python test frameworks. In the next section, we’ll explore best practices for effective reporting.

Best Practices for Effective Reporting

Structuring test cases for meaningful reports

Organize test cases logically and use meaningful names and descriptions to enhance the readability of the report.

Utilizing Extent Report features for maximum benefit

Explore all the features provided by Extent Report, such as adding system information, customizing test steps, and categorizing tests.

Analyzing and Interpreting Report Results

Regularly review and analyze the test reports to identify trends, patterns, and areas for improvement in your testing process.

With these best practices in mind, let’s move on to advanced techniques with Selenium and Extent Report.

Advanced Techniques with Selenium and Extent Report

Handling AJAX calls and asynchronous operations

Implement explicit waits and asynchronous handling techniques to deal with dynamic content and AJAX calls.

Data-driven testing with Extent Report

Enhance your tests by integrating data-driven testing approaches and include detailed data in the Extent Report.

Integrating with Continuous Integration Tools

Integrate your Selenium tests with Continuous Integration tools like Jenkins or GitLab CI for automated and scheduled test executions.

With these advanced techniques, your Selenium and Extent Report setup is now capable of handling complex scenarios. In the next section, we’ll cover troubleshooting and debugging.

Troubleshooting and Debugging

Common Issues with Selenium and Extent Report

Identify and address common issues, such as incorrect web element locators, synchronization problems, or configuration errors.

Debugging test scripts

Use debugging techniques to step through your code and identify issues during script execution.

Analyzing failed test cases in the report

Examine the Extent Report for detailed information on failed test cases, including screenshots and logs.

With troubleshooting and debugging covered, let’s proceed to the conclusion.

Before You Leave

In this comprehensive tutorial, you’ve learned how to set up Selenium for automation in Python and integrate Extent Report. It will help you add detailed and interactive test reporting in the test suites.

We further suggest you keep exploring new features in Selenium and Extent Report. Connect to us if you face any difficulties in understanding them. We’ll try our best to resolve your problems.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Happy testing,
TechBeamers.

Share This Article
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *