12

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
xliiv
  • 5,399
  • 5
  • 29
  • 35

2 Answers2

25

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • 1
    I couldn't find email to @vaultah so i'm writing here. I've updated license and attribution. I hope you'll forgive my initial innocence :). I also want to thank BoltClock for calm explaining my mistakes. – xliiv Sep 01 '14 at 15:21
  • where to put code from @vaultah solution? in unit tests folder __main__.py? – Sebastian Jun 17 '20 at 11:05
0

You could do something like:

from your_tests import TestSequenceFunctions
print('\n'.join([f.__name__ for f in dir(TestSequenceFunctions) if f.__name__.startswith('test_')]))

I'm not sure if there is an exposed method for this via unittest.main.

daniel
  • 2,568
  • 24
  • 32