Tests and finish
Last updated
The last lesson makes the library system something you can trust and hand to someone else. You'll write a pytest suite with fixtures that build a fresh library for every test, use the clock from C.4 to set “today”, type into the menu from a test, break a rule on purpose to watch a test catch it, and finish with a README, a tidy-up with ruff, and a last run-through.
By the end of this lesson you can
- Share set-up between tests with
pytestfixtures inconftest.py - Test code that depends on today's date by passing in a fixed clock
- Read a failing test's report, and use a test to find a broken rule
- Finish a project: a README, clean code, and every check passing
Fixtures: a fresh library for every test
Most tests of the library need the same start: a library, a fixed date, a few items and members. Writing that at the top of every test would be dozens of copies. Lesson 2.10 tested plain functions. Pytest's answer for set-up is the fixture, a function marked @pytest.fixture that makes something a test needs.
Fixtures in a file called conftest.py, in the tests folder, are shared by every test file there, with no import. Here's the reference's:
tests/conftest.py"""Fixtures: a fixed date and a small library, made fresh for every test.""" from datetime import date import pytest from library.clock import FixedClock from library.desk import Library from library.items import DVD, Book, ReferenceBook from library.members import STUDENT, Member @pytest.fixture def clock(): return FixedClock(date(2026, 3, 2)) @pytest.fixture def library(clock): library = Library(clock) library.catalogue.add(Book("b1", "Dune", 1965, "Frank Herbert", "9780441013593")) library.catalogue.add(Book("b2", "Emma", 1815, "Jane Austen", "9780141439587")) library.catalogue.add( ReferenceBook("r1", "Atlas of the World", 2020, "Map Society", "9780008320300") ) library.catalogue.add(DVD("d1", "Rivers of Ice", 2019, 52)) library.join(Member("sam", "Sam Okafor")) library.join(Member("ana", "Ana Lima", STUDENT)) return library
A test asks for a fixture by naming it as a parameter, and pytest calls the fixture and passes in what it returns:
tests/test_desk.py, lines 9–19def test_lend_sets_the_due_date(library): loan = library.lend("b1", "sam") assert loan.due_on == date(2026, 3, 23) assert not library.is_available(library.catalogue.get("b1")) def test_an_item_is_never_lent_twice(library): library.lend("b1", "sam") with pytest.raises(NotAvailable): library.lend("b1", "ana") assert len(library.open_loans()) == 1
Three things make fixtures more than shared code:
- Every test gets a fresh one. A loan made in one test can't leak into the next, so tests pass or fail on their own, in any order.
- Fixtures can ask for fixtures.
libraryasks forclock, and when a test asks for both, astest_give_back_on_time_costs_nothingdoes, it gets the same clock the library holds. So it can move the date on. - pytest has fixtures of its own.
tmp_pathis a new empty folder (C.6's storage tests save there), andcapsyscaptures what was printed (step 4).
The page can't run pytest, but it can run what a fixture does: build the library in a function, and call it at the start of each test. Press Run:
Tests that set the date
Here C.4's decision pays off. A fine depends on today's date. With date.today() inside Library, a test of a late fine could only pass on the right day. Because the library is handed a clock, the test hands it a FixedClock, and clock.advance(11) is 11 days later, on any day you run it:
tests/test_desk.py, lines 43–54def test_give_back_on_time_costs_nothing(library, clock): library.lend("b1", "sam") clock.advance(21) assert library.give_back("b1") == 0 assert library.is_available(library.catalogue.get("b1")) def test_give_back_late_costs_the_policy_fine(library, clock): library.lend("d1", "ana") clock.advance(7 + 4) assert library.give_back("d1") == 40
This is dependency injection at work: anything a class would otherwise reach out for (the date, a file, the keyboard) is passed in, so a test can pass in a stand-in. The library got clock, the menu got storage and ask, and every one of them has a test stand-in: FixedClock, MemoryStorage and a function that "types".
A test is an assert. If it's false, Python raises AssertionError, and the message after the comma says why. The wrong way: this test expects the wrong fine. Press Run:
AssertionError: expected 50 cents, got 40. Ana is a student, so 4 days late is 4 × 10 = 40. Here the test is wrong, not the code. A failing test means the two disagree, and you have to decide which one is right. (The test reaches into library._clock to move the date, which lesson 4.2 says to avoid. That's why the fixtures in step 1 keep their own clock to move instead.)
Break a rule, watch a test catch it
The most important rule from C.4: a refused loan changes nothing. Break it on purpose on your computer. In desk.py, move the limit check in lend() below the line that saves the loan:
def lend(self, item_id: str, member_id: str) -> Loan: item = self.catalogue.get(item_id) member = self.member(member_id) ... today = self.today() loan = Loan(item_id, member_id, today, today + timedelta(days=item.loan_days())) self._loans.append(loan) member.check_can_borrow(len(self.loans_of(member_id)) - 1) # moved: now too late return loan
Run pytest:
(.venv) $ pytest =================== test session starts =================== collected 46 items tests/test_catalogue.py ...... [ 13%] tests/test_cli.py ... [ 19%] tests/test_desk.py ....F.... [ 39%] ... ========================= FAILURES ======================== ___________ test_a_refused_loan_changes_nothing ___________ def test_a_refused_loan_changes_nothing(library): ... with pytest.raises(LimitReached): library.lend("b3", "ana") > assert library.is_available(library.catalogue.get("b3")) E AssertionError: assert False tests/test_desk.py:40: AssertionError ================ 1 failed, 45 passed in 0.31s =============
Read it from the bottom, like a traceback: 1 failed, 45 passed. Above that, the failure: test_a_refused_loan_changes_nothing, line 40 of tests/test_desk.py, the line marked >. The LimitReached was still raised, so the line before passed. But the loan had already been saved, so Middlemarch is out. E lines show what the values were: assert False.
The bug was a few lines moved. A person trying the menu would likely never notice, until a book was "on loan" to someone who'd been told no. Put the check back, run pytest, and all 46 pass.
Testing the menu
The menu reads from input() and prints. Both can be handled in a test, because C.7 made ask something you can pass in:
tests/test_cli.pyfrom library.cli import Menu, money from library.storage import MemoryStorage def typed(*lines): """Stands in for input(): hands back each line in turn.""" answers = iter(lines) return lambda prompt="": next(answers) def test_money(): assert money(125) == "$1.25" and money(5) == "$0.05" def test_refusals_are_plain_words(library, capsys): Menu(library, MemoryStorage(), typed("lend", "r1", "sam", "quit")).run() out = capsys.readouterr().out assert "Sorry: Atlas of the World can't be borrowed." in out assert "Traceback" not in out def test_quit_saves(library, clock): storage = MemoryStorage() Menu(library, storage, typed("lend", "b1", "sam", "quit")).run() assert len(storage.load(clock).open_loans()) == 1
typed() makes a stand-in for input: a function that hands back each line in turn, ignoring the prompt. capsys collects everything printed while the test ran, and readouterr().out gives it as one string. So test_refusals_are_plain_words types a session and checks the person sees a Sorry line and never a traceback. test_quit_saves checks the loan made it into storage.
Finish it
Three last jobs before the library system is done.
A README. README.md, in the project folder, is the first thing anyone opening the project reads, including you in six months. Say what it is, how to set it up, how to run it and how to check it. Here's the reference's:
README.md# Library A simple library management system for the command line. It keeps a catalogue of books, DVDs and magazines, registers members, lends items and takes them back with due dates, charges fines for late returns, searches the catalogue, and saves everything to `library.json` between runs. This is the reference version of the Simple Python capstone. ## Set up Needs Python 3.12 or newer. ``` python -m venv .venv .venv\Scripts\activate # on macOS or Linux: source .venv/bin/activate python -m pip install pytest ruff ``` ## Run it ``` python -m library ``` Type `help` for the commands. The first run starts with a small sample stock. ## Check it ``` pytest ruff check ruff format --check ``` ## How it's built | Module | What it holds | |---|---| | `items.py` | `LibraryItem`, an abstract dataclass, and `Book`, `ReferenceBook`, `DVD` and `Magazine` | | `members.py` | `Member`, and the `BorrowingPolicy` each member has | | `loans.py` | `Loan`, a frozen dataclass | | `errors.py` | `LibraryError` and its children | | `catalogue.py` | `Catalogue`, every item by id, with search | | `clock.py` | Where "today" comes from: `SystemClock`, or `FixedClock` in tests | | `desk.py` | `Library`: lending and taking back, with every rule | | `storage.py` | `JsonStorage` and `MemoryStorage`, behind the `Storage` protocol | | `reports.py` | Overdue loans, most borrowed items, a member's history | | `cli.py` | The menu | | `sample.py` | The starting stock | ## Windows (optional) `library_gui/` puts a window in front of the same library, for the course's two optional modules. `presenter.py` sits between any window and the library, and has its own tests. The windows are thin: ``` python -m library_gui.tk_app # tkinter: nothing to install python -m pip install customtkinter python -m library_gui.ctk_app # CustomTkinter 6 python -m pip install "flet[all]" python -m library_gui.flet_app # Flet 1.1 ``` All three were checked by hand on Windows 11 (CustomTkinter 6.0.0, Flet 1.1.4). The course's automatic checks don't install packages, so they test the presenter but don't open the windows.
Tidy and check. Run ruff format to lay out every file the same way, ruff check for likely mistakes, and pytest for the rules. All three should pass, every time, before you call a change finished:
(.venv) $ ruff format 21 files left unchanged (.venv) $ ruff check All checks passed! (.venv) $ pytest =================== test session starts =================== collected 46 items tests/test_catalogue.py ...... [ 13%] tests/test_cli.py ... [ 19%] tests/test_desk.py ......... [ 39%] tests/test_items.py ............ [ 65%] tests/test_members.py ........ [ 82%] tests/test_reports.py .... [ 91%] tests/test_storage.py .... [100%] =================== 46 passed in 0.28s ====================
A last run-through. Delete library.json, so it starts again with the sample stock. Run python -m library and try every command: find something, lend it, lend it again (refused), lend a reference book (refused), add a DVD, join a member, return a book, then quit. Run it again and check it all came back. Then move the clock on with your computer's date, or with a FixedClock in a small script, and look at overdue.
Where next. Some changes to try, each in a few classes you already know:
- Reservations.
library.reserve(item_id, member_id), andlend()refusing anyone else while a reservation is waiting. - Renewals. Lend an item again to the same member, as a new
Loanthat starts when the old one ends. - A window. Python's own
tkintercan put buttons and lists in front of the sameLibraryobject. Nothing indesk.pyneeds to change, which is the best test of how well it's built.
Check what you learned
That's the capstone done, and with it Simple Python. You started with a one-line program and finished with one of a dozen modules, built on the four ideas of object-oriented programming, with a test for every rule. Everything in it is ordinary Python, the same as in programs much bigger than this one.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.