Unit Testing Frameworks
A few assert lines at the bottom of a script stop at the first problem. A unit testing framework is a library and runner that discovers tests, runs them individually and reports their results. Python provides built-in unittest and third-party pytest; this lesson uses pytest and notes where unittest differs.
Three jobs a framework does
- Discovery. The runner finds tests by naming convention, so you need not maintain a list of tests to call.
- Isolation. Fixtures can give each test fresh starting data. One failing test normally does not stop the remaining tests.
- Reporting. The runner records results and produces a summary and an exit code that other tools can read.
A minimal pytest file looks like this:
# test_temperature.py
from temperature import c_to_f
def test_freezing_point():
assert c_to_f(0) == 32
def test_boiling_point():
assert c_to_f(100) == 212If both checks succeed, running pytest in that folder prints 2 passed. By default, pytest collects files named test_*.py or *_test.py and functions whose names start with test. A plain assert is enough, because pytest uses assertion rewriting to explain failed checks.
The unittest version uses a class and assertion methods:
import unittest
from temperature import c_to_f
class TestConversion(unittest.TestCase):
def test_freezing_point(self):
self.assertEqual(c_to_f(0), 32)Fixtures and parametrized tests
A test fixture is the known starting state a test needs, together with the code that creates it and cleans it up. In pytest, a test requests a fixture by naming its decorated function as a parameter. Code before yield is setup; code after it is teardown:
import pytest
from shop import Cart
@pytest.fixture
def empty_cart():
cart = Cart()
yield cart
cart.clear()
def test_new_cart_total_is_zero(empty_cart):
assert empty_cart.total() == 0unittest uses setUp and tearDown methods. By default, a pytest fixture has function scope: its setup runs once for every test case that requests it. Isolation still requires fixture code that creates independent state or restores shared state. Shared globals, external resources or a returned shared object can retain changes despite function scope.
For an unparametrized fixture, scope="module" or scope="session" reuses one fixture value across a file or the run. This saves setup time, but mutable state can persist between tests.
Parametrization runs one test function on several inputs. Each value in a @pytest.mark.parametrize list becomes a separate test case, and stacked decorators produce every combination:
Here, ni is the length of the i-th parameter list. Sum these products over all collected test functions to obtain the run's total.
Example: lists of 2 currencies and 4 amounts produce 2×4=8 test cases. A function-scoped fixture requested by all eight has 8 setups, assuming every case reaches that setup.
Reading the report
The frameworks classify ordinary results differently:
Outcome | pytest | unittest |
|---|---|---|
passed | The test body completed successfully | Same, shown as ok |
failed | An assertion or other ordinary exception arose in the test body | An assertion failed |
error | Setup or teardown raised; import problems can cause collection errors | An unexpected exception arose in the test, setup or teardown |
skipped | A skip marker or condition applied | A skip decorator or request applied |
Usually, a completed case contributes one summary outcome. However, a passing body followed by a teardown error contributes both 1 passed and 1 error. Summary counts therefore need not equal the number of cases.
For these basic outcomes, pytest returns 0 when collected tests pass or skip, 1 for test-body failures or setup/teardown errors, and 5 when no tests are collected. Collection errors, such as test-file import failures, interrupt execution by default and return 2. A CI server uses the exit code to detect an unsuccessful run.
Remember that a passing suite proves only what its assertions check.
What to remember
- Frameworks discover tests, support isolation and report results; teardown errors can add an extra summary count.
- Default pytest discovery uses test_*.py, *_test.py and function names starting with test.
- Function scope repeats setup; fixture code must create or restore independent state.
- Stacked parameter lists multiply the number of cases.
- Test failures and fixture errors normally return 1; collection errors interrupt the default run with 2.
Example: Predicting a pytest run before you start it
A pricing module provides apply_discount(price, rate), which should return the price after a fractional discount, so apply_discount(15.00, 0.1) should give 13.5. Its tests live in one module, test_pricing.py:
import pytest
from pricing import apply_discount
@pytest.fixture
def catalog():
print("loading catalog")
return {"pen": 2.00, "book": 15.00, "bag": 40.00}
@pytest.mark.parametrize("item", ["pen", "book", "bag"])
@pytest.mark.parametrize("rate", [0.0, 0.1])
def test_discount_never_negative(catalog, item, rate):
assert apply_discount(catalog[item], rate) >= 0
@pytest.mark.parametrize("rate", [0.1, 0.25])
def test_discount_reduces_price(catalog, rate):
assert apply_discount(catalog["book"], rate) < catalog["book"]
def test_zero_rate_is_identity(catalog):
assert apply_discount(catalog["bag"], 0.0) == catalog["bag"]
def check_rounding():
assert apply_discount(9.99, 0.5) == 5.00a) How many test cases does pytest collect from this file?
Stacked parametrize decorators multiply, so test_discount_never_negative expands to three items times two rates, which is ________ cases.
test_discount_reduces_price has one list of two rates, giving ________ cases, and test_zero_rate_is_identity has no parametrization, so it contributes ________ case.
check_rounding does not start with test, so discovery ignores it and it adds nothing.
pytest collects 9 test cases.
b) How many times does the setup of the catalog fixture run? How many times would it run if the decorator were changed to @pytest.fixture(scope="module")?
All ________ collected test functions list catalog as a parameter, so every one of the 9 cases requests it. The fixture has the default function scope, so pytest builds a fresh dictionary for each case. Running pytest -s, which turns off output capture, would print the loading message 9 times.
With scope="module", pytest builds the dictionary once for the module and hands the same object to all 9 cases. That sharing is safe here only because no test modifies the dictionary.
The setup runs 9 times with function scope and once with module scope.
c) A developer accidentally writes return price * rate, which returns the discount amount instead of the discounted price. Predict the summary line pytest prints.
Check each test against the buggy function.
- test_discount_never_negative: every price and rate is non-negative, so their product is never negative and all ________ cases pass.
- test_discount_reduces_price: the function returns 15.00×0.1=1.5 and 15.00×0.25=3.75, both below 15.00, so both cases pass even though the values are wrong.
- test_zero_rate_is_identity: the function returns 40.00 × 0.0 = ________, which does not equal 40.00, so the assertion fails.
The summary line reads 1 failed, 8 passed. Only the identity test caught the bug, because the other two tests assert properties that the wrong answer also has. A stronger test compares against a hand-computed value, such as apply_discount(15.00, 0.1) == pytest.approx(13.5).
A unittest.TestCase subclass defines the class methods setUpClass and tearDownClass, the instance methods setUp and tearDown, and a single test method test_parse. Assume this is the only test class, all setup and teardown methods complete successfully, and nothing is skipped. Arrange the events below in the order they happen when the file is run with python -m unittest.
Loading ordering steps…