Skip to content

Testing & Assertions

A test records a claim about a function and checks that claim after the code changes. For a scientific calculation, the expected answer must come from the problem definition or an independent calculation. Repeating the implementation inside the test can repeat its error.

This lesson builds a small pytest project around counts per million. The first suite exposes an omitted input check. The corrected implementation then passes tests for numerical results, invalid inputs, and mutation.

Create an empty directory named cpm_tests. Save this configuration as pyproject.toml inside it. The dependency versions define the environment used for the displayed results.

pyproject.toml
[project]
name = "cpm-tests"
version = "0.1.0"
requires-python = ">=3.13,<3.14"
dependencies = ["numpy==2.5.4"]
[dependency-groups]
dev = ["pytest==9.2.0"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]

Run uv sync from that directory to create its environment. The package lesson explains project files and the lockfile that uv creates. Save each Python block below under the filename in its first comment, creating the tests directory when needed.

The function accepts one nonempty vector of real, finite, nonnegative counts for a single sample. Its total must be positive. A missing count is an unknown measurement, so this example rejects it rather than replacing it with zero or removing it from the library total.

For valid input, the output has one value per input count and sums to one million within floating-point tolerance. Scaling every count by the same positive factor must leave CPM unchanged.

The first implementation omits several checks, including the check for missing values.

cpm_unchecked.py
import numpy as np
def cpm(counts: object) -> np.ndarray:
"""Calculate CPM with deliberately incomplete input validation.
Args:
counts: A numeric count vector for one sample.
Returns:
Counts divided by their total and multiplied by one million.
Raises:
ValueError: If a count is negative.
"""
values = np.asarray(counts, dtype=float)
if np.any(values < 0):
raise ValueError("counts must not be negative")
return values / values.sum() * 1e6

The expected values for [25, 75] come from a total of one hundred. The first entry is one quarter of that total. The final test asks the function to reject a missing measurement, as the contract requires.

tests/test_cpm_unchecked.py
import numpy as np
import pytest
from cpm_unchecked import cpm
def test_returns_one_value_per_count() -> None:
result = cpm([10, 20, 70])
assert result.shape == (3,)
assert np.issubdtype(result.dtype, np.floating)
def test_total_is_one_million() -> None:
assert cpm([10, 20, 70]).sum() == pytest.approx(1e6)
def test_known_answer() -> None:
np.testing.assert_allclose(cpm([25, 75]), [250_000, 750_000])
def test_rejects_negative_count() -> None:
with pytest.raises(ValueError, match="must not be negative"):
cpm([-1, 10])
def test_single_count() -> None:
np.testing.assert_allclose(cpm([42]), [1_000_000])
def test_rejects_missing_count() -> None:
with pytest.raises(ValueError, match="must be finite"):
cpm([10, np.nan, 70])

Run this suite from the project directory. Two -q options suppress the timing summary; the failed assertion and the progress symbols remain visible.

Terminal window
uv run pytest -qq --tb=short --color=no -p no:cacheprovider tests/test_cpm_unchecked.py
.....F [100%]
=================================== FAILURES ===================================
__________________________ test_rejects_missing_count __________________________
tests/test_cpm_unchecked.py:32: in test_rejects_missing_count
with pytest.raises(ValueError, match="must be finite"):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE ValueError
=========================== short test summary info ============================
FAILED tests/test_cpm_unchecked.py::test_rejects_missing_count - Failed: DID ...

The command exits with status 1 because the function does not raise the expected exception. Its sum becomes NaN, and division propagates that missing value through the entire output. Pytest rewrites assertions before execution to report intermediate values; it does not rerun a failed assertion.

Replacing the sum with np.nansum would change the denominator to the total of observed counts. That is a different rule, not a repair of the stated contract. It would also leave an all-zero vector without a valid denominator.

Save the complete corrected function as cpm.py. It checks the vector before division and rejects a total that overflows to infinity.

cpm.py
import numpy as np
def cpm(counts: object) -> np.ndarray:
"""Scale one complete count vector to counts per million.
Args:
counts: Nonempty one-dimensional numeric counts for one sample.
Returns:
A floating-point array containing counts per million.
Raises:
TypeError: If the array contains nonnumeric or complex values.
ValueError: If its shape, values, or library total is invalid.
"""
raw_counts = np.asarray(counts)
if raw_counts.ndim != 1 or raw_counts.size == 0:
raise ValueError("counts must be a nonempty one-dimensional vector")
if raw_counts.dtype.kind not in "iuf":
raise TypeError("counts must contain real numeric values")
values = raw_counts.astype(float)
if not np.isfinite(values).all():
raise ValueError("counts must be finite; resolve missing values first")
if np.any(values < 0):
raise ValueError("counts must not be negative")
with np.errstate(over="ignore"):
total = values.sum()
if not np.isfinite(total) or total <= 0:
raise ValueError("count total must be finite and positive")
return values / total * 1e6

