Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 386
xliiv Avatar asked Jun 29 '14 17:06

xliiv


People also ask

How do I run all Python unit tests in a directory?

Run all Python tests in a directoryFrom the context menu, select the corresponding run command. If the directory contains tests that belong to the different testing frameworks, select the configuration to be used. For example, select Run 'All tests in: <directory name>' Run pytest in <directory name>'.

Where are Python tests stored?

Tests are put in files of the form test_*. py or *_test.py , and are usually placed in a directory called tests/ in a package's root.

What is test library in Python?

It is where the test plans are being executed using script instead of a human. Python comes with the tools and libraries that support automated testing for your system. Python Test cases are comparatively easy to write. With the increased use of Python, Python-based test automation frameworks are also becoming popular.

How many types of testing are there in Python?

There are four different types of tests, each depending on the granularity of code being tested, as well as the goal of the test.


1 Answers

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.

like image 139
vaultah Avatar answered Oct 13 '22 03:10

vaultah