0
0
PytestHow-ToBeginner ยท 3 min read

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.
  • pytest without 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 pytest in 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' folder
Output
============================= test session starts ============================= collected 0 items ============================== no tests ran in 0.01s ==========================
๐Ÿ“Š

Quick Reference

Summary tips for running tests in a directory with pytest:

CommandDescription
pytestRun tests in current directory and subdirectories
pytest testsRun tests in the 'tests' directory
pytest tests/subdirRun tests in a specific subdirectory
pytest -v testsRun tests with verbose output in 'tests' directory
pytest --maxfail=1 testsStop 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.