How to Test with Metamorphic Relations
Test functions whose correct output is hard to compute by asserting invariant relationships between pairs of inputs and their outputs.
On this page
Introduction
Some of the most important functions are the hardest to test with an oracle. A ranking algorithm, a compiler optimizer, a numerical solver, or a search index rarely has an output you can write down by hand, and a golden file only proves the code still does what it did, not that what it did was right. Metamorphic testing sidesteps the missing oracle by asserting relationships between the outputs of related inputs. If you do not know the exact answer, you can still know that doubling the input cannot make a monotonic result smaller, or that sorting a list twice leaves it unchanged. This article explains the technique, how to pick relations, and how to combine it with property-based generators.
When You Cannot Assert Expected Output
The standard test pattern is input, expected output, compare. That pattern fails whenever the expected output is not knowable: a machine-learning model predicts a value nobody can derive; a scheduling heuristic produces a plan whose cost nobody can precompute; a distributed query returns results whose ordering depends on timing. You are left either to hardcode a snapshot, which locks in current bugs, or to assert nothing, which is not a test. Metamorphic testing gives you a third option by comparing two executions of the same function rather than comparing one execution to a constant.
The relationship between the two executions is the oracle. It does not tell you the exact answer, but it does tell you whether two answers are consistent with a transformation you apply to the input. A function that violates the relationship is wrong, and you have caught it without ever computing the correct output.
What a Metamorphic Relation Is
A metamorphic relation is a statement of the form: if I transform the input in way T, then the output must transform in way S. For a function that returns the maximum of a list, T is “append a value no larger than the current maximum” and S is “the output is unchanged”. For a shortest-path function, T is “increase every edge weight by a constant” and S is “the path is unchanged”. For a numerical integration function, T is “double the whole input” and S is “the output doubles too”.
import math, random
def rel_permutation_invariant(sort_fn, data):
"""Sorting must be invariant under permutation of the input."""
shuffled = data[:]
random.shuffle(shuffled)
assert sort_fn(data) == sort_fn(shuffled), "sorting depends on input order"
def rel_max_append_non_larger(max_fn, data):
"""Appending a value <= current max must not change the max."""
current = max_fn(data)
assert max_fn(data + [current - 1]) == current
def rel_scale_integral(integrate_fn, f, lo, hi):
"""Scaling f by 2 must scale the integral by 2."""
base = integrate_fn(f, lo, hi)
scaled = integrate_fn(lambda x: 2 * f(x), lo, hi)
assert math.isclose(scaled, 2 * base, rel_tol=1e-9)
Choosing Relations for Real Systems
Good relations come from invariants the domain guarantees, not from properties you hope hold. For sorting: permutation invariance, and idempotence under a second application. For encoders and decoders: round-trip, decode(encode(x)) equals x. For monotone aggregation: adding a non-negative element never decreases the sum. For caches: a cache hit and a cache miss must return equal values. For paginators: the concatenation of consecutive pages equals the full result. Enumerate the transformations your system must respect and turn each into a relation with a concrete pair of inputs.
Prefer relations that are cheap to evaluate and that fail loudly. A relation that is only approximately true needs a tolerance, and a tolerance that is too wide hides bugs, so derive the tolerance from the algorithm’s own error bound rather than guessing. Document why each relation holds, so the next person does not delete it thinking it is arbitrary.
Combining with Property-Based Generators
A relation is only as strong as the inputs you try it on. Hand-written examples cover the cases you thought of; a generator searches the input space, including the empty list, the single element, the huge value, and the unicode string that breaks an assumption. A property-based testing library shrinks any counterexample to a minimal failing case, which turns a vague failure into a small, reproducible input.
from hypothesis import given, strategies as st
import random
def mysort(xs):
return sorted(xs)
@given(st.lists(st.integers()))
def test_sort_is_permutation_invariant(xs):
shuffled = xs[:]
random.shuffle(shuffled)
assert mysort(xs) == mysort(shuffled)
@given(st.lists(st.integers()))
def test_sort_is_idempotent(xs):
once = mysort(xs)
assert mysort(once) == once
@given(st.lists(st.integers()), st.floats(allow_nan=False, allow_infinity=False))
def test_max_append_non_larger(xs, extra):
if not xs:
return
current = max(xs)
candidate = min(extra, current)
assert max(xs + [candidate]) == current
Interpreting Failures
When a relation fails, the failure is meaningful: either the implementation is wrong or the relation is not actually an invariant. Before blaming the code, confirm that the relation is sound. If appending a value equal to the maximum is supposed to leave the maximum unchanged, make sure ties are handled the same way; if the relation assumed strict ordering, a duplicate can break it legitimately. Once the relation is confirmed sound, the counterexample is a bug report.
Shrinking is what makes metamorphic failures actionable. A generator that finds a failure on a hundred-element list will, if the library supports shrinking, hand you the two-element list that is the smallest failing case. Always preserve the shrunk counterexample as a regression test so the bug cannot return, and record the relation it violated.
Limits and Pitfalls
Metamorphic testing proves consistency, not correctness. A function that always returns zero satisfies many scale relations while being useless, so pair relations with at least one concrete example that pins down a known-true answer. Relations also do not replace an oracle for the parts of the system where you do have one; use them where the oracle is missing.
Beware relations that are true by construction. If the transform and the assertion both read the same internal state, the test cannot fail and gives false confidence. Design each relation so the transformation is applied to the input and the assertion reads only the output, and periodically mutate the implementation by hand to confirm the test actually catches the change.
Conclusion
Metamorphic testing restores the ability to test the untestable by asserting relationships between outputs instead of comparing to a fixed answer. Derive relations from the domain’s real invariants, generate varied inputs with a property-based library, shrink failures to minimal counterexamples, and keep at least one concrete example so consistency does not drift into meaninglessness. Combined with mutation testing to confirm the relations actually bite, this gives you a practical oracle where none existed.
Sources: Hypothesis documentation, Metamorphic testing (Chen et al.), Property testing overview.
FAQ
- How is metamorphic testing different from property-based testing?
- Property-based testing generates random inputs and checks a single property. Metamorphic testing compares two executions of the same function under a transformation of the input. They combine well: use a generator to supply varied inputs and a metamorphic relation as the assertion.
- Can metamorphic relations prove a function is correct?
- No. They prove consistency between related executions, which is a necessary condition, not sufficiency. A trivially wrong function can satisfy several relations, so pair them with at least one concrete example that fixes a known-correct answer.
Report a problem with this articleOpens a pre-filled issue on GitHub.