BEGINNERCHAPTER 05

Choosing cases: boundaries, equivalence classes and the unhappy path

You cannot test every input. Split them into classes the code treats alike, test one inside each class, test both sides of every edge, then decide what the bad inputs should do

45 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-23
PREDICT

The rule says 5% off from ₦10,000 (1_000_000 kobo) upward. The code says subtotal > 1_000_000 by mistake. The suite checks 200_000 and 8_000_000 and passes. You may add exactly one test. Which one fails on the buggy code?

A function can accept billions of inputs. You will write ten tests. The skill is choosing which ten, and the choice is mostly mechanical once you know where the code changes its mind. This chapter gives you the method: split the inputs into equivalence classes, test the edges between them on both sides, decide what the unhappy inputs should do, and combine only where rules interact.

Why middle values pass

Look at the discount rule as a line of subtotals, in kobo. Below 1_000_000 the discount is 0%. From 1_000_000 up to 4_999_999 it is 5%. From 5_000_000 it is 10%.

0% off5% off10% off1_000_0005_000_000200_0008_000_000filled: the starter suite. open: last value out and first value in at each edge.

The starter suite in labs/testing/tests/unit/test_pricing.py uses the filled dots. Both of its discount tests sit well inside a band. A comparison written as >= and the same comparison written as > give identical answers at every filled dot. They disagree at one value only, the edge, so a test has to stand on the edge to see the difference.

This is not rare. The rules that move money are tiers, bands and windows, and every tier, band and window has edges. People also pick the middle by habit: round numbers, qty=2, distance=10. Round numbers sit in the middle of bands because the bands were chosen to be round.

Equivalence classes: draw them first

An equivalence class is a set of inputs the code should treat the same way. If the rule is correct for one member, you expect it to be correct for all. So one test per class is enough for the middle, and the effort goes to the edges.

Drawing the classes before writing tests is the useful part. checkout/pricing.py has three rules with classes.

Rule Input Classes Edges
Discount tier subtotal, kobo 0 to 999_999 (0%); 1_000_000 to 4_999_999 (5%); 5_000_000 and up (10%) 1_000_000 and 5_000_000
Delivery band distance, km 0 to 5 (₦1,500); 6 to 15 (₦3,000); 16 to 40 (₦5,000); 41 and up (₦9,000) 5, 15 and 40
Promo window the instant, read as a Lagos day before 1 December 2026; 1 to 31 December inclusive; after the first and last minute of the window

Two things to notice. First, the classes come from the specification, not the code. You can draw this table from the pricing rules without opening pricing.py. If you draw it from the code you draw what the code does, mistakes included. Second, every rule also has invalid classes: a negative distance, a quantity of zero, an empty cart. They come later, in the section on the unhappy path.

The delivery rule says “up to and including 5 km”. That sentence is the edge, in words: 5 belongs to the cheap band and 6 does not. When a spec is vague about which side owns an edge, you have found a question for the product owner, and you found it before the bug.

Boundaries: last value out, first value in

At each edge you test two values: the last one outside the class and the first one inside it. For the ₦10,000 tier those are 999_999 and 1_000_000 kobo. For integers the step is one. For kobo it is one kobo, which is why the lab works in kobo and not naira: ₦9,999.99 is a value that exists, and a test written in whole naira can never reach it.

Some people add a third value one past the edge (1_000_001). It rarely catches a bug the first two miss, but it costs one table row and it confirms the class is not a single point.

▶ SIMULATION
CODE UNDER TEST
price(): qty > 10 gets the 900 rate (the spec says 10 or more)
quantities it prices wrongly: 10
THE BUILD
tests run: 0
running
✓ the build is red whenever the code returns a wrong price✓ the build is green when the code is right
SCHEDULE
01[CODE]price(): qty > 10 gets the 900 rate (the spec says 10 or more)
02[SUITE]test: price(5) equals the spec
03[SUITE]test: price(30) equals the spec
04[SUITE]test: price(80) equals the spec
05[RUNNER]runner: report the build
06[RELEASE]release: the build is green, so ship it
Start of middle-of-range tests scenario. 6 steps.
// spec: 10 or more units get the 900 rate
if (qty > 10) return qty * 900;     // off by one: 10 is charged 1000 each

