Sub topic 2
A layered test strategy: what to test where
Assume you know Python and basic pytest, can work with Git pull requests, and have trained a model with scikit-learn or a similar library. This chapter shows how to divide an ML test suite so that each failure points to a useful cause.
Why ML needs several test layers
A conventional software feature usually depends on source code and a small set of inputs. An ML system depends on more:
- Source code, such as feature transformations and training logic.
- Data schema, values, and distributions.
- Model behavior and quality metrics.
- Configuration, dependencies, and random-number generation.
A change can leave the code valid while making the training data unusable. A model can load successfully while returning invalid probabilities. A new feature transform can pass its own test but break the complete pipeline.
A layered strategy tests each responsibility at the cheapest useful boundary.
| Layer | Main question | Typical speed |
|---|---|---|
| Code unit tests | Does one function behave correctly? | Very fast |
| Data tests | Does the input meet its contract? | Fast |
| Model tests | Does the trained model behave as required? | Medium |
| Pipeline smoke tests | Do the components work together? | Slowest |
The test flow
Run the layers from narrow to broad. A failure in a unit test should be fixed before spending time training a model.
This order is a practical default, not an absolute rule. Some model behavior tests need a small trained model, while others can use a saved fixture. Keep those tests independent from production-sized data.
Code unit tests
Unit tests check one function in isolation. For ML projects, common targets include:
- Missing-value handling.
- Encoding and scaling.
- Feature selection.
- Label conversion.
- Configuration parsing.
Test both ordinary inputs and the errors that callers should receive. For floating-point calculations, compare with a tolerance instead of requiring exact binary equality.
import pytest
def scale_income(income: float, median: float) -> float:
if median <= 0:
raise ValueError("median must be positive")
return income / median
def test_scale_income_basic():
assert scale_income(50_000.0, 25_000.0) == pytest.approx(2.0)
def test_scale_income_rejects_bad_median():
with pytest.raises(ValueError):
scale_income(50_000.0, 0.0)These tests should not read a remote data store or train a full model. Small, direct inputs make failures quick to reproduce.
Data contract tests
Data tests verify the contract between a dataset and the training code. A contract describes what the code expects, such as:
- Required column names.
- Data types.
- Allowed ranges and categories.
- Maximum missing-value fractions.
- Non-empty input.
Store a small representative sample in the repository or in a versioned test-data location. Test it in CI. A schema test catches accidental column renaming before the training job produces a misleading model.
Data validity is different from data usefulness. A dataset can have the right columns and still represent a new population. Distribution or drift checks belong beside these tests, but they often need a reference dataset and a separately chosen tolerance.
Model behavior tests
Model tests verify properties that should remain true across implementations. They should avoid asserting one exact prediction unless that prediction is part of a fixed, documented contract.
Useful properties include:
- The output has the expected shape.
- Class probabilities are between zero and one.
- Probability rows sum to one.
- Predictions do not depend on input row order.
- The model rejects an incompatible feature shape.
- A seeded training run produces stable results within a tolerance.
These tests catch wiring errors that ordinary accuracy checks can miss. A model may achieve a plausible score while swapping class labels or returning predictions in the wrong order.
Pipeline smoke tests
A smoke test runs the smallest realistic path through the system: load a tiny dataset, validate it, transform it, train or load a model, and produce evaluation metrics. It answers, “Can the pieces work together?”
Keep this test separate from unit tests because it is slower and has more dependencies. Use a tiny committed fixture and fixed settings. Do not use it as the only test: a smoke-test failure tells you that something is broken, but narrow tests help identify why.
Choosing checks for each trigger
Run fast, deterministic unit and data tests on every pull request. Run small model behavior tests there when their runtime is predictable. Schedule expensive full-data training, drift analysis, and large evaluation jobs, or run them on demand before release.
Record which layer failed and retain the relevant logs and metrics. This makes a CI result actionable instead of reducing it to a single red status.
Exercise
A feature function passes its unit tests, but the pipeline fails because the transformed matrix has the wrong number of columns. Which additional layer should detect this, and why?
Show answer
A pipeline smoke test should detect it by running the transformation with the model or downstream step. A unit test checks the function in isolation, while the smoke test checks the component boundary and feature contract.