How to run unittest discover from "python setup.py test"?
If you use py27+ or py32+, the solution is pretty simple:
test_suite="tests",
From Building and Distributing Packages with Setuptools (emphasis mine):
test_suite
A string naming a unittest.TestCase subclass (or a package or module containing one or more of them, or a method of such a subclass), or naming a function that can be called with no arguments and returns a unittest.TestSuite.
Hence, in setup.py
you would add a function that returns a TestSuite:
import unittestdef my_test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('tests', pattern='test_*.py') return test_suite
Then, you would specify the command setup
as follows:
setup( ... test_suite='setup.my_test_suite', ...)
You don't need config to get this working. There are basically two main ways to do it:
The quick way
Rename your test_module.py
to module_test.py
(basically add _test
as a suffix to tests for a particular module), and python will find it automatically. Just make sure to add this to setup.py
:
from setuptools import setup, find_packagessetup( ... test_suite = 'tests', ...)
The long way
Here's how to do it with your current directory structure:
project/ package/ __init__.py module.py tests/ __init__.py test_module.py run_tests.py <- I want to delete this setup.py
Under tests/__init__.py
, you want to import the unittest
and your unit test script test_module
, and then create a function to run the tests. In tests/__init__.py
, type in something like this:
import unittestimport test_moduledef my_module_suite(): loader = unittest.TestLoader() suite = loader.loadTestsFromModule(test_module) return suite
The TestLoader
class has other functions besides loadTestsFromModule
. You can run dir(unittest.TestLoader)
to see the other ones, but this one is the simplest to use.
Since your directory structure is such, you'll probably want the test_module
to be able to import your module
script. You might have already done this, but just in case you didn't, you could include the parent path so that you can import the package
module and the module
script. At the top of your test_module.py
, type:
import os, syssys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))import unittestimport package.module...
Then finally, in setup.py
, include the tests
module and run the command you created, my_module_suite
:
from setuptools import setup, find_packagessetup( ... test_suite = 'tests.my_module_suite', ...)
Then you just run python setup.py test
.
Here is a sample someone made as a reference.