Sub topic 2
A Layered Test Strategy: What to Test Where
This chapter assumes you can write pytest tests, work with pull requests, and have trained a model with scikit-learn or a similar library. Here you will decide which kind of check belongs at which point in the pipeline. The chapters that follow cover each layer in detail.
Why one test suite is not enough
An ML project can break in three places: the code, the data, and the model. A single flat folder of tests blurs these together. When a test fails, you can't tell whether a function has a bug, an upstream file changed, or the model got worse. A flat suite also tends to be slow, because a cheap check on a helper function sits next to a test that trains a model.
A layered strategy fixes both problems. Each layer targets one kind of failure, uses the smallest input that can expose it, and runs at the cheapest point where it is still meaningful. Cheap layers run first, so most mistakes fail within seconds.
The layers
| Layer | What it checks | Typical input | Typical cost | Failure usually means |
|---|---|---|---|---|
| Code unit tests | Feature and preprocessing functions behave correctly, including error cases | Hand-written values | Milliseconds | A logic bug in code |
| Data tests | Schema, dtypes, value ranges, missing values | A small committed sample file | Under a second | Validation rules or the data contract changed |
| Model behavior tests | Output shape, valid probabilities, invariances | A tiny seeded model on synthetic data | Seconds | The training or inference code changed behavior |
| Quality gate | Candidate metrics against an absolute floor and a baseline | Metrics from an evaluation run | Seconds, once metrics exist | The model got worse |
| Pipeline smoke test | Load, preprocess, train, evaluate, and save all connect | A few hundred rows | Seconds to a minute | A wiring or interface break between stages |
The diagram shows the order in which the layers run and where a failure stops the run.
The order is a cost ordering, not a strict dependency. The smoke test could run earlier, but a pipeline that can't pass a function-level test is a waste of a longer run.
Principles for placing a check
Three questions decide where a check belongs.
- What is the smallest input that can show this failure? A scaling bug needs one number, not a dataset. A schema break needs a sample file, not a full table. Choosing the smallest input keeps feedback fast.
- Is the result deterministic? Code and schema checks give the same answer every run. Model checks depend on seeds and library versions. Keep nondeterministic checks away from the layers that must be exact, and give them tolerances. Reproducibility has its own chapter.
- Who should act on the failure? A code failure goes to the author of the pull request. A data failure may need the data owner. Layers that map cleanly to owners make triage fast.
Assign each bug to the cheapest layer that catches it
| Bug | Cheapest layer that catches it |
|---|---|
| Income scaling divides by zero when the median is 0 | Code unit test |
| An upstream export renames `age` to `customer_age` | Data test |
| `label` contains the value 2 after a join | Data test |
| Predictions change when input rows are reordered | Model behavior test |
| Accuracy falls from 0.91 to 0.84 after a feature change | Quality gate |
| The training script reads a config key that the loader no longer produces | Pipeline smoke test |
If a bug is only caught by a smoke test, ask whether a cheaper test could have caught it. Often a missing unit test is the cause, and adding one gives faster feedback next time.
Organizing the test suite
Mirror the layers in the directory structure. This lets the CI workflow run whole layers by path, and it tells a reader where a new test belongs.
tests/
unit/ # feature and preprocessing functions
data/ # validation logic and the committed sample
sample.csv
model/ # behavioral tests on a tiny seeded model
gate/ # quality gate logic
smoke/ # end-to-end run on a small sampleDirectories handle most of the separation. Add a pytest marker for the few tests that are too slow for every pull request. The conftest.py below skips tests marked slow unless you pass --runslow. It is the pattern from the pytest documentation.
# tests/conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption(
"--runslow",
action="store_true",
default=False,
help="run tests marked slow",
)
def pytest_configure(config):
config.addinivalue_line(
"markers", "slow: tests that train on more than a small sample"
)
def pytest_collection_modifyitems(config, items):
if config.getoption("--runslow"):
return
skip_slow = pytest.mark.skip(reason="need --runslow option to run")
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)A developer running pytest locally gets fast feedback. A scheduled job runs pytest --runslow for the heavy checks.
Share the expensive setup
Model tests need a trained model, and training it for every test wastes time. A session-scoped fixture trains once and shares the result. Because the model is tiny and seeded, every test sees the same object.
# tests/model/conftest.py
import pytest
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
@pytest.fixture(scope="session")
def small_model():
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
model = LogisticRegression(max_iter=200)
model.fit(X, y)
return model, X
# tests/model/test_shapes.py
def test_predict_returns_one_label_per_row(small_model):
model, X = small_model
assert model.predict(X).shape == (len(X),)Session-scoped fixtures should not be modified by tests. If a test needs to change the model, it should build its own copy.
What each layer should not do
Layers fail in predictable ways when they take on the wrong job.
- Unit tests that check model quality. An assertion like "accuracy is above 0.9" does not belong in a unit test. It depends on data and training, so it will fail for reasons unrelated to the code under test. Put it in the quality gate.
- Data tests that need production data. CI should not pull a full production table on every pull request. It costs money, may expose private data, and makes the build depend on an external system. The committed sample tests your validation code. Checking real, fresh data belongs in the pipeline at run time and in scheduled jobs.
- Model tests that depend on exact numbers. Asserting that a coefficient equals 0.4132 breaks on a library upgrade. Assert properties instead: shapes, ranges, invariances, and approximate equality.
- Smoke tests that duplicate everything. A smoke test checks that stages connect and produce outputs of the right form. It is not a place to re-verify every function.
Avoiding duplicated checks
When two layers test the same property, a single failure produces two red tests, and both need fixing when the rule changes. Pick one home for each rule. The valid range for age belongs in the validation function, tested once by the data layer. The model layer should not re-check it. Reuse the function wherever it is needed instead of copying the rule.
A related trap is a test that only restates the implementation. A test that recomputes income / median in the assertion proves little. Prefer hand-computed expected values, such as 50,000 divided by 25,000 equals 2.
Reading a failure
Because layers map to failure types, the first red job gives you a starting hypothesis.
| First failing layer | Likely cause | First action |
|---|---|---|
| Code unit tests | Logic change in a function | Read the diff in the changed module |
| Data tests | Schema or range rule changed, or the sample was edited | Check whether the data contract changed on purpose |
| Model behavior tests | Training or inference change | Compare against the previous commit's model tests |
| Quality gate | Real metric regression, or a gate that is too tight | Inspect metrics, then decide whether to fix the model or adjust the threshold with justification |
| Smoke test | Interface mismatch between stages | Run the pipeline script locally on the sample |
Because later layers are skipped once an earlier one fails, you see the cheapest and most specific failure first. Fix it, rerun, and the next layer may reveal a second problem. That is expected.
A short checklist for adding a test
Before adding a test, decide the following:
- Which failure does it catch, and could a cheaper layer catch it?
- What is the smallest input that triggers the failure?
- Is it deterministic? If not, what tolerance or seed makes it stable?
- Does it duplicate a rule already tested elsewhere?
- Is it fast enough for every pull request, or should it carry the
slowmarker?
Exercise
Your team's pull-request build takes 25 minutes because one test trains a model on the full dataset and asserts accuracy above 0.9. That test also fails randomly when the training split changes. Using the layers from this chapter, describe how you would restructure it. Say what moves where, and which part runs on every pull request.
Show answer
Split the test into pieces by purpose. (1) Behavioral checks such as output shape, valid probabilities, and row-order invariance move to the model layer. They run on a tiny seeded model built from synthetic data, so they take seconds and run on every pull request. (2) The accuracy assertion moves to a quality gate that compares evaluation metrics with an absolute floor and a baseline drop limit. Fix the seed and the split so the metric is stable, and use a tolerance instead of a single magic number. (3) A smoke test on a few hundred rows replaces full-data training for checking that the stages connect. (4) Anything that still needs the full dataset gets the slow marker and runs in a scheduled job with --runslow. After this change the per-pull-request build holds only fast tests, and each failure points to one kind of problem.