Ref : stackoverflow
The best solution in my opinion is to use the unittest
command line interface which will add the directory to the sys.path
so you don't have to (done in the TestLoader
class).
For example for a directory structure like this:
new_project
โโโ antigravity.py
โโโ test_antigravity.py
You can just run:
$ cd new_project
$ python -m unittest test_antigravity
For a directory structure like yours:
new_project
โโโ antigravity
โย ย โโโ __init__.py # make it a package
โย ย โโโ antigravity.py
โโโ test
โโโ __init__.py # also make test a package
โโโ test_antigravity.py
And in the test modules inside the test
package, you can import the antigravity
package and its modules as usual:
# import the package
import antigravity
# import the antigravity module
from antigravity import antigravity
# or an object inside the antigravity module
from antigravity.antigravity import my_object
Running a single test module:
To run a single test module, in this case test_antigravity.py
:
$ cd new_project
$ python -m unittest test.test_antigravity
Just reference the test module the same way you import it.
Running a single test case or test method:
Also you can run a single TestCase
or a single test method:
$ python -m unittest test.test_antigravity.GravityTestCase
$ python -m unittest test.test_antigravity.GravityTestCase.test_method
Running all tests:
You can also use test discovery which will discover and run all the tests for you, they must be modules or packages named test*.py
(can be changed with the -p, --pattern
flag):
$ cd new_project
$ python -m unittest discover
This will run all the test*.py
modules inside the test
package.
@KevinMendietaP - Yes, this does work for Python 3! At least for my particular 3.6.5.
@flow2k -
path/to/python/lib/test
contains Python's own tests, which is importable asimport test
. So to avoid clashes one probably should use some other name for a folder containing tests. Or it might not be a problem for you.@StianHanssen
I think that's not really an issue with this particular approach to test discovery as it is one with imports in general. Some time ago I had the pleasure of receiving a rather comprehensive answer on a question on relative imports I posted on Stack Overflow. Building on that, my current approach is to always use absolute imports. That is, even though a shorter import might exist, I always import all the way from the top within a package. Combined with an install via
pip install -e ./
this allows for easy development of a package.Thanks for the Gist by the way! Useful and very much a proper solution in my opinion.