Home >Backend Development >Python Tutorial >How to Effectively Run Unit Tests in Python with a Standard Directory Structure?
Running Unit Tests with a Typical Directory Structure
Python's common module structure often involves separating unit tests into a dedicated test directory, as seen below:
new_project/ antigravity/ antigravity.py test/ test_antigravity.py setup.py etc.
Running these tests requires more than simply executing python test_antigravity.py from the test directory. Since antigravity is not on the import path, this approach will fail.
Instead, the most straightforward way to run the tests is to use the unittest command line interface. This utility will automatically add the directory to sys.path, making modules accessible for import.
For a directory structure like:
new_project ├── antigravity.py └── test_antigravity.py
Run the tests as follows:
$ cd new_project $ python -m unittest test_antigravity
For a structure like yours, with packages in both antigravity and test directories, you can import modules within antigravity as usual in test modules:
# 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 Specific Tests:
To run a specific test module (e.g., test_antigravity.py):
$ cd new_project $ python -m unittest test.test_antigravity
You can also run a single test case or method:
$ python -m unittest test.test_antigravity.GravityTestCase $ python -m unittest test.test_antigravity.GravityTestCase.test_method
Running All Tests:
Use test discovery to automatically discover and run all tests:
$ cd new_project $ python -m unittest discover
This will execute all test*.py modules within the test package. For more information, refer to the official documentation on discovery.
The above is the detailed content of How to Effectively Run Unit Tests in Python with a Standard Directory Structure?. For more information, please follow other related articles on the PHP Chinese website!