CLI planner project (4/6): tests with pytest
tmp_path fixtures, service tests, storage mocks, and coverage of errors such as an empty title or corrupt JSON. Twelve pytest exercises.
Getting started
Home Assistant
Buying
tmp_path fixtures, service tests, storage mocks, and coverage of errors such as an empty title or corrupt JSON. Twelve pytest exercises.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Tests isolate AgendaService with a temporary file per test (tmp_path, provided by pytest) or an in-memory fake storage. Aim for one assertion per behavior: a successful add, an empty list, deleting an unknown ID, invalid JSON.
Previous chapter: domain model.
tests/ layouttest_storage.py: round trip, missing file.test_service.py: business rules with controlled data.test_cli.py (optional): click’s CliRunner if you move to click later. With argparse, use subprocess, or refactor main() so you can inject dependencies.Exercise 1 — The command that runs pytest in verbose mode. Easy
pytest -v
Exercise 2 — A pytest fixture that returns an AgendaService pointing at tmp_path / "a.json". Intermediate
import pytest
@pytest.fixture def svc(tmp_path): return AgendaService(tmp_path / “a.json”)
Exercise 3 — A test with pytest.raises(ValueError) on an empty title. Easy
with pytest.raises(ValueError):
svc.add_event(title=" ", ...)
Exercise 4 — Why monkeypatch the current time in a deterministic test? Intermediate
# Freeze datetime.now() to avoid flaky tests.
Exercise 5 — Parametrize three cases for from_dict (ok, missing key, invalid date). Hard
@pytest.mark.parametrize("raw,exc", [(good, None), (bad, KeyError)])
def test_from_dict(raw, exc): ...
Exercise 6 — coverage run -m pytest — what is it for? Easy
Measure which lines ran; spot branches that were never tested.
Exercise 7 — An integration test: CLI add then list with subprocess and tmp_path. Hard
# subprocess.run([sys.executable, "-m", "agenda_cli", "add", ...], env={**os.environ, "AGENDA_FILE": str(p)})
Exercise 8 — Avoid order-dependent tests on UUIDs if you compare sets of IDs. Intermediate
assert {e.id for e in events} == expected_ids
Exercise 9 — xfail for a known bug — when do you use it? Intermediate
Document an expected failure until it is fixed; do not hide real bugs.
Exercise 10 — conftest.py: its role at the root of the tests. Easy
Fixtures and hooks shared by every test module.
Exercise 11 — Mock save_events to check that you do not save when validation fails. Hard
def save_events(*a, **k):
raise AssertionError("should not save")
# with mock.patch.object(storage, "save_events", save_events)
Exercise 12 — A checklist before a PR: green tests, lint, format. Easy
pytest ; ruff check ; optionally black --check
Check today’s price on Amazon
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).