Sub topic 4
Unit Testing Feature and Preprocessing Code
This chapter covers the first layer of an ML test suite: ordinary unit tests for the functions that turn raw records into model inputs. It assumes you can write and run pytest tests, use Git and pull requests, and have trained a model with scikit-learn or a similar library.
Why feature code needs its own tests
Feature and preprocessing code is the part of an ML project that behaves most like conventional software. It takes defined inputs and returns defined outputs, and it has no randomness. It is also where many silent failures start. A function that divides by the wrong value, drops a column, or mishandles a missing entry will not crash. It will produce numbers, the model will train on them, and the metrics will be slightly worse. Nobody will connect the drop to the change that caused it.
A unit test pins the intended behavior of one function. It runs in milliseconds, needs no dataset and no trained model, and points directly at the broken function when it fails. That is why this layer sits at the base of the test strategy. Run it first on every pull request, and run it often.
What to test in a feature function
Treat each feature function as a small contract. For each one, decide what a caller can rely on, then write tests that check it. Five categories cover most of what goes wrong.
- Typical values. One or two inputs with a result you can compute by hand.
- Boundaries. Zero, the smallest and largest valid values, and the point where a rule changes, such as an age cutoff.
- Missing and invalid input.
None,NaN, empty strings, empty frames, and negative numbers where they make no sense. Decide whether the function should raise, return a default, or pass the value through. Then test that decision. - Output shape and type. The same number of rows as the input, the expected column names, and the expected dtype.
- Purity. The function should not modify its input, and the same input should always give the same output.
A first example: a scalar transform
Here is a transform that scales income by a median. The function states its contract in code: the median must be positive, otherwise it raises.
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)Two details matter here.
First, pytest.approx compares floats within a tolerance. Floating-point arithmetic can differ in the last digits between machines and library versions, so comparing floats with == produces tests that pass locally and fail in CI. The default tolerance is a relative error of 1e-6. Use rel= or abs= to set your own, and keep the tolerance as tight as the function justifies.
Second, the failure case is tested as deliberately as the success case. pytest.raises fails the test if no exception is raised, so a later change that removes the guard is caught.
Testing many cases with parametrization
Boundary and edge cases tend to multiply. Writing a separate function for each one is repetitive. pytest.mark.parametrize runs one test body against a table of inputs, and each row is reported as its own test.
import pytest
def scale_income(income: float, median: float) -> float:
if median <= 0:
raise ValueError("median must be positive")
return income / median
@pytest.mark.parametrize(
"income, median, expected",
[
(50_000.0, 25_000.0, 2.0),
(0.0, 25_000.0, 0.0),
(25_000.0, 25_000.0, 1.0),
(12_500.0, 25_000.0, 0.5),
],
)
def test_scale_income_cases(income, median, expected):
assert scale_income(income, median) == pytest.approx(expected)
@pytest.mark.parametrize("median", [0.0, -1.0, -25_000.0])
def test_scale_income_rejects_non_positive_median(median):
with pytest.raises(ValueError):
scale_income(50_000.0, median)When one row fails, pytest names it, for example test_scale_income_cases[0.0-25000.0-0.0]. You can see which case broke without opening the file.
Testing DataFrame transforms
Most preprocessing works on whole tables. Test these functions with small frames that you build by hand inside the test. A frame of three or four rows is enough, and the expected result can be written out in full, so a reader can verify it by eye.
The next function fills missing ages with the median, adds a flag that records which rows were filled, and bins the result into groups.
import numpy as np
import pandas as pd
import pandas.testing as pdt
def add_age_features(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
out["age_missing"] = out["age"].isna().astype("int64")
out["age"] = out["age"].fillna(out["age"].median())
out["age_group"] = pd.cut(
out["age"],
bins=[-np.inf, 17, 64, np.inf],
labels=["minor", "adult", "senior"],
).astype("object")
return out
def test_add_age_features_fills_and_flags():
df = pd.DataFrame({"age": [20.0, np.nan, 40.0]})
result = add_age_features(df)
expected = pd.DataFrame(
{
"age": [20.0, 30.0, 40.0],
"age_missing": pd.Series([0, 1, 0], dtype="int64"),
"age_group": ["adult", "adult", "adult"],
}
)
pdt.assert_frame_equal(result, expected)
def test_add_age_features_group_boundaries():
df = pd.DataFrame({"age": [17.0, 18.0, 64.0, 65.0]})
result = add_age_features(df)
assert result["age_group"].tolist() == ["minor", "adult", "adult", "senior"]
def test_add_age_features_does_not_modify_input():
df = pd.DataFrame({"age": [20.0, np.nan, 40.0]})
before = df.copy()
add_age_features(df)
pdt.assert_frame_equal(df, before)The tests use pandas.testing.assert_frame_equal instead of ==. Comparing two frames with == returns another frame, not a single boolean, so it cannot be used directly in an assert. assert_frame_equal compares values, dtypes, column order, and the index, and its error message shows exactly which cell differs. It also compares floats with a tolerance by default.
The second test targets the bin edges. With pd.cut, the right edge of each interval is included by default, so 17 falls in the first group and 18 in the second. Boundary tests like this one catch the off-by-one mistakes that occur when someone changes a threshold or a right= argument.
The third test checks purity. The function copies its input before changing it. Without that copy, the caller's frame would be modified, which can corrupt a training set that is reused later in the same process.
Testing fitted transforms and train/serve consistency
Some preprocessing learns parameters from data: a scaler learns a mean and a standard deviation, an encoder learns the list of categories. These transforms add a rule that the unit tests must protect. Parameters are learned on the training data only, and the same parameters are applied unchanged at prediction time.
Use scikit-learn's own components where you can, and test the behavior you depend on.
import numpy as np
import pytest
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def test_scaler_uses_training_statistics_only():
train = np.array([[1.0], [3.0]])
new = np.array([[5.0]])
scaler = StandardScaler().fit(train)
# mean 2.0, std 1.0, so 5.0 becomes 3.0
assert scaler.transform(new)[0, 0] == pytest.approx(3.0)
def test_encoder_ignores_unseen_category():
encoder = OneHotEncoder(handle_unknown="ignore")
encoder.fit(np.array([["red"], ["blue"]]))
row = encoder.transform(np.array([["green"]])).toarray()
assert row.tolist() == [[0.0, 0.0]]The first test fails if someone refits the scaler on the incoming batch, which would leak information from the prediction data and change the scale of each request. The second test documents what happens when the service sees a category that did not exist at training time. Without handle_unknown="ignore", the encoder raises an error in production. The test makes the decision explicit.
For code you wrote yourself, apply the same idea. Call fit on a small frame, call transform on a different frame, and assert that the output reflects the first frame's parameters.
Keeping the tests fast and focused
Unit tests are only useful if people run them, and people stop running slow tests. A few habits keep this layer cheap.
- Build inputs inside the test or in a fixture. Do not read the full training set.
- Keep each test about one behavior, so a failure has one meaning.
- Share setup through fixtures, not through global state.
- Do not train a model here. Tests that need a model belong to the model layer.
A fixture is a function that pytest runs to prepare input for tests. This one provides a small frame to several tests.
import numpy as np
import pandas as pd
import pytest
@pytest.fixture
def small_frame() -> pd.DataFrame:
return pd.DataFrame(
{
"age": [25.0, np.nan, 61.0, 17.0],
"income": [40_000.0, 52_000.0, np.nan, 0.0],
}
)
def test_fixture_has_expected_missing_counts(small_frame):
assert small_frame["age"].isna().sum() == 1
assert small_frame["income"].isna().sum() == 1pytest calls the fixture once for each test that asks for it, so every test gets a fresh frame. Tests cannot affect each other by changing it.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Comparing floats with `==` | Tests pass locally and fail on another machine | Use `pytest.approx` |
| Using `assert df1 == df2` | Raises an error about an ambiguous truth value | Use `assert_frame_equal` |
| Only testing typical values | Boundary and missing-value bugs reach the model | Add parametrized edge cases |
| Reading the real dataset in a unit test | Slow tests that depend on data that can change | Build small frames in the test |
| Fitting on test or incoming data | Leaked statistics and unstable scaling | Test that `transform` uses stored parameters |
| Not checking that input is unchanged | Hidden side effects between pipeline steps | Compare the input before and after the call |
Where this layer ends
Unit tests tell you that each function does what you intended on inputs you chose. They do not tell you that the real data looks like those inputs. A function that handles every case in your tests can still fail when a column arrives with a new type or a different unit. That is the job of data validation, the next layer, which checks the actual dataset against a schema and expected ranges.
Exercise
A function bucket_income(income) returns "low" below 30,000, "mid" from 30,000 up to but not including 100,000, and "high" from 100,000. Which input values should a parametrized test include, and why?
Show answer
Include values at and around each boundary: 29,999.99 ("low"), 30,000 ("mid"), 99,999.99 ("mid"), and 100,000 ("high"). Add 0 as the lower extreme and a negative value or NaN if the function should reject or handle it. Boundary values catch off-by-one errors where < is written as <=, which typical mid-range values like 50,000 would never reveal.
Exercise
A test for a function that normalizes a DataFrame column writes assert normalize(df) == expected_df. It raises "The truth value of a DataFrame is ambiguous". What should replace the assertion, and what else does the replacement check?
Show answer
Use pandas.testing.assert_frame_equal(normalize(df), expected_df). Besides the values, it checks dtypes, column names and order, and the index. It compares floats within a tolerance and reports the differing cells in its error message.
Exercise
You add a unit test showing that StandardScaler.transform on one new row gives a result based on the statistics from the training data. What production bug does this test guard against?
Show answer
It guards against refitting the scaler on incoming data at prediction time. Refitting would compute the mean and standard deviation from the request batch, which leaks information from the prediction data and gives a single-row request a standard deviation of zero or a scale that differs from training.