smartyfy.mrindigi.com

Python Master Course V2 — 114. Parametrized Tests and Boundary-Value Design

What you will be able to do

  • Convert a behavior table into parametrized pytest cases
  • Cover empty, invalid and edge inputs without redundant tests
  • Use readable case IDs and explicit expected exceptions

Prerequisites: 112–113: fixtures, exception contracts and object state.

Your local workspace

Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson114, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.

Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.

python -m pip install pytest

The examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.

Let the policy choose the cases

Parametrization runs one test body with multiple named sets of inputs and expectations. It removes repeated mechanics while keeping each example visible in a failure report. It is most valuable when several cases ask the same behavioral question. Do not force unrelated behaviors into one enormous table full of flags and conditional assertions; that hides the specification instead of clarifying it.

Begin with a policy expressed in ordinary language. Our educational shipping calculation accepts a positive whole-number weight in grams. Up to and including 1000 grams costs 500 integer cents. Above 1000 and up to and including 5000 costs 900 cents. Heavier parcels up to and including 20000 cost 1500 cents. Larger parcels are rejected. These are fictional teaching bands, not a carrier quote. Integer cents and grams avoid an irrelevant floating-point rounding problem.

Each threshold creates partitions. Testing 1000 and 1001 distinguishes an inclusive boundary from an exclusive one; 999 confirms the lower side. The next threshold needs its own neighbors. A middle value from a partition can be useful, but ten nearly identical middle values usually add less evidence than a missing boundary. Zero, negative integers, floats, strings, None and booleans probe different contract violations.

Expected values must come from the policy, not from an expression that repeats the production algorithm. If the implementation uses weight <= 1000, calculating every expectation using the same conditional could reproduce the same defect. Write concrete cents in the case table. Readable IDs such as first-band-limit make a failure understandable even when a value appears in several scenarios.

A complete table-driven shipping suite

def shipping_cents(weight_g):
    if type(weight_g) is not int:
        raise TypeError("weight must be an integer")
    if weight_g <= 0 or weight_g > 20000:
        raise ValueError("weight must be from 1 to 20000 grams")
    if weight_g <= 1000:
        return 500
    if weight_g <= 5000:
        return 900
    return 1500

Save the tests as test_shipping.py. The decorator names match the test parameters. Each tuple supplies one complete case. pytest.param allows an explanatory ID on a particular row. Invalid values are separated by error type, so the intended contract remains obvious.

import pytest
from shipping import shipping_cents


@pytest.mark.parametrize("weight,expected", [
    pytest.param(1, 500, id="minimum"),
    pytest.param(999, 500, id="below-first-limit"),
    pytest.param(1000, 500, id="first-band-limit"),
    pytest.param(1001, 900, id="above-first-limit"),
    pytest.param(4999, 900, id="below-second-limit"),
    pytest.param(5000, 900, id="second-band-limit"),
    pytest.param(5001, 1500, id="above-second-limit"),
    pytest.param(20000, 1500, id="maximum"),
])
def test_valid_weight(weight, expected):
    assert shipping_cents(weight) == expected


@pytest.mark.parametrize("weight", [-1, 0, 20001])
def test_out_of_range(weight):
    with pytest.raises(ValueError, match="1 to 20000"):
        shipping_cents(weight)


@pytest.mark.parametrize("weight", [1.5, "1000", None, True])
def test_wrong_type(weight):
    with pytest.raises(TypeError, match="integer"):
        shipping_cents(weight)
python -m pytest --collect-only -q test_shipping.py
python -m pytest -q test_shipping.py
python -m pytest -q test_shipping.py -k first-band-limit

Expected collection: 15 cases. Expected execution: all 15 pass; the filtered command runs the single first-band-limit case. Version-specific formatting and timings are not fixed output. A tiny demonstration has a deterministic result:

from shipping import shipping_cents
print([shipping_cents(w) for w in [1000, 1001, 5000, 5001]])

