0
0
PytestHow-ToBeginner ยท 3 min read

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_*.py or *_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.py instead of test_sample.py)
  • Test functions not prefixed with test_
  • Test classes not starting with Test or 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

PatternDescription
test_*.py or *_test.pyFile names pytest looks for
test_*Function names pytest recognizes as tests
Test*Class names pytest treats as containers for tests
No __init__ in test classesTest classes should not have __init__ methods
Run `pytest` in root folderStart 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.