Skip to content
Advertisement

Specify specific testcases in Python unit test TestLoader

I have the following folder structure.

Unit
    smoke.py
    Test1
         Test1.py
    Test2
         Test2.py

Both the test files have two test cases each.

File smoke.py contains

suite1 = unittest.TestLoader().discover('Test1', pattern = "Test*.py")
suite2 = unittest.TestLoader().discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity=2).run(alltests)

The above code runs four test cases which is expected.

Is there a way to run some specific test cases from file test1.py and test2.py where I can explicitly add those testcases to the suite1 and suite 2 in the above code.

If Test1.py contains a testcase name test_system in the class Test1, how can TestLoader load that specific test case instead of running all the testcases in that module.

Advertisement

Answer

You can configure your test loader to run only tests with a certain prefix:

loader = unittest.TestLoader()
loader.testMethodPrefix = "test_prefix"# default value is "test"

suite1 = loader.discover('Test1', pattern = "Test*.py") 
suite2 = loader.discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity=2).run(alltests)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement