Using Python Selenium with Unittest

Let’s create a couple of automated tests using Python’s unittest module:

Use Cases

  • As a user, when I open www.google.com on my web browser, the web browser tab will show the word Google as its title
  • As a user, when I open www.google.com on my web browser and search for the word Red Hat, the web browser tab will show the word Red Hat as its title

Python Code

Here is the Python code that will automate these tests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import unittest

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


class GoogleTestCase(unittest.TestCase):

    def setUp(self):
        """Explicitly create a Chrome browser instance."""
        self.browser = webdriver.Chrome()
        self.addCleanup(self.browser.quit)

    def test_page_title(self):
        """Assert that title of page says 'Google'."""
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)

    def test_search_page_title(self):
        """Assert that Google search returns data for 'Red Hat'."""
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)
        element = self.browser.find_element_by_id('lst-ib')
        assert element is not None
        element.send_keys('Red Hat' + Keys.RETURN)
        assert self.browser.title.startswith('Red Hat')


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

Now we can execute these tests:

python tests/unittest/test_SeleniumUnittest.py
test_page_title (__main__.GoogleTestCase)
Assert that title of page says 'Google'. ... ok
test_search_page_title (__main__.GoogleTestCase)
Assert that Google search returns data for 'Red Hat'. ... ok

----------------------------------------------------------------------
Ran 2 tests in 7.765s

OK