Sub topic 14
Testing the parts that can break quietly
Most bugs in a machine learning project do not crash. A mistyped config key, a string where a number belongs, a leaked row, or an unseeded generator all produce a model and a metric. The metric is just wrong or unrepeatable. This chapter covers a small set of tests that catch these failures early.
This chapter assumes you can write basic pytest tests, and that your project has the src/ package layout, the typed YAML config loader, and the set_seed helper from earlier chapters. It also assumes the package is installed in editable mode with pip install -e ., so tests can import my_project.
What to test and what to skip
You cannot unit-test "the model is good". Spend effort where a failure is silent and a check is cheap.
| Area | Silent failure | Check |
|---|---|---|
| Config loading | Typo in a key, wrong type, missing value | Loader raises, types are correct |
| Overrides | Value arrives as a string, override ignored | Parsed types match |
| Data | Missing column, empty file, null target | Validation function raises |
| Splits | Same row in train and test | Overlap check raises |
| Seeding | Runs differ although a seed is set | Same seed gives same draws |
Do not test library internals, and do not assert exact accuracy numbers from a full training run. Those tests are slow and break for reasons unrelated to your code.
Testing configuration
The config loader is the first place a quiet error can enter. The TrainConfig dataclass already raises a TypeError for unknown or missing keys, but only if the loader is wired as intended. A test pins that behavior down.
from pathlib import Path
import pytest
from my_project.config import apply_overrides, load_config
VALID = (
"data_path: data/processed/train.csv\n"
"seed: 42\n"
"learning_rate: 0.001\n"
"batch_size: 32\n"
)
def write(tmp_path, text):
path = tmp_path / "train.yaml"
path.write_text(text)
return path
def test_overrides_keep_numeric_types(tmp_path):
cfg = load_config(write(tmp_path, VALID), ["learning_rate=0.01", "batch_size=64"])
assert cfg.learning_rate == 0.01
assert isinstance(cfg.batch_size, int)
def test_unknown_override_key_fails(tmp_path):
with pytest.raises(TypeError):
load_config(write(tmp_path, VALID), ["learnin_rate=0.01"])
def test_missing_key_fails(tmp_path):
text = VALID.replace("batch_size: 32\n", "")
with pytest.raises(TypeError):
load_config(write(tmp_path, text))
def test_committed_config_loads():
path = Path(__file__).resolve().parents[1] / "configs" / "train.yaml"
cfg = load_config(path)
assert cfg.batch_size > 0The first test guards against the most common override bug: a value that arrives as the string "64". The second turns a typo into a hard failure, because the misspelled key becomes an unexpected argument to the dataclass. The last test loads the real file in configs/, so someone who edits the YAML and breaks it finds out in the test run, not in a training job.
A type gap in dataclasses
A dataclass does not check types at runtime. The annotation learning_rate: float is documentation only. PyYAML also reads 1e-3 as a string, because its float pattern requires a decimal point. So learning_rate=1e-3 as an override gives the loader the string "1e-3", the dataclass accepts it, and the failure appears later inside the optimizer.
One way to close the gap is a test that asserts the types of every field after loading:
from dataclasses import fields
from my_project.config import TrainConfig, load_config
def test_every_field_has_its_declared_type(tmp_path):
path = tmp_path / "train.yaml"
path.write_text(
"data_path: data/processed/train.csv\n"
"seed: 42\n"
"learning_rate: 1.0e-3\n"
"batch_size: 32\n"
)
cfg = load_config(path)
for field in fields(TrainConfig):
assert isinstance(getattr(cfg, field.name), field.type), field.nameThis works because the annotations in TrainConfig are real classes (str, int, float). If you later add from __future__ import annotations, field.type becomes a string and this test needs adjusting.
Testing data
Data tests belong in a plain function that the pipeline also calls. That way the same check protects both the test suite and the real run. Put it in src/my_project/data/checks.py:
def check_training_frame(df, required_columns, target):
missing = [c for c in required_columns if c not in df.columns]
if missing:
raise ValueError(f"missing columns: {missing}")
if len(df) == 0:
raise ValueError("frame has no rows")
if df[target].isna().any():
raise ValueError(f"target column {target!r} contains missing values")
def check_no_overlap(train_ids, test_ids):
overlap = set(train_ids) & set(test_ids)
if overlap:
raise ValueError(f"{len(overlap)} ids appear in both train and test")Tests use tiny hand-built frames, not your real dataset. They run in milliseconds and need no data files.
import pandas as pd
import pytest
from my_project.data.checks import check_no_overlap, check_training_frame
COLUMNS = ["age", "income", "label"]
def test_valid_frame_passes():
df = pd.DataFrame({"age": [30, 41], "income": [50.0, 62.5], "label": [0, 1]})
check_training_frame(df, COLUMNS, "label")
def test_missing_column_is_reported():
df = pd.DataFrame({"age": [30], "label": [1]})
with pytest.raises(ValueError, match="income"):
check_training_frame(df, COLUMNS, "label")
def test_null_target_is_rejected():
df = pd.DataFrame({"age": [30], "income": [50.0], "label": [None]})
with pytest.raises(ValueError, match="missing values"):
check_training_frame(df, COLUMNS, "label")
def test_overlapping_ids_are_rejected():
with pytest.raises(ValueError, match="1 ids"):
check_no_overlap([1, 2, 3], [3, 4])Train/test overlap is the classic quiet error. The model scores well because it has seen the test rows, and nothing warns you. Calling check_no_overlap right after the split costs one line.
Testing seeding
Seeding is easy to claim and easy to break. A test that draws numbers twice from the same seed confirms the helper reaches every generator it should. Here set_seed is assumed to live in src/my_project/seeding.py.
import random
import numpy as np
from my_project.seeding import set_seed
def draw():
return random.random(), np.random.rand(3).tolist()
def test_same_seed_gives_same_draws():
set_seed(7)
first = draw()
set_seed(7)
assert draw() == first
def test_different_seeds_differ():
set_seed(7)
first = draw()
set_seed(8)
assert draw() != firstThe second test matters as much as the first. A set_seed that does nothing would pass a repeatability test only if the generators were never touched, and the difference test catches a seed that is ignored.
This test covers only the standard library and NumPy. If you use PyTorch or another framework, add its seeding call and a draw from it to both the helper and the test. Even then, some GPU operations are nondeterministic, so do not promise bit-identical training. Test the data order and the initial weights, not the final loss.
Running the tests
Run the suite from the project root:
pytest -qKeep the whole suite under a few seconds. A slow suite gets skipped, and a skipped suite catches nothing. If you want one slow end-to-end check, mark it and run it separately:
import pytest
@pytest.mark.slow
def test_pipeline_runs_on_tiny_data():
...Register the slow marker in pyproject.toml under [tool.pytest.ini_options], then run pytest -m "not slow" for the quick loop. The next chapter in the plan covers running these checks automatically on every push, which is where fast tests pay off.
Common errors
- Testing against real data files. The tests fail on a teammate's machine because
data/is not in Git. Build small frames in the test. - Asserting a metric value. A test that expects
accuracy == 0.91breaks on any library upgrade. Assert that a metric lies in a plausible range, or skip it. - Tests that import from the notebook directory. Tests should import only from the installed package, which is another reason logic lives in
src/. - Validation only in tests. If the check is not also called in the pipeline, real data never passes through it.
Exercise
A teammate runs python -m my_project.train --config configs/train.yaml learning_rate=1e-3 and training silently uses no learning rate decay logic correctly, because the optimizer receives a string. Why does the frozen TrainConfig accept this value, and what test would catch it?
Show answer
PyYAML parses 1e-3 as a string because its float pattern requires a decimal point, and a dataclass does not enforce its type annotations at runtime, so TrainConfig stores the string without complaint. A test that loads a config with the override and asserts isinstance(cfg.learning_rate, float) fails on the string. Looping over dataclasses.fields(TrainConfig) and checking each value against field.type covers every field at once. Writing the override as 1.0e-3 or 0.001 avoids the problem.
Exercise
Write a test for check_no_overlap that passes when the train and test id lists share no values.
Show answer
def testdisjointidspass(): checkno_overlap([1, 2, 3], [4, 5]) The function returns None when there is no overlap, and the test fails only if it raises a ValueError.