Sobes.tech
Junior — Middle

How does PyTest determine which test functions or cases to execute during testing?

sobes.tech AI

Answer from AI

PyTest automatically detects test functions and methods based on certain naming rules and structure. By default, it looks for:

  • Functions whose names start with test_.
  • Methods inside classes whose names start with test_, provided that the class also starts with Test and does not inherit from unittest.TestCase.
  • Files with names starting with test_ or ending with _test.py.

Thus, PyTest scans directories, finds such files, imports them, and runs all functions and methods that meet these criteria. This makes it easy to organize tests without explicitly registering them.

Example:

# test_example.py

def test_sum():
    assert sum([1, 2, 3]) == 6

class TestMath:
    def test_multiply(self):
        assert 2 * 3 == 6

When running pytest, these two tests will be discovered and executed.

How does PyTest determine which test functions or… - sobes.tech