· Lewis Wright

Using Selenium Webdriver with Python's unittest framework

In this tutorial, we'll be going over how to use Selenium Webdriver with Python's unittest framework. We'll use webdriver-manager to automatically download and install the latest version of Chrome.

Installing the packages

First off, we'll need to install the required packages:

pip install webdriver-manager selenium
# or if you prefer to use poetry
poetry add webdriver-manager selenium

Setting up the test package

Next, we'll create a test directory and add an empty __init__.py file to it. Python automatically looks in all packages when running tests, so you can name this directory anything you want - or even embed it within other packages. Just make sure you include an __init__.py file so that Python recognises it as a package.

mkdir test
touch test/__init__.py

Writing our first test

Now that we're setup, we can go write our first test. We'll create a test_example.py file in the test directory. It's important that the file name starts with test_ so that Python recognises it as a test file.

test/test_mytest.py
import unittest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
 
class test_mytest(unittest.TestCase):
    browser = None
 
    @classmethod
    def setUpClass(cls) -> None:
        # This can be any browser supported by webdriver
        cls.browser = webdriver.Chrome(service=Service(executable_path=ChromeDriverManager().install()))
 
    @classmethod
    def tearDownClass(cls) -> None:
        cls.browser.quit()
 
    # Custom this or add more tests!
    def test_Google(self):
        self.browser.get('https://google.com')
        self.assertIn('Google', self.browser.title)
 
if __name__ == "__main__":
    unittest.main()

You may have noticed that we've chosen to use the setUpClass and tearDownClass methods instead of the conventional setUp and tearDown. This is because the setUpClass and tearDownClass methods are only called once per test class, whereas the setUp and tearDown methods are called for each test method. By doing this, we save time by only starting and stopping the browser once per test class.

Running your test

All that's left to do now is run our test. To do this, simply run the following command:

python -m unittest

You can also run a specific test by passing the test file name to the command:

python -m unittest test.test_mytest

Customising your test

Unless you work at Google, you'll probably want to customise your test to do something more useful! We suggest you check out the Selenium Webdriver's getting started guide for some detailed examples of how to use Selenium Webdriver.