Sub topic 5
Testing Stages and the Whole Pipeline
This chapter assumes you know Python functions, dataclasses, pytest, and the basic train–test workflow in scikit-learn. It also assumes your training code already has separate stages such as load_data, split, train, evaluate, and run_pipeline.
Testing a pipeline means checking both individual stages and the connections between them. A stage test finds local errors quickly. A full-pipeline test checks that the stages still work together after a change.
Test the boundaries between stages
Each stage should have an explicit contract. A contract describes the inputs it accepts and the outputs it returns.
| Stage | Input contract | Output contract |
|---|---|---|
| `load_data` | No arguments | Feature data `X` and labels `y` |
| `split` | `X`, `y`, and configuration | Training and test partitions |
| `train` | Training data and configuration | A fitted model |
| `evaluate` | Model and test data | A metrics dictionary |
| `run_pipeline` | Configuration | Model and metrics, or a gate failure |
Start with tests that check these contracts. Do not begin by checking every internal detail of a random forest. Internal implementation details can change while the stage’s contract remains valid.
Unit-test individual stages
A unit test checks one small piece of behavior in isolation. For example, a split test can verify that the configured test size is respected and that labels remain aligned with features.
# test_pipeline.py
import pytest
from training_pipeline import (
TrainConfig,
evaluate,
load_data,
run_pipeline,
split,
train,
)
def test_load_data_has_matching_rows():
X, y = load_data()
assert len(X) == len(y)
assert len(X) > 0
def test_split_preserves_rows_and_labels():
cfg = TrainConfig(test_size=0.2)
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
assert len(X_train) + len(X_test) == len(X)
assert len(y_train) + len(y_test) == len(y)
assert len(X_train) == len(y_train)
assert len(X_test) == len(y_test)
def test_train_produces_a_model_that_can_predict():
cfg = TrainConfig(n_estimators=10)
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)
assert "accuracy" in metrics
assert 0.0 <= metrics["accuracy"] <= 1.0
def test_pipeline_is_deterministic():
cfg = TrainConfig()
_, first_metrics = run_pipeline(cfg)
_, second_metrics = run_pipeline(cfg)
assert first_metrics == second_metrics
def test_pipeline_rejects_a_model_below_the_gate():
cfg = TrainConfig(min_accuracy=1.01)
with pytest.raises(ValueError, match="below the gate"):
run_pipeline(cfg)These tests cover normal behavior and an expected failure. The final test is important because an evaluation gate is part of the pipeline’s behavior, not merely a logging message.
The tests use small values such as n_estimators=10 when model quality is not the subject of the test. This keeps the suite fast. Use a fixed seed so that a test failure points to a code change instead of random variation.
Add smoke tests for the complete pipeline
A smoke test is a small end-to-end test. It runs the real stages together with a small, known configuration. It does not prove that the model is production-quality. It proves that the main path still executes and produces usable outputs.
def test_pipeline_smoke():
cfg = TrainConfig(
n_estimators=10,
min_accuracy=0.5,
)
model, metrics = run_pipeline(cfg)
assert model is not None
assert metrics["accuracy"] >= cfg.min_accuracyKeep this test separate from detailed unit tests. If a split test fails, you want a short failure that identifies the split contract. If only the smoke test fails, investigate the connection between stages or a missing dependency.
Test failures without making tests fragile
A useful test checks an observable promise. A fragile test checks an accidental implementation detail.
Prefer these assertions:
- The output has the required keys.
- Rows and labels remain aligned.
- A metric is within its valid range.
- A configured gate blocks an unacceptable result.
- The same configuration produces the same result when determinism is required.
Avoid asserting:
- The exact order of trees in an ensemble.
- A private attribute that the library may rename.
- A particular warning text unless the warning itself is part of your contract.
- A precise accuracy value when several valid models could achieve different values.
Use deliberately invalid inputs to test error handling. For example, a stage may reject an empty dataset or mismatched feature and label counts. These tests make failures easier to diagnose before an orchestrator retries the whole run.
Run tests locally and in CI
Run the test suite from the repository root:
python -m pytest -qA continuous integration system can run the same command for every pull request. Keep unit tests fast enough to run on every change. Run slower tests, such as large-data or hardware-specific tests, in a separate job.
The pipeline code should expose failures through its exit status. pytest returns a nonzero status when a test fails, and run_pipeline should raise an exception when the evaluation gate fails. CI can then stop before publishing or promoting the model.
Exercise
Why should a pipeline have both unit tests for individual stages and a smoke test for the complete run?
Show answer
Unit tests identify local contract violations quickly, while the smoke test checks that the real stages connect and complete successfully.