© Sujay Raghavendra 2021
S. RaghavendraPython Testing with Seleniumhttps://doi.org/10.1007/978-1-4842-6249-8_12

12. Using Test Cases with a Screenshot

Sujay Raghavendra1 
(1)
Dharwad, Karnataka, India
 

The program in Python on Selenium that tests a specified element on a web application or web page is called a test case. Selenium with Python is a popular choice for testing a web application or web page because there is a lower learning curve to implement it. Python is an easy-to-understand language. Testing requires you to generate simple, understandable test reports for a web application, which can be done with Python and Selenium combined.

This chapter discusses the various test cases used to take a screenshot. In the previous chapter, you learned how POM creates a test case.

Let’s now study the most widely used framework supported by Python in Selenium. The framework implementation as a test case for a web page is also discussed. First, let’s quickly review the test outcomes.

Test Outcomes

The test code has three outcomes: pass, fail, or error. These outcomes define the changes that need to be provided in a test case. The following offers a quick description.

Pass/OK

Pass/OK is the outcome that a developer usually expects. It means that the application is ideal and errorless in terms of functionality and client satisfaction. It is achieved by rigorously testing the web page or application. When a test passes, the application does not need any changes or bug fixes.

Fail

A test fails when a test condition is not satisfied in the corresponding web elements or its behavior. When a test case fails, an AssertionError exception is raised by the system. This error is stated to the developer to make the necessary changes, which are also tested.

Error

An error occurs when an exception is raised. The error may be due to logic, syntax, or semantics and can be traced by the raised exception. This exception is not an AssertionError.

Let’s now look at a few test cases in which the same goal is achieved using multiple approaches.

Test Case 1: Taking a Screenshot

This test case takes a picture (i.e., screenshot) of the web page. The size of the screenshot is determined by specifying the height and width. This is useful in bug analyses reports, for seeing the test case flow, and in recovering failed test cases.

Three methods can be used to capture screen images in Selenium. Each one is described next.

save_screenshot (‘name_of_file’)

In this method, the screenshot is taken during the execution of a test case. The screenshot image is available in a .png extension. The following is the Python code for it.
from selenium import webdriver
new_driver=webdriver.Firefox()
new_driver.get('https://apress.com')
new_driver.save_screenshot('screenshot1.png')

get_screenshot_as_file (‘name_of_file’)

This method directly saves the screenshot as image in .png format. Any other image extension apart from .png throws an error. The following is the Python code for it.
#get_screenshot_as_file()
from selenium import webdriver
driver=webdriver.Firefox()
driver.get('https://apress.com')
driver.get_screenshot_as_file('screenshot2.png')
#Error Occurs when image extension is changed
#driver.get_screenshot_as_file('screenshot2.jpg')

get_screenshot_as_png( )

In this method type, the screenshot is captured in binary form, which is then converted to an image. The saved image is stored in .png format. The following is the Python code for it.
#Get method
from selenium import webdriver
from PIL import Image
from io import BytesIO
driver= webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
driver.get('http://apress.com/')
#Logo Image extraction
element=driver.find_element_by_class_name('brand')
location=element.location
#saves logo image as screenshot
size=element.size
png=driver.get_screenshot_as_png()
driver.quit()
#PIL library is used to open image in memory
image=Image.open(BytesIO(png))
#Logo size extraction
left= location['x']
top= location['y']
right= location['x'] + size['width']
bottom= location['y'] + size['height']
#Saving Logo for extracted dimension size
image=image.crop((left, top, right, bottom))
image.save('C:\Users\ADMINDesktop\python books\#Go Lang\Done\finalApresspython testing\codes\screenshot3.png')

The Python Imaging Library (PIL) Library is used for converting a binary image. It is available in Python. The size of the image is specified before implementing this function.

Note

In Python on Selenium, the save_screenshot ( ) and get_screenshot_as_file ( ) methods can only store the image in .png format, whereas the get_screenshot_as_png ( ) method can store the image in multiple formats.

Now we’ll look at the testing frameworks and the most popular testing framework used in Selenium implementation.

Testing Frameworks

