Skip to content

Module 20 · Building Real Python Applications — topic 10 of 13

Application testing

Testing a whole application: unit tests for the service layer, testing command-line output, testing persistence with temporary folders, injecting fake clocks and collaborators, and deciding what to test at each level.

Beginner 12 min read·Lesson 303 of 306 in Python Programming

Learning objectives

  • Unit-test the service layer
  • Test command-line output and persistence
  • Use fakes and injected dependencies to make tests repeatable

Definition

Application testing combines unit tests of individual classes and functions with tests of larger pieces — the command loop, storage, the full flow — using temporary files and fake collaborators so tests are fast and repeatable.

Introduction

Unit tests on small functions are a start. A real application also needs confidence that commands print the right thing and data really is saved.

Why it matters

Testing at several levels catches both small logic bugs and integration problems between components.

Detailed explanation

Unit tests check logic classes and functions with no files or input involved — they are fast and should be the majority.

Integration tests check components together: the service with real file storage in a temporary folder.

End-to-end tests drive the application like a user — feeding commands and checking output.

Capture printed output with contextlib.redirect_stdout (or pytest's capsys) and compare it with the expected lines.

Use tempfile.TemporaryDirectory (or pytest's tmp_path) so tests never touch real data and clean up after themselves.

Inject things that vary — the current date, random numbers, network calls — so tests can supply fixed values.

A smoke test runs the main flow once to confirm nothing is fundamentally broken; run it before every demo.

Write a test for every bug you fix, at the lowest level that reproduces it.

Syntax

Python
import io
from contextlib import redirect_stdout
buf = io.StringIO()
with redirect_stdout(buf):
run(["add 250", "report"])
assert buf.getvalue().splitlines() == ["total 250.00", ...]
  • Mostly unit tests.
  • Capture output for CLI tests.
  • Temporary folders and fakes.

Code examples

Testing the service layer

Python
import io
import unittest
class ExpenseBook:
def __init__(self):
self.items = []
def add(self, amount, category):
if amount <= 0:
raise ValueError("amount must be positive")
self.items.append((amount, category))
def total(self, category=None):
return sum(a for a, c in self.items if category in (None, c))
class TestExpenseBook(unittest.TestCase):
def setUp(self):
self.book = ExpenseBook()
def test_totals(self):
self.book.add(250, "food")
self.book.add(40, "travel")
self.assertEqual(self.book.total(), 290)
self.assertEqual(self.book.total("food"), 250)
def test_rejects_non_positive(self):
with self.assertRaises(ValueError):
self.book.add(0, "food")
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestExpenseBook)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun, result.wasSuccessful())
Output
2 True

Testing command-line output

Python
import io
from contextlib import redirect_stdout
def run(commands):
total = 0
for c in commands:
if c.startswith("add "):
total += float(c[4:])
print(f"total {total:.2f}")
else:
print("unknown")
buf = io.StringIO()
with redirect_stdout(buf):
run(["add 250", "add 40.5", "oops"])
assert buf.getvalue().splitlines() == ["total 250.00", "total 290.50", "unknown"]
print("CLI output test passed")
Output
CLI output test passed

More examples

Persistence with a fake clock

Python
import json
import tempfile
from datetime import date
from pathlib import Path
class Diary:
def __init__(self, path, today=date.today):
self.path = Path(path)
self.today = today
def write(self, text):
entries = json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else []
entries.append({"date": self.today().isoformat(), "text": text})
self.path.write_text(json.dumps(entries), encoding="utf-8")
return len(entries)
def test_diary_persists_with_fixed_dates():
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "diary.json"
assert Diary(path, today=lambda: date(2026, 11, 27)).write("started project") == 1
assert Diary(path, today=lambda: date(2026, 11, 28)).write("added tests") == 2
saved = json.loads(path.read_text(encoding="utf-8"))
assert [e["date"] for e in saved] == ["2026-11-27", "2026-11-28"]
test_diary_persists_with_fixed_dates()
print("persistence test passed with a fake clock")
Output
persistence test passed with a fake clock

Step-by-step explanation

  • Diary takes today as a parameter, defaulting to the real date.today.
  • The test supplies fixed dates, so its expected output never changes.
  • A temporary directory keeps the test away from real files and is deleted automatically.

Expected output

Running “Persistence with a fake clock” prints exactly:

TextOutput
persistence test passed with a fake clock

Practical applications

  • CI pipelines running unit, integration and end-to-end tests.
  • Testing time-dependent features such as reminders and due dates.

Best practices

  • Write mostly fast unit tests.
  • Use temporary folders for storage tests.
  • Inject clocks and other changing inputs.

Common mistakes

Tests that use real data files

Avoid

store = ExpenseFile("expenses.json") # the user's real file

Prefer

with tempfile.TemporaryDirectory() as tmp:
store = ExpenseFile(Path(tmp) / "expenses.json")

Tests could overwrite real data and depend on its contents.

Tests depending on today's date

Avoid

assert entry["date"] == "2026-11-27" # fails tomorrow

Prefer

Inject a fake clock and assert against its value.

Tests must give the same result every day.

Important notes

  • pytest's tmp_path, capsys and monkeypatch fixtures make all of these techniques shorter.

Key takeaways

  • Test logic, components and the full flow.
  • Capture output and use temporary folders.
  • Inject fakes for repeatability.

Try it yourself

  1. 1
    Write an end-to-end test that adds three expenses through the command loop and checks the report output.
  2. 2
    Inject a fake clock into a reminder feature and test that overdue items are detected.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “Building Real Python Applications” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat does MVP stand for when planning an application?
  • AdvancedWhere should input validation ideally happen?
  • AdvancedWhat is printed?
Practise this module