// tests
expect(price(5)).toBe(5000);
expect(price(30)).toBe(27000);
expect(price(80)).toBe(64000);       // every one in the middle of a band

Run the sim with the middle-of-range schedule first and watch the verdict: every test passes and the buggy code ships. Switch to the edge schedule and the same buggy code goes red at 10. The sim shows the mechanism with a quantity rule. The lab shows it with money and dates, where the edges are less obvious.

Where edges hide

A numeric comparison is the easy edge. Others take more care.

Inclusive and exclusive ends. The promo’s ends_on is the last day, inclusive. A test at “31 December” has to say which instant on 31 December. Midday passes with either <= or <. Only the last minute separates them.

Time zones. The promo runs on Lagos days, and Lagos is UTC+1 with no daylight saving. Midnight at the start of 1 December in Lagos is 23:00 UTC on 30 November. A test that builds datetime(2026, 12, 1) with no zone is read in the machine’s own zone, so it passes on a laptop in Lagos and fails on a CI server in UTC. Always build the instant with an explicit zone, and choose the edge in the zone the rule uses.

Units. The tier edge is ₦10,000 and the code compares kobo. A test that writes 10_000 has tested a subtotal of ₦100. If you name the constant (TEN_THOUSAND_NAIRA = 1_000_000) a reader sees the edge at once.

Rounding. VAT at 7.5% is rounded half up to the kobo in checkout/money.py. A rounding rule has edges too: the amounts where a half kobo appears. That is a different rule from the tier edge, with its own cases, and a later chapter on testing money goes through it.

First, last and nothing. Zero items, one item and the first value above a maximum are edges on almost every rule that has a size. Collections add the empty and the single-element cases.

The unhappy path

Everything so far tested inputs the rules cover. The unhappy path is the rest: an empty cart, a quantity of zero, a negative price, a distance of minus one. These are invalid classes, and they teach something the happy path cannot, because the specification is usually silent about them. So the test cannot be written from the spec. Somebody has to decide.

Run price_cart on an empty list and on a negative price and you see what the code decides today without anyone choosing:

Input What price_cart does now
[], 3 km a quote with a total of 150_000: ₦1,500 for delivery of nothing
one line at minus ₦5,000, 3 km a total of minus 387_500 kobo: Ojaline would owe the buyer ₦3,875
a line with qty 0 ValueError("qty must be at least 1"), already decided
a distance of minus 1 ValueError("distance cannot be negative"), already decided

The API in front of the function does not let an empty list or a negative price through today: the request model needs at least one line and the prices come from the database. That is why the bugs have not hurt yet. It is not a reason the function is right. The next caller (a seller tool, a batch re-pricing job) may not have that guard.

You have three honest options for each invalid class: refuse it with an error, return a defined harmless answer, or leave it undefined and say so. Leaving it undefined is allowed. Leaving it undefined without noticing is the bug. For a pricing function that sits in front of a card charge, refusing is the safe default: a loud ValueError in the quote step beats a quiet minus ₦3,875 reaching the payment step. Write the test for the decision first. It fails, and the failure is the evidence that the function had no rule.

A free sample, a price of zero, is different from a negative price. It is a legitimate input, so give it a test that says it is allowed. A test that pins an allowed edge stops a later tidy-up from “fixing” it.

How many cases is enough

Three tiers, four bands and two promo states make 24 combinations. You do not write 24 tests, because in price_cart the discount and the delivery fee do not depend on each other: the fee is added after the discount, and nothing about the band changes the tier. When rules are independent you test each across its own classes and edges (7 and 7 and 4 cases here) and add a few tests where rules do touch. The one interaction that matters in this function is order: the promo comes off what is left after the tier discount, not off the subtotal. One test with both discounts live pins that.

When parameters really do interact, as in a form with ten options that influence one another, the number of combinations explodes. Testers then use methods that pick a small covering set, such as pairwise testing, which makes sure every pair of values from any two parameters appears together at least once. The survey in the Reading list covers these strategies. Start by asking whether the parameters interact at all. Most of the time they do not, and one test per class plus the edges is enough.

Where the expected value comes from

