Sub topic 5
Testing stages and the whole pipeline
This chapter assumes you can write Python functions and dataclasses, run pytest, and train a scikit-learn model. It also assumes you have read the earlier chapters. There you split training into stages that take their inputs and a TrainConfig as arguments, and you made runs reproducible with seeds and a config fingerprint. Here you test that code.
Why pipeline code needs tests
A training pipeline fails in two ways. It can crash, which you notice at once. Or it can finish and produce a worse model because of a silent bug. A split that leaks test rows into training, a shifted label column, or a seed that is no longer applied will not raise an error. The accuracy number still looks plausible.
Tests catch both kinds of failure before a long run starts. The stage design from earlier chapters makes this cheap. Each stage is a plain function with explicit inputs and outputs, so you can call it from a test with small data and no orchestrator, database, or GPU.
Pipeline tests fall into three layers:
| Layer | What it checks | Typical cost | Example |
|---|---|---|---|
| Unit test | One stage, with tiny or synthetic input | Milliseconds | `split` keeps class proportions |
| Smoke test | The whole pipeline runs end to end on a small configuration | Seconds | `run_pipeline` returns a model and metrics |
| Property test | An invariant that must hold across runs | Seconds | Two runs with one config give equal metrics |
Run unit tests on every commit. Run the smoke and property tests in CI, and again before any long training job.
The code under test
The examples use the stages from this tutorial. Save them as pipeline.py. The file below also includes the configuration dataclass and the fingerprint function.
import dataclasses
import hashlib
import json
from dataclasses import dataclass
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def config_fingerprint(cfg: TrainConfig) -> str:
payload = json.dumps(dataclasses.asdict(cfg), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]
def load_data():
X, y = load_iris(return_X_y=True)
return X, y
def split(X, y, cfg):
return train_test_split(
X, y, test_size=cfg.test_size, random_state=cfg.seed, stratify=y
)
def train(X_train, y_train, cfg):
model = RandomForestClassifier(
n_estimators=cfg.n_estimators, random_state=cfg.seed
)
return model.fit(X_train, y_train)
def evaluate(model, X_test, y_test):
return {"accuracy": accuracy_score(y_test, model.predict(X_test))}
def run_pipeline(cfg):
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
model = train(X_train, y_train, cfg)
metrics = evaluate(model, X_test, y_test)
if metrics["accuracy"] < cfg.min_accuracy:
raise ValueError(
f"accuracy {metrics['accuracy']:.3f} is below the gate of {cfg.min_accuracy}"
)
return model, metricsPut your tests in test_pipeline.py next to it. Every test snippet below belongs in that file, and the imports shown in the first snippet are shared by all of them.
Unit tests for stages
A unit test should check a property of one stage that you could break by accident. Do not re-test scikit-learn. Test your own decisions: which arguments you pass, which data you return, and which shapes you promise.
Testing the split stage
The split stage makes three promises: the sizes follow test_size, no row appears in both sets, and class proportions are preserved because of stratify=y.
import numpy as np
import pytest
from pipeline import (
TrainConfig,
config_fingerprint,
evaluate,
load_data,
run_pipeline,
split,
train,
)
def test_split_sizes_follow_config():
X, y = load_data()
cfg = TrainConfig(test_size=0.2)
X_train, X_test, y_train, y_test = split(X, y, cfg)
assert len(X_test) == int(round(len(X) * 0.2))
assert len(X_train) + len(X_test) == len(X)
assert len(X_train) == len(y_train)
assert len(X_test) == len(y_test)
def test_split_keeps_class_proportions():
X, y = load_data()
_, _, y_train, y_test = split(X, y, TrainConfig())
train_share = np.bincount(y_train) / len(y_train)
test_share = np.bincount(y_test) / len(y_test)
assert np.allclose(train_share, test_share, atol=0.05)
def test_split_has_no_overlap():
X, y = load_data()
X_train, X_test, _, _ = split(X, y, TrainConfig())
train_rows = {tuple(row) for row in X_train}
test_rows = {tuple(row) for row in X_test}
# Iris contains a few duplicate rows, so compare counts, not identity.
assert len(train_rows & test_rows) <= 1The overlap test shows a common edge case. Real data often has duplicate rows, so a strict "no shared rows" assertion can fail even when your split is correct. Iris has a few exact duplicates, and the test allows for them. If your data has a unique ID column, assert on the IDs instead. That check is exact.
Testing a stage on synthetic data
Real datasets make tests slow and hide intent. For stages that do not depend on the specific dataset, build a small array in the test. That keeps the test fast, and a reader sees what the input looks like.
def test_evaluate_reports_accuracy_for_known_predictions():
class FixedModel:
def predict(self, X):
return np.array([0, 1, 1, 0])
X_test = np.zeros((4, 2))
y_test = np.array([0, 1, 0, 0])
metrics = evaluate(FixedModel(), X_test, y_test)
assert metrics == {"accuracy": 0.75}The FixedModel stub is a test double: a stand-in object with the same interface as the real one. Because evaluate only calls predict, the stub is enough. The expected value of 0.75 is computed by hand (three of four predictions match), so the test is independent of the library.
Testing the train stage
Training is harder to test, because the quality of a fitted model is not an exact value. Check what you can state with certainty: the return type, that the model is fitted, and that configuration reaches the model.
def test_train_applies_config_to_model():
X, y = load_data()
cfg = TrainConfig(n_estimators=7, seed=3)
X_train, _, y_train, _ = split(X, y, cfg)
model = train(X_train, y_train, cfg)
assert model.n_estimators == 7
assert model.random_state == 3
assert len(model.estimators_) == 7
assert set(model.classes_) == {0, 1, 2}This catches a frequent bug: a stage that ignores a config field because someone hard-coded a value or forgot to pass it through. Without the test, changing n_estimators in the config would silently do nothing.
Smoke tests for the whole pipeline
A smoke test runs the full pipeline end to end and checks only that it completes and returns outputs of the right shape. It does not judge model quality. The name comes from hardware: power the device on and see whether smoke comes out.
def test_pipeline_smoke():
cfg = TrainConfig(n_estimators=5)
model, metrics = run_pipeline(cfg)
assert hasattr(model, "predict")
assert set(metrics) == {"accuracy"}
assert 0.0 <= metrics["accuracy"] <= 1.0Note the small n_estimators=5. A smoke test should use the cheapest configuration that still exercises every stage. On a real project this means a sampled subset of the data, a few training steps, and one epoch. Provide that as a named config, such as a smoke_config() helper, so every test uses the same cheap settings.
Smoke tests catch wiring errors that unit tests cannot: stage A returns a tuple in a different order from what stage B expects, or a new stage was added but never connected.
Testing reproducibility
The chapter on reproducibility argued that one configuration should give one result. That claim needs a test. If it is untested, it will stop being true without anyone noticing.
def test_pipeline_is_deterministic():
cfg = TrainConfig()
_, first = run_pipeline(cfg)
_, second = run_pipeline(cfg)
assert first == secondThis test compares dictionaries of floats with ==. That is correct here because RandomForest with a fixed random_state on a single machine is bit-for-bit repeatable. For other libraries, such as GPU training or multi-threaded gradient boosting, tiny floating-point differences can appear even with fixed seeds. In that case compare with a tolerance:
def test_pipeline_is_deterministic_within_tolerance():
cfg = TrainConfig()
_, first = run_pipeline(cfg)
_, second = run_pipeline(cfg)
assert first["accuracy"] == pytest.approx(second["accuracy"], abs=1e-9)Pick the tolerance deliberately. A tolerance of 0.05 would hide the very seed bugs this test exists to find.
A second reproducibility test checks the opposite direction: different seeds must be able to give different splits. If they never do, the seed is not reaching train_test_split.
def test_seed_changes_the_split():
X, y = load_data()
a = split(X, y, TrainConfig(seed=1))
b = split(X, y, TrainConfig(seed=2))
assert not np.array_equal(a[1], b[1])Testing the config fingerprint
The fingerprint identifies a run, so it must be stable for equal configurations and different for unequal ones.
def test_fingerprint_is_stable_and_sensitive():
assert config_fingerprint(TrainConfig()) == config_fingerprint(TrainConfig())
assert config_fingerprint(TrainConfig()) != config_fingerprint(
TrainConfig(n_estimators=101)
)
assert len(config_fingerprint(TrainConfig())) == 12Testing the evaluation gate
The gate is a stage that decides whether a model may move on, so it deserves tests of its own. Test both sides of the threshold. A gate that never fires and a gate that always fires both look fine if you only test one side.
def test_gate_passes_when_threshold_is_met():
cfg = TrainConfig(min_accuracy=0.5)
_, metrics = run_pipeline(cfg)
assert metrics["accuracy"] >= 0.5
def test_gate_blocks_when_threshold_is_unreachable():
cfg = TrainConfig(min_accuracy=1.01)
with pytest.raises(ValueError, match="below the gate"):
run_pipeline(cfg)Setting min_accuracy=1.01 makes failure certain, because accuracy cannot exceed 1.0. This lets you test the failure path without needing a deliberately bad model.
How the tests fit together
The tests form a pyramid. Many fast unit tests sit at the bottom, and fewer slower pipeline tests sit above them.
When a pipeline test fails, look at the unit tests first. If they all pass but the smoke test fails, the fault is in how the stages are connected.
Common errors
- Testing with the production dataset size. Tests that take minutes get skipped. Use a sample or synthetic data, and keep the full run for the real job.
- Asserting a model-quality number as a unit test. A line such as
assert accuracy > 0.97fails when someone changes a seed or library version. Quality belongs in the gate, which is configured. Tests should check behavior. - Tests that depend on each other or on files left by earlier runs. Each test must create what it needs. Use pytest's
tmp_pathfixture for any output files. - Forgetting that global state leaks. If a stage reads
numpy.randomdirectly instead of a seed from the config, the determinism test may pass in isolation and fail when the test order changes. Passing the seed explicitly, asTrainConfigdoes, avoids this. - Comparing floats with
==where tolerance is needed. See the tolerance example above. - Never testing the failure path. Gates, retries, and input validation are all failure behavior. Test that they fail.
Running the tests
From the directory holding both files, install the dependencies and run pytest.
pip install scikit-learn numpy pytest
pytest -qTo run only the fast tests during development, mark the slow ones. A marker registered in pytest.ini lets you choose.
import pytest
@pytest.mark.slow
def test_full_size_pipeline():
from pipeline import TrainConfig, run_pipeline
_, metrics = run_pipeline(TrainConfig(n_estimators=500))
assert metrics["accuracy"] >= 0.8[pytest]
markers =
slow: tests that take more than a few secondsRun pytest -m "not slow" on every save and plain pytest in CI.
Exercises
Exercise
A teammate adds a new stage that drops rows with missing values. Which kind of test would you write first for that stage, and what is one property it should check?
Show answer
A unit test on the stage alone, using a small synthetic array that contains missing values. It should check that no missing values remain in the output and that rows without missing values are all kept, so the output length equals the input length minus the number of incomplete rows. A smoke test of the full pipeline should then confirm the new stage is connected in the correct order.
Exercise
The determinism test passes on your laptop but fails in CI with a difference of about 1e-12 in accuracy. Name two likely causes and say how you would change the test.
Show answer
Likely causes are different library versions or CPU and thread behavior in the CI environment, which change the order of floating-point operations. Also check that the environment is pinned the same way. Change the test to compare with a tight tolerance, for example pytest.approx(second["accuracy"], abs=1e-9), instead of ==, and keep the tolerance small enough that a missing seed would still be detected.
Exercise
Why does test_gate_blocks_when_threshold_is_unreachable use min_accuracy=1.01 instead of training a deliberately bad model?
Show answer
Accuracy cannot exceed 1.0, so a threshold of 1.01 guarantees the gate fires for any model. This tests the failure path directly, is fast, and does not depend on how a bad model happens to behave.