Sub topic 14
Testing the Parts That Can Break Quietly
Assume you know basic Python, Git, the command line, and have trained a model with scikit-learn or PyTorch. This chapter focuses on tests for machine learning projects. These tests catch incorrect inputs, configuration mistakes, data leakage, and changes that produce plausible but wrong results.
What to test
A model can fail loudly when Python raises an exception. More dangerous failures produce valid output with the wrong meaning. For example:
- A feature column is renamed, but the data loader silently drops it.
- A configuration override remains a string, such as
"0.01", instead of becoming a number. - The test set is accidentally used during preprocessing.
- A pipeline writes output to the wrong directory.
- A random change makes results vary between runs.
- A model predicts successfully after the feature order changes.
Test small pieces before testing a complete training run. Small tests are faster and make failures easier to locate.
Test contracts at boundaries
A boundary is a point where one part of the project hands data to another part. Define what is allowed at each boundary.
For a prepared feature table, a contract might require specific columns, numeric values, and at least one row. A test should check these rules directly rather than relying on training to expose a problem.
# tests/test_prepare.py
import pandas as pd
import pytest
from my_project.data.prepare import validate_features
def test_validate_features_accepts_expected_columns():
frame = pd.DataFrame(
{"age": [21, 35], "income": [40_000, 65_000]}
)
result = validate_features(frame)
assert list(result.columns) == ["age", "income"]
assert len(result) == 2
def test_validate_features_rejects_missing_columns():
frame = pd.DataFrame({"age": [21]})
with pytest.raises(ValueError, match="income"):
validate_features(frame)The pytest.raises block checks that invalid input raises the expected exception. The match argument also checks that the error identifies the missing field.
Test configuration and randomness
Configuration tests should verify both values and types. A test that only checks whether loading succeeds may miss a string-to-number error.
Test seeding when randomness affects preprocessing, splitting, or model initialization. Call the same seeded function twice and compare its results. For floating-point model metrics, use a tolerance instead of requiring exact equality.
def test_apply_overrides_parses_types():
raw = {"learning_rate": 0.1}
output = apply_overrides(
raw, ["learning_rate=0.01", "batch_size=32"]
)
assert output["learning_rate"] == 0.01
assert output["batch_size"] == 32
assert isinstance(output["batch_size"], int)Test against leakage
Data leakage happens when information from evaluation data influences training. Keep a small fixture dataset and test that preprocessing fits only on the training portion. Also check that the test split has no shared row identifiers with the training split.
Run tests in continuous integration
Run fast unit tests on every commit. Add a small integration test that loads a fixture, runs one training step, and verifies that the expected model artifact exists. Keep large datasets and long training jobs outside the normal commit check.
Exercise
A feature loader receives a table with an extra column and silently ignores it. What test should you add?
Show answer
Add a schema test that either rejects unknown columns or explicitly records the accepted schema. Choose one policy and test it so future changes cannot alter it silently.