Sub topic 4
Unit Testing Feature and Preprocessing Code
Assume you know Python, pytest, pandas, and the basic train–test workflow for machine learning. This chapter focuses on testing transformations before they affect model training.
Feature code converts raw values into model inputs. Preprocessing code may fill missing values, scale numbers, encode categories, or create derived columns. A small defect can change every training example, so these functions need focused tests.
What a unit test should prove
A unit test checks one small behavior in isolation. For a feature function, test its contract:
- Which inputs are accepted?
- What output type and shape are returned?
- What value is produced for ordinary input?
- What happens at boundaries?
- Which invalid inputs raise an error?
Prefer deterministic functions. A function that receives values and returns transformed values is easier to test than one that reads files, accesses global state, or trains a model.
| Test target | Example assertion |
|---|---|
| Normal calculation | Income of 50,000 scaled by 25,000 equals 2.0 |
| Output type | The result is a `float` |
| Boundary value | Zero or an empty category follows the documented rule |
| Invalid input | A non-positive median raises `ValueError` |
A small preprocessing function
Suppose a training pipeline scales income by the training-set median. Scaling puts values on a comparable numeric scale. The median must be positive because division by zero is invalid and a negative median would indicate bad input for this feature.
Save this function in features.py:
def scale_income(income: float, median: float) -> float:
"""Scale income using a positive training-set median."""
if median <= 0:
raise ValueError("median must be positive")
return income / medianThe function has a narrow contract. It does not calculate the median itself. The caller must provide the median learned from training data. This separation prevents a test or prediction request from accidentally recomputing preprocessing statistics on new data.
Testing normal and failure cases
Save the following as test_features.py:
import pytest
from features import scale_income
def test_scale_income_basic():
assert scale_income(50_000.0, 25_000.0) == pytest.approx(2.0)
def test_scale_income_preserves_zero_income():
assert scale_income(0.0, 25_000.0) == pytest.approx(0.0)
def test_scale_income_rejects_zero_median():
with pytest.raises(ValueError, match="median must be positive"):
scale_income(50_000.0, 0.0)
def test_scale_income_rejects_negative_median():
with pytest.raises(ValueError, match="median must be positive"):
scale_income(50_000.0, -1.0)Run the test file from the project directory:
pytest test_features.py -qpytest.approx compares floating-point results with a small tolerance. Exact equality can fail because computers represent many decimal values approximately.
The pytest.raises context manager verifies both that an error occurs and, with match, that it has the expected message. This catches a useful class of regression: silently accepting invalid preprocessing parameters.
Testing dataframe transformations
For a pandas transformation, assert the resulting columns, values, and missing-value behavior. Keep the input small so a failure is easy to understand.
import pandas as pd
def add_income_per_age(df: pd.DataFrame) -> pd.DataFrame:
if (df["age"] <= 0).any():
raise ValueError("age must be positive")
result = df.copy()
result["income_per_age"] = result["income"] / result["age"]
return resultA test should also verify that the function does not unexpectedly mutate its input:
def test_add_income_per_age_does_not_mutate_input():
source = pd.DataFrame({"age": [25], "income": [50_000.0]})
original = source.copy(deep=True)
result = add_income_per_age(source)
pd.testing.assert_frame_equal(source, original)
assert result["income_per_age"].iloc[0] == pytest.approx(2_000.0)Copying the dataframe makes the transformation safer when the same input is reused by another pipeline step.
Common mistakes
- Testing only typical values and missing zero, empty, or invalid inputs.
- Comparing floats with
==when rounding can occur. - Using production data in a unit test instead of a tiny fixed example.
- Allowing a test to depend on the current time, random state, or network.
- Testing an entire training pipeline when a one-function test would identify the defect more clearly.
- Forgetting to test whether a dataframe was mutated.
Exercise
Why should a test for a dataframe transformation compare the input with a copy of the original input?
Show answer
It detects accidental mutation. A transformation that changes its input can corrupt later pipeline steps or make test results depend on execution order.