Running Unit Tests with a Standard Test Directory Structure
Many Python projects adopt a typical directory structure where unit tests are kept in a separate "test" directory. This raises the question: how does one run these tests effectively?
The Issue and Problem
Running test_antigravity.py from the "test" directory directly will fail because the antigravity module is not on the system path. Modifying PYTHONPATH and similar path-related tricks may not be an optimal solution. Copy-pasting the test file into a different directory seems inefficient.
The Solution: Using the unittest Command Line Interface
The most recommended approach is to utilize the unittest command line interface. It automatically adds the current directory to the sys.path, allowing seamless importing of the module under test.
For a Structure Like:
new_project └── test_antigravity.py
Simply run:
$ python -m unittest test_antigravity
For a Structure Like:
new_project ├── antigravity │ └── antigravity.py └── test ├── test_antigravity.py
You can run a single test module:
$ python -m unittest test.test_antigravity
Run a single test:
$ python -m unittest test.test_antigravity.GravityTestCase
Run a single test method:
$ python -m unittest test.test_antigravity.GravityTestCase.test_method
Run all tests:
$ python -m unittest discover $ # Also works without discover for Python 3 $ # as suggested by Burrito in the comments $ python -m unittest
This approach is convenient for users to execute unit tests by simply following the instruction: "To run the unit tests, do X."
The above is the detailed content of How Can I Effectively Run Unit Tests from a Standard \'test\' Directory in Python?. For more information, please follow other related articles on the PHP Chinese website!