Skip to main content

Metamorphic testing (K3)

Why This Matters

To test something you need to know the right answer: the test oracle. For an ML model you usually don’t. What is the correct loan score for a 40-year-old with an income of $60,000 and a credit score of 680? Nobody knows; that is why there is a model. Metamorphic testing gets around this. You cannot say what the right score is, but you can say how the score must change when you change the input. That turns the oracle problem into something you can automate.

It is one of the four K3 learning objectives of CT-AI v2.0: in the exam you derive metamorphic relations and follow-up test cases, and the question counts double.

What you will learn

  • Derive metamorphic relations from a specification or from common sense about the domain
  • Generate source and follow-up test cases from a relation, by hand and in code
  • Test a model that gives a slightly different answer every time, without flaky tests

Syllabus: AI-6.1.5 (apply metamorphic testing), HO-6.1.6 (hands-on metamorphic testing).

The idea

A metamorphic relation (MR) says how the output must change when you change the input in a specific way. You run the system twice:

  1. The source test case: an input, and its output. Ideally one that passed: an output you have checked, or at least find plausible. You often cannot say exactly what it should be.
  2. The follow-up test case: the input changed according to the relation, and its output.

The test checks the relation between the two outputs. If it does not hold, at least one of the two outputs is wrong, and you found that without knowing either right answer.

Examples:

SystemChange to the inputRelation between the outputs
Loan modelHigher credit score, rest the sameScore is not lower
Loan modelOther name, rest the sameScore is the same
Sentiment modelAdd “Overall, " in front of the reviewSame sentiment
Sentiment modelReplace “good” with “excellent”Sentiment is not more negative
House price predictorAdd a bedroom, rest the samePrice is not lower
Search engineAdd a filterResults are a subset of the results without it
Image classifierRotate the photo 5°Same class

The syllabus names three things a relation can check: invariance (the output stays the same under a change that should not matter: a name, a slight rotation, a synonym), monotonicity (the output moves in one direction with the input: more income, more bedrooms, more cigarettes smoked gives a lower predicted age at death) and consistency (related outputs agree with each other: the results with a filter are part of the results without it). Where do relations come from? From the requirements (“the decision must not depend on name or gender”), from domain knowledge (a bigger house is not cheaper) and from laws of the domain, such as physics (a heavier car needs a longer braking distance).

Derive relations by hand

This is how the exam asks it. The practice loan model takes: name, gender, age, income, credit score, years of employment and zip code. The bank says:

  • A higher credit score or a higher income must never lead to a worse decision.
  • Longer employment must never lead to a worse decision.
  • The decision must not depend on name or gender.

Source test case: Sam Taylor, male, 40, income $60,000, credit score 680, 4 years employed, zip 60601.

From each rule, derive a relation and a follow-up test case:

MRFollow-up test caseExpected relation
MR1 credit score upthe same, with credit score 760follow-up score ≥ source score
MR2 income upthe same, with income $90,000follow-up score ≥ source score
MR3 employment upthe same, with 10 years employedfollow-up score ≥ source score
MR4 namethe same, named Maria Taylorfollow-up score = source score
MR5 genderthe same, gender femalefollow-up score = source score

Two things to notice. Change one thing per follow-up test case: if you change name and gender together and the score changes, you don’t know which caused it. And one relation gives many test cases: MR2 holds for income $90,000, and also for $300,000. Follow-up test cases at the extremes are where the defects hide.

The problem with a model that varies

Ask the practice model the same question twice and the score differs by a few points: it adds noise, like many real models (dropout at inference, sampling, a model that is retrained every night). So “follow-up score = source score” fails by accident half the time, and “follow-up ≥ source” fails whenever the noise goes the wrong way. A flaky test is worse than no test: people learn to ignore it.

Two things fix it:

  • Average. Score each input 20 times and compare the averages. The noise averages out; a real effect does not.
  • Tolerance. Compare with a margin: “follow-up ≥ source − 3 points”, “the difference is at most 3 points”. The margin has to be bigger than the averaged noise and smaller than the effect you want to find. For this model the noise is ±5 points per call, so the average of 20 calls varies by about one point, and the defects you are looking for are 10 points or more.

The /predict/batch endpoint scores up to 100 applicants in one call, so 20 runs is one request. With a seed the whole batch is reproducible, and your test gives the same result on every run.

Write the tests

You continue in the practice project from the lesson Set up your practice project:

cd ai-testing-practice
source .venv/bin/activate          # Windows: .venv\Scripts\activate

Create the folder module-7 with the file module-7/test_metamorphic.py:

"""Lesson "Metamorphic testing (K3)": test a model without knowing the right answer, by relating outputs to each other."""
import pytest

APPLICANT = {
    "name": "Sam Taylor", "gender": "Male", "age": 40, "income": 60000,
    "creditScore": 680, "employmentYears": 4, "zipCode": "60601",
}
RUNS = 20        # the model is not deterministic: average over several runs
TOLERANCE = 3    # score points; the averaged noise stays well within this


