Sub topic 9
Smoke-testing the Whole ML Pipeline on a Small Sample
This chapter assumes that you know Python and pytest, have used Git pull requests, and understand the basic flow of training a scikit-learn model. A smoke test is a fast test that checks whether the main pipeline can run from input data to a useful output. It does not prove that the model is accurate.
Why a smoke test matters
An ML pipeline connects several parts:
- Data loading
- Validation
- Feature preprocessing
- Model training
- Prediction
- Metric calculation
- Artifact or metric output
A unit test checks one part in isolation. A smoke test checks that the parts work together. It can catch problems such as:
- A renamed column that the feature code still expects
- A preprocessing step that produces the wrong number of features
- A model that receives text instead of numeric values
- A training function that returns the wrong object
- A metric function that receives predictions with the wrong shape
- A missing configuration value
Use a small, committed dataset so the test stays fast and deterministic.
A small pipeline
The following example trains a classifier from a pandas DataFrame. The pipeline handles preprocessing and modeling together. The test uses a fixed sample instead of downloading data or reading a production data store.
# ml_pipeline.py
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.metrics import accuracy_score
FEATURES = ["age", "income", "plan"]
TARGET = "label"
def build_pipeline() -> Pipeline:
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
categorical = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("encode", OneHotEncoder(handle_unknown="ignore")),
])
preprocess = ColumnTransformer([
("numeric", numeric, ["age", "income"]),
("categorical", categorical, ["plan"]),
])
return Pipeline([
("preprocess", preprocess),
("model", LogisticRegression(max_iter=200, random_state=0)),
])
def train_and_evaluate(df: pd.DataFrame) -> dict[str, float]:
missing = set(FEATURES + [TARGET]) - set(df.columns)
if missing:
raise ValueError(f"missing columns: {sorted(missing)}")
model = build_pipeline()
model.fit(df[FEATURES], df[TARGET])
predictions = model.predict(df[FEATURES])
return {
"accuracy": float(accuracy_score(df[TARGET], predictions)),
"rows": float(len(df)),
}The smoke test supplies both classes in the target column. This matters because logistic regression needs more than one class during training.
# tests/test_pipeline_smoke.py
import pandas as pd
from ml_pipeline import train_and_evaluate
def test_pipeline_runs_on_small_sample():
sample = pd.DataFrame({
"age": [22, 31, 45, 58, 27, 39],
"income": [32000, 48000, 72000, 91000, 41000, 65000],
"plan": ["basic", "basic", "premium", "premium", "basic", "premium"],
"label": [0, 0, 1, 1, 0, 1],
})
result = train_and_evaluate(sample)
assert result["rows"] == 6
assert 0.0 <= result["accuracy"] <= 1.0Run it with:
pytest tests/test_pipeline_smoke.py -qThe test does not assert a high accuracy threshold. The sample is too small for a meaningful quality judgment. It asserts that the pipeline completes and returns a valid metric.
Designing a useful smoke test
Keep the test boundary clear:
- Build or load a tiny fixture.
- Run the same public pipeline function used by a training job.
- Check that the result exists and has the expected structure.
- Check basic invariants, such as row counts, metric ranges, and artifact paths.
- Avoid network calls, large files, and production credentials.
A smoke test can also verify that a saved model can be loaded and used for prediction. That check belongs in the smoke test when model serialization is part of the delivery path.
| Check | Smoke test question |
|---|---|
| Input | Can the pipeline read the expected columns? |
| Processing | Does preprocessing fit and transform the sample? |
| Model | Can training and prediction finish? |
| Output | Are metrics and artifacts produced in the expected form? |
Common failure modes
A smoke test is less useful when its fixture is too artificial. For example, an empty DataFrame may allow input validation to pass while missing a failure that occurs during model fitting. Include missing values and representative category values when those cases are valid in production.
Do not hide failures with broad exception handling. Let pytest show the original error. Also avoid using a separate test-only implementation of the pipeline. If the test calls different code from production, it can pass while the real job is broken.
Exercise
Why should a smoke test avoid using the full training dataset?
Show answer
A full dataset makes the test slow, costly, and harder to run on every pull request. A small realistic fixture checks pipeline wiring while larger quality and performance checks run separately.