Home > Backend Development > Python Tutorial > How to Effectively Run Unit Tests in Python with a Standard Directory Structure?

How to Effectively Run Unit Tests in Python with a Standard Directory Structure?

Mary-Kate Olsen
Release: 2024-11-26 06:40:11
Original
410 people have browsed it

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.
Copy after login

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
Copy after login

Run the tests as follows:

$ cd new_project
$ python -m unittest test_antigravity
Copy after login

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
Copy after login

Running Specific Tests:

To run a specific test module (e.g., test_antigravity.py):

$ cd new_project
$ python -m unittest test.test_antigravity
Copy after login

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
Copy after login

Running All Tests:

Use test discovery to automatically discover and run all tests:

$ cd new_project
$ python -m unittest discover
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template