Every row in the table needs an expected answer, and the tempting source is the function itself: run it, copy the number, paste it into the row. Do not. A test whose answer came from the code agrees with the code by construction, mistakes included. If > had been in the file when you copied the numbers, the row at 1_000_000 would say 0 and the test would defend the bug.

Work the answer out from the rule, by hand, before you run anything. The row for exactly ₦10,000 is arithmetic you can do on paper: 5% of 1_000_000 is 50_000, so the net is 950_000. VAT at 7.5% of 950_000 is 71_250. The delivery fee for 3 km is 150_000. The total is 1_171_250 kobo, and the test says so in its last line. If the code disagrees, one of you is wrong, and finding out which is the point of the test. When a number is hard to compute by hand, use a second source: the product owner’s worked example, a spreadsheet, or last month’s real invoice.

Choosing which edges earn a test

Not every edge deserves the same attention. Spend the cases where a wrong answer costs money, breaks a promise to a customer or is hard to see afterwards.

  • Edges that move money. The tier floors, the delivery bands and the promo window. A mistake here is paid for in every order near the edge, and nobody sees a ₦1,500 difference on one receipt.
  • Edges that cross a boundary of the system. The first and last minute of a Lagos day, where UTC and local time disagree. These fail only for a few hours a day, which makes them hard to catch in manual testing and easy to catch in a unit test.
  • Edges the code already guards. Zero quantity and negative distance raise errors. A test confirms the guard exists, and it fails the day someone removes it.
  • Edges nobody can reach. A cart of 2^31 lines is an edge of the integer type, not of Ojaline’s rules. Skip it until a caller can send it.

A good test of this choice is the review question: if this edge were off by one, would anyone find out before a customer did? If the answer is no, the edge needs a row.

Reading the edges out of the code

You can list the edges of a function by reading it for comparisons. Each comparison against a constant is an edge, and each edge needs two rows: the last value on one side and the first value on the other. A lower bound written x >= c gives c - 1 and c. An upper bound written x <= c gives c and c + 1. A window written a <= x <= b has two edges and so four rows. The code decides which side owns the edge value, and the rule in the product owner’s words is what you check it against.

Run this over pricing.py and the list writes itself. The two tier floors give four rows around 1_000_000 and 5_000_000. The three delivery edges at 5, 15 and 40 km give six rows, because each band is “up to and including”, so the edge value belongs to the cheaper band and the value after it to the dearer one. The promo window has two edges and four rows, and because the code compares Lagos days and not UTC instants, each row is a minute to either side of local midnight. That is 14 edge rows from three rules. They are 4 of the 7 tier rows in the lab’s table, 6 of its 7 delivery rows and all 4 promo rows; the rest are a zero and a value one step past each edge, for company. Nothing in the method needs cleverness. It needs you to open the file and look at every <, <=, > and >=.

Two kinds of edge hide from this reading. The first is a loop or a collection, where the edges are counts, not constants: none, one, and many. The empty cart is the count that is easy to forget, and the lab ends on it. The second is an edge in a unit, where a number changes meaning: naira against kobo, a UTC instant against a Lagos day. There is no comparison to read, so you find it by asking, of each input, what its units are and who else might read it differently. A habit that catches both is to look at every input type and say its smallest, its largest and its first surprising value out loud.

Sometimes the edge you find has no owner. The rule says “5% off orders of ₦10,000 or more” and the code agrees, so the row at 1_000_000 is easy. Suppose instead the rule said “over ₦10,000”. Then the code with > is right, the same row expects 0%, and the test pins the opposite answer. The test cannot settle which sentence was meant. When you reach an edge where the written rule is silent or ambiguous, do not copy the code’s answer into the table. Write the question down, put it to whoever owns the rule (the product owner, the pricing team, finance), and record the answer in the test’s name or comment. A boundary row that carries its source, such as “per the pricing policy of 2026-11”, is worth more than three that carry none.

Coverage is a floor, not the goal

The starter suite already shows 92% branch coverage on pricing.py. The missing three lines are the two guards and the promo discount. You can close the gap with three more middle-value tests, reach 100%, and still ship the edited >=. The lab does exactly this, because the number only feels meaningful until you watch it say 100% over a broken edge. The lesson 100% coverage, bug intact shows the same trap, and a later chapter on coverage and mutation testing gives you the tool that measures it: it edits the code and counts how many edits your tests notice. In this chapter you do that by hand, four times.

