How to Discover Tests in pytest: Syntax and Examples
pytest discovers tests automatically by looking for files, classes, and functions that follow specific naming patterns like
test_*.py for files and test_* prefix for functions. Running pytest in your project folder triggers this discovery process without extra configuration.Syntax
pytest discovers tests based on naming conventions and locations. It looks for:
- Files named
test_*.pyor*_test.py - Test functions prefixed with
test_ - Test classes prefixed with
Test(without an__init__method)
Run pytest [options] [path] to start test discovery and execution.
bash
pytest [options] [path]
Example
This example shows a simple test file named test_sample.py with a test function. Running pytest in the folder will discover and run this test automatically.
python
def test_addition(): assert 1 + 1 == 2 # Save this as test_sample.py and run `pytest` in the same folder
Output
============================= test session starts ==============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes that prevent pytest from discovering tests include:
- File names not starting or ending with
test(e.g.,sample.pyinstead oftest_sample.py) - Test functions not prefixed with
test_ - Test classes not starting with
Testor having an__init__method - Running pytest from a wrong directory or specifying incorrect paths
Always follow naming conventions and run pytest from the root folder of your tests.
python
## Wrong example (test not discovered): # Filename: sample.py # Function name: add_test() def add_test(): assert 1 + 1 == 2 ## Right example: # Filename: test_sample.py # Function name: test_addition() def test_addition(): assert 1 + 1 == 2
Quick Reference
| Pattern | Description |
|---|---|
| test_*.py or *_test.py | File names pytest looks for |
| test_* | Function names pytest recognizes as tests |
| Test* | Class names pytest treats as containers for tests |
| No __init__ in test classes | Test classes should not have __init__ methods |
| Run `pytest` in root folder | Start discovery from your test root directory |
Key Takeaways
pytest discovers tests by default using file and function name patterns like test_*.py and test_*.
Test classes must start with Test and should not have an __init__ method to be discovered.
Run pytest from the root folder containing your tests to ensure proper discovery.
Incorrect naming of files or functions is the most common reason tests are not found.
Use `pytest [path]` to specify a folder or file if you want to limit discovery.