Selenium Unittest example in Python

To support test automation, we need 'unittest' unit testing framework was originally inspired by JUnit. Unittest is included test module by default in the Python standard library. Its API will be familiar to anyone who has used any of the JUnit/nunit.

Unittest supports test automation, by sharing setup and shutdown code for tests. The setUp() and tearDown() methods allows to define set of instructions /commands to be executed before and after each test method. If the setUp() method it self raises an exception while executing tests, the test methods will not be executed. But If setUp() is executed successfully, tearDown() will run even if the test method is passed or not.

Below is the simple example to test a string method using unittest framework.

import unittest
 
class FirstStringTest(unittest.TestCase):
 
    # Return true or false. 
    def test_StringUpper(self):        
        self.assertEqual('foo'.upper(), 'FOO', 'Something wrong')
 
if __name__ == '__main__':
    unittest.main()

Best way to run test is to include below code at the bottom of each test file, and then simply run the script directly from the command line:

if __name__ == '__main__':
unittest.main()

A testcase is created by subclassing unittest.TestCase. The above test 'FirstStringTest' has a single test_StringUpper() method, whose names start with the letter test. This naming convention informs the test runner about which methods represent tests.

We are using assertEqual(first, second, msg) to test that first and second are equal. If the values do not compare equal, the test will fail.

Below are the features which unittest supports:-

test fixture:
A test fixture represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.

test case:
A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.

test suite:
A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.

test runner:
A test runner is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.

The standard workflow for unittest is:-

Step 1 : Define a class derived from unittest.TestCase.
Step 2 : Add functions that start with ‘test_’.
Step 3 : Run the tests by placing unittest.main() in your file, usually at the bottom.

Below section demonstrates a quick look on unittest features using Selenium Webdriver:-

import unittest
from selenium import webdriver

class InputFormsCheck(unittest.TestCase):

    #Opening browser.
    def setUp(self):
        self.driver = webdriver.Chrome(r'C:\Users\pc\Downloads\chromedriver.exe')

    #Testing Single Input Field.    
    def test_singleInputField(self):
        pageUrl = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
        driver=self.driver
        driver.maximize_window()
        driver.get(pageUrl)

        #Finding "Single input form" input text field by id. And sending keys(entering data) in it.
        eleUserMessage = driver.find_element_by_id("user-message")
        eleUserMessage.clear()
        eleUserMessage.send_keys("Test Python")

        #Finding "Show Your Message" button element by css selector using both id and class name. And clicking it.
        eleShowMsgBtn=driver.find_element_by_css_selector('#get-input > .btn')
        eleShowMsgBtn.click()

        #Checking whether the input text and output text are same using assertion.
        eleYourMsg=driver.find_element_by_id("display")
        assert "Test Python" in eleYourMsg.text
 
    # Closing the browser.
    def tearDown(self):
        self.driver.close()

# This line sets the variable “__name__” to have a value “__main__”.
# If this file is being imported from another module then “__name__” will be set to the other module's name.
if __name__ == "__main__":
    unittest.main()

To run the above program from the command line, enter $ python InputFormsCheck.py. You can run by passing -v (verbose output) option which will enable a higher level of verbosity, and produce the output with more detailed results.

What is the above program doing ?

Step 1: It Opens chrome browser
Step 2: Enters the URL and maximize the browser
Step 3: Enters text 'Test Python' in the input text field
Step 4: Clicks on a button
Step 5: Finally, it checks for the text we have entered and the closes the browser.

If the test is passed, it returns 'OK' which means that the tests are passed.

Selenium Tutorials: 

Add new comment