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 withTestand does not inherit fromunittest.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.