teluzia.Cloud Engineer · Day 32
CHAPTER 05 · PYTHON AUTOMATION

pytest fundamentals

4–5 hours including independent practice3 topics
LET’S MAKE THIS SIMPLE

What you’re learning today

Write tests around an observable function contract rather than mirroring every implementation line. You will test normal values, boundary values and invalid inputs using pytest in a virtual environment. A deliberate logic change should make a meaningful test fail and explain exactly which policy was violated. pytest discovers test files and test functions by naming conventions such as test_rules.py and test_threshold. Plain assert expressions produce informative comparisons when they fail. Run the suite with the intended interpreter using python -m pytest. Passing tests establish only the behaviors actually exercised, not universal correctness. Parametrization runs one behavior check over several explicit cases. Boundary values are especially useful for comparisons, ranges and empty collections. Cover below, at and above a threshold, then add invalid input only if the function defines an invalid-input contract. Avoid creating dozens of redundant cases that exercise no distinct behavior.

Think of it this way

Tests are independent measuring gauges: they check the promised result rather than congratulating the machine for moving its gears.

TOPIC 01 / 03Step by step

Discovery and assertions

pytest discovers test files and test functions by naming conventions such as test_rules.py and test_threshold. Plain assert expressions produce informative comparisons when they fail. Run the suite with the intended interpreter using python -m pytest. Passing tests establish only the behaviors actually exercised, not universal correctness. A test asserting classify(80)=="warning" directly checks the inclusive threshold contract; it should fail if the implementation accidentally changes from >=80 to >80 in the production function being exercised by that test. Contract-focused tests detect meaningful regressions and remain useful after internal refactoring, while interpreter-specific invocation helps ensure imports and dependencies come from the same environment as the application code under investigation today rather than an unrelated global installation. A test that repeats the exact implementation expression may preserve the same defect; derive expected outcomes from the stated behavior and select cases that would expose a plausible mistake rather than merely run the code without observing its result carefully.

WORKED EXAMPLE
A test asserting classify(80)=="warning" directly checks the inclusive threshold contract; it should fail if the implementation accidentally changes from >=80 to >80 in the production function being exercised by that test.
Why this matters

Contract-focused tests detect meaningful regressions and remain useful after internal refactoring, while interpreter-specific invocation helps ensure imports and dependencies come from the same environment as the application code under investigation today rather than an unrelated global installation.

A common trap

A test that repeats the exact implementation expression may preserve the same defect; derive expected outcomes from the stated behavior and select cases that would expose a plausible mistake rather than merely run the code without observing its result carefully.

Read all topics in this lesson

A complete reference to revisit alongside the guided steps above.

Discovery and assertions

pytest discovers test files and test functions by naming conventions such as test_rules.py and test_threshold. Plain assert expressions produce informative comparisons when they fail. Run the suite with the intended interpreter using python -m pytest. Passing tests establish only the behaviors actually exercised, not universal correctness. A test asserting classify(80)=="warning" directly checks the inclusive threshold contract; it should fail if the implementation accidentally changes from >=80 to >80 in the production function being exercised by that test. Contract-focused tests detect meaningful regressions and remain useful after internal refactoring, while interpreter-specific invocation helps ensure imports and dependencies come from the same environment as the application code under investigation today rather than an unrelated global installation. A test that repeats the exact implementation expression may preserve the same defect; derive expected outcomes from the stated behavior and select cases that would expose a plausible mistake rather than merely run the code without observing its result carefully.

WORKED EXAMPLE
A test asserting classify(80)=="warning" directly checks the inclusive threshold contract; it should fail if the implementation accidentally changes from >=80 to >80 in the production function being exercised by that test.

Why this matters

Contract-focused tests detect meaningful regressions and remain useful after internal refactoring, while interpreter-specific invocation helps ensure imports and dependencies come from the same environment as the application code under investigation today rather than an unrelated global installation.

A common trap

A test that repeats the exact implementation expression may preserve the same defect; derive expected outcomes from the stated behavior and select cases that would expose a plausible mistake rather than merely run the code without observing its result carefully.

Parametrization and boundaries

Parametrization runs one behavior check over several explicit cases. Boundary values are especially useful for comparisons, ranges and empty collections. Cover below, at and above a threshold, then add invalid input only if the function defines an invalid-input contract. Avoid creating dozens of redundant cases that exercise no distinct behavior. @pytest.mark.parametrize("value,expected",[(79,"normal"),(80,"warning"),(81,"warning")]) makes the policy boundary visible as three independently reported cases rather than hiding all cases in a long loop that provides less precise failure reporting. Small distinct cases maximize diagnostic value and make failure reports identify the violated condition quickly, which helps you repair actual logic rather than broadly rewriting correct code or adding arbitrary additional examples to make the suite look larger to its reader. Testing only a comfortable midpoint misses off-by-one defects; include exact boundaries and avoid calling a test comprehensive when required errors, empty inputs or state transitions have not been considered against the documented function contract.

WORKED EXAMPLE
@pytest.mark.parametrize("value,expected",[(79,"normal"),(80,"warning"),(81,"warning")]) makes the policy boundary visible as three independently reported cases rather than hiding all cases in a long loop that provides less precise failure reporting.

Why this matters

Small distinct cases maximize diagnostic value and make failure reports identify the violated condition quickly, which helps you repair actual logic rather than broadly rewriting correct code or adding arbitrary additional examples to make the suite look larger to its reader.

A common trap

Testing only a comfortable midpoint misses off-by-one defects; include exact boundaries and avoid calling a test comprehensive when required errors, empty inputs or state transitions have not been considered against the documented function contract.

Fixtures and exception checks

Fixtures provide reusable setup and cleanup through dependency injection. tmp_path gives each test an isolated temporary directory, making file tests independent. pytest.raises asserts an expected exception type. Test isolation means execution order should not matter; shared files or global mutable state can undermine that goal and create intermittent failures. with pytest.raises(ValueError): validate_percent(101) checks a declared error; a tmp_path fixture can hold a synthetic log without reading or overwriting any user’s real project data during the test run performed on their machine. Isolated resources and explicit error checks make failures reproducible and prevent a suite from accidentally modifying real data, while cleanup-aware fixtures are useful when later tests exercise temporary files or controlled services that must be released after execution ends. Depending on a previous test’s output creates order-sensitive failures; build required state in fixtures or the test itself and assert the specific exception instead of accepting any failure as proof that the intended validation behavior was correctly implemented.

WORKED EXAMPLE
with pytest.raises(ValueError): validate_percent(101) checks a declared error; a tmp_path fixture can hold a synthetic log without reading or overwriting any user’s real project data during the test run performed on their machine.

Why this matters

Isolated resources and explicit error checks make failures reproducible and prevent a suite from accidentally modifying real data, while cleanup-aware fixtures are useful when later tests exercise temporary files or controlled services that must be released after execution ends.

A common trap

Depending on a previous test’s output creates order-sensitive failures; build required state in fixtures or the test itself and assert the specific exception instead of accepting any failure as proof that the intended validation behavior was correctly implemented.

KEEP THESE WITH YOU

Today’s takeaways

Test contracts rather than syntax.

Select distinct boundary cases.

Isolate temporary state.

CLOSE THE LOOP

Ready to complete this day?

Verify the practical steps and pass the knowledge check (at least two thirds correct).

Lab steps verifiedKnowledge check passed