0
0
PyTesttesting~5 mins

Test discovery rules in PyTest

Choose your learning style9 modes available
Introduction

Test discovery rules help pytest find your test files and test functions automatically. This saves time and avoids mistakes in running tests.

When you want pytest to find and run all your tests without listing them manually.
When organizing tests in multiple files and folders.
When adding new tests and you want them to run automatically.
When you want to avoid running non-test code by mistake.
When you want consistent test naming to keep your project clean.
Syntax
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.

Examples
This file and function follow discovery rules and will be found by pytest.
PyTest
# File: test_math.py

def test_add():
    assert 1 + 1 == 2
Class name starts with Test and method starts with test_, so pytest finds this test.
PyTest
# File: math_test.py

class TestMath:
    def test_subtract(self):
        assert 2 - 1 == 1
This file and function do not follow naming rules, so pytest will ignore them.
PyTest
# File: example.py

def add():
    return 1 + 1
Sample Program

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_.

PyTest
# 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
OutputSuccess
Important Notes

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.

Summary

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.