Run Selected Python Unit Tests from the Command Line
Janne Kemppainen |It doesn’t always make sense to run the full suite of tests when you’re developing a part of a program. So how can you run only a portion of your Python unit tests on the command line?
If you don’t provide any arguments to the unittest
module it will run in test discovery mode by default. That means that it is looking for all tests that it can find in the common places.
>> python3 -m unittest
If you want to run only a smaller subset of tests you need to define the module, class or the single test in the command. Assuming that your tests are located in a module called tests
:
>> python3 -m unittest tests
>> python3 -m unittest tests.test_my_class
>> python3 -m unittest tests.test_my_class.TestMyClass
>> python3 -m unittest tests.test_my_class.TestMyClass.test_my_method
Depending on the argument this will run:
- all tests in the
tests
directory - all tests in the
tests/test_my_class.py
file - all tests in the
TestMyClass
test class - the
test_my_method
test case insideTestMyClass
.
As you can see, the paths, classes and methods are separated by periods. You can add more than one rule by separating them with space. This way you can run only a subset of tests. This can be handy in case you have differentiated the tests between integration tests and unit tests, and want your test command (or even a Makefile) to run the tests selectively.
The command also supports filenames, so you can use tab completion to quickly find the correct test file. The following works too:
>> python3 -m unittest tests/test_my_class.py
Internally the .py
extension is dropped and all /
characters are replaced with periods.
If your test file defines the unittest main as the entry point when run as a script then you can also invoke it directly without specifying the unittest
module. So if your test file ends with
if __name__ == '__main__':
unittest.main()
then you can run all tests within that file like this:
>> python3 tests/test_my_class.py
However, due to the way that imports work and depending on where your test files are located this may cause an ImportError
. I’ve generally found it easier to work with the unittest
module since that way the imports are easier to handle.
If your project structure looks something like this:
.
├── code
│ ├── __init__.py
│ ├── names.py
├── requirements.txt
└── tests
├── __init__.py
└── test_names.py
then the normal imports should work when you run the unit tests from the project root with python -m unittest
or a similar command:
from code import names
Read next in the Python bites series.
Previous post
Make an NPM Package Executable with npx