What the counterexample is#
Hypothesis generates inputs from strategies, and when one fails a test it shrinks it. Its glossary describes the result: the minimal failing test case is the failing case "which has been fully shrunk (minimized) by Hypothesis", and "Hypothesis reports only the minimal failing test case to the user at the end of the test." The shrunk input is usually small enough to read at a glance, which is what makes the next step possible. A failure has three possible owners: the code, the property (the assertion), or the strategy (the inputs it allowed). The counterexample tells you which once you compare it with what the code promises.
This constructed module has two documented functions:
def encode_reading(x: float) -> str:
"""Serialize a sensor reading. Every float, including NaN and the
infinities, is accepted and round-trips through decode_reading."""
return json.dumps({"v": x})
def decode_reading(s: str) -> float:
return json.loads(s)["v"]
def split_evenly(total: int, parts: int) -> list[int]:
"""Split total into `parts` integers that sum to total and differ
by at most 1. Requires total >= 0 and parts >= 1."""
base = round(total / parts)
return [base] * (parts - 1) + [total - base * (parts - 1)]
The tests below ran with Hypothesis 6.170.17, pytest 9.2.0 and Python 3.11.18.
A wrong property: equality on NaN#
The round-trip test uses the strategy st.floats(), which includes NaN and the infinities, as the docstring promises:
@given(st.floats())
def test_reading_round_trips(x):
assert decode_reading(encode_reading(x)) == x
x = nan
> assert decode_reading(encode_reading(x)) == x
E assert nan == nan
E + where nan = decode_reading('{"v": NaN}')
E + where '{"v": NaN}' = encode_reading(nan)
E Failing test case: test_reading_round_trips(
E x=nan,
E )
Not every run finds it: in three runs here with a fresh example database, one generated no NaN and passed. NaN is inside the contract, so the input is valid. The output is valid too: the encoder wrote NaN, which the Python 3.11.18 json documentation specifies for the default setting ("If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used"), and the decoder returned a NaN. The failing piece is ==: a NaN never compares equal to anything, including itself. The property demanded identity under a comparison that cannot express it for this input. Fix the assertion:
@given(st.floats())
def test_reading_round_trips(x):
y = decode_reading(encode_reading(x))
assert y == x or (math.isnan(x) and math.isnan(y))
It passes without narrowing the strategy.
A wrong strategy: inputs the contract excludes#
The first version of the split test allowed any integer for parts:
@given(st.integers(min_value=0, max_value=10_000), st.integers(max_value=50))
def test_split_evenly_unchecked(total, parts):
shares = split_evenly(total, parts)
assert sum(shares) == total
Hypothesis reports two distinct failures, each shrunk separately:
| ExceptionGroup: Hypothesis found 2 distinct failures. (2 sub-exceptions)
| AssertionError: assert -1 == 1
| + where -1 = sum([-1])
| Failing test case: test_split_evenly_unchecked(
| total=1,
| parts=-1,
| )
...
| ZeroDivisionError: division by zero
| Failing test case: test_split_evenly_unchecked(
| total=0, # or any other generated value
| parts=0,
| )
Both look like code bugs, and a ZeroDivisionError reads like a crash. Neither input is valid: the docstring says "Requires total >= 0 and parts >= 1." The fix is st.integers(min_value=1, max_value=50) for parts, which encodes the precondition. If the contract had said the function raises ValueError on bad input, the same counterexamples would have been code bugs, because the function raises a different exception and returns a wrong sum instead.
The disconfirming counterexample: a valid input and a broken promise#
With the strategy fixed and the full contract written as assertions, the test fails again:
@given(st.integers(min_value=0, max_value=10_000), st.integers(min_value=1, max_value=50))
def test_split_evenly(total, parts):
shares = split_evenly(total, parts)
assert len(shares) == parts
assert sum(shares) == total
assert max(shares) - min(shares) <= 1
total = 2, parts = 4
> assert max(shares) - min(shares) <= 1
E assert (2 - 0) <= 1
E + where 2 = max([0, 0, 0, 2])
E + and 0 = min([0, 0, 0, 2])
E Failing test case: test_split_evenly(
E total=2,
E parts=4,
E )
This one flips the verdict. total=2, parts=4 meets both preconditions, and the result [0, 0, 0, 2] breaks the documented promise that shares differ by at most 1. The code is wrong. The shrunk input also points at the cause: 2 / 4 is exactly 0.5, and the Python documentation for round says "if two multiples are equally close, rounding is done toward the even choice", giving round(0.5) as its own example of a result of 0. So base is 0 and the last share absorbs the remainder. Rounding was the wrong tool for the job, so the fix replaces it with divmod:
q, r = divmod(total, parts)
return [q + 1] * r + [q] * (parts - r)
With that change, the corrected round-trip test and the split test pass (2 passed, 1 deselected in 0.20s, the deselected test being the narrowed one discussed below). Pin the counterexample so it runs on every build. The replaying failures page describes @example as adding "an explicit input which Hypothesis will run every time". Do not rely on Hypothesis's example database for that: the same page says that by default it is "in the local .hypothesis directory", which CI machines often discard.
Why narrowing the strategy is the risky fix#
The quick response to the NaN failure is to stop generating NaN. Hypothesis's own introduction does that for a sorting test, because "sorting in the presence of nan is not well defined. As a result, we may decide that we don't want to generate them while testing." That is right when the contract excludes NaN. When the contract includes it, the narrowed test stops checking a promise.
To see the cost, this variant of the encoder breaks the promise by switching to strict JSON:
return json.dumps({"v": x}, allow_nan=False)
Against it, a test using st.floats(allow_nan=False, allow_infinity=False) passes. The test with the full strategy and the corrected assertion fails:
E ValueError: Out of range float values are not JSON compliant
E Failing test case: test_reading_round_trips(
E x=inf,
E )
FAILED test_fixed.py::test_reading_round_trips - ValueError: Out of range flo...
1 failed, 2 passed in 0.48s
The docstring promises infinities and NaN. The narrowed strategy would have let this regression through. So when you decide a property is wrong, fix the assertion to state the contract, and narrow the strategy only to match a documented precondition.
Decide from the contract#
| What the counterexample shows | Evidence to collect | Decision |
|---|---|---|
Input the contract excludes (here parts=0) | The documented precondition | Fix the strategy to encode the precondition |
| Valid input, result breaks a documented promise | The docstring or specification and the shrunk input | Fix the code; pin the input with @example |
| Valid input, valid output, assertion cannot express it (NaN equality) | Whether the output satisfies the contract | Fix the assertion, keep the strategy |
| Valid input, property asks for more than the contract (uniqueness, ordering) | The documented promise | Fix the property, or file the missing promise |
| No written contract for the input | The callers that can produce it | Write the contract down, then decide |
The counterexample is a ready regression test, as the guide to turning a comment into a test describes. When a property test fails only sometimes, the guide to flaky test comments covers what to check before blaming the input.