Direct answer
Write the invariant before writing the generator, bound the inputs you generate, and keep the failing example when one appears. Hypothesis lets you define input ranges and selects examples, including edge cases the author may not have anticipated. A property states something true for every input in a class, and the framework searches that class for a case where it is false.
The workflow is five moves. Choose a behavior worth generalizing. State the invariant in plain language, independently of how the code works. Bound and describe the generated inputs. Run the property, and when a counterexample appears, keep it and shrink it. Decide whether the property or the code was wrong, then add a concrete regression test for the case that failed.
Generated inputs do not cover every possible case, and a passing property is not correctness. The value is that a broad class of inputs gets searched automatically, and that a counterexample is a specific, reproducible input you can hand to someone else.
Why hand-picked edge cases miss the ones that matter
A developer writing example-based tests chooses inputs they can think of. The choices cluster around the obvious boundaries: zero, one, empty, maximum. The failures that escape are usually combinations the author did not consider, such as a negative value alongside a specific string length, or a value just past a limit the author assumed was unreachable.
Property-based testing changes the search from a human one to a mechanical one. The author supplies the invariant and the input description. The framework supplies the examples, and it selects from the boundaries of the described ranges as well as from the middle. Hypothesis documents this selection behavior behind its own description of choosing examples and edge cases.
The economic argument is the one the cost per verified change guide makes: a test that searches a class of inputs is a different unit of verification from a test that asserts one example. The property costs more to write correctly and less per case it examines.
There is a corresponding loss, and it is the reason this post spends time on grounding. A property that is derived from the implementation rather than from intended behavior will pass on every input the code accepts, and it will find nothing. The search is only as good as the claim being searched.
Evidence and its limits
Official, F016: Hypothesis lets users define input ranges and selects examples, including edge cases the author may not have anticipated. Generation is constrained by the strategies and assumptions supplied. A property can only search the inputs its strategies describe.
Official, F017: Pytest parametrization supports parametrizing test functions and fixtures. That is the example-based complement to property generation: explicit named cases run alongside generated ones.
Derived, F018: Pair broad generated examples with a small concrete regression test after diagnosing a counterexample. This is a workflow recommendation, not a guarantee that the regression test is sufficient.
Official: Pact and Stryker appear in this post as neighboring techniques: a contract records consumer-used interactions, and a mutant tests whether an assertion could fail. SemVer is referenced only for the compatibility question that a behavior change can raise. Claude Code best practices supports a pass-or-fail check as the way to close a work loop.
No coverage percentage, defect-detection rate, or performance number is claimed. A passing property is not proof of correctness, and no benchmark is cited.
Choose a behavior worth generalizing
Not every behavior should become a property. A property pays off when the behavior has an invariant that holds across a class of inputs and can be stated without reference to the implementation. A single conditional branch with two outcomes is usually cheaper to test with two explicit examples.
Behaviors that generalize well share a shape. A function that transforms data and must preserve something, such as a serializer whose output parses back to the input. A function with a mathematical or logical identity, such as adding zero or applying an operation twice. A function that must produce output within constraints regardless of input, such as a validator that never accepts an invalid value. A function whose output must stay ordered or bounded whatever the input.
| Property | Input strategy | Invariant | Excluded cases |
|---|---|---|---|
| Round-trip encode and decode | Arbitrary strings, including empty and unicode | Decode(encode(x)) equals x | Inputs the encoder documents as unsupported |
| Validator never accepts invalid | Values outside the accepted set | Reject returns false, never throws | Values the schema defines as valid |
| Sort is idempotent | Arbitrary lists of integers | Sort(sort(x)) equals sort(x) | Lists the sort documents as unstable input |
| Discount never exceeds total | Totals and rates in valid ranges | Discount is between zero and the total | Rates outside the documented range |
| Parsed amount preserves sign | Positive and negative amounts | Sign of parsed equals sign of input | Formats the parser does not claim to support |
The excluded-cases column matters as much as the invariant. Every strategy excludes something, and the exclusions should be written down so a reader knows what the property does not claim. A property that excludes the interesting cases has narrowed itself into uselessness, and that failure is invisible unless the exclusions are explicit.
The duplication guide covers the neighboring question of whether two similar behaviors should be one generalized property or two independent tests. Two behaviors with different contracts are usually two properties, not one.
Write the invariant in plain language
State the invariant before writing the generator, and state it in a sentence a reviewer can check without reading the code. If the sentence depends on how the function is implemented, the property is derived from the implementation and will not catch a wrong implementation.
Compare two statements about a discount function. “The discount equals rate multiplied by total” is derived from the implementation, and it will pass whenever the code does that multiplication, including when the multiplication is wrong. “The discount is never negative and never exceeds the total” is grounded in intended behavior, and it fails when the code produces a discount above the total regardless of how it computes it.
| Weak property | Stronger property | Why the stronger one helps |
|---|---|---|
| Output equals the algorithm’s result | Output satisfies the documented constraint | Does not inherit the algorithm’s errors |
| Sorted output equals the reference sort | Output is ordered and is a permutation of input | Checks the contract, not one implementation |
| Parsed value matches the formula | Parsed value is within the valid range | Catches out-of-range results |
| Response matches the builder | Response satisfies the schema | Independent of how the response was built |
The stronger version is harder to write, because it requires knowing the contract rather than the code. That difficulty is the point. A property derived from the current implementation is the oracle-bias problem described in the generated tests guide, and grounding the claim in intended behavior is what makes the search meaningful.
When the invariant concerns what a consumer can rely on across a network boundary, the contract tests guide covers recording that expectation explicitly rather than leaving it implicit in a generator.
Bound and describe generated inputs
Unbounded generation is a resource problem before it is a correctness problem. A strategy that produces arbitrarily large structures can consume memory or time until the run fails for reasons unrelated to the property. Bound the inputs deliberately and record the bound.
Hypothesis documents that generation is constrained by the strategies supplied, behind F016. That constraint is a feature, and using it well means choosing bounds that match the documented contract rather than bounds that are merely convenient. A function documented to accept strings up to 255 characters should be tested with strings in that range and at that boundary, not with strings of unbounded length.
| Generated input | Bound to set | Boundary case to include | Reason for the bound |
|---|---|---|---|
| Text field | Maximum documented length | Empty, one character, maximum | Matches the schema |
| Numeric amount | Documented range and precision | Minimum, maximum, zero | Matches the contract |
| List | Maximum documented size | Empty, one item, maximum | Prevents runaway generation |
| Nested structure | Maximum depth | Minimum and maximum depth | Bounds memory use |
| Collection of identifiers | Unique or non-unique as documented | Duplicates if allowed | Matches real inputs |
Documenting the exclusions is the companion step. A property that assumes non-negative amounts should say so, and a reader should be able to tell that negative amounts are untested by that property. Assumptions that filter inputs are part of the claim, and an undocumented assumption is how a property quietly stops covering the case that matters.
The bounded case at the edge is the one most likely to fail, and the framework’s selection behavior behind F016 is what makes including it worthwhile. A range described as zero to 255 will be tested at zero and at 255 as well as in the middle.
Keep generation reproducible
A property that fails once and cannot be reproduced is a lead, not a bug report. Reproducibility is what turns a counterexample into something a teammate can verify and fix.
Two mechanisms cover this. The framework records the seed and the counterexample when a property fails, so the exact input can be replayed. Save that example rather than regenerating it. The second mechanism is an explicit seed in the test when the run must be identical across machines, which the deterministic tests guide covers alongside clock control.
A reproducible run has a cost worth acknowledging: a fixed seed tests one sequence, not the class. The property still searches a class on each run, and the seed makes a failure comparable across runs. Use both. Seed the run for repeatability, and let the property search the class within that run.
| Goal | Mechanism | What it does not do |
|---|---|---|
| Replay a failure | Saved counterexample | Does not cover the rest of the class |
| Compare runs fairly | Fixed seed | Does not cover other sequences |
| Search the input class | Property with strategies | Does not guarantee every case |
| Isolate the failure | Shrinking to a minimal input | Does not diagnose the cause |
The isolation row connects to the minimal repro guide, which covers shrinking a failure while preserving its signal. Shrinking a counterexample is the same discipline applied to a generated input.
Inspect the smallest counterexample
When a property fails, the framework reports a counterexample and reduces it. Inspect the reduced form before changing anything. The minimal case usually shows which assumption failed, and the full-sized case usually hides it.
Reading a counterexample is a diagnostic task, and the record should separate the observation from the explanation. Write down the input, the actual output, and the expected output according to the invariant. Then write the hypothesis about why. The debug log guide covers recording the prediction before the observation so the explanation cannot be rewritten after the fact.
| Counterexample | Minimized form | Diagnosis | Change made |
|---|---|---|---|
| Empty string | Empty string | Contract did not define the empty case | Property adjusted, code clarified |
| Rate of 1.5 | Rate just above 1 | Code assumed rate at most 1 | Code validates the range |
| Very long list | List of two equal items | Ordering assumption broken | Code fixed for equal elements |
| Negative total | Total of negative one | Property excluded invalid totals | Assumption documented, case excluded |
The first and last rows are the two honest outcomes. Sometimes the property was wrong, and the fix is to the property. Sometimes the code was wrong, and the fix is to the code. Deciding which is the next section.
Decide whether property or code is wrong
A counterexample means the invariant and the code disagree. One of them is wrong, and choosing wrongly produces either a weakened test or an unnecessary code change.
Three questions settle most cases. What does the documented contract say about this input? If the contract excludes it, the property is wrong and the input should be excluded explicitly. Does the intended behavior, stated independently of the code, actually cover this input? If it does and the code disagrees, the code is wrong. Is the invariant a real requirement or a convenient assumption the author added while writing the property? Convenient assumptions are the common failure, and they should be removed rather than defended.
The decision should be recorded with the counterexample. A property that was narrowed to exclude a real input is a weaker test, and the narrowing should be visible to whoever maintains it. A code change made because a property found a genuine defect should say so, because that is evidence the property earned its place.
| Diagnosis | Response | Recorded evidence |
|---|---|---|
| Input outside the contract | Exclude it explicitly in the property | The documented exclusion |
| Input inside the contract, code wrong | Fix the code | Counterexample and expected output |
| Invariant was an unsupported assumption | Remove the assumption | The reason the assumption was dropped |
| Invariant correct but imprecise | Tighten the property | The precise invariant and why |
A genuine code defect found by a property can also have a compatibility dimension. A behavior that changes for existing consumers is not only a fix, and the SemVer decision guide covers choosing the version increment from consumer impact rather than from the size of the change.
Add a concrete regression example
After diagnosing a counterexample, keep a small explicit test for the exact input that failed. This is the derived recommendation behind F018, and the reason is durability. A property searches a class on each run, and a future change to the strategies or the bounds could stop producing the failing case. The explicit example cannot be skipped by the generator.
The explicit test also documents the contract for a human reader. A property expresses a rule; the example expresses a case. Both are useful, and the example is what a reviewer reads first when they want to know what the function does with a specific input. Pytest’s parametrization behind F017 is the natural place for it: add the minimized counterexample as one named case among the explicit ones.
| Generated property | Concrete regression test | Remaining gap |
|---|---|---|
| Round-trip over arbitrary strings | Round-trip for the empty string | Encodings the strategy excludes |
| Discount within valid range | Discount for a total of zero | Rates outside the documented range |
| Sort is ordered and a permutation | Sort with duplicate elements | Very large inputs |
| Validator rejects invalid values | Rejects the specific invalid value found | Valid values not asserted |
The remaining-gap column is the honest part of the pattern. A regression test covers one case. It closes the specific failure and leaves the rest of the class to the property. Neither mechanism alone is sufficient, which is why they are paired.
The mutation testing guide covers the adjacent question of whether any of these tests could fail at all. A property with a weak invariant is a mutant that survives, and the survivor shows which assertions need strengthening.
Document excluded input classes
Every property excludes inputs, and the exclusions are part of the claim. Writing them down is what allows a reviewer to notice when an exclusion covers the case that matters.
Record three things per property. The bounds on the generated inputs, so a reader knows the range searched. The assumptions that filter inputs, so a reader knows what was assumed rather than tested. The exclusions the documented contract justifies, with a pointer to that contract so the exclusion can be checked rather than trusted.
A property with a large exclusion set is a narrow property, and that is legitimate when the exclusions match the contract. A property with undocumented exclusions is a property that claims more than it tests, which is the failure mode the false-success discussion describes in the wider testing context.
| Excluded input class | Reason | Where it is documented | Who can change it |
|---|---|---|---|
| Strings above 255 characters | Schema maximum | Next to the strategy | Schema owner |
| Negative amounts | Contract covers positive only | Next to the property | Product owner |
| Concurrency during the call | Property is single-threaded | Test module comment | Engineering owner |
| Locales other than the test default | Formatting tested elsewhere | Next to the property | Platform team |
The exclusions also define what to add when the property’s scope changes. If the contract begins to accept negative amounts, the exclusion becomes a gap, and the test selection guide is how the gap gets into the run for the change that widens the contract.
Review property tests with Claude Code
A property is a good fit for the pass-or-fail loop described in the official best practices guidance: a named test, a clear result, and a bounded change. Give the agent the property, the bounds, and the command, and ask for the result and any counterexample in full.
Review the proposed property for the two failures this post emphasizes. The first is a property derived from the implementation, which passes whenever the code runs and finds nothing. The second is an unbounded strategy, which costs runtime and can fail for resource reasons rather than for the invariant. Both are reviewable in the diff before the test ever runs.
The agent can also help shrink a counterexample and propose the concrete regression case. Treat the proposed regression as a draft to review. A minimized input is evidence, and the contract it asserts still has to be read by a person.
When the property concerns a value a consumer relies on, the snapshot review guide covers reading a recorded output before accepting it, and the flaky tests triage guide covers the case where a property fails only under some conditions.
Worked example: a discount that exceeds the total
Suppose a pricing function applies a rate to a cart total, and the intended behavior is that the discount is never negative and never exceeds the total. The property states exactly that, over totals from zero to a documented maximum and rates from zero to one.
The framework generates a total of 30 with a rate of 1.5, which the strategy allowed because the upper bound was set too loosely. The computed discount is 45, which exceeds the total. The counterexample is minimized to a rate just above 1.
| Counterexample | Minimized form | Diagnosis | Change made |
|---|---|---|---|
| Total 30, rate 1.5 | Rate just above 1 | Code accepted a rate the contract excludes | Code validates rate is at most 1 |
The diagnosis uses the documented contract: rates are between zero and one. The code should have rejected 1.5 rather than computing with it. The fix is a range check, and the property is retained with its bound tightened to match the contract. A concrete regression test is added for a rate of exactly 1, and another for a rate just above 1.
| Generated property | Concrete regression test | Remaining gap |
|---|---|---|
| Discount within zero to total, over valid totals and rates | Rate of exactly 1 and just above 1 | Totals above the documented maximum |
The concrete win is a boundary defect found by a search over a class of inputs, with a minimized case that names the assumption. The concrete loss is that the property only covers totals and rates within the documented range: a change to the contract that widens either range makes the exclusions stale, and the property will not notice on its own.
Related workflow guides in this batch
Property tests sit alongside the other verification techniques in this batch, and each covers a failure the others do not. Mutation testing asks whether any test could fail, which is the question a weak invariant raises. Contract tests record what a consumer relies on across a boundary. Snapshot review covers reading a recorded output before accepting a change to it.
For the inputs a property generates, deterministic time and randomness covers seeding a run so a counterexample is comparable across machines. For a failure that needs further reduction, minimal repro discipline covers shrinking while preserving the signal. For the evidence habit behind every diagnosis, a debug log of facts and hypotheses covers recording the prediction before the observation.
When a property fails only under some conditions, flaky tests triage applies. When it fails because two tests share state, fixture isolation covers the boundary. Selecting checks for changed code places properties in the run order for the module they cover.
Beyond the testing lane, a property that finds a real defect can raise a compatibility question, which is covered by deciding a version increment. Enforcing the property in the pipeline is covered by defining merge checks and choosing a branch policy. If a module resists a clean invariant, complexity-driven refactoring and choosing reuse or independence cover the structural work that often explains why.
Stop conditions and follow-up
Stop and narrow the property when it fails on inputs the documented contract excludes, and record the exclusion rather than fixing the code. Stop and widen the search when the property passes but the bounds are visibly narrower than the contract, because the property is not covering what it claims. Stop and reconsider the invariant when it can only be stated in terms of the implementation, because such a property cannot catch a wrong implementation.
Follow-up takes three forms. A saved counterexample should become a concrete regression case before the next change, while the input is still available. A property with an unbounded strategy should get bounds that match the contract. An exclusion that the contract no longer justifies should become a covered case in the change that widens the contract.
For release traceability, atomic commits and commit messages that encode intent keep the property, the code fix, and the regression case traceable together, and the release checklist connects them to the candidate that ships.
Data gap and future update
No measured defect-detection rate, coverage percentage, or runtime cost appears in the source set for this post. Hypothesis’s self-description behind F016 describes its selection behavior, not a measured effect. No benchmark is cited, and no claim is made that generated inputs cover every possible case.
The source set contains no specific property suite, no measured shrink effectiveness, and no repository-specific strategy configuration. A future update should add three things. A measured comparison of property-based and example-based testing on a real module. A documented pattern for keeping exclusions synchronized with a schema that changes. Fresh content review of the Hypothesis documentation for the version a reader is likely to run, since the page was content-fetched but the framework changes.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.
For a separate OpenAI-format agent, One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That is a different client and request format, not a workaround for Claude Code authentication. Review the free model list and eligibility notes before choosing an agent route.
FAQ
Do generated inputs cover every possible case?
No. Generation is constrained by the strategies and assumptions supplied, per F016. A property searches the class its bounds describe, and it excludes whatever its assumptions filter out. A passing property is evidence about that class, not a proof over all inputs.
How do I stop the property from just restating the implementation?
State the invariant in plain language before writing the generator, and state it in terms of the documented contract rather than the algorithm. A property that asserts the code’s own formula passes whenever the code runs and finds nothing. The generated tests oracle bias guide covers this inversion in the wider testing context.
What do I do with a counterexample?
Save it, shrink it, and diagnose it before changing anything. Then decide whether the property or the code was wrong using the documented contract. Per F018, pair the broad property with a small concrete regression test for the minimized input afterwards, so the specific case cannot be lost by a future change to the strategies.
Are property tests a replacement for example-based tests?
They answer different questions. A property expresses a rule over a class of inputs, and an example asserts a specific case a reader can check at a glance. Pytest parametrization behind F017 supports the explicit cases. Most modules are clearer with both, and the example is what a reviewer reads first.
Can unbounded generation break the test run?
Yes. A strategy that produces arbitrarily large structures can exhaust memory or time, and the run fails for resource reasons rather than for the invariant. Bound the inputs to match the documented contract, and document the bounds and exclusions so a reader knows what was searched.
More Claude Code troubleshooting
- Claude Code Async Races: Make Scheduling Deterministic
- Claude Code Memory Leaks: Compare Allocation Snapshots
- Claude Code Git Bisect: Automate Regression Hunts
- Claude Code Static Analysis: Baseline the Noise
- Claude Code Dead Code: Prove Usage Before Removal
- Claude Code Git Stash: Recover Work Without Dropping It
- Claude Code Merge Conflicts: Resolve Behavior, Not Lines
- Claude Code Merge Queue: Recover Failed Groups
- Claude Code Release Tags: Use Annotated Markers
- Claude Code Hotfix Backports: Cherry-Pick Carefully
- Claude Code Rollback: Plan a Revert Before Release
- Claude Code Changelog: Write Consumer-Facing Changes
Sources
- Official: Hypothesis documentation, supporting defined input ranges and selection of edge cases (F016).
- Official: Pytest parametrization, supporting parametrized test functions and fixtures (F017).
- Official: Pact documentation, neighboring technique for recording consumer-used interactions.
- Official: Stryker mutation testing, neighboring technique for investigating assertion quality.
- Official: Semantic Versioning 2.0.0, reference for the compatibility question a behavior fix can raise.
- Official: Claude Code best practices, supporting pass-or-fail checks and the derived pairing of properties with regression cases (F018).