Skip to content
Advertisement

How do I structure my tests with the Python ‘unittest’ module?

I’m trying to build a test framework for automated web testing in Selenium and unittest, and I want to structure my tests into distinct scripts.

So I’ve organised it as following:

File base.py – this will contain, for now, the base Selenium test case class for setting up a session.

import unittest
from selenium import webdriver

# Base Selenium Test class from which all test cases inherit.
class BaseSeleniumTest(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()
    def tearDown(self):
        self.browser.close()

File main.py – I want this to be the overall test suite from which all the individual tests are run.

import unittest
import test_example

if __name__ == "__main__":
    SeTestSuite = test_example.TitleSpelling()
    unittest.TextTestRunner(verbosity=2).run(SeTestSuite)

File test_example.py – an example test case. It might be nice to make these run on their own too.

from base import BaseSeleniumTest

# Test the spelling of the title
class TitleSpelling(BaseSeleniumTest):
    def test_a(self):
        self.assertTrue(False)

    def test_b(self):
        self.assertTrue(True)

The problem is that when I run main.py, I get the following error:

Traceback (most recent call last):
  File "H:Pythontestframeworkmain.py", line 5, in <module>
    SeTestSuite = test_example.TitleSpelling()
  File "C:Python27libunittestcase.py", line 191, in __init__
    (self.__class__, methodName))
ValueError: no such test method in <class 'test_example.TitleSpelling'>: runTest

I suspect this is due to the very special way in which unittest runs and I must have missed a trick on how the docs expect me to structure my tests. Any pointers?

Advertisement

Answer

I am not 100% sure, but in main.py, you might need a:

SeTestSuite = unittest.defaultTestLoader.discover(start_dir='.')

And the runner line should be (maybe):

# If your line didn't work
unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(SeTestSuite))
Advertisement