How do I skip a test_utility file when running Python unittest?
I have a utilities package, and am including tests for some of the utilities. However, one of the directories has a bunch of django TestCase specific reusable classes, and it keeps running and failing when I run:
python -m unittest
The file's name is testutils.py and is for other Django apps to import and use, not to be tested itself. Is there a settings or skip file where I can tell my package not to look at that file when running tests?
unittest
defaults to checking files that match the following glob for tests: test*.py
. As you can see, testutils.py
matches that pattern and so is always searched for tests -- even if they are only meant to be stubs.
You need to either rename testutils.py
to something that does not match this pattern or change the glob pattern that unittest
uses to discover test files. As an example, you could name all your test files like test_*.py
(eg. test_foo.py
) and then run your tests like:
python -m unittest discover -p 'test_*.py'
The underscore in the pattern will match things like test_foo.py
, but will stop it from matching testutils.py
.
One file structure might look like:
./main.py
./util.py
./tests/util.py
./tests/test_main.py
./tests/test_util.py
All test files whether they contain tests or utility functions and classes are contained under the tests/
directory. Thus, we know that tests/util.py
contains utilities for tests rather than being part of the main application's code. And that test_util.py
is a file that is being used to test code in ./util.py
.
Side note
util
isn't a very good descriptor for a module or file. It basically means "junk that I can't really think of a good name for". From a brief description of your tests maybe something like django_test_harness
might be appropriate.