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

8. Assertions

Sujay Raghavendra1 
(1)
Dharwad, Karnataka, India
 

In the preceding chapters, you studied locating web elements like links, buttons, frames, and textboxes, and the test cases related to them. Before automating any test case for a web app or page, you need to validate it, which is done by providing conditions about the web element. This validation or check is done by using assertion functions, which are available in Selenium with Python.

The assertion allows you to validate or check an expected value with the allocated value of the web elements. The allocated value may be any attribute associated with it, and the expected value is the one we compare in a test. This chapter explains the assertions provided by Python in Selenium with its types and usage to automate any test cases. These assertions are also part of the unittest framework, which is discussed in a later chapter of this book. In this chapter, we study several assertion methods that are provided by Selenium in Python, making debugging easier for test cases to be written.

The Need for Assertion

Assertion is a method primarily used to check or verify a specified condition or test case related to a web element. The assertion function or method gives two results: pass or fail (i.e., True or False in Boolean terms).

A test case passes only when two parameters or values in a test condition are the same, and no exception was raised during run time. Similarly, a test case fails when two values are not the same, and an AssertionError exception is raised (only when the assert function is used).

An assertion is mainly used to test a single web element in a test case, which is also called a unit test . It makes reports on the results of the related test case. The report informs developers about any errors or bugs associated with the test case.

The remaining sections organize assertion types by usage. Each type includes a brief definition, including syntax and example code.

Basic Asserts

There are basic asserts provided by Python in Selenium that evaluate two values defined in it. The test case is successful or fails, depending on the results from the function. An exception is raised when a test case fails. An optional text message may also be provided.

assertTrue

assertTrue tests whether a given condition or result is true. A test case passes when a condition is true and fails when it is false. It verifies a single value, followed by a text message, which is optional. The following is an example of its syntax.
assertTrue(value1, text_msg=null)
import unittest
from selenium import webdriver
class test_case1(unittest.TestCase):
        def test1(self):
                s1 ="Python"
                s2 ="Ruby"
                # Verifying Numbers
                self.assertTrue(s1== s2, "It's not a Match.")
if __name__ =="__main__":
        unittest.main()

assertFalse

The assertFalse method passes a test when a specified condition is false. A test fails when the condition is true, and an exception is raised. It uses a single value. The following is an example of its syntax.

assertFalse(value1, text_msg=null)
def test2(self):
        s1 ="Python"
        # Verifying Numbers
        self.assertFalse(s1 == 'Ruby', "It’s a Match.")

assertIs

The assertIs function matches value1 with value2 to see if they are the same or not. When two values are the same, the test case passes; otherwise, an exception is raised. The following is an example of its syntax.
assertIs(value1, value2, text_msg = null)
def test_lang(self):
        lang="Python"
        #Check lang
        self.assertIs("Selenium", lang, "value do not Match.")

assertIsNot

assertIsNot verifies whether value1 with value2 are the same or not. If they are not the same, then the test case passes; if they are the same, the test case fails. The following is an example of its syntax.
assertIsNot(value1, value2, text_msg = null)
def test_lang(self):
        lang="Python"
        #Check lang
        self.assertIsNot("Python", lang, "Value is Match.")

assertIsNone

assertIsNone checks whether the given condition or value is null. If null, then the test case passes; if it is not null, then the function raises an exception. The following is an example of its syntax.
assertIsNone(value, text_msg = null)
Here, value can be an expression or condition or parameter.
def test(self):
        color=None
                # Check if value is null.
                self.assertIsNone(color, "color is not null")

assertIsNotNone

The assertIsNotNone method passes a test case if the specified condition or value is not null; otherwise, the test case fails. The following is an example of its syntax.
assertIsNotNone(value, text_msg = null)
def test(self):
        color="green"
        # Check if value is not null.
        self.assertIsNotNone(color, "color is null")

assertIsInstance

assertIsInstance checks whether a given value is an instance of a class. An exception occurs if the object is not an instance. The following is an example of its syntax.
assertIsInstance(value, cls, text_msg = null)

assertNotIsInstance

assertNotIsInstance raises an exception when the given value is an instance of the class. If the value is not an instance of the class, then the corresponding test case passes. The following is an example of its syntax.
assertNotIsInstance(value, cls, text_msg = null)

Compare Assert

Assertion functions can be compared with each other. Two values are compared as greater or lesser by using the following assertions.

assertEqual

The assertEqual method compares two values. If the two values are equal, then the test case passes, and if they are not equal, then the test case fails to raise an exception. The pass and fail are in terms of the Boolean value returned by the function. The following is an example of its syntax.

assertEqual(value1, value2, text_msg=null)
The syntax defines two values for comparison, and a text message may be stated if both values do not match. The text message can be null, and hence, it is optional to use. The following is a simple example to test page title values (the executable path is the same as described in earlier chapters).
import unittest
from selenium import webdriver
class test_case1(unittest.TestCase):
        def test1(self):
                driver=webdriver.Firefox()
                driver.get("https://apress.com")
                title1 =driver.title
                title2 ="Apress Home"
                # Verifying Page Title
                self.assertEqual(title1, title2, "Title Page do not Match.")
if __name__ =="__main__":
        unittest.main()

assertNotEqual