A table of cases is also a document. Name the edges in the table (ids= on parametrize) so a failure reads first-minute and not case 2. The pytest page on parametrize in the Reading list shows pytest.param, and its example page on test IDs shows ids.

LAB Boundaries, coverage and the empty cart ~40 MIN
YOU NEEDPython 3.9 or laterlabs/testing set up with its .venv (see its README)No Docker, no network

You will measure the starter suite, raise its coverage to 100% with middle values, show that an edge bug survives, close it with a table of edges, and then decide what the empty cart should do. Work from labs/testing. Python caches compiled files by modification time to the second, so a quick edit and revert can leave a stale file in use. Start with:

export PYTHONDONTWRITEBYTECODE=1

1. Measure the starter suite.

.venv/bin/pytest -p no:randomly --cov=checkout.pricing --cov-branch --cov-report=term-missing
checkout/pricing.py 61 3 14 3 92% 56, 69, 93, then 23 passed, 1 skipped, 1 deselected. Line 56 is the qty < 1 guard, 69 the negative-distance guard and 93 the promo discount. The percentage records which lines ran. Nothing in it says the answers were right.

2. Reach 100% with middle values only.

Create tests/unit/test_pricing_middle.py:

from datetime import datetime, timezone

import pytest

from checkout.pricing import Line, delivery_fee, line_total, price_cart

NOW = datetime(2026, 12, 15, 12, 0, tzinfo=timezone.utc)

def test_zero_quantity_is_refused():
    with pytest.raises(ValueError):
        line_total(Line(250_000, 0))

def test_negative_distance_is_refused():
    with pytest.raises(ValueError):
        delivery_fee(-1)

def test_promo_discount_is_taken_mid_month():
    quote = price_cart([Line(300_000, 2)], distance_km=3, now=NOW, promo_code="HARMATTAN")
    assert quote.promo_discount == 60_000
.venv/bin/pytest -p no:randomly --cov=checkout.pricing --cov-branch --cov-report=term-missing
checkout/pricing.py 61 0 14 0 100%, then 26 passed, 1 skipped, 1 deselected. Every line and every branch ran.

Now edit the tier comparison by hand, run the suite, and put the file back:

sed -i.bak -e 's/subtotal >= floor/subtotal > floor/' checkout/pricing.py
diff checkout/pricing.py.bak checkout/pricing.py
.venv/bin/pytest -q -p no:randomly
mv checkout/pricing.py.bak checkout/pricing.py
The diff shows if subtotal >= floor: changed to if subtotal > floor:. The run ends 26 passed, 1 skipped, 1 deselected. A real defect, 100% branch coverage and a green suite. The last command restores the original.

3. Write the table of edges.

Create tests/unit/test_pricing_boundaries.py:

from datetime import datetime, timezone

import pytest

from checkout.pricing import (
    PROMOS,
    Line,
    delivery_fee,
    discount_bp,
    price_cart,
    promo_applies,
)

HARMATTAN = PROMOS["HARMATTAN"]

@pytest.mark.parametrize(
    "subtotal, expected_bp",
    [
        (0, 0),
        (999_999, 0),          # N9,999.99: last kobo below the first tier
        (1_000_000, 500),      # exactly N10,000: the tier starts here
        (1_000_001, 500),
        (4_999_999, 500),      # last kobo below the second tier
        (5_000_000, 1000),     # exactly N50,000
        (5_000_001, 1000),
    ],
)
def test_discount_tier_edges(subtotal, expected_bp):
    assert discount_bp(subtotal) == expected_bp

@pytest.mark.parametrize(
    "km, expected_fee",
    [
        (0, 150_000),
        (5, 150_000),          # the band is 'up to and including 5 km'
        (6, 300_000),
        (15, 300_000),
        (16, 500_000),
        (40, 500_000),
        (41, 900_000),
    ],
)
def test_delivery_band_edges(km, expected_fee):
    assert delivery_fee(km) == expected_fee

def utc(*args):
    return datetime(*args, tzinfo=timezone.utc)