A test case is governed by a set of rules and regulations, which is done by a framework. The framework is used for testing and hence called a testing framework. A testing framework makes a test case more efficient and robust. The framework includes features like handling test data, test standards, test repositories, page objects, and so forth.

Several Python frameworks can be used with Selenium. One of the most commonly used frameworks is unittest. The unittest framework, including its modules and functions, is described next.

The Unittest Framework

The unittest framework is a Python testing framework that is based on the XUnit framework design pattern developed by Kent Beck and Erich Gamma. It is also known as PyUnit. The unittest framework is commonly used to generate reports based on automated test cases.

In this framework, a test case is tested in small individual units (like functions, methods, class, etc.) that determine the correctness of the web element or web page tests. These tests are carried out in small chunks or units by defining classes as methods and using assert functions.

Before jumping into the code, you need to know the following components that the unittest framework supports.
  • A test fixture executes one or more test cases and the related cleanup actions. Creating proxy or temporary databases, starting a process on a server, or creating new directories are some examples of a text fixture.

  • In a test case module, small individual units are tested. These units are related to the web elements that are to be tested. The unittest framework contains a base class and the test cases that are used for creating new test cases.

  • A test suite aggregates multiple test cases. It can also be a combination of test suites. The execution of a test suite is the same as a test case.

  • A test runner helps to run all the test cases and their associated results. The runner can be integrated with interfaces, such as a graph, text, or a special value indicating return values from the test case.

  • A test report is the generated result or output of a test case (i.e., whether it is passed or failed). The test case’s execution time is arranged in a systematic way to generate the report. These details are summarized in a report for the client.

Test Case 2: Unittest

First, the unittest library needs to be downloaded using pip in Python. The unittest framework code has several instances that can be incorporated in a test case.

setUp( )

The setUp() method initializes the setup that is required to run a test case. It runs at the beginning of the test case. The number of test cases determines the setUp() method to be executed. For example, if there are ten test cases, then the setUp() method is executed ten times before any test case. This method configures the initial stages of a test case, such as setting a web driver and its associated components.
import unittest
from selenium import webdriver
class Test(unittest.TestCase):
        #setUp Class method
        def setUp(self):
                self.driver=webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
                print("Firefox Browser Opened")
        def test_apress(self):
                self.driver.get("https://apress.com")
                print("Apress")
        def test_google(self):
                self.driver.get("https://google.com")
                print("Google")
        def test_facebook(self):
                self.driver.get("https://facebook.com")
                print("Facebook")
        def test_twitter(self):
                self.driver.get("https://twitter.com")
                print("Twitter")
if __name__ =="__main__":
        unittest.main()

The setUp() method is beneficial when there are multiple test cases for the same web application or web page. This reduces the initial configuration or setup that is required before a test.

tearDown( )

The tearDown() method is executed after each test case is executed. It is a class method in unittest that is only stated once. It is executed for each test case available in the unittest program.
import unittest
from selenium import webdriver
class Test(unittest.TestCase):
        def setUp(self):
                self.driver=webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
                print("Opened Firefox Browser")
        def test_apress(self):
                self.driver.get("https://apress.com")
                print("Apress")
        def tearDown(self):
                self.driver.quit()
                print("Quit Browser")
if __name__ =="__main__":
        unittest.main()

This method contains actions such as closing the web driver or browser, and logout or any closure action related to the test case. The tearDown() method is executed once the setUp() method is executed regardless of the test case results (i.e., pass/fail).

Note

A test case can contain both the setUp( ) and tearDown( ) methods in the same test class in unittest.

setUpClass

setUpClass is a class in unittest that is executed before any setUp or tearDown functions or any test cases present in the same test class. A class that contains this method executes it only once, and it is passed as a single argument. setUpClass has a class known as @classmethod that is stated before the setUp() function.
import unittest
from selenium import webdriver
#Class Setup
class Test(unittest.TestCase):
        @classmethod
        def setUpClass(suc):
                suc.driver=webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
                print("Open Browser using setUpClass method")
        def test_apress(self):
                self.driver.get("https://apress.com")
                print("Open Apress Site")
