top of page
Writer's pictureReka Narayanasamy

UnitTest (HTML Report) and Behave BDD (Allure Report)-Sample Python Code

In this blog we will be seeing how to write Python Code for UnitTest and generate HTML Report and how to write Python code for Behave BDD and generate Allure Report.


Lets see a sample code for Login using UnitTest, run the code using TestRunner and generate HTML report .


Unit tests

Unit tests are segments of code written to test other pieces of code, typically a single function or method, that we refer to as a unit. They are a very important part of the software development process, as they help to ensure that code works as intended and catch bugs early on.

Unit Tests tests specific methods and logic in the code


Why do we need unit testing? With unit testing, developers can have more control over their individual code block quality before integrating different components and then sent for regression testing. Also, it is easier to identify and rectify mistakes or defects at the code level.


Here we will be using setUpClass(),tearDownClass() ,@classMethod, and HtmlTestRunner to write a code .


setUpClass()

setUpClass is called only once and that is before all the tests


setUp()

This method is called before the invocation of each test method in the given class.


@classMethod

A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

@classmethod                                                                             
def setUpClass(cls):
def tearDownClass(cls):

tearDownClass()

tearDownClass is called only once and that is after all the tests.


tearDown()

This method is called after the invocation of each test method in given class. This class method is called exactly once for a test case, after its final test method completes. Override this method to perform any cleanup after all test methods have ended.


HtmlTestRunner

HtmlTest runner is a unittest test runner that save test results in Html files, for human readable presentation of results. To run the test and generate the HTML report


Assertion

Assertion determines the state of the application whether it is the same what we are expecting or not. If the assertion fails, then the test case is failed and stops the execution.


from selenium import webdriver
import unittest
import HtmlTestRunner
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

class nopCommerce(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        serv_obj = Service('C://Users//Reka//Drivers//chromedriver.exe')
        cls.driver = webdriver.Chrome(service=serv_obj)
        cls.driver.maximize_window()

    def test_homepagetitle(self):
        self.driver.get("https://admin-demo.nopcommerce.com/")
        self.assertEqual("Your store. Login",self.driver.title)

    def test_login(self):
        self.driver.get("https://admin-demo.nopcommerce.com/")
        self.driver.find_element(By.XPATH,"//*[@id='Email']").clear()
        self.driver.find_element(By.XPATH,"//*[@id='Email']").send_keys("admin@yourstore.com")
        self.driver.find_element(By.XPATH,"//*[@id='Password']").clear()
        self.driver.find_element(By.XPATH,"//*[@id='Password']").send_keys("admin")
        self.driver.find_element(By.XPATH,"//button[normalize-space()='Log in']").click()
        self.assertEqual("Dashboard / nopCommerce administration",self.driver.title)

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()
        print("test completed")

if __name__=='__main__':
    #unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='C://Users//Reka//PycharmProjects//UnitTestFramework//Reports'))
    
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='..\\Reports'))   #project directory

#unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='C://Users//Reka//PycharmProject//UnitTestFramework//Reports//report.log'))

To run the code and to generate the HTML report we have to execute the following commands in Terminal .


 # run in terminal: to generate reports:  
  python TestCase_nopcommerce_login.py
 

HTML Report


Lets see a sample Python code on how to do data driven in BDD and generate Allure report.


Project Structure :

Feature File

Scenario 1 with hardcoded values

Scenario 2 with Examples for Data Driven , Passing 4 sets of data with 1 valid input and 3 invalid input to Validate the Login page by increasing Test coverage .

Feature: nopCommerce Login

  Scenario: Login to nopCommerce with Hardcoded valid parameters
    Given Launch Chrome browser
    When Open nopCommerce page
    And Enter username "admin@yourstore.com" and password "admin"
    And Click on login button
    Then User must be successfully able to login to dashboard page
    And Close browser

  Scenario Outline: Login to nopCommerce with valid parameters
   Given Launch Chrome browser
   When Open nopCommerce page
   And Enter username "<username>" and password "<password>"
   And Click on login button
   Then User must be successfully able to login to dashboard page
   Examples:
   | username            | password |
   | admin@yourstore.com | admin    |
   | adm@yourstore.com   | admin123 |
   | admin@yourso.com    | adminxyz |
   | admin@yourstore.com | admin&*  |

StepDefinition for the steps in feature file

Import behave to do Behavior Driven Development


Passing data from feature file to stepdefinition and asserting the output with the title of the page when it logins and fails to login . So we are Passing 2 Test Cases with valid input and failing 3 Test Cases with invalid input .

from selenium.webdriver.common.by import By
from behave import *
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
@given('Launch Chrome browser')
def launchbrowser(context):
    #context.driver=webdriver.Chrome()
    serv_object = Service("C://Users//Reka//Drivers//chromedriver.exe")
    context.driver = webdriver.Chrome(service=serv_object)
    #context.driver.implicitly_wait(5)
@when('Open nopCommerce page')
def openpage(context):
    context.driver.get("https://admin-demo.nopcommerce.com")

@when('Enter username "{user}" and password "{pwd}"')
def entercredentials(context,user, pwd):
    context.driver.find_element(By.XPATH,"//input[@id='Email']").clear()
    context.driver.find_element(By.XPATH,"//input[@id='Email']").send_keys(user)

    context.driver.find_element(By.XPATH,"//input[@id='Password']").clear()
    context.driver.find_element(By.XPATH,"//input[@id='Password']").send_keys(pwd)

@when('Click on login button')
def loginpage(context):
    context.driver.find_element(By.XPATH,"//button[normalize-space()='Log in']").click()

@then('User must be successfully able to login to dashboard page')
def dashboardpage(context):
    status=context.driver.title
    try:
        text=context.driver.find_element(By.XPATH,"//h1[normalize-space()='Dashboard']").text
    except:
        context.driver.close()
        assert False, "Test Failed"

    if status=="Dashboard / nopCommerce administration":
        context.driver.close()
        assert True,"Test Passed"

@then('Close browser')
def closebrowser(context):
    print(" sucessfully executed")
    #context.driver.close()

To run the code and to generate Allure report execute the below command in Terminal

To run the code :
#  terminal: behave features\nopcommerce.feature
To generate the json format report and save in reports folder
#  terminal: behave -f allure_behave.formatter:AllureFormatter -o 
               reports/ features
To generate Allure Report 
#  terminal: allure serve reports/

Allure Report which shows 2 Test Cases passed and 3 Test Cases failed


Conclusion:



I hope, This article will help you to understand How to generate Allure report in BDD and Html report in python UnitTest.


You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.



Happy Learning

1,694 views

Recent Posts

See All
bottom of page