Is there a consensus about the best place to put Python unittests?
Should the unittests be included within the same module as the functionality being tested (executed wh
It does not really make sense to use the __main__
trick. Just assume that you have several files in your module, and it does not work anymore, because you don't want to run each source file separately when testing your module.
Also, when installing a module, most of the time you don't want to install the tests. Your end-user does not care about tests, only the developers should care.
No, really. Put your tests in tests/
, your doc in doc
, and have a Makefile ready around for a make test
. Any other approaches are just intermediate solutions, only valid for specific tiny modules.
Personally, I create a tests/ folder in my source directory and try to, more or less, mirror my main source code hierarchy with unit test equivalents (having 1 module = 1 unit test module as a rule of thumb).
Note that I'm using nose and its philosophy is a bit different than unittest's.
tests/
subdirectory in your package for larger projects.It's a matter of what works best for the project you're creating.
Sometimes the libraries you're using determine where tests should go, as is the case with Django (where you put your tests in models.py
, tests.py
or a tests/
subdirectory in your apps).
If there are no existing constraints, it's a matter of personal preference. For a small set of modules, it may be more convenient to put the unittests in the files you're creating.
For anything more than a few modules I create the tests separately in a tests/
directory in the package. Having testing code mixed with the implementation adds unnecessary noise for anyone reading the code.
I usually have them in a separate folder called most often test/. Personally I am not using the if __name__ == '__main__' check, because I use nosetests and it handles the test detection by itself.
if __name__ == '__main__'
, etc. is great for small tests.
I generally keep test code in a separate module, and ship the module/package and tests in a single distribution. If the user installs using setup.py
they can run the tests from the test directory to ensure that everything works in their environment, but only the module's code ends up under Lib/site-packages
.