How to Run Unit Tests in a Common Test Directory Structure
In Python, it's common practice to organize unit tests in a separate test directory. However, this raises the question of how to execute these tests efficiently.
Problem
When attempting to run python test_antigravity.py from within the test directory, the import of the antigravity module fails due to the module not being on the path. Modifying the PYTHONPATH or using other search path tricks may be feasible, but they lack simplicity, especially for users who simply want to verify the test results.
Solution
The recommended approach is to utilize the unittest command line interface. Its TestLoader class adds the necessary directory to sys.path, resolving the path issue.
For example, in a directory structure like this:
new_project ├── antigravity.py └── test_antigravity.py
You can execute the tests with:
$ cd new_project $ python -m unittest test_antigravity
For a directory structure like the one provided:
new_project ├── antigravity │ ├── __init__.py │ └── antigravity.py └── test ├── __init__.py └── test_antigravity.py
You can achieve similar functionality by declaring both antigravity and test as packages with __init__.py files. In the test modules, you can import the antigravity package and its modules as usual.
Running Specific Tests
To run a single test module, such as test_antigravity.py:
$ cd new_project $ python -m unittest test.test_antigravity
You can also run individual test cases or methods:
$ python -m unittest test.test_antigravity.GravityTestCase $ python -m unittest test.test_antigravity.GravityTestCase.test_method
Running All Tests
You can use test discovery to automatically run all tests. This requires that the test modules and packages are named test*.py (customizable via the -p or --pattern flag):
$ cd new_project $ python -m unittest discover
For users who prefer simplicity, you can instruct them to run the following command:
To run the unit tests, do: $ python -m unittest discover
The above is the detailed content of How to Efficiently Run Unit Tests from a Separate Test Directory in Python?. For more information, please follow other related articles on the PHP Chinese website!