How pytest Finds Tests
One of pytest's best features is automatic test discovery. You do not need to register tests manually. pytest searches your project for files, classes, and functions that match specific naming conventions.
File Discovery
By default, pytest collects test files that match these patterns:
test_*.py # Files starting with test_
*_test.py # Files ending with _test
Any Python file with one of these names will be scanned for test functions and classes.
Function Discovery
Inside test files, pytest looks for functions and methods that start with test_:
# This WILL be collected as a test
def test_login():
assert True
# This will NOT be collected
def login():
assert True
# Helper functions should not start with test_
def helper_function():
return 42
Class Discovery
pytest also collects test classes. Classes must start with Test and contain methods that start with test_:
class TestCalculator: # Collected
def test_add(self):
assert 1 + 1 == 2
def helper(self): # NOT collected (no test_ prefix)
pass
class calculator: # NOT collected (does not start with Test)
def test_add(self):
assert 1 + 1 == 2
Customizing Discovery
You can override the default patterns in pytest.ini:
[pytest]
python_files = test_*.py check_*.py
python_classes = Test* Check*
python_functions = test_ check_
This tells pytest to also look for files named check_*.py and functions starting with check_.