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.

Illustration : écran de résultats de tests avec coches vertes et une croix rouge, bras robotisé inspectant des cartes sur un tapis roulant

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/ layout

  • test_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.

Exercises (12)

Exercise 1 — The command that runs pytest in verbose mode. Easy

Show the solution
pytest -v

Exercise 2 — A pytest fixture that returns an AgendaService pointing at tmp_path / "a.json". Intermediate

Show the solution
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

Show the solution
with pytest.raises(ValueError):
    svc.add_event(title=" ", ...)

Exercise 4 — Why monkeypatch the current time in a deterministic test? Intermediate

Show the solution
# Freeze datetime.now() to avoid flaky tests.

Exercise 5 — Parametrize three cases for from_dict (ok, missing key, invalid date). Hard

Show the solution
@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

Show the solution
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

Show the solution
# 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

Show the solution
assert {e.id for e in events} == expected_ids

Exercise 9 — xfail for a known bug — when do you use it? Intermediate

Show the solution
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

Show the solution
Fixtures and hooks shared by every test module.

Exercise 11 — Mock save_events to check that you do not save when validation fails. Hard

Show the solution
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

Show the solution
pytest ; ruff check ; optionally black --check

Next

CLI with argparse

Amazon

Check today’s price on Amazon

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.