How to Run Tests in a Directory Using pytest
To run all tests in a directory using
pytest, open your terminal and run pytest path/to/directory. This command will discover and execute all test files and functions inside that directory automatically.Syntax
The basic syntax to run tests in a directory with pytest is:
pytest <directory_path>: Runs all tests found in the specified directory and its subdirectories.pytestwithout arguments: Runs tests in the current directory by default.
Pytest automatically finds files named test_*.py or *_test.py and runs test functions inside them.
bash
pytest <directory_path>
Example
This example shows how to run all tests inside the tests directory. It assumes you have test files named like test_example.py inside that folder.
bash
pytest tests
Output
============================= test session starts =============================
collected 3 items
tests/test_example.py ... [100%]
============================== 3 passed in 0.03s ==============================
Common Pitfalls
Common mistakes when running tests in a directory include:
- Running
pytestin the wrong directory, so no tests are found. - Test files not named correctly (must start or end with
test). - Test functions not starting with
test_, so pytest ignores them. - Using relative paths incorrectly or with typos.
Always check your current directory and file names if tests are not discovered.
bash
pytest wrong_folder # Wrong directory, no tests found
# Correct usage:
pytest tests # Runs tests in 'tests' folderOutput
============================= test session starts =============================
collected 0 items
============================== no tests ran in 0.01s ==========================
Quick Reference
Summary tips for running tests in a directory with pytest:
| Command | Description |
|---|---|
| pytest | Run tests in current directory and subdirectories |
| pytest tests | Run tests in the 'tests' directory |
| pytest tests/subdir | Run tests in a specific subdirectory |
| pytest -v tests | Run tests with verbose output in 'tests' directory |
| pytest --maxfail=1 tests | Stop after first failure in 'tests' directory |
Key Takeaways
Run
pytest <directory> to execute all tests in that directory and its subfolders.Ensure test files and functions follow pytest naming conventions for discovery.
Check your current directory and paths if no tests are found.
Use options like
-v for more detailed output when running tests.Pytest automatically finds tests recursively inside the given directory.