def average_score(api, applicant, model="v1"):
    """Score the same applicant RUNS times in one batch call and return the mean score."""
    response = api.post(
        f"{api.base}/predict/batch",
        json={"applicants": [applicant] * RUNS, "model": model, "seed": 1},
        timeout=10,
    )
    response.raise_for_status()
    scores = [p["score"] for p in response.json()["predictions"]]
    return sum(scores) / len(scores)


def follow_up(**changes):
    return {**APPLICANT, **changes}

APPLICANT is the source test case and follow_up makes a follow-up test case by changing one or more fields. Now the monotonic relations, MR1 to MR3, as one parametrized test:

# MR1 and MR2: more of something good must never lower the score.
@pytest.mark.parametrize(
    "changes",
    [
        {"creditScore": 760},
        {"income": 90000},
        pytest.param({"income": 300000}, marks=pytest.mark.xfail(strict=True, reason="defect: very high income lowers the score")),
        {"employmentYears": 10},
    ],
    ids=["credit 680->760", "income 60k->90k", "income 60k->300k", "employment 4->10 years"],
)
def test_more_of_something_good_never_lowers_the_score(api, changes):
    source = average_score(api, APPLICANT)
    followup = average_score(api, follow_up(**changes))
    print(f"\n  source {source:.1f}  follow-up {followup:.1f}")
    assert followup >= source - TOLERANCE

And the invariance relations MR4 and MR5, for both versions of the model:

# MR3 and MR4: a change that should not matter must not change the score.
V1_BIAS = pytest.mark.xfail(strict=True, reason="defect: v1 uses gender and name")


@pytest.mark.parametrize(
    "changes",
    [{"name": "Maria Taylor"}, {"gender": "Female"}],
    ids=["name Sam->Maria", "gender Male->Female"],
)
@pytest.mark.parametrize("model", [pytest.param("v1", marks=V1_BIAS), "v2"])
def test_irrelevant_change_keeps_the_score(api, model, changes):
    source = average_score(api, APPLICANT, model)
    followup = average_score(api, follow_up(**changes), model)
    print(f"\n  {model}: source {source:.1f}  follow-up {followup:.1f}")
    assert abs(followup - source) <= TOLERANCE

The defects you will find are marked xfail(strict=True): expected to fail. The test run stays green while the defect is there, and turns red the day someone fixes it without telling you (strict=True makes an unexpected pass a failure). That is how you keep a known defect visible in a test suite without blocking every build.

Run it

pytest module-7 -v -s
module-7/test_metamorphic.py::test_more_of_something_good_never_lowers_the_score[credit 680->760]
  source 75.8  follow-up 90.0
PASSED
module-7/test_metamorphic.py::test_more_of_something_good_never_lowers_the_score[income 60k->90k]
  source 75.8  follow-up 85.1
PASSED
module-7/test_metamorphic.py::test_more_of_something_good_never_lowers_the_score[income 60k->300k]
  source 75.8  follow-up 54.3
XFAIL
module-7/test_metamorphic.py::test_more_of_something_good_never_lowers_the_score[employment 4->10 years]
  source 75.8  follow-up 79.7
PASSED
module-7/test_metamorphic.py::test_irrelevant_change_keeps_the_score[v1-name Sam->Maria]
  v1: source 75.8  follow-up 64.1
XFAIL
module-7/test_metamorphic.py::test_irrelevant_change_keeps_the_score[v1-gender Male->Female]
  v1: source 75.8  follow-up 60.0
XFAIL
module-7/test_metamorphic.py::test_irrelevant_change_keeps_the_score[v2-name Sam->Maria]
  v2: source 74.9  follow-up 75.0
PASSED
module-7/test_metamorphic.py::test_irrelevant_change_keeps_the_score[v2-gender Male->Female]
  v2: source 74.9  follow-up 75.2
PASSED

========================= 5 passed, 3 xfailed

Three defects, found without knowing a single correct score:

  • Income $300,000 lowers the score from 75.8 to 54.3: below the approval threshold of 60. The model treats a very high income as a fraud signal. Maybe that is intended, but then it is a business rule that should be written down, not something a tester discovers.
  • v1 gives Maria 12 points less than Sam, with everything else the same.
  • v1 gives a woman 16 points less than a man. That turns an approval into a borderline case.

Version 2 passes both invariance relations: name and gender were removed from the model. Does that make v2 fair? The exercise answers that.

See it fail

Remove the xfail from the v1 tests, to see what the failure looks like without the marker. In the parametrize line, replace pytest.param("v1", marks=V1_BIAS) with "v1" and run pytest module-7:

E       assert 11.774999999999991 <= 3
E        +  where 11.774999999999991 = abs((64.06500000000001 - 75.84))
E       assert 15.790000000000006 <= 3
E        +  where 15.790000000000006 = abs((60.05 - 75.84))
2 failed, 5 passed, 1 xfailed

A difference of 11.8 and 15.8 points with a tolerance of 3: no noise explains that. Put the marker back when you are done.

Limits of metamorphic testing