if __name__ =="__main__":
        unittest.main()

The setUp() function is not mandatory in setUpClass. If this class fails to execute, it raises an exception, and the test cases or tearDown() function in it do not execute.

tearDownClass

The tearDownClass class is executed after setUpClass and all related test cases that are present in the same test class. This class is executed once before exiting the program.
import unittest
from selenium import webdriver
#Class Setup
class Test(unittest.TestCase):
        @classmethod
        def setUpClass(suc):
                suc.driver=webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
        print("Open Browser using setUpClass method")
        def test_apress(self):
                self.driver.get("https://apress.com")
                print("Open Apress Site")
        @classmethod
        def tearDownClass(suc):
                suc.driver.quit()
                print("Close Browser using tearDownClass method")
if __name__ =="__main__":
        unittest.main()

You can use this method regardless of the setUpClass method.

An example of all the classes and functions is shown in the following simple test case.

setUpModuleandtearDownModule

There are two modules available in Python on Selenium. The execution of setUpModule takes place at the beginning, and the teardownModule execution is at the end. These two modules were recently added to the unittest framework.
import unittest
from selenium import webdriver
class Test(unittest.TestCase):
        #Class setup
        @classmethod
        def setUpClass(suc):
                suc.driver=webdriver.Firefox(executable_path=r'C:UsersADMINDesktopgeckodriver.exe')
                print("Open Browser using setUpClass method")
        def setUp(self):
                print("Execute setUp")
        #test case
        def test_apress(self):
                self.driver.get("https://apress.com")
                print("Executing Test Case: Open Apress Site")
        def tearDown(self):
                print("Execute tearDown")
        @classmethod
        def tearDownClass(suc):
                suc.driver.quit()
                print("Close Browser using tearDownClass method")
        #Two Modules
        def setUpModule():
                print("Executes setUpModule")
        def tearDownModule():
                print("Executes tearDownModule")
if __name__ =="__main__":
        unittest.main()

In the program, the print statement in setUpModule() is printed first followed by setUpClass(), setUp(), test_apress(), tearDown(), tearDownClass(), and finally, tearDownModule() is printed.

Test Execution Order

Since there are different modules, classes, functions, and test cases defined, it is important to know the order of execution in the unittest framework. The execution order is determined by the priority given to the modules, classes, and functions, which are defined regardless of the positions in the program. The entire execution flow of a test case is shown in Figure 12-1.
../images/494993_1_En_12_Chapter/494993_1_En_12_Fig1_HTML.png
Figure 12-1

Order of execution in unittest framework

The order of execution for test cases is in alphabetical order by default in unittest. To prioritize, you can define the same name to all the test cases followed by a sequential number for each; for example, test1, test2, test3, test4, and so on.

Note

If there are multiple test cases, then they are executed in alphabetical order.

Testing Tool Comparisons

Many testing tools can be used with Python on Selenium to generate reports and test web applications. Some of them are featured in Table 12-1.
Table 12-1

Testing Tools in Python

Testing Tool

Category

License Type

Description

DocTest

Unit Testing

Freeware

Generates test cases based on the output of a Python interpreter

Nose2

Unit Testing

Freeware

The successor of the nose testing framework

Extends features more than the nose framework; very easy to understand

Pytest

Unit Testing

Freeware

A beginner-friendly tool that supports integration with unittest and nose

Easy to build small tests that can later scale to complex functionality testing

Robot

Acceptance Testing

Freeware

A generic framework for acceptance test-driven development (ATDD) and robotic process automation (RPA)

Offers a simple syntax; easy to implement with other frameworks

Testify

Unit Testing

Freeware

Python-based testing plugin providing more functionality and modules related to reporting

Offers features beyond unittest and nose

Summary

This final chapter explained the test cases intended to get the same results using different approaches. The unitttest framework is also used by Google to automate test cases. The framework is elaborated with basic terminologies and modules. Each module was examined with a testing example associated with it. When all the modules are combined in a single test case, the order of each module execution forms a flowing pattern. We wrapped up the chapter with a comparison of different testing tools supported by Python Selenium.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.36.30