Test Suite for an Earlier Project
A comprehensive pytest test suite for a small, self-contained TaskManager module — an add/complete/overdue-check workflow, the kind of class you might have built back in Chapter 11's OOP chapter. The project itself is the test suite: fixtures for clean per-test state, happy-path and edge-case coverage, and a mocked external dependency so a test never actually sends a real notification.
Example run
$ python3 -m pytest solution.py -v
============================= test session starts ==============================
collected 13 items
solution.py::test_add_task_returns_task_with_given_title PASSED [ 7%]
solution.py::test_add_task_appends_to_manager_tasks_list PASSED [ 15%]
solution.py::test_add_task_rejects_empty_title PASSED [ 23%]
solution.py::test_add_task_rejects_whitespace_only_title PASSED [ 30%]
solution.py::test_complete_task_marks_matching_task_done PASSED [ 38%]
solution.py::test_complete_task_returns_false_when_no_match PASSED [ 46%]
solution.py::test_complete_task_only_affects_first_pending_match PASSED [ 53%]
solution.py::test_get_overdue_tasks_returns_only_past_due_incomplete_tasks PASSED [ 61%]
solution.py::test_get_overdue_tasks_excludes_completed_tasks_even_if_past_due PASSED [ 69%]
solution.py::test_get_overdue_tasks_empty_when_no_tasks_added PASSED [ 76%]
solution.py::test_notify_overdue_calls_notifier_send_once_per_overdue_task PASSED [ 84%]
solution.py::test_notify_overdue_does_not_count_failed_sends PASSED [ 92%]
solution.py::test_notify_overdue_never_touches_the_real_notification_sender PASSED [100%]
============================== 13 passed in 0.05s ==============================
starter.py below into an empty folder. You'll need pytest installed (pip install pytest) — unlike earlier chapters, this project isn't standard-library-only, since pytest itself is the tool being taught. Then run python3 -m pytest starter.py -v.
The code under test: TaskManager
This part is already finished for you — it's the "earlier project," not what you're building today. Read it closely, since every test you write targets it directly.
class TaskManager:
def __init__(self, notifier=None):
self.tasks = []
# Dependency injection: a real NotificationSender by default,
# but a caller (or a test) can swap in something else entirely.
self.notifier = notifier if notifier is not None else NotificationSender()
def add_task(self, title, due_date):
if not title or not title.strip():
raise ValueError("Task title cannot be empty.")
task = Task(title, due_date)
self.tasks.append(task)
return task
def complete_task(self, title):
for task in self.tasks:
if task.title == title and not task.completed:
task.completed = True
return True
return False
def get_overdue_tasks(self, now=None):
return [task for task in self.tasks if task.is_overdue(now)]
def notify_overdue(self, recipient, now=None):
overdue = self.get_overdue_tasks(now)
sent = 0
for task in overdue:
if self.notifier.send(task.title, recipient):
sent += 1
return sent
Two design choices make this class genuinely testable, worth noticing before you write a single test:
- The notifier is injected, not hardcoded.
TaskManager(notifier=mock_notifier)swaps in a test double without touchingTaskManager's code at all. - Overdue checks accept an explicit
now. Every method that cares about "is this overdue" takesnowas a parameter instead of always callingdatetime.now()internally — so a test can hand it a fixed, known moment in time instead of depending on when the test happens to actually run.
Writing the mocked test
This is the one worth studying closest — it's the test that proves a notification was requested without ever actually sending one.
def test_notify_overdue_calls_notifier_send_once_per_overdue_task(fixed_now):
mock_notifier = MagicMock()
mock_notifier.send.return_value = True
manager = TaskManager(notifier=mock_notifier)
manager.add_task("Late thing", fixed_now - timedelta(days=1))
manager.add_task("Also late", fixed_now - timedelta(days=2))
manager.add_task("Not due yet", fixed_now + timedelta(days=1))
sent_count = manager.notify_overdue("dev@example.com", now=fixed_now)
assert sent_count == 2
assert mock_notifier.send.call_count == 2
mock_notifier.send.assert_any_call("Late thing", "dev@example.com")
mock_notifier.send.assert_any_call("Also late", "dev@example.com")
Thought process: a mock stands in for the real dependency, so the test should assert on the mock's call history (call_count, assert_any_call) rather than on any real side effect — if a test can't tell the difference between "sent successfully" and "was asked to send," it isn't actually verifying the right thing. Injecting the notifier through the constructor (rather than patching a module-level import) keeps the test simple and keeps TaskManager's own code free of any test-only branching.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a pytest test function for TaskManager.notify_overdue(recipient, now=None). TaskManager accepts a `notifier` object in its constructor with a .send(task_title, recipient) method that returns True/False. In the test: create a unittest.mock.MagicMock() as the notifier, set its .send.return_value = True, inject it via TaskManager(notifier=mock_notifier), add two tasks with due dates before a fixed `now` datetime and one task due after it, call notify_overdue("dev@example.com", now=fixed_now), then assert the returned count equals 2, mock_notifier.send.call_count equals 2, and use mock_notifier.send.assert_any_call() to confirm it was called with each overdue task's exact title and the recipient string. Never let this test call a real notification service.The pieces
Task/TaskManager/NotificationSender: the finished code under test.managerfixture: a fresh, emptyTaskManagerfor every test.fixed_nowfixture: a fixeddatetimeso overdue checks never depend on real wall-clock time.- 13 test functions: happy-path and edge-case coverage for
add_task(),complete_task(), andget_overdue_tasks(), plus 3 tests exercising the mockednotify_overdue().
Ideas to make it your own
- Point this same pattern at one of your own earlier chapter projects instead of the built-in
TaskManagerexample. - Add a
@pytest.mark.parametrizetest that checks several empty/whitespace/Nonetitles all raiseValueErrorin one test function. - Add a test for what happens when
NotificationSender.send()raises an exception instead of returningFalse.
Why this project matters
A test suite is what lets you change code later without re-checking everything by hand — and mocking is what makes that practical the moment your code talks to anything external (an API, a database, the clock, a notification service). Writing tests against real code, not a toy example, is what makes the difference between "I know the syntax" and "I can actually protect a real project."
More project ideas
From Chapter 7 onward, you get a genuine choice of what to build. The Test Suite above is fully built out with a starter and reference solution — the four ideas below are not. Each is a real, grounded use case solvable with only what's been taught through Chapter 27. No starter or solution files are provided on purpose — building one of these unassisted is the point.
1 A Test Suite for a REST API Client
Problem: A small API client class makes real HTTP requests — but a test suite should never make a real network call.
What it should do: Write pytest tests that mock the HTTP layer and assert the client parses a mocked JSON response correctly, handles a mocked error status code, and passes the right URL/parameters to the mocked call.
Suggested approach: Inject the client's HTTP dependency the same way TaskManager injects its notifier, then unittest.mock.patch it in tests — never let a test actually reach the network.
2 A Test Suite for a CSV Data-Cleaning Pipeline
Problem: A CSV-cleaning function (strip whitespace, drop blank rows, convert types, flag malformed rows) needs confidence it handles messy real-world data correctly.
What it should do: Write pytest tests using small in-memory CSV strings covering a clean row, a row with extra whitespace, a blank row, a bad numeric field, and an entirely empty file.
Suggested approach: Reuse Chapter 13's CSV-reading logic as the function under test; io.StringIO feeds in fake CSV content without touching the real filesystem.
3 Tests That Mock the Clock for a Subscription-Expiry Checker
Problem: An is_subscription_expired(subscription, now=None)-style function needs testing at multiple points in time without depending on today's real date.
What it should do: Write pytest tests that pass a fixed datetime for signup day, the day before expiry, the exact expiry moment, and well after expiry — asserting the correct True/False at each boundary.
Suggested approach: A @pytest.fixture returning a fixed datetime, plus @pytest.mark.parametrize to run the same test body against several fixed "now" values.
4 Parametrized Tests for a Validation Function
Problem: A single validation function has many valid and invalid input cases worth checking, and one near-identical test per case gets repetitive fast.
What it should do: Write ONE pytest test function using @pytest.mark.parametrize that runs the same assertion against 8-10+ (input, expected_result) pairs, including boundary cases.
Suggested approach: @pytest.mark.parametrize("text,expected", [...]) above a test function — pytest runs and reports it once per tuple, each as its own named test result.