Metamorphic testing is powerful because it needs no expected results, and that is also where it can mislead you:

  • A wrong relation gives false confidence, or false alarms. “More income never lowers the score” sounds obvious, but if the bank really does treat a very high income as a fraud signal, the relation is wrong and the “defect” is a rule nobody wrote down. Validate relations before you rely on them: with a domain expert, against the requirements, or against a reference model.
  • Incomplete relations leave gaps. Five relations check five properties. Everything else the model does is untested.
  • It finds relational errors, not absolute ones. If the model gives every applicant a score 20 points too low, every relation still holds. Metamorphic testing cannot see that; ML functional performance testing against labelled data can.
  • It depends on the source test case. The syllabus advises starting from a source test case that passed: an input whose output you have checked, or at least find plausible. If the source output is already wrong, a follow-up test that agrees with it proves nothing. When you have no passing source tests at all, metamorphic testing still finds inconsistencies, but it cannot tell you which of the two outputs is the wrong one.

So use it alongside other techniques, not instead of them.

Exercise

  1. Version 2 no longer uses name and gender. Write an invariance relation for the zip code: moving to another zip code in the same city should not change the score. Use 60601 (Chicago) and 10001 (New York; also a big city, so not a fair “same city” test, but try it) and 60602 (Chicago). Run it for v1 and v2. What do you find?
  2. A sentiment model gives a review a score from −1 (negative) to +1 (positive). Derive three metamorphic relations, with one follow-up test case each, for the source review “The battery is good and the screen is bright.”
Show suggested answer
  1. Add a third case to the invariance test, or a test of its own:

    @pytest.mark.parametrize("model", ["v1", "v2"])
    @pytest.mark.parametrize("zip_code", ["60602", "10001"])
    def test_zip_code_does_not_matter(api, model, zip_code):
        source = average_score(api, APPLICANT, model)
        followup = average_score(api, follow_up(zipCode=zip_code), model)
        print(f"\n  {model} {zip_code}: source {source:.1f}  follow-up {followup:.1f}")
        assert abs(followup - source) <= TOLERANCE
    

    60602 passes for both models (74.9 and 74.8). 10001 fails for both: v1 drops from 75.8 to 58.7, and v2 from 74.9 to 54.5, a bigger drop than in v1. Version 2 removed name and gender but kept a penalty on a few zip codes, and a zip code can be a proxy for income, ethnicity or both. Passing the name and gender relations did not make v2 fair. This is why the lesson Testing for bias looks at outcomes per group and not only at which inputs a model uses.

  2. For example:

    • Invariance, neutral addition: “Overall, the battery is good and the screen is bright.” Same score (within a tolerance).
    • Monotonicity, stronger word: “The battery is excellent and the screen is bright.” Score not lower.
    • Negation: “The battery is not good and the screen is not bright.” Score lower than the source, and negative.

    Other good answers: change the product name (invariance), swap the two halves of the sentence (invariance), add a negative clause such as “but it broke after a week” (score lower).

Exam-style questions

Quiz

1. A model predicts the delivery time of a parcel from distance, weight and the day of the week. Which is a valid metamorphic relation?

  • A. The predicted delivery time for 100 km is 2 days
  • B. If the distance increases and everything else stays the same, the predicted delivery time does not decrease
  • C. The model’s accuracy on the test set is above 90%
  • D. The predicted delivery time is always a whole number of days
Show answer
B. It relates the outputs of a source and a follow-up test case. A is an expected result, which needs an oracle; C is a performance metric; D is a property of a single output, not a relation between two.
Quiz

2. Source test case: a credit model scores an applicant aged 30, income €40,000, female. The relation is “the score does not depend on gender”. Which is the right follow-up test case?

  • A. Aged 30, income €40,000, male
  • B. Aged 31, income €40,000, male
  • C. Aged 30, income €45,000, female
  • D. Aged 30, income €40,000, female, run again on the next day
Show answer
A. Only the input the relation is about is changed. B changes two inputs, so a different score cannot be attributed to gender. C tests another relation (income). D repeats the source test case: that tests determinism, not this relation.
Quiz

3. A model adds random noise to its output. A metamorphic test compares one source run with one follow-up run, with no tolerance, and fails on about half of the runs. What should the tester do?

  • A. Remove the test, because metamorphic testing does not work for non-deterministic systems
  • B. Accept the failures as defects
  • C. Run each test case several times, compare the averages, and allow a tolerance that is larger than the remaining noise
  • D. Report a defect in the noise
Show answer
C. Metamorphic testing works for non-deterministic systems when the relation is checked statistically: averages over several runs and a tolerance chosen between the noise and the size of the effect you want to detect.

Your project so far

ai-testing-practice/
├── ...
├── module-3/
│   └── test_first_model.py
├── module-4/
│   └── test_metrics.py
├── module-6/
│   └── test_dataset_constraints.py
└── module-7/
    └── test_metamorphic.py    new in this lesson

The finished version is in the example repository: module-7/test_metamorphic.py.