Test discovery rules help pytest find your test files and test functions automatically. This saves time and avoids mistakes in running tests.
Test discovery rules in PyTest
pytest discovers tests by looking for: - Files named test_*.py or *_test.py - Functions named test_* inside those files - Classes named Test* without an __init__ method - Methods inside those classes named test_*
Test files must be named with test_ prefix or _test suffix.
Test functions and methods must start with test_ to be discovered.
# File: test_math.py def test_add(): assert 1 + 1 == 2
Test and method starts with test_, so pytest finds this test.# File: math_test.py class TestMath: def test_subtract(self): assert 2 - 1 == 1
# File: example.py def add(): return 1 + 1
This file has two tests that pytest will find and run. The method not_a_test is ignored because it does not start with test_.
# test_sample.py def test_true_is_true(): assert True is True class TestNumbers: def test_one_plus_one(self): assert 1 + 1 == 2 def not_a_test(self): assert False # This will not run # Run pytest in terminal with: pytest
pytest ignores files and functions that do not follow the naming rules.
You can customize discovery rules with command line options or configuration files if needed.
Keeping consistent naming helps pytest find tests quickly and avoids confusion.
pytest finds tests by looking for files, classes, and functions with specific name patterns.
Test files: start or end with test, test functions and methods: start with test_.
Following these rules means pytest runs your tests automatically without extra setup.