Search code examples
pythonunit-testingnose

Python unittest - get TestCase id's from nested TestSuite


I have a unittest.TestSuite instance. It is a tree of nested TestSuite/TestCase objects (of arbitrary shape/depth).

I want to get a list of individual test id's contained in the entire suite, without actually running the tests. (similar to nose's "--collect-only" option).

do i need to recursively walk the TestSuite, or is there something in unittest I can re-use? any tips for approaching this?


Solution

  • FWIW, this works great:

    via testtools:

    def iterate_tests(test_suite_or_case):
        """Iterate through all of the test cases in 'test_suite_or_case'."""
        try:
            suite = iter(test_suite_or_case)
        except TypeError:
            yield test_suite_or_case
        else:
            for test in suite:
                for subtest in iterate_tests(test):
                    yield subtest
    

    you can use testtools.testsuite.iterate_tests(suite) to iterate over the nested suite. for example, get a list of test id's, using a list comprehension:

    [test.id() for test in testtools.testsuite.iterate_tests(suite)]