@pytest.mark.parametrize(
    "instant, live",
    [
        (utc(2026, 11, 30, 22, 59), False),  # 23:59 on 30 Nov in Lagos
        (utc(2026, 11, 30, 23, 0), True),    # 00:00 on 1 Dec in Lagos: first minute
        (utc(2026, 12, 31, 22, 59), True),   # 23:59 on 31 Dec in Lagos: last minute
        (utc(2026, 12, 31, 23, 0), False),   # 00:00 on 1 Jan in Lagos
    ],
    ids=["day-before", "first-minute", "last-minute", "day-after"],
)
def test_promo_window_edges_use_the_lagos_day(instant, live):
    assert promo_applies(HARMATTAN, instant) is live

def test_order_of_exactly_ten_thousand_naira_is_discounted():
    quote = price_cart([Line(1_000_000, 1)], distance_km=3, now=utc(2026, 11, 23, 9, 0))
    assert quote.tier_discount == 50_000
    assert quote.net == 950_000
    assert quote.vat == 71_250
    assert quote.total == 950_000 + 71_250 + 150_000

def test_promo_comes_off_after_the_tier_discount():
    quote = price_cart(
        [Line(3_000_000, 2)], distance_km=7, now=utc(2026, 12, 15, 12, 0), promo_code="HARMATTAN"
    )
    assert quote.tier_discount == 600_000     # 10% of 6,000,000
    assert quote.promo_discount == 540_000    # 10% of what is left, 5,400,000
    assert quote.total == 4_860_000 + 364_500 + 300_000
.venv/bin/pytest -p no:randomly tests/unit/test_pricing_boundaries.py -v
Twenty lines ending PASSED, with names such as test_promo_window_edges_use_the_lagos_day[first-minute] and test_discount_tier_edges[1000000-500], then 20 passed. The ids come from ids= and from the values in each row. The table is the specification: the edges are written where a reviewer can read them.

4. Make the edits by hand and count what notices.

for edit in \
  's/subtotal >= floor/subtotal > floor/' \
  's/distance_km <= upto/distance_km < upto/' \
  's/starts_on <= day <= promo.ends_on/starts_on < day <= promo.ends_on/' \
  's/<= day <= promo.ends_on/<= day < promo.ends_on/'; do
  sed -i.bak -e "$edit" checkout/pricing.py
  echo "== $edit"
  .venv/bin/pytest -q -p no:randomly 2>&1 | grep -E "^FAILED|passed|failed"
  mv checkout/pricing.py.bak checkout/pricing.py
done
Four blocks. The tier edit fails three tests: test_discount_tier_edges[1000000-500], test_discount_tier_edges[5000000-1000] and test_order_of_exactly_ten_thousand_naira_is_discounted; the rows at 999_999 and 1_000_001 pass. The delivery edit fails the rows at 5, 15 and 40 (3 failed, 43 passed). The promo start edit fails only [first-minute] and the end edit fails only [last-minute]. Each edit is caught by the value on the edge and by nothing in the middle. Before step 3 the same four edits all ended passed.

5. The unhappy path: characterise, decide, then change the code.

First see what the function does today:

.venv/bin/python - <<'EOF'
from datetime import datetime, timezone
from checkout.pricing import Line, price_cart
now = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)
print(price_cart([], 3, now).total)
print(price_cart([Line(-500_000, 1)], 3, now).total)
EOF
150000 and then -387500. An empty cart is quoted ₦1,500. A line at minus ₦5,000 produces a total below zero.

Decide: both are refused, and a free sample stays legal. Create tests/unit/test_pricing_unhappy.py before you touch the code:

from datetime import datetime, timezone

import pytest

from checkout.pricing import Line, line_total, price_cart

NOW = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)

def test_empty_cart_is_refused():
    with pytest.raises(ValueError):
        price_cart([], distance_km=3, now=NOW)

def test_negative_price_is_refused():
    with pytest.raises(ValueError):
        line_total(Line(-500_000, 1))

def test_free_sample_is_allowed():
    assert line_total(Line(0, 1)) == 0
.venv/bin/pytest -q -p no:randomly tests/unit/test_pricing_unhappy.py
2 failed, 1 passed. Both refusal tests fail with DID NOT RAISE. The free-sample test passes because that is what the code does already, and the test now pins it.