assertNotEqual acts contrast to the assertEqual function. A test case passes when two values are not equal; otherwise, test case fails. The following is an example of its syntax.
assertNotEqual(value1, value2, text_msg=null)
def test2(self):
        num1 =7
        num2 =5
        # Verifying Numbers
        self.assertNotEqual(num1, num2, "Numbers Match.")

assertGreater

assertGreater checks whether the first value is greater than the second value; if yes, then the test passes, or else the test case is a failure. The following is an example of its syntax.

assertGreater (value1, value2, txt_msg = null)

assertGreaterEqual

The assertGreaterEqual function checks whether value1 is greater than or equal to value2; if yes, then the test case passes. The following is an example of its syntax.

assertGreaterEqual (value1, value2, txt_msg = null)

assertLess

With assertLess , a test case passes when value1 is less than value2, and the test case fails when value1 is less. A text message is optional. assertLess behaves opposite the assertGreater function. The following is an example of its syntax.

assertLess (value1, value2, txt_msg = null)

assertLessEqual

The assertLessEqual method passes the test case only when value1 is less than or equal to value2; otherwise, the test leads to failure with an exception raised. The following is an example of its syntax.
assertLessEqual (value1, value2, txt_msg = null)
def test_cmp(self):
        num1 =7
        num2 =5
        #Check num1 is greater
        self.assertGreater(num1, num2, "num1 is less.")
        #Check num1 is greater than or equal to
        self.assertGreaterEqual(num1, num2, "num1 is less.")
        #Check num1 is less
        self.assertLess(num1, num2, "num1 is greater.")
        #Check num1 is less than or equal to
        self.assertLessEqual(num1, num2, "num1 is greater.")

Collection Assert

Collections are special types of data storage where multiple elements can be stored. The collection includes list, tuples, set, dict, and so forth that are built in the Python language.

Lists

The assertListEqual function allows us to compare two lists. When both lists contain the same elements, then the test case passes; if lists do not have the same elements, then the test case fails. The following is an example of its syntax.

assertListEqual(list1, list2, text_msg=null)
def test_list(self):
        list1 = ["python", "selenium", "apress"]
        list2 = ["python", "selenium", "apress"]
        #Check elements in both lists
        self.assertListEqual(list1, list2, "Lists don't Match.")

Tuples

The comparison of elements is made between two tuples. When these two tuples have the same elements in them, then the function returns a Boolean value as True, which means that the test case passes and vice versa. The following is an example of its syntax.

assertTupleEqual(tuple1, tuple2, text_msg=null)
def test_tuple(self):
        tuple1 = ("python", "selenium", "apress")
        tuple2 = ("python", "selenium", "apress")
        #Check elements between two tuples
        self.assertTupleEqual(tuple1, tuple2, "Tuples don't Match.")

Sets

Similar to the previous functions, the assertSetEqual function compares elements between two sets. If the two sets contain the same elements, then the test case passes or vice versa. The following is an example of its syntax.

assertSetEqual(set1, set2, text_msg=null)
def test_set(self):
        set1 = {"python", "selenium", "apress"}
        set2 = {"java", "selenium", "apress"}
        #Check elements from two sets
        self.assertSetEqual(set1, set2, "Sets don't Match.")

Dictionary

In the assertDictEqual method, all the available elements from one dictionary are matched with another dictionary. If all elements are the same, then the test case is successful; if the elements are not the same, then the test case is a failure. The text message is optional. The following is an example of its syntax.
assertDictEqual(dict1, dict2, text_msg=null)
def test_dict(self):
        dict1 = {"lang":"python", "tool":"selenium", "publication":"apress", "year":"2020"}
        dict2 = {"lang":"kotlin", "tool":"selenium", "publication":"apress", "year":"2020"}
        #Check elements from two sets
        self.assertDictEqual(dict1, dict2, "Dictionaries don't Match.")

assertIn

assertIn checks whether value1 is available in value2. If the value is available, then the test case passes without any exceptions. The following is an example of its syntax.

assertIn(value1, value2, text_msg = null)
Note

Collection assert is used to check availablility of web element from the collection.

assertNotIn

Like the assertIn function, assertNotIn checks whether value1 is present in value2. If it is present, then the test case fails; if it is not present, then the test case is a success. The following is an example of its syntax.
assertNotIn(value1, value2, text_msg = null)
The following program checks for an element’s availability in any given collection data using the assertIn() and assertNotIn() functions.
def test_item(self):
        collection=set(["Python", "Selenium", "Apress"])
        #Check for Python element in a set
        self.assertIn("Python", collection, "Element is not available in the set.")
        #Check for Java element in a set
        self.assertNotIn("Java", collection, "Element is available in the set.")
Note

Some of the assertion functions have not been included because they are deprecated in the new version of Python.

This completes all the assertion functions that can be utilized in Python for a test case created using Selenium.

Summary

You learned about assertions in test cases. You also looked at different assertion techniques, such as basic asserts, compare asserts, and collection asserts with multiple functions.

The assertions explained in this chapter evaluate or validate the web elements present in a web application. Assertions allow you to make a report on debugging issues that occur in a test case so that developers can solve them quickly.

The next chapter discusses various exceptions in Selenium and ways to handle them.

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

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