🐍 Python for Everyone

← Back to all chapters

Chapter 27 of 33 Intermediate 75 min read

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

Chapter 12 taught you to handle exceptions so your code fails gracefully. This chapter is about catching mistakes before they ship at all — a test suite is the difference between "I think this still works" and "I know this still works, because 40 checks just ran in half a second and all passed."
Sub-topic 1 of 6

1. Why testing matters

At a glance
  • 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."
Why this matters: a function you tested once by hand, three months ago, tells you nothing about whether it still works today — after five refactors by you and two by a teammate. A test that still runs today tells you immediately.

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.

What is... an automated test? A small piece of code that calls your function with a known input and asserts the result matches a known-correct expected output. If the two match, the test passes silently. If they don't, it fails loudly — immediately, with the exact input, expected value, and actual value shown. Nobody has to remember to check by hand ever again.

This is exactly the gap between manual and automated testing, made concrete:

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:

cart_total_buggy.py
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
actual output of cart_total_buggy.py
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.

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."

Quick recap
  • 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.
Sub-topic 2 of 6

2. Writing tests with unittest

At a glance
  • unittest is 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 with test_.
  • Assertions like assertEqual, assertTrue, and assertRaises are how a test states its expected claim.
Why this matters: 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.
What is... 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:

calc.py
def add(a, b):
    return a + b


def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
test_calc_unittest.py
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:

actual output of: python -m unittest test_calc_unittest -v
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:

What is... test discovery? Running 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:

test_fail_demo.py
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)
actual output of test_fail_demo.py
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.

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.

Quick recap
  • unittest is built into Python — tests are methods (named test_...) on a class inheriting TestCase.
  • Assertions (assertEqual, assertRaises, etc.) state the exact claim each test is checking.
  • python -m unittest -v discovers and runs every test, printing a clear pass/fail with a full traceback on failure.
Sub-topic 3 of 6

3. Writing tests with pytest

At a glance
  • pytest is 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 own assert statement directly.
  • It's run from the command line with the single word pytest.
Why this matters: if a job posting or an open-source project mentions "tests," it's overwhelmingly likely to mean pytest, not unittest — less boilerplate to write, sharper failure output to read, and a huge plugin ecosystem (coverage reporting, mocking helpers, parallel test runs) built around it.

The exact same calc.py from Sub-topic 2, tested with pytest instead:

test_calc_pytest.py
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
running: pytest test_calc_pytest.py -v
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:

test_fail_pytest.py
def calculate_discount(price, percent):
    return price - (price * percent / 100)


def test_ten_percent_discount():
    assert calculate_discount(100, 10) == 91  # wrong on purpose
running: pytest test_fail_pytest.py -v
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 =====================
What is... pytest's assertion rewriting? Normally, a plain 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.

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.

Quick recap
  • pytest tests are plain test_... functions using bare assert — install with pip install pytest.
  • Failures show the actual values involved via assertion rewriting, without needing a family of assertX methods.
  • The bare pytest command auto-discovers and runs every test in a project — the most common way real teams run their suite.
Sub-topic 4 of 6

4. Fixtures and setup/teardown

At a glance
  • 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.
  • unittest provides setUp/tearDown methods, 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.
Why this matters: tests that quietly share state — one test's leftover data becoming another test's starting point — are one of the most common causes of a test suite that passes alone but fails when run together, or passes in one order but fails in another. Fresh setup per test is what prevents this.

Here's unittest's version — setUp runs before every single test method, building a fresh, isolated cart each time:

test_setup.py
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)
actual output of test_setup.py
  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.

What is... a fixture? A fixture is any setup a test needs in order to run — a fresh object, a temp file, a mock connection — built once per test (or once per group of tests) so every test doesn't have to duplicate that setup code itself. 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:

test_fixture_pytest.py
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 == []
running: pytest test_fixture_pytest.py -v -s (documented pytest behavior)
  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.

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.

Quick recap
  • Fixtures give every test fresh, independent setup instead of copy-pasted or shared state.
  • unittest uses setUp/tearDown methods; pytest uses @pytest.fixture functions 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.
Sub-topic 5 of 6

5. Mocking and test doubles

At a glance
  • 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.Mock creates a fake object; patch temporarily 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.
Why this matters: a test suite that makes a real API call, a real database write, or a real payment charge on every run is slow, flaky (the network can fail for reasons that have nothing to do with your code), and in the payment case, actively dangerous to run repeatedly. Mocking removes the real dependency while still testing your code's logic around it.
What is... a Mock? 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:

test_mock_basic.py
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)
actual output of test_mock_basic.py
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:

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:

test_mock_patch.py
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)
actual output of test_mock_patch.py
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.

What is... 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.
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.

Quick recap
  • 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.object temporarily replaces something that already exists, then restores it.
  • Mock external dependencies specifically (API, database, time, payment) — not every internal helper function.
Sub-topic 6 of 6

6. Test coverage and what "good tests" actually look like

At a glance
  • Test coverage is the percentage of your code that runs at least once when your test suite runs — measured by the coverage package.
  • 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.
Why this matters: it's easy to write tests that only exercise the "happy path" — the input everything was designed around — and call it done. The bugs that actually reach production are almost always in the edge cases nobody thought to test, not the main case everyone tested first.
What is... the 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:

coverage_trap.py
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:

test_discount_edge_cases.py
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
running: pytest test_discount_edge_cases.py -v (documented pytest behavior)
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.

The AAA structure works with bare assert even outside a test runner — try editing the inputs below and see which assertions still hold:

try_it.py
Click "Run Code" — try changing an input above to see an assertion fail.

Just as important as what to test is what not to test:

What is... the "happy path"? The happy path is the normal, expected case — valid input, nothing unusual, everything works as designed. It's important to test, but it's also the case every developer already runs by hand while writing the code in the first place, so it's the least likely place for an undiscovered bug to hide. Edge cases (empty input, zero, negative numbers, the maximum size) are where real bugs concentrate, precisely because they're the cases nobody ran by hand.
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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →