pythonunit-testing

How to load tests from some files and not others?


I want to run a suite of unit tests in the tests folder. The basic code is:

suite = unittest.defaultTestLoader.discover('tests')

I want only some of these tests to run, for example test_e1 if file e1.py is present, test_e5 if e5.py is present, but not test_e2 and test_e11 (because files e2.py and e11.py are missing).

I tried the pattern argument of the discoverer() function, which defaults to test_*.py, but it does not allow enough control for what I need (see How to match specific files with a shell pattern in unit test discoverer? ).

One answer in that thread suggests finding these tests with unittest.TestLoader().loadTestsFromNames, so I tried this code:

    file_list = []

    for some_file in some_file_list:
        full_filepath = os.path.join(some_dir, some_file)
        if not os.path.exists(full_filepath):
            continue
        file_list.append("tests/test_%s.TestDocs" % some_file)

    suite = unittest.TestLoader().loadTestsFromNames(file_list)
    print(suite)

The name TestDocs is the class name that inherits from the unit test:

class TestDocs(unittest.TestCase):

But this shows a list of failed tests such as:

<unittest.suite.TestSuite tests=[<unittest.loader._FailedTest testMethod=tests/test_>]>

How can I run tests only for a certain set of files?


Solution

  • You are passing hybrid file-path/object names to loadTestsFromNames. Drop the tests from the name, and ensure that tests appears on your module search path, either by

    1. Modifying sys.path before calling the method, or
    2. Adding tests to the PYTHONPATH environment variable before running your tests.