Skip to content
LeetQuant
QD02 Python Software Engineering

QD02 · Python Software Engineering · Lesson 3 of 5

Testing with pytest

Test layout, fixtures, parametrize and pytest.raises, tolerances with pytest.approx, property tests over random inputs, and testing Monte Carlo code with seeds and standard errors.

17 min

Objective

Numerical code rarely crashes when it is wrong; it returns a plausible number. By the end of this lesson you should be able to write a pytest suite for a pricing module that checks known values with sensible tolerances, covers many cases without copy-paste, tests mathematical properties over random inputs, and tests random code deterministically. Everything below was run with pytest 9.2 on Python 3.11.

How pytest finds and runs tests

pytest collects files named test_*.py, and inside them functions named test_*. A test is a plain function with a plain assert; on failure pytest rewrites the assertion to show both sides, so you do not need assertEqual methods. Tests live in a tests/ directory beside src/, one test file per module, and each test checks one behaviour, named so that a failure line reads as a sentence: test_expiry_pays_intrinsic, not test_bs_2. A good test is fast (milliseconds), deterministic, and independent of every other test and of test order.

The module under test, pricing.py (bs_put uses the direct formula, not parity, for a reason that will matter below):

import math
import random


def norm_cdf(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def bs_call(s: float, k: float, t: float, r: float, vol: float) -> float:
    if vol <= 0:
        raise ValueError("vol must be positive")
    if t <= 0:
        return max(s - k, 0.0)
    sd = vol * math.sqrt(t)
    d1 = (math.log(s / k) + (r + 0.5 * vol**2) * t) / sd
    return s * norm_cdf(d1) - k * math.exp(-r * t) * norm_cdf(d1 - sd)


def bs_put(s: float, k: float, t: float, r: float, vol: float) -> float:
    if t <= 0:
        return max(k - s, 0.0)
    sd = vol * math.sqrt(t)
    d1 = (math.log(s / k) + (r + 0.5 * vol**2) * t) / sd
    return k * math.exp(-r * t) * norm_cdf(-(d1 - sd)) - s * norm_cdf(-d1)


def mc_call(s: float, k: float, t: float, r: float, vol: float,
            n: int, rng: random.Random) -> tuple[float, float]:
    """Return (price estimate, standard error)."""
    drift = (r - 0.5 * vol**2) * t
    sd = vol * math.sqrt(t)
    disc = math.exp(-r * t)
    pay = [disc * max(s * math.exp(drift + sd * rng.gauss(0.0, 1.0)) - k, 0.0)
           for _ in range(n)]
    mean = sum(pay) / n
    var = sum((p - mean) ** 2 for p in pay) / (n - 1)
    return mean, math.sqrt(var / n)

Note that mc_call takes its random generator as an argument instead of using the global random module. That one design decision is what makes it testable.

Fixtures, parametrize, raises and approx

  • A fixture is a function decorated with @pytest.fixture; a test receives its return value by naming it as a parameter. Use fixtures for shared inputs and for setup and teardown (code after a yield in the fixture runs after the test). scope="module" or "session" builds an expensive fixture once; built-in fixtures include tmp_path (a fresh temporary directory) and monkeypatch (temporarily replace an attribute or environment variable). Shared fixtures go in tests/conftest.py, which pytest loads automatically.
  • @pytest.mark.parametrize runs one test body over a table of cases, and each case is reported separately.
  • with pytest.raises(ValueError, match="..."): asserts that the block raises, and checks the message against a regular expression.
  • x == pytest.approx(expected) compares floats with a tolerance. The defaults are rel=1e-6 and abs=1e-12, and the comparison passes if either is met: pytest.approx(100.0) displays as 100.0 ± 1.0e-04, so 100.00005 passes and 100.0002 fails. Against zero only the absolute tolerance helps: 1e-13 == approx(0.0) is true, 1e-10 == approx(0.0) is false. approx also works on lists, dicts and NumPy arrays (or use np.testing.assert_allclose).

Choose the tolerance from the numerics, not by loosening until green. A closed-form price computed in double precision agrees with a reference to about 10−1210^{-12} relative; a reference value copied to six decimals needs abs=1e-6; a Monte Carlo estimate needs a tolerance in standard errors.

Worked example

a test suite for the pricer

Write tests that check (1) the at-the-money call against a published value, (2) expiry payoffs for in-, at- and out-of-the-money cases, (3) input validation, (4) put–call parity C−P=S−Ke−rTC - P = S - K e^{-rT} and the no-arbitrage bounds max⁡(S−Ke−rT,0)≤C≤S\max(S - K e^{-rT}, 0) \le C \le S over many random inputs, and (5) the Monte Carlo pricer, both against the closed form and for reproducibility.

Show solution
import math
import random

import pytest

from pricing import bs_call, bs_put, mc_call


@pytest.fixture
def atm() -> dict[str, float]:
    return {"s": 100.0, "k": 100.0, "t": 1.0, "r": 0.05, "vol": 0.2}


def test_atm_call_known_value(atm):
    assert bs_call(**atm) == pytest.approx(10.450584, abs=1e-6)


@pytest.mark.parametrize(
    "s, k, expected",
    [
        (100.0, 100.0, 0.0),   # at the money
        (120.0, 100.0, 20.0),  # in the money
        (80.0, 100.0, 0.0),    # out of the money
    ],
)
def test_expiry_pays_intrinsic(s, k, expected):
    assert bs_call(s, k, 0.0, 0.05, 0.2) == expected


def test_rejects_non_positive_vol(atm):
    with pytest.raises(ValueError, match="vol must be positive"):
        bs_call(**{**atm, "vol": 0.0})


def test_put_call_parity_random_inputs():
    rng = random.Random(7)
    for _ in range(1000):
        s, k = rng.uniform(50, 150), rng.uniform(50, 150)
        t, r, vol = rng.uniform(0.01, 3), rng.uniform(0, 0.1), rng.uniform(0.05, 1)
        lhs = bs_call(s, k, t, r, vol) - bs_put(s, k, t, r, vol)
        assert lhs == pytest.approx(s - k * math.exp(-r * t), rel=1e-9, abs=1e-9)


def test_call_bounds_random_inputs():
    rng = random.Random(11)
    for _ in range(1000):
        s, k = rng.uniform(50, 150), rng.uniform(50, 150)
        t, r, vol = rng.uniform(0.01, 3), rng.uniform(0, 0.1), rng.uniform(0.05, 1)
        c = bs_call(s, k, t, r, vol)
        assert max(s - k * math.exp(-r * t), 0.0) - 1e-9 <= c <= s


def test_monte_carlo_agrees_within_four_standard_errors(atm):
    est, se = mc_call(**atm, n=20_000, rng=random.Random(42))
    assert abs(est - bs_call(**atm)) < 4 * se


def test_monte_carlo_is_reproducible(atm):
    a = mc_call(**atm, n=1_000, rng=random.Random(1))
    b = mc_call(**atm, n=1_000, rng=random.Random(1))
    assert a == b
$ pytest -v
test_pricing.py::test_atm_call_known_value PASSED                        [ 11%]
test_pricing.py::test_expiry_pays_intrinsic[100.0-100.0-0.0] PASSED      [ 22%]
test_pricing.py::test_expiry_pays_intrinsic[120.0-100.0-20.0] PASSED     [ 33%]
test_pricing.py::test_expiry_pays_intrinsic[80.0-100.0-0.0] PASSED       [ 44%]
test_pricing.py::test_rejects_non_positive_vol PASSED                    [ 55%]
test_pricing.py::test_put_call_parity_random_inputs PASSED               [ 66%]
test_pricing.py::test_call_bounds_random_inputs PASSED                   [ 77%]
test_pricing.py::test_monte_carlo_agrees_within_four_standard_errors PASSED [ 88%]
test_pricing.py::test_monte_carlo_is_reproducible PASSED                 [100%]

============================== 9 passed in 0.04s ===============================

Points worth saying out loud:

  • The reference 10.450584 is the standard textbook value to six decimals (the function returns 10.450583572185565), so the tolerance is abs=1e-6, matching the precision of the reference.
  • Expiry payoffs are exact (max(s - k, 0.0)), so exact == is correct there. Use tolerances where rounding happens, not everywhere by reflex.
  • The Monte Carlo run gives 10.4047 with standard error 0.1032, so it is 0.046 (0.44 standard errors) from the closed form. If the pricer were unbiased and the test unseeded, a 4-standard-error test would fail by chance with probability 2(1−Φ(4))≈6.3×10−52(1 - \Phi(4)) \approx 6.3 \times 10^{-5} per run, about once in 16,000 runs. A test that compares with a fixed number such as 10.40 would instead break whenever the simulation changes in a harmless way, such as drawing normals in a different order.
  • The seed makes the test deterministic. Pass the generator in (as here, or np.random.default_rng(seed)), never seed a global generator inside library code.

Worked example

a property test catches a sign error

A colleague's bs_put uses norm_cdf(d1 - sd) where it should use norm_cdf(-(d1 - sd)). Which of the tests above catches it, and what does pytest show?

Show solution

The known-value and expiry tests only exercise the call, so they pass. The parity test fails on its first random input:

______________________ test_put_call_parity_random_inputs ______________________

    def test_put_call_parity_random_inputs():
        rng = random.Random(7)
        for _ in range(1000):
            s, k = rng.uniform(50, 150), rng.uniform(50, 150)
            t, r, vol = rng.uniform(0.01, 3), rng.uniform(0, 0.1), rng.uniform(0.05, 1)
            lhs = bs_call(s, k, t, r, vol) - bs_put(s, k, t, r, vol)
>           assert lhs == pytest.approx(s - k * math.exp(-r * t), rel=1e-9, abs=1e-9)
E           assert 21.870264880831982 == 18.214151814430238 ± 1.8e-08
E
E             comparison failed
E             Obtained: 21.870264880831982
E             Expected: 18.214151814430238 ± 1.8e-08

The > marks the failing line and the E lines show both sides and the effective tolerance (rel=1e-9 of 18.2 is 1.8e-08). This is the property-based idea: instead of a few hand-picked cases, state a relation that must hold for all valid inputs (parity, bounds, monotonicity in strike, symmetry) and check it on many generated inputs. The Hypothesis library automates this: it generates inputs from declared strategies and, on failure, shrinks the input to a minimal failing example. A seeded loop, as here, is the dependency-free version.

Two lessons about test design. First, the parity test only has value because bs_put is computed independently; had bs_put been defined from parity, the test would be a tautology and pass whatever the bug. Second, when a random-input test fails, copy the failing input into a parametrized regression case so it is checked explicitly forever.

Knowledge check

With pytest's default tolerances, which assertion fails?

Knowledge check

A Monte Carlo pricer test, unseeded, asserts the estimate is within 2 standard errors of the closed form. The pricer is correct. Roughly how often will CI fail?

Knowledge check

A library defines bs_put(s, k, t, r, vol) as bs_call(...) - s + k * exp(-r * t). What does a put-call parity test on this library verify?

Key takeaways

  • Plain assert in test_* functions; one behaviour per test, named as a sentence; fast, deterministic, order-independent.
  • Fixtures for shared setup (conftest.py, tmp_path, monkeypatch), parametrize for tables of cases, pytest.raises for errors.
  • pytest.approx defaults to rel=1e-6, abs=1e-12; set tolerances from the numerics, and remember only abs helps near zero.
  • Test properties (parity, bounds, monotonicity) over many seeded random inputs, with the two sides computed independently.
  • Test random code by injecting a seeded generator and asserting within a few standard errors of a known answer.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).