Testing Your Code
Every chapter so far ended the same way: run the code, look at the output, decide by eye whether it's right. That works for a chapter exercise. It falls apart on a real codebase — nobody re-reads every function's output by eye before every change, forever. This chapter is about writing code that checks your code, automatically, every time, so a mistake gets caught by a failing test in seconds instead of by a user in production.
How to read this chapter
- Sub-topic 1 covers why testing matters — what a test actually verifies, and what breaks without one.
- Sub-topic 2 covers
unittest, Python's built-in testing framework —TestCase, assertions, and running tests. - Sub-topic 3 covers
pytest, the more common real-world choice — plainassert, less boilerplate, better output. - Sub-topic 4 covers fixtures and setup/teardown — sharing setup across tests without letting tests depend on each other.
- Sub-topic 5 covers mocking — testing code that talks to an API, a database, or the clock, without actually calling any of them.
- Sub-topic 6 covers test coverage and what a genuinely good test looks like — the AAA pattern, edge cases, and what NOT to test.
- A note on scope: this chapter's new material is
unittest,pytest, andunittest.mock. Every example otherwise sticks to what Chapters 1–26 already taught — functions, classes, exceptions, file handling, decorators, APIs.
1. Why testing matters
- Manual testing means running your code by hand and eyeballing the output — it doesn't scale, and it silently stops happening as a codebase grows.
- Automated testing means writing code that runs your code and checks the result against a known-correct answer, every time, with no human required.
- A test doesn't verify that code "looks right" — it verifies one specific, stated claim: "given this input, the output must be exactly this."
Picture a real, common situation: a function that calculates a shopping cart's total has worked fine for months. Someone refactors it — maybe to add a discount feature — and in the process breaks the case where the cart is empty. Nothing crashes. No exception. The function just quietly starts returning the wrong number for one specific case, and nobody notices until a customer complains weeks later.
This is exactly the gap between manual and automated testing, made concrete:
- Manual testing catches a bug only if a human happens to try the exact input that triggers it, at the exact moment they're paying attention.
- Automated testing catches it every single time that test runs — on every commit, every refactor, forever — whether or not anyone remembers the bug ever existed.
- A well-known trap: a bug gets reported, fixed, and closed — with no test written for it. Six months later, an unrelated change reintroduces the exact same bug, because nothing was checking for it anymore. A test written at fix time would have caught the regression instantly.
Here's a small function with a real, silent bug in one case — the kind manual testing is likely to miss entirely, because the "happy path" looks fine:
def cart_total(prices):
total = prices[0]
for price in prices[1:]:
total += price
return total
print(cart_total([10, 20, 30])) # looks fine: 60
print(cart_total([])) # IndexError -- crashes on an empty cart
60
Traceback (most recent call last):
...
IndexError: list index out of range
A manual test run with [10, 20, 30] looks completely
correct — the bug only shows up on the empty-cart case, which
is exactly the kind of edge case a human tester is most likely to
forget to try by hand. An automated test suite that includes an
empty-cart case catches this every time, without anyone having to
remember to think of it again after the first time it's written.
- A test verifies one specific, stated claim about your code — not a vague sense that it "seems to work."
- Automated tests catch regressions — a bug that was fixed once and quietly comes back — which manual testing structurally cannot do reliably.
- The rest of this chapter covers two ways to write these tests in Python: the built-in
unittest, and the far more commonly usedpytest.
Go Deeper: does testing prove code has no bugs?
No — a passing test suite proves only that the specific cases you wrote tests for still behave as expected. It says nothing about cases nobody thought to test. This is exactly why Sub-topic 6 spends real time on which cases are worth testing, not just "write more tests."
- Manual testing relies on a human remembering to check the right case, every time, forever — it doesn't scale.
- Automated tests check a stated claim mechanically, catching regressions manual testing reliably misses.
- A bug fixed once with no test can silently come back later — the test is what actually locks the fix in place.
2. Writing tests with unittest
unittestis Python's built-in testing framework — no install required, part of the standard library.- Tests are written as methods on a class that inherits from
unittest.TestCase, with method names starting withtest_. - Assertions like
assertEqual,assertTrue, andassertRaisesare how a test states its expected claim.
unittest ships with every Python install — it's always available, no setup, which makes it the natural starting point even though Sub-topic 3 covers the tool most real teams reach for day to day.
unittest.TestCase?
A base class from the unittest module. Any class that inherits from it and defines methods starting with test_ becomes a group of tests unittest can discover and run automatically — each test_ method is one independent test.
Here's a small module to test, and a TestCase class
that checks it:
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
import unittest
from calc import add, divide
class TestCalc(unittest.TestCase):
def test_add_two_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)
def test_divide_raises_on_zero(self):
with self.assertRaises(ValueError):
divide(10, 0)
def test_divide_normal_case(self):
self.assertTrue(divide(10, 2) == 5.0)
if __name__ == "__main__":
unittest.main()
Run it from the command line with python -m unittest
— the -v flag lists every test by name as it
runs:
test_add_negative_numbers (test_calc_unittest.TestCalc.test_add_negative_numbers) ... ok
test_add_two_positive_numbers (test_calc_unittest.TestCalc.test_add_two_positive_numbers) ... ok
test_divide_normal_case (test_calc_unittest.TestCalc.test_divide_normal_case) ... ok
test_divide_raises_on_zero (test_calc_unittest.TestCalc.test_divide_raises_on_zero) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
Thought process: a good test file covers the normal case, a different-but-still-normal case (negative numbers, not just positive), and the one documented error case (dividing by zero) — picking those three is the actual design work, not just calling assertEqual once. assertRaises specifically needs the risky call inside a `with` block, since the exception has to happen *during* the assertion's watch, not before it.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python unittest.TestCase class called TestCalc testing this module:
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
Include: a test for add() with two positive numbers, a test for add() with two negative numbers, a test that divide() raises ValueError when dividing by zero (using assertRaises as a context manager), and a test for a normal divide() case. Use assertEqual and assertTrue appropriately. Add an if __name__ == "__main__": unittest.main() block at the bottom.Four assertions are doing the real work here, and each one states a different kind of claim:
self.assertEqual(a, b)— fails unlessa == b; the most common assertion by far.self.assertTrue(x)/self.assertFalse(x)— fails unlessxis truthy (or falsy).self.assertRaises(ExceptionType), used as awithblock — fails unless the code inside the block raises exactly that exception type.self.assertIn(item, container)— fails unlessitemis found insidecontainer(a list, string, or dict).
python -m unittest with no filename tells unittest to automatically find every file matching the pattern test*.py in the current directory (and subdirectories), import it, and run every TestCase it finds — no manual list of test files to maintain. This is why test files are conventionally named test_something.py, not something arbitrary.
A failing test is just as important to see clearly as a passing one — here's the exact same idea with a deliberately wrong expected value, to show what a failure actually looks like:
import unittest
def calculate_discount(price, percent):
return price - (price * percent / 100)
class TestDiscount(unittest.TestCase):
def test_ten_percent_discount(self):
self.assertEqual(calculate_discount(100, 10), 91) # wrong on purpose
if __name__ == "__main__":
unittest.main(verbosity=2)
test_ten_percent_discount (test_fail_demo.TestDiscount.test_ten_percent_discount) ... FAIL
======================================================================
FAIL: test_ten_percent_discount (test_fail_demo.TestDiscount.test_ten_percent_discount)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_fail_demo.py", line 10, in test_ten_percent_discount
self.assertEqual(calculate_discount(100, 10), 91)
AssertionError: 90.0 != 91
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
The failure message tells you exactly what was expected
(91), exactly what actually happened
(90.0), and exactly which line and which test caused
it — no guessing, no re-running the function by hand to see
what it prints. This is the whole point: a broken assumption
becomes a specific, readable failure instead of a silent wrong
answer.
unittest.TestCasegroups related tests as methods on a class, each namedtest_....assertEqual/assertTrue/assertRaises/assertIneach state a different kind of expected claim.python -m unittest(orpython -m unittest -vfor detail) discovers and runs every test file automatically.
Go Deeper: why "Test" as a class name prefix?
It's a convention, not a hard rule — unittest's
discovery actually looks for any class inheriting from
TestCase, regardless of its name. Naming classes
TestSomething and methods test_something
is just the near-universal convention that makes test files
instantly recognizable, both to humans skimming them and to
discovery tools that also look for the test_ prefix
by default.
unittestis built into Python — tests are methods (namedtest_...) on a class inheritingTestCase.- Assertions (
assertEqual,assertRaises, etc.) state the exact claim each test is checking. python -m unittest -vdiscovers and runs every test, printing a clear pass/fail with a full traceback on failure.
3. Writing tests with pytest
pytestis a third-party testing framework (pip install pytest) — not built in, but the de facto standard across the real-world Python ecosystem.- Tests are plain functions named
test_...— no class, no inheritance required, using Python's ownassertstatement directly. - It's run from the command line with the single word
pytest.
The exact same calc.py from Sub-topic 2, tested with
pytest instead:
import pytest
from calc import add, divide
def test_add_two_positive_numbers():
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-1, -1) == -2
def test_divide_raises_on_zero():
with pytest.raises(ValueError):
divide(10, 0)
def test_divide_normal_case():
assert divide(10, 2) == 5.0
test_calc_pytest.py::test_add_two_positive_numbers PASSED
test_calc_pytest.py::test_add_negative_numbers PASSED
test_calc_pytest.py::test_divide_raises_on_zero PASSED
test_calc_pytest.py::test_divide_normal_case PASSED
======================== 4 passed in 0.01s ========================
Thought process: the goal is a like-for-like comparison with the unittest version — same four cases, same claims — so the only real difference on display is the mechanism (plain functions and bare assert vs. a class and assert* methods), not different test coverage. pytest.raises mirrors assertRaises exactly: still a context manager wrapping the call expected to fail.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Rewrite this unittest.TestCase into pytest style: plain test functions named test_..., using Python's bare assert statement instead of self.assertEqual, and pytest.raises(...) instead of self.assertRaises(...). Keep the exact same four cases: add() with two positive numbers, add() with two negative numbers, divide() raising ValueError on zero, and a normal divide() case.
class TestCalc(unittest.TestCase):
def test_add_two_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)
def test_divide_raises_on_zero(self):
with self.assertRaises(ValueError):
divide(10, 0)
def test_divide_normal_case(self):
self.assertTrue(divide(10, 2) == 5.0)
Notice everything that disappeared: no class, no
self, no assertEqual — just a plain
function and Python's own assert keyword. That's the
"less boilerplate" half of pytest's appeal. The other half is
failure output — pytest doesn't just say two values weren't
equal, it shows exactly which sub-expression failed:
def calculate_discount(price, percent):
return price - (price * percent / 100)
def test_ten_percent_discount():
assert calculate_discount(100, 10) == 91 # wrong on purpose
test_fail_pytest.py::test_ten_percent_discount FAILED
================================= FAILURES =================================
______________________ test_ten_percent_discount ___________________________
def test_ten_percent_discount():
> assert calculate_discount(100, 10) == 91
E assert 90.0 == 91
E + where 90.0 = calculate_discount(100, 10)
test_fail_pytest.py:5: AssertionError
==================== 1 failed in 0.01s =====================
assert x == y that fails just says AssertionError with no detail. pytest rewrites the bytecode of every assert statement in a test file at import time so a failure shows the actual values on both sides — the E assert 90.0 == 91 line above. This is what lets pytest keep the plain assert keyword instead of needing a family of assertX methods like unittest does.
Test discovery works the same way in spirit: running the bare
pytest command in a project directory finds every file
matching test_*.py or *_test.py, and
every function inside them named test_... — no
class required, though pytest can also run unittest.TestCase
classes unchanged, which makes migrating an existing
unittest suite to pytest incremental rather than all
-or-nothing.
- pytest tests are plain functions using bare
assert— no class orselfrequired. - pytest rewrites
assertat import time to show the actual failing values, not just "AssertionError." - Running
pytestin a directory auto-discovers and runs everything matchingtest_*.py/*_test.py.
Go Deeper: if pytest is more popular, why does this chapter teach unittest first?
Because unittest requires nothing extra to try
— it's already installed with Python, so Sub-topic 2's
examples run on literally any machine with Python on it. Real
production codebases skew heavily toward pytest for day-to-day
work, which is why it gets equal weight here rather than being an
afterthought — but knowing unittest still
matters, since some codebases (and some interview questions)
use it, and pytest can run unittest-style tests
directly.
- pytest tests are plain
test_...functions using bareassert— install withpip install pytest. - Failures show the actual values involved via assertion rewriting, without needing a family of
assertXmethods. - The bare
pytestcommand auto-discovers and runs every test in a project — the most common way real teams run their suite.
4. Fixtures and setup/teardown
- Shared setup is anything several tests need in common (a fresh list, a database connection, a temp file) built fresh, before each test, rather than copy-pasted into every test.
unittestprovidessetUp/tearDownmethods, run automatically before/after every test method in a class.- pytest provides
@pytest.fixture— a function that produces a value tests can request by naming it as a parameter.
Here's unittest's version — setUp
runs before every single test method, building a fresh, isolated
cart each time:
import unittest
class TestCartWithSetup(unittest.TestCase):
def setUp(self):
self.cart = []
print(" setUp: fresh cart created")
def tearDown(self):
print(" tearDown: cart discarded")
def test_add_one_item(self):
self.cart.append("apple")
self.assertEqual(self.cart, ["apple"])
def test_cart_starts_empty(self):
self.assertEqual(self.cart, [])
if __name__ == "__main__":
unittest.main(verbosity=2)
setUp: fresh cart created
tearDown: cart discarded
setUp: fresh cart created
tearDown: cart discarded
test_add_one_item ... ok
test_cart_starts_empty ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
Thought process: the point being proven is isolation, so the two tests are deliberately written so their order wouldn't matter — test_cart_starts_empty would fail immediately if it ran after test_add_one_item and somehow shared state, which is exactly what setUp's "fresh cart every time" print statements make visible.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a unittest.TestCase class called TestCartWithSetup that proves each test method gets its own fresh, isolated cart list, not shared state. Add a setUp(self) method that sets self.cart = [] and prints " setUp: fresh cart created", and a tearDown(self) method that prints " tearDown: cart discarded". Add two test methods: test_add_one_item (appends "apple" and asserts the cart equals ["apple"]), and test_cart_starts_empty (asserts the cart is still empty). Run with unittest.main(verbosity=2) so setUp/tearDown output is visible around each test.
Notice setUp ran twice — once before each test
— not once for the whole class. That's exactly the guarantee
that matters: test_cart_starts_empty sees a genuinely
empty cart no matter what test_add_one_item did,
because it never touches that other test's cart at all. They're
two separate lists, built fresh each time.
unittest's setUp/tearDown and pytest's @pytest.fixture are two different mechanisms for the same underlying idea.
pytest's version uses a decorator instead of two special method
names. A fixture is a plain function decorated with
@pytest.fixture; any test that wants it simply names
it as a parameter, and pytest supplies the value automatically:
import pytest
@pytest.fixture
def empty_cart():
print(" fixture: fresh cart created")
cart = []
yield cart
print(" fixture: cart discarded")
def test_add_one_item(empty_cart):
empty_cart.append("apple")
assert empty_cart == ["apple"]
def test_cart_starts_empty(empty_cart):
assert empty_cart == []
fixture: fresh cart created
test_fixture_pytest.py::test_add_one_item PASSED
fixture: cart discarded
fixture: fresh cart created
test_fixture_pytest.py::test_cart_starts_empty PASSED
fixture: cart discarded
======================== 2 passed in 0.01s ========================
The yield is what splits setup from teardown in one
function: everything before yield runs as setup,
the yielded value (cart) is what gets handed to the
test as its parameter, and everything after yield
runs as teardown — once the test finishes, pass or fail.
unittest: definesetUp(self)/tearDown(self)on the class — run automatically before/after every test method.- pytest: define a function decorated
@pytest.fixture; tests request it by naming it as a parameter;yieldsplits setup from teardown. - Both exist to give every test fresh, independent state — avoiding tests that only pass when run in a specific order.
Go Deeper: what's a "test interdependence" bug in practice?
A classic version: Test A creates a row in a database and never cleans it up. Test B, which checks "there are zero rows," happens to pass when run alone, then mysteriously fails whenever it runs after Test A in the same session. The fix is never "run B before A" — it's giving both tests their own isolated setup/teardown so neither can affect the other, regardless of run order.
- Fixtures give every test fresh, independent setup instead of copy-pasted or shared state.
unittestusessetUp/tearDownmethods; pytest uses@pytest.fixturefunctions requested by parameter name.- A test suite that only passes in one specific run order is a sign of hidden shared state — fixtures are the fix.
5. Mocking and test doubles
- A mock is a fake stand-in object that replaces a real dependency during a test — it looks like the real thing to the code under test, but does nothing real.
unittest.mock.Mockcreates a fake object;patchtemporarily swaps a real object out for a mock, for the duration of one test.- You mock anything external to the function you're actually testing — a network call, a database, the current time — so tests stay fast, reliable, and free of side effects.
unittest.mock.Mock() creates an object that accepts any attribute access or method call and simply records what happened — no real logic behind it. You configure what it should return (mock.fetch.return_value = ...) and later ask it what was actually called and with what arguments (mock.fetch.assert_called_once_with(...)).
Picture code that fetches weather data from an external API client — testing it for real would mean an actual network call every time the test suite runs:
from unittest.mock import Mock
import unittest
def get_weather(city, api_client):
data = api_client.fetch(city)
return data["temp"]
class TestWeather(unittest.TestCase):
def test_get_weather_uses_mocked_api(self):
mock_client = Mock()
mock_client.fetch.return_value = {"temp": 72}
result = get_weather("Austin", mock_client)
self.assertEqual(result, 72)
mock_client.fetch.assert_called_once_with("Austin")
if __name__ == "__main__":
unittest.main(verbosity=2)
test_get_weather_uses_mocked_api ... ok
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Thought process: get_weather() takes its api_client as a parameter specifically so a test can substitute a Mock for it — that's the actual design decision that makes this testable at all; a function that builds its own real API client internally would leave no seam for a test to intercept. The mock's job here is twofold: return a canned value AND let the test verify fetch() was actually called with the right city.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a unittest.TestCase test for this function using unittest.mock.Mock instead of a real API call:
def get_weather(city, api_client):
data = api_client.fetch(city)
return data["temp"]
Create a Mock() as a fake api_client, configure mock_client.fetch.return_value to be {"temp": 72}, call get_weather("Austin", mock_client), assert the result equals 72, and assert mock_client.fetch was called exactly once with the argument "Austin" using assert_called_once_with.Two things happened in that one test, and both matter:
- The mock stood in for a real API client, returning a fixed, predictable value instead of whatever a real network call happens to return that day.
assert_called_once_with("Austin")verified how the code under test used its dependency — that it called.fetch()exactly once, with exactly the right city — not just that it returned the right final number.
patch handles the more common real case: the
dependency isn't passed in as an argument, it's used directly
inside the function or method. This is the payment-API scenario
— testing code that charges a customer, without a single
real charge ever happening:
from unittest.mock import patch
import unittest
class Payment:
def charge(self, amount):
raise RuntimeError("This should never actually run in tests!")
def process_order(amount, payment):
return payment.charge(amount)
class TestPayment(unittest.TestCase):
@patch.object(Payment, "charge")
def test_process_order_calls_charge(self, mock_charge):
mock_charge.return_value = "charged"
payment = Payment()
result = process_order(50, payment)
self.assertEqual(result, "charged")
mock_charge.assert_called_once_with(50)
if __name__ == "__main__":
unittest.main(verbosity=2)
test_process_order_calls_charge ... ok
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
@patch.object(Payment, "charge") replaces
Payment.charge with a mock for the duration of this
one test only, and passes that mock in as an extra argument
(mock_charge). The real charge method
— the one that would raise an error if it somehow ran for
real — never executes at all. Outside this test, the real
method is completely untouched.
patch vs. Mock?
Mock() creates a brand-new fake object from scratch, useful when a dependency is passed in as an argument (as with api_client above). patch (or patch.object) temporarily replaces something that already exists — a method, a class, a module attribute — with a mock, for exactly the duration of the test, then restores the original automatically afterward.
- Mock an external dependency — a network call, a database, a payment charge, the current time — anything with real-world side effects or unpredictable results.
Mock()builds a fake object for a dependency that's passed as an argument;patch/patch.objecttemporarily swaps out something used directly inside the code.- A mock lets a test check both the return value and that the dependency was called correctly (
assert_called_once_with), without ever touching the real thing.
Go Deeper: is mocking ever overused?
Yes — mocking every single collaborator, including simple in-process helper functions with no side effects, produces tests that pass even when the real integration between pieces is broken, because nothing real ever actually ran together. The rule of thumb: mock things with real-world side effects or that are genuinely external (network, disk, time, payment) — let plain, deterministic Python functions call each other for real inside a test.
- A mock is a fake stand-in that replaces a real dependency during a test, with no real side effects.
Mock()builds a fake object;patch/patch.objecttemporarily replaces something that already exists, then restores it.- Mock external dependencies specifically (API, database, time, payment) — not every internal helper function.
6. Test coverage and what "good tests" actually look like
- Test coverage is the percentage of your code that runs at least once when your test suite runs — measured by the
coveragepackage. - 100% coverage does not mean 100% correct — it only means every line executed, not that every meaningful case was checked.
- The AAA pattern (Arrange, Act, Assert) is a simple structure that keeps individual tests readable: set up, do the one thing, check the result.
coverage package?
coverage (installed with pip install coverage, commonly run as coverage run -m pytest then coverage report) tracks which lines of your source files actually executed while the test suite ran, and reports a percentage per file. It answers "did any test even touch this line?" — a useful signal for finding completely untested code, but not a measure of test quality by itself.
Here's exactly why 100% coverage can still hide a real bug — this function is fully covered by one test, and still wrong:
def apply_discount(price, percent):
return price - (price * percent / 100)
def test_apply_discount():
# "covers" every line of apply_discount -- but never checks
# percent=0, percent=100, or a negative price
assert apply_discount(100, 10) == 90.0
That one test runs every line of apply_discount, so a
coverage report would show it at 100%. But nothing checks what
happens with a 0% discount, a 100% discount, or a negative price
— and a bug in any of those cases would ship completely
unnoticed, hidden behind a "fully covered" report.
Thought process: the goal here is picking edge cases that are actually plausible for this specific function's domain — a discount really can be 0% or 100%, and a price really shouldn't be negative — rather than testing arbitrary extra numbers just to add test count. Naming each test after the exact case it checks (test_apply_discount_zero_percent, not test_apply_discount_2) is what makes a failing test self-explanatory without opening it.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write pytest tests for this function that go beyond the happy path:
def apply_discount(price, percent):
return price - (price * percent / 100)
Write one test per case, named to describe exactly what it checks: a normal discount (e.g. 10% off 100), a 0% discount (price should be unchanged), a 100% discount (price should become 0), and a negative price. Use the Arrange-Act-Assert structure in each test (set up inputs, call the function once, assert the result) with a comment marking each of the three steps.Each test below follows the AAA pattern — Arrange the inputs, Act by calling the one thing under test, Assert the result — which is why each one stays short and instantly readable even without comments:
def apply_discount(price, percent):
return price - (price * percent / 100)
def test_apply_discount_normal_case():
# Arrange
price, percent = 100, 10
# Act
result = apply_discount(price, percent)
# Assert
assert result == 90.0
def test_apply_discount_zero_percent():
assert apply_discount(100, 0) == 100.0
def test_apply_discount_full_percent():
assert apply_discount(100, 100) == 0.0
test_discount_edge_cases.py::test_apply_discount_normal_case PASSED
test_discount_edge_cases.py::test_apply_discount_zero_percent PASSED
test_discount_edge_cases.py::test_apply_discount_full_percent PASSED
======================== 3 passed in 0.01s ========================
Test names are doing real work here too — each one
describes exactly what it checks, so a failure is understandable
from the test name alone, in a CI log, without opening the file:
test_apply_discount_zero_percent failing tells you
immediately which case broke, unlike a generic name like
test_discount_2.
- Name every test after the exact behavior it checks — readable in a failure log, not just in the file.
- Test boundaries and edge cases deliberately: zero, negative numbers, empty collections, the maximum allowed value — not just the input everything was designed around.
- Structure each test as Arrange (set up inputs) → Act (call the one thing under test) → Assert (check the result) — one clear unit of behavior per test.
The AAA structure works with bare assert even outside
a test runner — try editing the inputs below and see which
assertions still hold:
Just as important as what to test is what not to test:
- Don't test the language or the standard library itself — a test asserting
1 + 1 == 2or thatlist.append()appends is testing Python, not your code. - Don't test private implementation details that could change during a harmless refactor — test the public behavior/output a caller actually depends on.
- Don't chase 100% coverage as a goal in itself — a handful of well-chosen edge-case tests on the code that actually matters beats mechanically covering every line of trivial code.
Go Deeper: what coverage percentage is "good enough"?
There's no universal number — teams commonly target somewhere around 80–90% as a practical floor, not 100%. Chasing the last few percent often means writing tests for trivial code (simple getters, one-line wrappers) that add little real safety, while the same effort spent on edge cases for complex, business-critical logic would catch far more real bugs. Coverage is a tool for finding completely untested code, not a target to maximize for its own sake.
- Coverage measures which lines ran during tests — not whether the right cases were actually checked.
- The AAA pattern (Arrange, Act, Assert) keeps each test short, focused, and readable.
- Test edge cases deliberately and name tests descriptively; don't test the language itself or chase 100% coverage as a goal.
- Every serious open-source Python project and production codebase runs its test suite automatically on every pull request (CI) — a red test blocks a merge before a broken change ever reaches other people's work.
- Mocking is what makes testing code around payments, external APIs, and databases possible at all in a fast, repeatable test suite — without it, the suite would be slow, flaky, and in the payment case, would trigger real charges on every run.
- "We had a bug, fixed it, and it came back six months later" is one of the most common reasons teams adopt stricter testing discipline — a regression test written at fix time is what actually locks a fix in place permanently.
Points to Remember
- Automated tests check a stated claim mechanically, every run, catching regressions manual testing structurally cannot catch.
unittest(built-in): tests are methods on a class inheritingTestCase, usingassertEqual/assertTrue/assertRaises/assertIn; run withpython -m unittest.- pytest (the common real-world choice): plain
test_...functions using bareassert, with detailed failure output via assertion rewriting; run withpytest. - Fixtures give every test fresh, independent setup:
setUp/tearDownin unittest,@pytest.fixture(withyieldsplitting setup/teardown) in pytest. - Mock external dependencies — APIs, databases, the clock, payments — with
unittest.mock.Mock/patch, so tests stay fast, reliable, and side-effect-free. - Coverage measures which lines ran, not whether the right cases were tested; good tests follow the AAA pattern, cover edge cases deliberately, use descriptive names, and skip testing the language itself.