Definition
Hypothesis is a Python §12.23 library for property-based testing §10.7: a test states a property, a rule that must hold for every input of some kind, and the library generates many inputs and checks the rule on each. The test describes its inputs with strategies, objects that define which values may be generated, such as the integers from 0 to 16. When an input breaks the rule, Hypothesis shrinks it: it searches for a simpler input that still breaks the rule and reports that input. David R. MacIver started the project.
The idea
A function set_count(n) must accept a record count from 0 to 16 and reject every other value. A developer writes example tests for 0, 3 and 16, and all three pass. The implementation in fact rejects only negative values and values above 17, so it wrongly accepts 17, and no test asked about 17. Example-based tests check only the inputs that someone thought of. Property-based testing replaces “this input gives this output” with “for every input of this kind, this rule holds”, and lets a program choose the inputs.
A strategy is a fence around the inputs that Hypothesis may try. Hypothesis searches inside the fence, often thoroughly, and never outside it. Inside the fence, no particular value is promised in a given run. Whether a test covers the boundary values and the invalid inputs is therefore decided by reading where the fences stand and by naming the critical values explicitly, not by trusting the generator. The fence picture stops at one point: Hypothesis does not search inside the fence evenly. It deliberately favors small and special values, so a probability calculation that assumes every value is equally likely does not describe it.
How it works
A test imports the strategies with from hypothesis import strategies as st. The domain of a strategy is the set of values it can produce.
st.integers(min_value=a, max_value=b): the integers from to , both bounds included; a bound left out leaves that side unbounded.st.binary(max_size=k): byte strings of at most bytes.st.lists(e, max_size=k, unique=True): lists of at most elements produced by the strategye, never with the same element twice.st.one_of(s1, s2): a value from either strategy; its domain is the union of both domains.s.filter(p): only those values ofsfor which the functionpreturns true.
A Python decorator is a line that starts with @, written directly above a function definition, that wraps the function in extra behavior. The decorator @given(...) attaches strategies to a test function, which then runs under pytest §12.31 or Python’s unittest module. One run passes through four phases in order.
Explicit. Every input listed with the decorator
@example(...)is tried, in every run.Reuse. Inputs that failed in earlier runs are replayed from the example database, by default the directory
.hypothesis/examples.Generate. New inputs are drawn, by default 100; the setting
max_exampleschanges the number. Inputs rejected by a filter, or by a falseassume(condition)inside the test, do not count, and if too many are rejected, Hypothesis fails the test with a health-check error, its report that the strategies rarely produce usable inputs.Shrink. If an input failed, Hypothesis simplifies it, reports the simplest failing input it reaches and saves that input in the database.
Shrinking works on the record of how an input was built: the sequence of choices, such as “a list of length 3” or “the integer 41”, from which the strategy built it. The shrinker tries shorter and smaller choice sequences, builds the input again from each through the same strategy, and keeps a candidate when the test still fails with the same error. Every candidate therefore lies inside the strategy’s domain.
By default, a test call that takes longer than 200 milliseconds for one input fails the test (the deadline setting), and an input that failed and then passes when replayed produces a Flaky error, because the outcome depended on something besides the input. To see which classes of input a run reached, the test calls event("above 16"), or a similar label, for each class it meets; pytest run with the option --hypothesis-show-statistics then prints the percentage of inputs that recorded each label.
Worked example
The requirement: set_count(n) returns normally when and raises ValueError for every other integer. The implementation raises ValueError only when or , an off-by-one error that accepts 17. The boundary values are 0 and 16; the values just outside the range are and 17.
Test 1 uses the strategy st.integers(min_value=0, max_value=16) and the property “set_count(n) returns normally”. Its domain, , has values and excludes 17, so the test cannot detect the error however many inputs it draws. It passes in every run.
Test 2 uses st.integers(), with no bounds, and a two-sided test oracle §10.5, the rule that decides pass or fail: for the call must return normally, and otherwise it must raise ValueError. Now 17 lies inside the domain, but the error shows at exactly one value. Suppose, for illustration, that each input were drawn uniformly from the integers from to . One draw is 17 with probability . None of 100 independent draws is 17 with probability , so the run finds the error with probability about , under 5%. Hypothesis does not draw uniformly, but it promises no particular value either.
Test 3 is Test 2 plus the decorators @example(-1), @example(0), @example(16) and @example(17). With the explicit phase enabled, Hypothesis tries the supplied examples; 17 fails at once, and Hypothesis reports . Had the implementation accepted every value above 16, a generated failure such as could shrink to 17. The integer strategy tries to move toward zero, and 17 is the smallest failing positive value here. Keeping 17 as an explicit example tests that boundary directly.
Stated precisely
Let be a strategy, its domain, and the property, a check that passes or fails for one input. One run of a test decorated with @given(s) checks for every input in three sets: , the explicit examples; , the inputs replayed from the database; and , the generated inputs that were not discarded, a subset of with at most max_examples members. A passing run establishes that passed for every in , and , and nothing about any other input.
Let be a class of inputs, such as the integers above 16. Leaving replayed inputs aside: if shares no member with or with , no run ever tries a member of ; if shares a member with , every run tries one; if shares members with only, a run may or may not try one. When a run fails, the reported input fails , and the shrinker found no simpler failing input among the candidates it tried; a simpler one can still exist.
Both statements assume that the test depends only on its input. If it also depends on time, thread scheduling or files, a replayed input need not fail again, and Hypothesis reports Flaky. Their value further assumes that is a correct test oracle, one that expresses the requirement: a property that repeats the implementation’s own logic passes whenever the implementation repeats its own mistake.
Limits and common mistakes
A passing run is not a proof: Test 2 tries about 100 integers out of infinitely many. When the domain is small enough to list, exhaustive enumeration §10.33, which tries every value, gives a complete answer.
Strategies exclude classes silently. Common cases are a bound that stops at the largest valid value; unique=True, which never produces a duplicate; a max_size below a buffer’s capacity; a filter that removes zero; and st.text(), which produces Python text strings, so a parser that reads raw bytes never meets bytes that fail to decode as text. Such a parser needs st.binary().
Invalid inputs need their own oracle. A property that only says valid inputs work tests nothing about rejection; it must state what must happen to an invalid input, for example “raises ValueError and changes no state”.
Shrinking gives a simpler failing input, not the cause of the failure. The delta debugging §10.39 entry treats the reduction of failing inputs in general.
The example database is a local directory, and a seed, the starting value of Hypothesis’s random choices, reproduces only those choices. A build server that starts from a clean copy of the code replays no earlier failure, so copy each failure found into an @example(...) decorator, where it becomes a permanent regression test §10.4. Clocks, threads and other outside state must be controlled by other means; the deterministic replay §10.37 entry describes them.
A test that runs on a desktop computer says nothing about code compiled for a microcontroller §6.1, its interrupts §6.11 or its timing, unless the same code runs in the test.
Questions answered
Does a strategy cover the intended boundary and invalid cases?
A strategy does not cover the boundary and invalid cases automatically: a Hypothesis strategy produces only the values in its domain, the set that its bounds, sizes, filters and options allow, and even inside that domain it promises no particular value in a given run. The strategy st.integers(min_value=0, max_value=16), for example, produces integers from 0 to 16 with both bounds included, and never produces or 17, the first invalid value on each side.
To make sure of coverage, list the input classes the requirement defines, including each boundary value, the value just outside each boundary and each kind of invalid input, such as a wrong length, a duplicate or bytes that are not valid text. Check that every class lies in some strategy’s domain, given its inclusive bounds, size limits, unique option, filters and value type, and add a strategy for invalid values with st.one_of where needed. List every boundary value and just-outside value with @example, so that every run tries it. Give the property an oracle that states what rejection must look like. Finally, confirm which classes generation reached with event() and --hypothesis-show-statistics.
Related entries: Property-based testing (§10.7), Boundary-value testing (§10.31), Deterministic replay (§10.37), Delta debugging (§10.39), Test oracle (§10.5), Equivalence partitioning (§10.32). Further reading: [44].