Selenium unittest – Build A Selenium Python Test Suite From Scratch Using Unittest

Selenium Python – Unittest in Python

Selenium unittest: Most of the high-level programming languages have a unit test framework associated with them. Like Java has JUnit, .Net has NUnit. Similarly, Python has PyUnit or unit test associated with it. It was created by Kent Beck and Erich Gamma. The unit test framework supports test automation, with the help of text fixtures. We will learn more about it in this chapter.

Structure

  • What is a unit test?
  • Structure of unit test
  • Writing first unit test
  • Adding assertions in the test

Objective

Pyunit tutorial: When we are writing our test scripts, it is important that we structure them with the help of a unit test framework. The Python programming language makes the available unit tests, which is the unit test framework. In this chapter, we will understand how we use it to structure our code and write scripts.

The most unit and their structure

The unit test is the unit testing framework in Python. Its features are inspired by JUnit, which is a unit testing framework for the Java programming language. Applying a unit testing framework at the code level helps us introduce structure to our code. It also ensures
that we can add assertions in the test code, which we require as we are writing test automation scripts.

In a general unit test case, the class which we create is derived from a unit test.TestCase. We can have a set)p() andatearDown()
method there. In the setup () method, we generally write code that helps in preparing the system and test environment. And in the
tearDown () method, we write scripts to clean up the environment. In between these methods, we have our functions which are where the
code to actually test is created. These functions are written using the test_ prefix. We then execute the tests by calling unit tests.main()
the method at the end of the file.

A unit test contains the following important entities:

  • Test fixture: It expresses the process to execute the test, followed by a clean-up action.
  • Test case: It is the basic unit of testing.
  • Test suite: It is a collection of test cases.
  • Test runner: A test runner manages the execution of the test and presents the result to the user.

Let us see an example of a script for login logout, where we will be applying unit test:

from selenium import webdriver
import unittest

class login(unittest.Testcase):
      def setup(self):
      self.driver=webdriver.chrome(executable_path="D:\Eclipse\BPB\seleniumpython\seleniumpython\drivers\chromedriver.exe")
      self.base_url = "http://practice.bpbonline.com/catalog/index.php"

def test_login(self):
    driver = self.driver
    driver.get(self.base_url)
    driver.find_element_by_link_text("My Account").click( )
    driver.find_element_by_name("email_address").clear( )
    driver.find_element_by_name("email_address").send_keys("bpb@bpb.com")
    driver.find_element_by_name("password").clear( )
    driver.find_element_by_name("password").send_keys("bpb@123")
    driver.find_element_by_id("tab1").click( )
    driver.find_element_by_link_text("log off").click( )
    driver.find_element_by_link_text("continue").click( )

def tearDown(self):
    self.driver.quit( )

if_name_=="_main_":
    unittest>main( )

So in the preceding script, we see the automation test is structured in different sections.

• set up ( ): In this, we generally put statements to initialize the browser. Invoke the WebDriver object with the URL we would like to launch.

• test_login( ): In this method, we have written the steps to perform the actual test on the application. Please note that we have not added any assertion action yet. We will see that in the next section.

• tearDown( ): This is the cleanup method. In this, we generally put action to clean up the environment. So here, we have written the statement to close the browser.

Once the structure is complete, we execute the tests by calling the unit test.main( ) method.

Assertions

Assertions are ways to validate our actions. The PyUnit provides us the following set:

Assert method Explanation
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertls(a,b) a is b
assertlsNot(a, b) a is not b
assertlsNone(x) x is None
assertlsNotNone(x) x is not None
assertln(a, b) a in b
assertNotln(a, b) a not in b
assertlslnstance(a, b) isinstancefa, b)
assertNotlsInstance(a, b) not isinstnacefa, b)
assertRaisesfexc, fun, args, *kwds) fun(*args, **kwds) raises exc
assertRaisesRegexpfexc, r, fun, args, *kwds) round(a-b, 7) == 0
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b
assertGreaterEqual(a, b) a >= b
assertLessfa, b) a < b
assertLessEqual(a, b) a <= b
assertRegexpMatches(s, r) r.search(s)
assertNotRegexpMatchesfab) not r.search(s)
assertltemsEqual(a, b) sorted(a) == sorted(b) Works with unhashable objects
assertDictContains Subset(a, b) All the key-value pairs in a exist in b

We will now see a test automation script of login logout where we will use assertion to validate- valid user login, by checking the presence of text My Account Information.

def test_login(self):
    driver=self.driver
    driver.get(self.base_url)
    driver.find_element_by_link_text("My Account").click( )
    driver.find_element_by_name("email_address").clear( )
    driver.find_element_by_name("email_address").send_keys("bpb@bpb.com")
    driver.find_element_by_name("password").clear( )
    driver.find_element_by_name("password").send_keys("bpb123")
    driver.find_element_by_id("tab1").click( )
    pgsrc=driver.page_source
    if(pgsrc.index("My Account Information")>-1):
       print("user is valid")
       driver.find_element_by_link_text("log off").click( )
       driver.find_element_by_link_text("continue").click( )
       self.assertTrue(True,"User is valid")
else:
    print("User is Invaild")
    self.assertFalse(False, "User is invalid")

In the preceding script, we can see usage of self .assertTrue() and self .assentFalse() statement to mark the test pass or fail depending on the presence of the text My Account Information.

Conclusion

So in this chapter, we have seen how can we use the unit test framework to structure our test in setUp(), test_method(), and teardown() methods. We have also seen, how we can use assertions to mark our test as pass and fail. You can follow this link if you want to read more about it- https://docs.python.0rg/3/library/unittest.html.

In the next chapter, we will be discussing the concept of waits. We will see how we can synchronize our tests using static and dynamic waits and why is that important.

Related Articles: