Search code examples
pythonpython-unittesttest-suite

How to list available tests with python?


How to just list all discovered tests? I found this command:

python3.4 -m unittest discover -s .

But it's not exactly what I want, because the above command executes tests. I mean let's have a project with a lot of tests. Execution time is a few minutes. This force me to wait until tests are finished.

What I want is something like this (above command's output)

test_choice (test.TestSequenceFunctions) ... ok
test_sample (test.TestSequenceFunctions) ... ok
test_shuffle (test.TestSequenceFunctions) ... ok

or even better, something more like this (after editing above):

test.TestSequenceFunctions.test_choice
test.TestSequenceFunctions.test_sample
test.TestSequenceFunctions.test_shuffle

but without execution, only printing tests "paths" for copy&paste purpose.


Solution

  • Command line command discover is implemented using unittest.TestLoader. Here's the somewhat elegant solution

    import unittest
    
    def print_suite(suite):
        if hasattr(suite, '__iter__'):
            for x in suite:
                print_suite(x)
        else:
            print(suite)
    
    print_suite(unittest.defaultTestLoader.discover('.'))
    

    Running example:

    In [5]: print_suite(unittest.defaultTestLoader.discover('.'))
    test_accounts (tests.TestAccounts)
    test_counters (tests.TestAccounts)
    # More of this ...
    test_full (tests.TestImages)
    

    This works because TestLoader.discover returns TestSuite objects, that implement __iter__ method and therefore are iterable.