0
0
PyTesttesting~10 mins

Test discovery rules in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks how pytest discovers test functions in a file based on naming conventions. It verifies that only functions starting with test_ are executed as tests.

Test Code - pytest
PyTest
import pytest

def test_addition():
    assert 1 + 1 == 2

def addition_test():
    assert 2 + 2 == 4

def test_subtraction():
    assert 5 - 3 == 2

class TestMathOperations:
    def test_multiplication(self):
        assert 3 * 3 == 9
    
    def multiplication_test(self):
        assert 4 * 4 == 16

if __name__ == "__main__":
    pytest.main(["-v"])
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test runner starts and scans the test file for test functions and classespytest identifies functions and classes matching discovery rulesFunctions starting with 'test_' and classes starting with 'Test' are selectedPASS
2pytest runs function 'test_addition'Function 'test_addition' executesassert 1 + 1 == 2PASS
3pytest skips function 'addition_test' because it does not start with 'test_'Function 'addition_test' is not executed-PASS
4pytest runs function 'test_subtraction'Function 'test_subtraction' executesassert 5 - 3 == 2PASS
5pytest finds class 'TestMathOperations' and runs its method 'test_multiplication'Method 'test_multiplication' executesassert 3 * 3 == 9PASS
6pytest skips method 'multiplication_test' because it does not start with 'test_'Method 'multiplication_test' is not executed-PASS
7Test run completes with all discovered tests passedpytest reports 3 tests run, 0 failed, 0 skipped-PASS
Failure Scenario
Failing Condition: A test function named incorrectly (not starting with 'test_') is expected to run but is skipped
Execution Trace Quiz - 3 Questions
Test your understanding
Which function will pytest run as a test?
Aaddition_test
Btest_addition
Cmultiplication_test
Dall functions
Key Result
pytest discovers tests by looking for functions and methods starting with 'test_' and classes starting with 'Test'. Naming tests correctly is essential for them to run.