Most of the bugs that survive code review and make it to production aren't caused by logic you forgot to test. They are caused by inputs you never considered. For years I wrote example-based unit tests the way most teams do: a handful of hand-picked cases, a few edge cases like empty strings and nulls, and a confident assertion that the function under test should return exactly X. That approach catches regressions, but it rarely finds the subtle invariant violations that appear only with specific combinations of data. After a serialization bug that corrupted payloads for only 0.3% of users, I rebuilt that service's test suite around property-based testing. Within an hour, hypothesis in Python and fast-check in TypeScript had reproduced the failure with a minimal sequence I would never have written by hand. Property-based testing does not replace examples; it complements them by asserting general properties that must hold for all valid inputs and then systematically searching for violations.
Beyond Example-Based Tests: Why Hand-Picked Inputs Leave Blind Spots
In my experience, example-based tests suffer from confirmation bias. You write the implementation, then you write tests that confirm the implementation does what you just told it to do. If your mental model of the function is wrong, your tests will share the same blind spot. I have seen this repeatedly with string normalization, date arithmetic, and input validation where the developer correctly handled the three cases they imagined and missed the fourth that occurs in production data.
Property-based testing inverts this. Instead of saying "for input [1, 2, 3] the output should be [1, 2, 3]," you say "for any list of integers, sorting twice should be the same as sorting once" or "for any valid user object, encoding and then decoding should return the original." The framework then generates hundreds of random inputs, runs the property, and reports a failure if any input violates it. This shifts the effort from inventing cases to defining correctness.
This distinction matters because human intuition is poor at exploring combinatorial spaces. A function that takes two strings and a boolean has an effectively infinite input domain. A handful of examples covers less than 0.01% of that space. Generators in property-based frameworks are designed to cover that space more intelligently, including edge values like empty collections, maximum integers, Unicode boundaries, and NaN that rarely appear in hand-written tests.
If you have relied on high line coverage as a safety net, this is a humbling correction. As discussed in Mutation Testing: Why 100% Code Coverage Does Not Mean Bug-Free, coverage tells you what code was executed, not whether you asserted the right behavior. Property-based tests directly address that gap by failing when a property is insufficiently specified, not just when a line is uncovered.
The Oracle Problem and Why Properties Solve It
A classic challenge in testing is the oracle problem: how do you know the expected output for a random input? With example tests you hard-code the expected value. With property-based testing you avoid needing a perfect oracle by checking relationships that must hold universally. Idempotence, commutativity, round-trip serialization, and monotonicity are all properties you can check without knowing the exact correct answer for every random input. In my teams, we now require that any utility function with a plausible inverse or algebraic property has at least one property test alongside its example tests.
Properties Not Examples: Defining Invariants, Round-Trips, and Metamorphic Relations
The hardest part of property-based testing is not the tooling; it is learning to articulate properties. I've found that most useful properties fall into four categories. Once you learn to recognize them, you start seeing them everywhere in application code.
First, invariants. These are conditions that must remain true after an operation. For a sorting function, the output length must equal the input length, and every element in the output must be present in the input. For a cache, a successful get after a put must return the stored value. Invariants are simple but they eliminate large classes of truncation, duplication, and off-by-one bugs.
Second, round-trips. If you have two functions that should be inverses, their composition must be the identity. encode(decode(x)) == x and decode(encode(x)) == x for serialization, compression, encryption, and formatting are classic cases. I once found a Base64 URL-safe encoder that silently dropped padding for inputs whose length was 1 mod 3. Example tests with "hello" passed; a round-trip property with arbitrary bytes failed within 20 iterations.
Third, idempotence and commutativity. sort(sort(xs)) == sort(xs), deduplicate(deduplicate(xs)) == deduplicate(xs), and set union being commutative are easy to express and powerful for data pipeline code.
Fourth, metamorphic relations and model-based comparisons. Here you do not assert an absolute result, but a relation between two executions. For example, adding an item to a shopping cart and then removing it should leave the cart's total unchanged, or increasing a price should never decrease the total. For complex logic, you can also implement a slow but obviously correct reference model and compare it to the optimized implementation for all inputs.
Writing a Falsifiable Property
A good property must be falsifiable and sufficiently strict. assert result is not None is a property, but it is too weak to catch bugs. I review properties with the same rigor as production code, asking whether a completely broken implementation could still pass it. Pairing a round-trip test with an invariant check usually provides that strictness. For detailed guidance on what to look for during that review, I recommend the practices in Code Review Checklists: What to Look for Beyond Style applied specifically to test properties.
from hypothesis import given, strategies as st
# Property: sorting is idempotent and preserves elements
@given(st.lists(st.integers(min_value=-10_000, max_value=10_000)))
def test_sort_properties(xs):
ys = sorted(xs)
# Invariant: same length and same multiset of elements
assert len(ys) == len(xs)
assert sorted(ys) == ys # result is sorted
assert sorted(ys) == sorted(xs) # preserves elements
# Idempotence: sorting twice is same as sorting once
assert sorted(ys) == ys
# Property: encode/decode round-trip
@given(st.binary(min_size=0, max_size=1024))
def test_base64_roundtrip(data):
encoded = base64.urlsafe_b64encode(data)
decoded = base64.urlsafe_b64decode(encoded)
assert decoded == data
The binary strategy above is deliberately unconstrained. In early iterations I tried to be clever by filtering to "realistic" data and missed bugs that only appeared with null bytes and non-UTF-8 sequences. Start broad, then constrain only to exclude inputs that violate your function's documented preconditions.
Modeling Generators and Strategies: Taming Hypothesis and fast-check Input Spaces
Generators are the engine of property-based testing, and misusing them is the most common source of weak tests. Both hypothesis and fast-check provide strategies/arbitraries for primitive types, but real application code needs domain-specific generators that produce valid, interesting inputs with the right distribution.
In hypothesis, you compose strategies with st.builds, st.composite, and st.flatmap. In fast-check, you use fc.record, fc.array, fc.option, and custom fc.letrec for recursive structures. The key is to generate data that satisfies your invariants so you are not wasting cycles on inputs your function is supposed to reject. For example, if your API defines an email field as a string matching a specific regex, generate strings that match that regex rather than arbitrary text and then filtering.
Filtering is a code smell. Writing st.text().filter(lambda s: is_valid_email(s)) forces the framework to generate and discard thousands of invalid strings, which is slow and can cause health check failures in hypothesis. Instead, build a generator that constructs valid emails from local parts and domains you control, as shown below. I have measured a 10-50x speed improvement by replacing filtered strategies with constructive ones.
Controlling Size, Shrinking, and Database Validity
Both frameworks let you control size and complexity. In fast-check, fc.integer({min: 0, max: 1_000_000}) is more precise than filtering an unconstrained integer. Use .filter only for cheap post-conditions, and use fc.map or st.builds to transform valid base data. Also be aware of how shrinking interacts with generation. A generator that produces database records should ensure referential integrity is preserved when shrinking. For example, if you generate an order with line items, shrinking should not produce an order that references a non-existent product ID.
When your generators need to interact with real infrastructure, keep them pure. Generate identifiers and payloads with property tests, but validate persistence against ephemeral resources. Our team separates pure property tests from integration-level property tests that use Integration Testing with Testcontainers: Real Databases in Your Test Suite to run the same properties against a PostgreSQL container. This prevents coupling your shrinking logic to network latency or external state.
import fc from 'fast-check';
// Constructive generator for valid emails, not a filtered string
const validEmailArb = fc.record({
local: fc.stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789._-'), {minLength: 1, maxLength: 20}),
domain: fc.constantFrom('example.com', 'test.org', 'acme.co'),
}).map(({local, domain}) => `${local}@${domain}`);
// Property: normalizeEmail is idempotent and lowercases domain
function normalizeEmail(email: string): string {
const [local, domain] = email.split('@');
return `${local}@${domain.toLowerCase()}`;
}
fc.assert(
fc.property(validEmailArb, (email) => {
const once = normalizeEmail(email);
const twice = normalizeEmail(once);
// Idempotence
if (once !== twice) return false;
// Invariant: domain is lowercased
const domain = once.split('@')[1];
return domain === domain.toLowerCase();
}),
{ numRuns: 1000, verbose: true }
);
// Property: JSON round-trip preserves structure for serializable values
// See MDN for JSON serialization limits https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const jsonValueArb = fc.letrec(tie => ({
prim: fc.oneof(fc.string(), fc.integer(), fc.boolean(), fc.constant(null)),
arr: fc.array(tie('prim'), {maxLength: 5}),
obj: fc.dictionary(fc.string({minLength: 1}), tie('prim'), {maxKeys: 5})
})).obj;
fc.assert(fc.property(jsonValueArb, (value) => {
const serialized = JSON.stringify(value);
const parsed = JSON.parse(serialized);
return JSON.stringify(parsed) === serialized;
}));
For authoritative details on the underlying language semantics you are testing against, the MDN Web Docs provide precise definitions for behaviors like JSON.stringify handling of undefined, NaN, and circular references. The Python Documentation is similarly essential when reasoning about Hypothesis strategies for floats, decimals, and datetime edge cases such as leap seconds and NaT.
Shrinking Failures Into Readable Counterexamples That Point to the Bug
Finding a failing input is only half the value. The other half is shrinking: the automated process of reducing a large, random failing input to the smallest input that still fails. In my experience, shrinking quality determines whether developers love or abandon property-based testing.
Hypothesis and fast-check both shrink aggressively, but they do it differently. Hypothesis integrates shrinking into its core engine and will try to simplify strings by deleting characters, reduce integers toward zero, and remove elements from collections while preserving the failure. fast-check performs a deterministic binary search over the produced value's structure, attempting to remove array elements and minimize numeric values. Both will print the minimal counterexample and, when configured, the sequence of shrinks that led there.
A common mistake is to write assertions that mask the true property. If you use try/except inside the test and convert an exception to a boolean, the shrinker cannot tell which input caused which exception. Let the property throw. A raw AssertionError with a reproducible example is far more actionable than a swallowed error. Enable verbose output and example databases so failures are reproducible across CI runs.
Interpreting Shrunken Output in Practice
When a property fails, I follow a fixed routine. First, copy the printed minimal counterexample and create a focused regression test with that exact input. Second, read the shrunken value literally: if the failure is text='a\x00b', the presence of \x00 is the signal, not the a and b around it. Third, check whether the property or the implementation is wrong. About one in five failures in my teams turns out to be an incorrect or underspecified property, especially around Unicode normalization and floating-point equality.
To make shrinking effective, avoid unshrinkable generators. A generator that uses random.random() or reads from the system clock internally is opaque to the shrinker. Use only the framework's arbitraries and derived combinators so the shrinker can traverse the generation tree. If you must use custom logic, expose it via st.composite or fc.letrec rather than hiding it behind an opaque function call.
Stateful and Model-Based Testing: Finding Race Conditions and Sequence-Dependent Bugs
Stateless properties catch data-transformation bugs, but many production failures are sequence-dependent. A queue that works for single enqueue/dequeue operations can still lose ordering after interleaved operations, and an in-memory cache can pass all single-key tests while failing when eviction and concurrent writes interact. Stateful property-based testing is designed for this.
Hypothesis provides RuleBasedStateMachine and the newer hypothesis.stateful APIs. You define state transitions as rules with preconditions and invariants. The framework generates random sequences of rules, executes them against both the system under test and an in-memory model, and compares the results after each step. fast-check offers fc.commands and fc.modelRun with a similar approach, letting you define commands with check and run methods.
In one service, we used a stateful machine to test an optimistic concurrency control layer. The model was a simple integer version counter, while the real system used a database row version. After about 300 steps, fast-check produced a failing sequence: read -> write(expectedVersion=1) -> concurrentWrite -> write(expectedVersion=1). The second write should have been rejected with a conflict error but was incorrectly accepted because we cached the version check result. No example-based test had generated that exact interleaving.
Stateful tests pair naturally with deterministic simulation. If your system uses concurrency or retries, control the scheduler or clock in the test harness so generated command sequences are reproducible. For units that depend on randomness or time, inject a seedable PRNG and a controllable clock via test doubles. Guidance on choosing between fakes and stubs for this injection is covered well in Test Doubles Explained: Mocks, Stubs, Fakes and Spies, and I specifically prefer fakes over mocks for model-based testing because the model needs to observe state rather than verify interactions.
Designing Commands and Models Without Overfitting
The risk with stateful testing is building a model that is just a copy of the implementation. To avoid this, keep the model trivial and obviously correct, even if it is inefficient. For a rate limiter, the model can be an array of timestamps and a linear scan, not the optimized sliding window. For a CRDT, the model can be a last-writer-wins register. The property is that the system's observable behavior matches the model for all generated sequences, not that the internal data structures match.
Integrating Property-Based Testing Into CI Without Flaky Builds or Timeout Drift
Teams often hesitate to add property-based tests because they run longer and can appear non-deterministic. In practice, both concerns are solvable with a few conventions I now enforce in every repository.
First, budget time explicitly. I configure hypothesis with max_examples=200 for local development and max_examples=1000 for CI, using profiles. fast-check is similarly tuned with numRuns: 200 locally and 1000 in CI. This keeps the local loop under two seconds per property while still providing deep coverage in CI. For expensive properties that touch a database, I lower runs to 100 and increase them only after a failure is fixed and added as a regression case.
Second, make failures deterministic and shareable. Commit the hypothesis example database (.hypothesis/examples) and configure fast-check to log the seed and path on failure. When CI fails, the log should contain a line like Counterexample: [{"local":"a","domain":"test.org"}] Seed: 123456 that any developer can paste into a local reproduction script. This eliminates "works on my machine" discussions.
Third, treat property tests as supplemental, not exclusive. Keep your fast example-based unit tests for documentation and quick feedback, and run property tests in a separate CI job that can run in parallel. Use labels like property to allow pytest -m "not property" when iterating quickly. Do not disable property tests in CI to save time; if they are consistently slow, your generators are too broad or your system under test is doing real I/O where it should use a fake.
| Aspect | Example-Based Tests | Property-Based Tests (hypothesis / fast-check) |
|---|---|---|
| Input selection | Hand-written values chosen by developer | Random generation from strategies/arbitraries with controlled distribution |
| Oracle type | Exact expected output for each example | Universal property (invariant, round-trip, relation) checked for all inputs |
| Failure output | Diff of expected vs actual for fixed case | Minimal shrunken counterexample plus seed for reproduction |
| Best at finding | Regressions and documented behavior | Edge cases, boundary interactions, sequence-dependent bugs |
| Maintenance cost | Low per test, high volume needed for coverage | Higher initial design cost, fewer tests needed for equivalent coverage |
| CI considerations | Fast and deterministic | Tunable runs; requires seed persistence and time budget |
The payoff is cumulative. After three months of incremental adoption on a Python and TypeScript monorepo, our property suite of 42 properties found 17 distinct bugs that had survived 92% line coverage. Four of those bugs had existing example tests that asserted the wrong expected value. Without property-based testing, those incorrect assertions would have continued to pass indefinitely.
Frequently Asked Questions
How many examples should I run per property?
Start with 200 runs locally for fast feedback and 500 to 1000 runs in CI for thoroughness. For pure functions with cheap generators, 1000 runs typically finishes in under a second with both hypothesis and fast-check. For properties that involve database or network fakes, lower the count to 50 to 100 and compensate by running them more frequently. Always measure duration with your worst-case generator, not the average case, and set timeouts per property rather than globally.
When should I choose hypothesis versus fast-check?
Use the framework native to the language you are testing. hypothesis is the most mature option for Python and integrates with pytest via the @given decorator and health checks; fast-check is the standard for JavaScript and TypeScript and works with Jest, Vitest, and Mocha via fc.assert. If your system is polyglot, I define the same logical properties in both languages and share generators for cross-service contracts like JSON schemas or protobuf messages. Do not try to test Python code with fast-check or TypeScript code with hypothesis through interop layers.
Does property-based testing replace example tests and code review?
No. I still keep concise example tests because they document intended behavior for specific, business-meaningful cases that a random generator might never hit, such as a named promotional code or a regulatory edge case. Properties complement examples by verifying general invariants, while code review catches design, naming, and requirement issues that no automated test can detect. The strongest suites combine all three: examples for readability, properties for coverage, and mutation analysis to verify the tests themselves.
How do I handle properties for functions that can throw or reject invalid inputs?
Separate validation from core logic and generate only valid inputs for the core property. For the validation layer, write a property that asserts invalid inputs are rejected with a documented error, not that they produce a specific output. In hypothesis, use st.builds to construct valid domain objects and a separate strategy for invalid ones; in fast-check, create distinct arbitraries for valid and invalid partitions. Never write a property that expects an exception for random inputs drawn from an unconstrained generator, because the shrinker cannot distinguish expected from unexpected failures.