Query:
Numerous Python projects adopt a directory structure that separates unit tests into a dedicated test directory. However, running these tests directly from the test directory can result in import failures. This poses the question: how can we conveniently run unit tests in such a structure?
Answer:
The recommended approach involves utilizing the unittest command-line interface:
$ python -m unittest test_antigravity
In our example directory structure:
new_project/ antigravity/ antigravity.py test/ test_antigravity.py
Executing the above command will add the project directory to the system path (sys.path), allowing you to import the antigravity module effortlessly from the test file.
Benefits:
Additional Options:
Running a specific test module: Use the following syntax:
$ python -m unittest test.test_antigravity
Running a test case or method: Execute a single test case or method with:
$ python -m unittest test.test_antigravity.GravityTestCase $ python -m unittest test.test_antigravity.GravityTestCase.test_method
Discovering and running all tests: Employ test discovery:
$ python -m unittest discover $ python -m unittest
This will automatically discover and run all test modules within the test package.
The above is the detailed content of How Can I Easily Run Unit Tests in a Python Project with a Separate Test Directory?. For more information, please follow other related articles on the PHP Chinese website!