Expected output

[500, 900, 900, 1500]

Guided lab: find defects with the smallest evidence

Make one intentional change: replace the first <= comparison with <. Predict the failing case before running the suite. The 1000-gram case should now expose the boundary mistake. Restore the correct code, then repeat with the upper limit: change > 20000 to >= 20000. The maximum case should fail. These experiments demonstrate whether your tests distinguish plausible implementation errors.

Now extend the policy with a separate declared-value parameter only on paper. Decide whether its partitions interact with weight. If an insurance charge is independent of weight, testing every possible combination may be wasteful. If insurance eligibility changes above a weight threshold, interaction cases become necessary. Stacking two parametrization decorators produces the Cartesian product, not paired rows. Three weights and four declared values create twelve tests.

Write a brief test-design note with columns described in prose: condition, representative value, expected behavior and reason. Explain why None is a wrong type rather than an empty parcel. Input strings from a command line should be converted by a separate parsing layer; this function's contract intentionally does not coerce "1000". Separating parsing from policy gives each layer clearer tests.

If a parametrized test mutates a list argument, that object is not automatically copied for every use. Avoid sharing mutable case values, make fresh copies in setup, or parametrize immutable descriptions that a fixture converts into resources. A failing table should identify a behavior, not depend on whichever row ran before it.

Questions worth asking

Is parametrization the same as a for loop inside one test?

Both can visit several inputs, but pytest parametrization collects separate cases. A failed row has its own identity and does not prevent other collected rows from running. A plain loop often stops at its first failed assertion and gives less focused reporting.

Why include both 1000 and 1001?

They lie on opposite sides of an inclusive threshold. A broad normal-case test might pass even if the comparison operator is wrong. Boundary neighbors are selected because they discriminate between the correct policy and a plausible off-by-one implementation.

Should each row use a fixture?

Not necessarily. Pure scalar inputs are clearer directly in the table. Fixtures are useful for resource setup and lifecycle. Combining parametrization and fixtures is powerful, but unnecessary indirection makes a small behavioral specification harder to inspect.

Why reject True when it behaves like 1?

The specification says whole-number parcel weight, and treating a truth value as a measured weight would conceal a caller bug. Python allows the relationship at the language level, but the domain contract can intentionally impose stricter acceptance rules.

What if all cases pass after I break the code?

Check collection first, then identify whether the changed behavior is actually covered. Add an independently specified example that distinguishes the defect. Do not merely add more random normal inputs; tests gain value when they rule out a concrete wrong behavior.

How many boundary tests are enough?

There is no universal count. Cover the stated partitions, transition points and meaningful interactions, then account for past defects and consequences of failure. The 15 cases here are evidence for this small contract, not a formula for every application.

Practice, then compare your solution

1. Explain collection size

How many cases result from two stacked decorators with 2 and 3 values?

Worked solution and reasoning

Six: each of the two values combines with each of the three. Use one decorator containing three paired tuples if you mean three specific input pairs instead of all combinations.

2. Add a regression

A former bug charged 900 cents for 19999 grams. Add a regression row.

Worked solution and reasoning

Add pytest.param(19999, 1500, id="heavy-parcel-regression") to the valid table. Its purpose is a documented past defect, even though it is in an already sampled partition. The expected valid-case count becomes nine.

3. Check monotonicity

For valid weights, should cost ever decrease as weight increases?

Worked solution and reasoning

No under this policy. A secondary property can compare a sorted set of weights and assert its costs are nondecreasing. Keep explicit threshold checks too: a function returning 500 for every weight would satisfy monotonicity while still being wrong.

Mastery checkpoint

Produce a case table that a reviewer can trace directly to the shipping rules. Demonstrate one failing boundary mutation and restore it. Explain collection counts, IDs, type partitions and the limits of repetition. The next lesson replaces unstable dependencies while preserving this same behavior-first approach.

Official documentation and next steps

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.