Contract & property-based testing
Generating tests from a schema, stating invariants, and triaging what generated tools report.
Contract testing from a schema
Generate one test per operation from the API's own specification, and let it check the promises the service makes.
A schema-driven tool reads an API specification, generates requests that are valid according to it, and checks that the responses are valid according to it too. That covers a category of defect example-based tests systematically miss: undocumented status codes, responses whose shape does not match what was declared, content-type violations and server errors on inputs nobody thought to try. The value is proportional to how honest the specification is, which is the point — a contract test measures the gap between what a service does and what it promises, and closing that gap is worth doing regardless of testing. Load the schema from the application object rather than a running server where the framework allows it, so the generated tests remain collectable without anything running. Keep the generated example count modest in the pull-request pipeline and raise it substantially for a nightly run, because these tests are cheap per example but the count multiplies across every operation in the specification.
Key points
- One generated test per operation covers undocumented statuses, wrong response shapes and content-type violations
- The tool measures the gap between what a service does and what its specification promises
- Keep example counts low in the merge gate and raise them substantially for a nightly run
Code
schema = schemathesis.openapi.from_asgi("/openapi.json", app)
@pytest.mark.contract
@schema.parametrize()
@hypothesis_settings(max_examples=15, deadline=None)
def test_api_conforms_to_its_openapi_spec(case):
"""One generated test per operation in the specification."""
case.call_and_validate()
# Built-in checks: not_a_server_error, status_code_conformance,
# content_type_conformance, response_schema_conformance, positive_data_acceptance.
#
# A failure prints a curl command that reproduces it, which goes straight into
# the ticket without anybody having to reconstruct the request by hand.Loading the schema from the application object keeps these tests collectable with nothing running.
See it in the framework
- Used by · Contract tests:
tests/services/test_contract_and_properties.py— live · reviewed - Used by · OpenAPI schema source:
sut/app.py— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- Expecting value from a specification nobody maintains — the tool can only check the promises that were written down
- Running a large example count on every pull request, which multiplies across operations and slows the gate
Practice exercise
Point a schema-driven tool at an API you work with and run it once. Record every finding, then classify each as a real defect, a specification gap, or an artifact of the tool.
Property-based testing: invariants, not examples
State a rule that must always hold; the tool hunts for a counterexample and shrinks it to something readable.
Example-based tests check the cases somebody thought of. A property-based test states a rule that must hold for all inputs, and the tool searches for a counterexample and then shrinks it to the smallest input that still fails, which is what makes the output actionable rather than a wall of random data. Good properties are invariants rather than examples: a round trip where reading back what you created returns the same thing, an invariance such as a total always equalling the sum of its parts, idempotence where doing something twice equals doing it once, a robustness property that no input produces a server error, and symmetry where complementary filters partition a collection exactly. Choosing between this and a parametrized table is straightforward. A fixed curated list — boundary values, known injection payloads — belongs in a table, where each row gets its own name and works with ordinary fixtures. Generation belongs where you want inputs you did not think of, and it costs discipline, since a generated test that reuses a fixture must reset its own state.
Key points
- A property states a rule for all inputs; shrinking turns a random failure into a minimal readable one
- Round trip, invariance, idempotence, no-server-errors and symmetry are the properties worth reaching for first
- Use a parametrized table for curated inputs and generation for inputs you did not think of
Code
@given(quantities=st.lists(st.integers(min_value=1, max_value=5), min_size=1, max_size=4))
@hypothesis_settings(
max_examples=20,
deadline=None,
suppress_health_check=[HealthCheck.function_scoped_fixture],
)
def test_cart_total_always_equals_sum_of_lines(shop_as_user, quantities):
"""The invariant, not the example.
Suppressing the fixture health check means taking responsibility for
isolation yourself - hence the reset on the first line.
"""
shop_as_user.cart.clear()
products = shop_as_user.products.list(in_stock=True)[: len(quantities)]
expected = 0.0
for product, quantity in zip(products, quantities, strict=False):
shop_as_user.cart.add_item(product.id, quantity)
expected += product.price * quantity
cart = shop_as_user.cart.get()
approx_money(cart.total, expected)
approx_money(sum(line.line_total for line in cart.items), cart.total)The reset on the first line is the price of reusing a function-scoped fixture across generated examples.
See it in the framework
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- Restating an example as a property, which pays the machinery cost without gaining any search
- Suppressing a fixture health check without then resetting state in the test, so examples contaminate each other
Practice exercise
Write one property for a feature you know that is not already covered by an example test. Break the implementation deliberately and confirm the tool finds and shrinks a counterexample.
Triaging what generated tools report
Tools produce findings, humans produce verdicts — and every suppression carries its reason in the code.
Generated testing tools report three kinds of thing, and telling them apart is the skill that decides whether such a job stays useful or becomes permanently yellow and ignored. Some findings are real defects in the system. Some are real gaps in the specification, where the service behaves sensibly but never documented the behaviour; the fix is to document it, and doing so sometimes exposes a second finding when the documentation you just wrote is itself wrong. And some are artifacts of the tool meeting the shape of your interface rather than statements about the system at all — an optional parameter whose schema permits a value the transport cannot express, or a generator running out of distinct inputs for an operation that takes no parameters and reporting that it filtered too many examples. The discipline that makes this sustainable is simple: every exclusion or suppression carries a written reason immediately beside it. An unexplained suppression is indistinguishable from a bug somebody hid, and six months later nobody can tell which it was.
Key points
- Findings split three ways: a real defect, a specification gap, or an artifact of the tool
- Documenting a gap can create a second finding if the documentation you wrote is itself wrong
- Every exclusion carries its reason beside it, or the job decays into permanent yellow
Code
# A real triage log from this course's own suite, kept in the test's docstring:
#
# 1. Undocumented status 400/401 REAL. The service returns them and the
# specification never said so. Fixed by documenting them.
# 2. Response schema mismatch on 422 REAL, and caused by the fix for (1):
# we declared detail as a string while the framework returns a list of
# error objects. A wrong contract is worse than a missing one.
# 3. Rejected ?in_stock=null NOT a defect. An optional query parameter is
# "boolean or null" in the schema, but a query string cannot express JSON
# null, so the generator sends the text "null" and the server correctly
# rejects it. A limitation of the specification format, not a bug.
case.call_and_validate(excluded_checks=[positive_data_acceptance])
# ^ excluded because of finding (3), recorded aboveThree findings, three different verdicts — and the exclusion is readable next to the code it affects.
See it in the framework
- Used by · Contract/property tests:
tests/services/test_contract_and_properties.py— live · reviewed - Services notes:
docs/03-services.md— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- Suppressing a check to make the job green without recording why, which is indistinguishable from hiding a defect
- Assuming every generated finding is a product bug, which burns credibility with developers on the first false positive
Practice exercise
Run a schema-driven tool against an API you own and triage every finding into the three categories. For anything you suppress, write the reason in the code and have a colleague check the reasoning holds.