Phase 1 — Foundations · Lesson 10 · 20 XP
Testing with pytest
A pytest test is just a function named test_something that asserts things. Run the whole suite with pytest. No test framework boilerplate, no classes required — plain functions and assert statements are enough for almost everything.
import pytest
@pytest.fixture
def sample_todos():
return [{"title": "milk", "done": False}]
@pytest.mark.parametrize("n,expected", [(2, 4), (3, 9), (5, 25)])
def test_square(n, expected):
assert n * n == expectedA fixture is shared setup that pytest injects into any test that names it as a parameter — no copy-pasted setup code at the top of every test, and pytest handles teardown too if the fixture needs it. @pytest.mark.parametrize runs the same test body against a list of input/expected pairs, so five similar tests become one.
Exercise
Write pytest tests for your Lesson 1-3 scripts (the log parser, the CSV summarizer): a fixture providing sample data, and parametrize covering edge cases like an empty file and a malformed line.
Check yourself
1. What problem does a fixture solve compared to calling a setup function manually at the top of every test?
2. Why is parametrize better than five nearly-identical test functions with different hardcoded inputs?
Project: concurrent fetcher with retries, timeouts, validation
Answer the check-yourself questions to unlock this