Input checks use explicit exceptions. Python can remove bare assertions when it runs with -O, so assertions cannot protect inputs that a caller supplies. A pytest assertion has a different role: it compares observed behavior with the test’s expectation.

The test table includes empty vectors, matrices, strings, missing values, infinity, negative values, and invalid totals. Named parameter cases make a failing boundary visible in the test report.

tests/test_cpm.py
import numpy as np
import pytest
from cpm import cpm
def test_known_answer_and_shape() -> None:
result = cpm([25, 75])
assert result.shape == (2,)
assert np.issubdtype(result.dtype, np.floating)
np.testing.assert_allclose(result, [250_000, 750_000])
def test_single_count() -> None:
np.testing.assert_allclose(cpm([42]), [1_000_000])
def test_positive_rescaling_preserves_cpm() -> None:
np.testing.assert_allclose(cpm([1, 2, 7]), cpm([100, 200, 700]))
def test_does_not_modify_input() -> None:
counts = np.array([25, 75])
before = counts.copy()
cpm(counts)
np.testing.assert_array_equal(counts, before)
def test_seeded_counts_keep_cpm_invariants() -> None:
rng = np.random.default_rng(42)
counts = rng.poisson(100, size=5)
result = cpm(counts)
assert result.shape == counts.shape
assert np.isfinite(result).all()
assert result.sum() == pytest.approx(1e6)
@pytest.mark.parametrize(
("counts", "error_type", "message"),
[
pytest.param([], ValueError, "nonempty", id="empty"),
pytest.param([[1, 2]], ValueError, "one-dimensional", id="matrix"),
pytest.param(["1", "2"], TypeError, "numeric", id="text"),
pytest.param([True, False], TypeError, "numeric", id="booleans"),
pytest.param([1 + 2j], TypeError, "numeric", id="complex"),
pytest.param([-1, 10], ValueError, "negative", id="negative"),
pytest.param([10, np.nan], ValueError, "finite", id="missing"),
pytest.param([10, np.inf], ValueError, "finite", id="infinite"),
pytest.param([0, 0], ValueError, "positive", id="zero-total"),
pytest.param([1e308, 1e308], ValueError, "finite", id="overflow"),
],
)
def test_rejects_invalid_input(counts, error_type, message) -> None:
with pytest.raises(error_type, match=message):
cpm(counts)

Run only the corrected suite. The earlier suite remains deliberately red because it imports cpm_unchecked.

Terminal window
uv run pytest -qq --tb=short --color=no -p no:cacheprovider tests/test_cpm.py
............... [100%]

Create random generators inside each test that needs them. A fixed seed makes an input reproducible without making the test depend on another test’s random draws. An unseeded test can still check a valid property, but an unexplained failure is harder to reproduce.

A seed does not fix every numerical difference across package versions or platforms. Keep the project lockfile when reproducing a numerical result and choose tolerances that reflect the calculation.

Test Defect it can expose
A small answer computed by hand The denominator or scale factor is incorrect.
Shape and dtype checks The function transposes, truncates, or drops values.
Positive rescaling The result depends on a count scale that should cancel.
Invalid-input cases A missing or zero denominator reaches the calculation.
Input preservation The function changes the caller’s array unexpectedly.

For a plot, test the plotted values and labels, then inspect the rendered figure. Image comparisons can also detect visual regressions, but they do not establish that the analysis is correct. For a model, test a known signal and the required output contract before asserting an exact metric that depends on the numerical environment.

The file and command-line project extends these tests to temporary files, malformed records, output protection, and process exit statuses. Its tests invoke the command as another process, so they check the interface that a terminal user actually calls.

The Create a package lesson runs one test suite against both the development package and its installed wheel. It checks that the distributed source preserves the public import and input rules.

The pytest assertion guide explains numerical expectations, expected exceptions, and assertion introspection. These mechanisms distinguish a wrong answer from an input that the function must reject.

The pytest parametrization guide explains how one test runs against several named cases. Use it to add a new boundary without copying the test body.

The pytest output guide documents verbosity and traceback controls. The commands on this page retain the failure while suppressing the elapsed-time summary.

The NumPy nansum reference explains how missing values affect that reduction. Compare its behavior with the explicit missing-count policy in this lesson before using it for a library total.