Now edit checkout/pricing.py. In line_total, after the qty check, add:

    if line.unit_price_kobo < 0:
        raise ValueError("price cannot be negative")

In price_cart, as the first statement:

    if not lines:
        raise ValueError("cart is empty")
.venv/bin/pytest -p no:randomly --cov=checkout.pricing --cov-branch --cov-report=term-missing
.venv/bin/pytest -q
checkout/pricing.py 65 0 18 0 100% and 49 passed, 1 skipped, 1 deselected; the second run, in random order, ends the same way. The two new guards add four branches and the tests exercise every one.

Break it. In tests/unit/test_pricing_boundaries.py delete the two rows that sit exactly on an edge, (1_000_000, 500) and (5_000_000, 1000), and delete test_order_of_exactly_ten_thousand_naira_is_discounted. Run the file: still green, 17 tests. Now run the first edit from step 4 (subtotal >= floor to subtotal > floor) against the whole tests/unit folder. It ends passed, with no failure. The table still holds 999_999, 1_000_001 and the values around both edges, and the bug lives. The edge value itself is the test. Put the rows back and the three failures return.

When you are done, put the lab back as you found it: run git checkout checkout/pricing.py (or remove the two guards by hand) and delete tests/unit/test_pricing_middle.py, test_pricing_boundaries.py and test_pricing_unhappy.py. The next chapters count from 10 passed in tests/unit/ and 23 passed, 1 skipped, 1 deselected in the whole suite, and the unhappy-path tests would fail without the guards.

DECIDE

Jelani is merging the change that makes price_cart raise on an empty cart. Sibusiso, who reviews it, points out that Ojaline's seller tool also calls price_cart to preview a basket while a seller is still adding items, and a preview with nothing in it is normal. The API cannot send an empty cart. What should the function do?

READING
  1. PAPER
    Ostrand and Balcer, The Category-Partition Method for Specifying and Generating Functional Tests (CACM, 1988) Thomas Ostrand, Marc Balcer, 1988

    The origin of 'draw the classes from the specification first'. Read how categories and choices become a list of test cases, which is the table you built by hand. The publisher page blocks scripted fetches; Crossref confirms the record. Read: The part that defines categories, choices and constraints and turns them into test frames; skip anything specific to the authors' tool.

  2. PAPER
    Grindal, Offutt and Andler, Combination testing strategies: a survey (STVR, 2005) Mats Grindal, Jeff Offutt, Sten Andler, 2005

    A map of the ways to choose combinations when parameters do interact, from one value of each to all pairs. Read it before inventing your own scheme. The publisher blocks scripted fetches; Crossref confirms the record. Read: The introduction and the descriptions of the each-choice, base-choice and pairwise strategies; skip the comparison tables.

  3. DOC
    pytest: How to parametrize fixtures and test functions

    The syntax of the tables in the lab: parametrize, pytest.param with marks, and ids. Read the first sections; skip indirect parametrization until you have fixtures to feed.

  4. DOC
    pytest: Parametrizing tests, different options for test IDs

    Shows how `ids=` names each row of a table, so a failure reads first-minute and not case 2. Read only the section on test IDs; it is short and the lab uses the technique in step 3.

  5. DOC
    Coverage.py: Branch coverage measurement

    What branch coverage is and what a partial branch is (the lab output's `BrPart` column counts them). Short; read all of it so you know what the 100% in step 2 does and does not claim.

  6. POST
    Fowler, Test Coverage Martin Fowler

    A short argument that coverage finds the code you did not test and says little about the code you did. Read it with step 2 fresh in mind.

  7. BOOK
    Khorikov, Unit Testing: Principles, Practices, and Patterns (Manning, 2020) Vladimir Khorikov, 2020

    A working engineer's view on spending tests where they find bugs. Read it after this chapter to judge a table of cases by what it protects. Read: Chapter 4 on what makes a good unit test; skip the C# specifics.

  8. POST
    Bloch, Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken (Google Research blog, 2006) Joshua Bloch, 2006

    The incident in the Why, in the author's words: a proven algorithm with a boundary bug that appears at 2^30 elements. Read the explanation of the overflow and the closing section on what to take from it.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Running tests on every change →