Phase 19 of 25 · Topic 19.1

PyTest Fundamentals & Assertion Rewriting

1Concept

PyTest uses standard Python `assert` statements instead of boilerplate `self.assertEqual()`. Its Assertion Rewriting feature intercepts assertions at bytecode load time, providing clear diffs showing exact values upon failure.

2Architecture Diagram

assert computed_user == expected_user ---> PyTest prints exact dict difference on failure!

3Code Example

Python 3.12
# PyTest test case pattern
def calculate_tax(salary: float, rate: float) -> float:
    return round(salary * rate, 2)

# Test function
def test_calculate_tax():
    result = calculate_tax(100_000.0, 0.25)
    assert result == 25_000.0, f"Expected 25000.0, got {result}"

test_calculate_tax()
print("PyTest Assertion Passed: test_calculate_tax verified successfully!")

4Expected Output

PyTest Assertion Passed: test_calculate_tax verified successfully!

5Key Takeaways

  • Test files should start with `test_*.py`; test functions should start with `test_*()`.
  • Use `pytest.raises(ValueError)` to verify that expected exceptions are thrown.
  • `pytest -v -s` shows verbose output and prints stdout.