Learn Python · lesson 47 of 60 · about 9 minutes
Capstone: Errors and Testing
Make the tracker robust: back Sam's habits up to a file, read them back safely, and test the core logic with assert.
What you'll learn
- Save data to a file and load it back
- Handle missing or broken files
- Write simple tests with assert
A backup Sam can trust
Sam's ticks only last as long as the assistant is running, so the tracker backs them up to habits.json. JSON can't hold a set, so each habit's days are saved as a sorted list. Then the assistant proves the backup works: it prints the file, reads it back into sets, and uses assert to check it matches the habits exactly. While it's there, three more asserts test streak(): no days, two days in a row, and two days with a gap. If every check passes, it says so.
Saving with JSON
The json module turns dictionaries and lists into text and back. Sets aren't supported, so convert them to sorted lists when saving and back to sets when loading.
If the file is missing the first time, start with an empty tracker instead of crashing.
save() and load()
import json
def save(habits, path):
data = {name: sorted(days) for name, days in habits.items()}
with open(path, "w") as f:
json.dump(data, f)
def load(path):
try:
with open(path) as f:
data = json.load(f)
except FileNotFoundError:
return {}
return {name: set(days) for name, days in data.items()}
print(load("habits.json"))
save({"read": {"2026-05-02", "2026-05-01"}}, "habits.json")
print(open("habits.json").read())
print(sorted(load("habits.json")["read"]))Output
{}
{"read": ["2026-05-01", "2026-05-02"]}
['2026-05-01', '2026-05-02']Testing with assert
assert condition does nothing if the condition is True and raises AssertionError if it's False. A handful of asserts proves your core logic still works after every change.
Tests for streak()
from datetime import date, timedelta
def streak(done, today):
count, day = 0, today
while day.isoformat() in done:
count += 1
day -= timedelta(days=1)
return count
today = date(2026, 5, 3)
assert streak(set(), today) == 0
assert streak({"2026-05-03"}, today) == 1
assert streak({"2026-05-02", "2026-05-03"}, today) == 2
assert streak({"2026-05-01"}, today) == 0
print("All tests passed")Output
All tests passedNow try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.