Fixtures, Parametrization, and Mocks
Scenario: Ten tests need the same temporary config, and a real network call would make them slow and unreliable.
New words, in plain English
- Fixture - reusable test setup and cleanup
- Parametrization - running one test logic against several inputs
- Mock - a controlled replacement for an external collaborator
- Integration test - a test exercising several real parts together
Pytest fixtures supply resources; parametrization reduces repeated cases; unittest.mock replaces boundaries. Mock what you own at the point it is looked up, and keep integration tests for real wiring.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
import pytest
@pytest.mark.parametrize("raw,want", [("1", 1), ("02", 2)])
def test_parse(raw, want):
assert int(raw) == want
Tip: Too many mocks can make tests pass while the real system is broken.
Goal: Practice this idea in the py-pytest-suite challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.