Skip to main content

pytest-quint-connect: Quinty the starfish inspects a contract. Model-based testing for Python under pytest.

pytest-quint-connect

PyPI CI Python 3.11+ Quint 0.33.1 Typed Apache-2.0 Agent skill Documentation

Model-based testing for Python under pytest. Write the rules of a stateful API once, as a small Quint model. pytest-quint-connect replays the histories Quint generates from it against your real code, and fails when the code disagrees.

Set it up with your coding agent

Paste this into Claude Code, Codex, Cursor or another coding agent, in your repository:

Add pytest-quint-connect to this repository. Fetch https://pytest-quint-connect.readthedocs.io/en/latest/agent-setup.md and follow it.

The agent picks one part of your code that keeps state, writes its rules down as a short model, connects the model to the code, adds deliberate bugs the check must catch, adds a CI job, and reports what it verified. You review the model. It is the specification. An agent can write a wrong model, which then checks the wrong rules, so read it before you merge. The tests themselves run without AI, in CI, on every change. This is the split Quint's authors describe in Reliable Software in the LLM Era and Quint Connect. To do it by hand, follow the tutorial.

In plain words

  • Model: a short Quint file that says what your API should do: its operations, and what you should be able to read back after each one.
  • History: a sequence of operations generated from the model, with the expected state after each step. Some are scenarios you name; the rest are sampled from a fixed seed.
  • Driver: a few lines of Python that apply each step to your real code and read its state back. It never computes the answer.
  • Mutant: a deliberately broken version of your code. Every run must catch it, which proves the check can fail.

Hand-written tests check the cases someone thought of, and a change can rewrite them along with the code. A contract checks every generated history against rules kept apart from the code. So a change by a person or a coding agent is judged against the rules, not against tests the same change may have edited. Why, with real output · Tutorial · Run it in CI

Read the documentation · Related tools

This is a community Python integration in the spirit of Quint Connect (Rust) and Quint's model-based testing guide. It is not an official Quint project and is not endorsed by its maintainers.

test_lru_contract.py::test_lru_cache[witness-evictsLeastRecentlyUsedTest] FAILED

Quint contract 'lru-cache': implementation state differs from the model
  trace:  .artifacts/quint-connect/lru-cache/witness-evictsLeastRecentlyUsedTest-0.itf.json
  state:  3 after action fetch(key='a')
  seed:   7
  4 difference(s):
  entries[0].key: values differ
      expected: 'b'
      actual:   'a'
  ...
  reproduce: pytest test_lru_contract.py::test_lru_cache --quint-replay .artifacts/quint-connect/lru-cache/witness-evictsLeastRecentlyUsedTest-0.itf.json

Quick start

Install the plugin, plus Node.js 22+ with npm. On first use the plugin installs its locked Quint 0.33.1 into a per-user cache. To use your own Quint, pass --quint PATH or set QUINT.

pip install pytest-quint-connect

To try unreleased changes, install from Git instead: pip install "pytest-quint-connect @ git+https://github.com/gigaverse-app/pytest-quint-connect".

Generate a typed driver base from the model, then declare the contract:

pytest-quint-connect codegen quint-connect.json  # writes lru_cache_driver.py
# test_cache_contract.py
from pytest_quint_connect import quint_contract

test_cache = quint_contract("quint-connect.json", driver="cache_driver")

Subclass the generated base. It has one typed method per model action and an observe() typed as the model's observed state, so a type checker flags a driver that has drifted from the spec:

# conftest.py
import pytest
from lru_cache_driver import LruCacheDriver, Read, View  # generated
from my_cache import LRUCache


class CacheDriver(LruCacheDriver):
    def __init__(self) -> None:
        self.cache, self.last = LRUCache(2), {"tag": "NoRead"}

    def init(self) -> None: ...
    def inspect(self) -> None: ...

    def store(self, key: str, value: int) -> None:  # apply one model action to the real code
        self.cache.put(key, value)

    def fetch(self, key: str) -> None:
        value = self.cache.get(key)
        self.last: Read = {"tag": "Miss"} if value is None else {"tag": "Hit", "value": value}

    def observe(self) -> View:  # read the real state back
        return {"entries": [{"key": k, "value": v} for k, v in self.cache.items()], "lastRead": self.last}


@pytest.fixture
def cache_driver():
    return lambda context: CacheDriver()  # called once per history: fresh state each time
pytest --quint-require-complete

In CI, add the report as the next step. It keeps one comment on each pull request with what ran, what failed and the command that reproduces each failure, and keeps a README block like this repository's current:

- run: pytest --quint-require-complete
- uses: gigaverse-app/pytest-quint-connect/report@v1  # job permission: pull-requests: write
  if: ${{ !cancelled() }}

A hand-written driver that implements step(step) and observe() works too; see drivers.

examples/lru_cache is the complete version. It checks a list-based cache and an OrderedDict refactor against the same generated histories, catches a cache whose reads forget to refresh recency, and runs from the installed wheel in CI.

What a contract run does

quint-connect.json ──► quint typecheck ──► quint test  (named witnesses)  ──► witness-*.itf.json ─┐
                                      └──► quint run --mbt (seeded samples) ──► sample-*.itf.json  ─┤
                                                                                                 ▼
pytest: test_x[witness-…] test_x[sample-N] ──► fresh driver per history ──► step → observe → compare
        test_x[mutant-…]   every trace through the mutant; only an observed mismatch counts
        test_x[coverage]   every declared action reached
                                                                                                 ▼
                     .artifacts/quint-connect/results.json, traces, logs, mismatch-*.json
  • Real pytest cases. Each witness, sample, mutant and the coverage check is a parametrized case: selectable with -k, listed by --collect-only, reported in JUnit (with quint_trace, quint_seed and quint_detected_by properties), with ordinary fixture setup and teardown.
  • Fresh Quint, every run. Traces are regenerated from the model with the manifest's seed and bounds; the output directory is emptied first. Collection never runs Quint; a Quint failure is a setup error for every case of that contract.
  • Mutation controls. A mutant passes only when some generated history produces an observed-state mismatch. An exception while building or running the mutant fails the case: it is not detection. Mutants are planted fake bugs that prove the tests are meaningful. Bugs a contract found and that were fixed (bugs_found) lead the report; a mutant that reintroduces one is replayed through every history, and the report says how many diverge.
  • Complete or not. With --quint-require-complete, the session fails unless every contract in quint_required_contracts ran every case and passed. A -k-filtered run is recorded as partial, a replay as replay-only; a crash leaves running, never an earlier passed.
  • Actionable failures. A mismatch names the trace, state, action and arguments, a field-level expected/actual difference, the seed and a command that replays that exact trace (--quint-replay, optionally --quint-mutant). An exception from the driver keeps its own type and message and gains the same location as a note.

To / Read

To Read
See why, with real output docs/why.md
Build your first contract step by step docs/tutorial.md
Make contracts a required CI check docs/ci.md
Set it up with a coding agent the agent setup procedure, also served raw at agent-setup.md
Write a manifest docs/manifest.md
Write a driver and choose a step convention docs/drivers.md
Know what a passing run does and does not prove docs/limits.md
Configure options and read the receipt docs/reference.md
See it on production integrations pytest-obligation's report-merge contract, pytest-selective's selection contract, dry-lint's campaign ledger contract

Measured

This repository's own contract, from the receipt of its last complete CI run. The block is generated, and CI fails when it no longer matches the evidence:

What pytest-quint-connect's contracts caught in gigaverse-app/pytest-quint-connect's pull requests

Quint contracts: 1 contract passed · 8 histories · 4/4 mutants caught

✅ 1 contract · 13/13 cases · 4/4 mutants caught · 8 histories
Contract Cases passed Mutants caught
✅ session-receipts test_session_contract.py::test_session_receipts
8 histories (4 witnesses, 4 samples, seed 11) · every action covered · Quint 0.33.1
13/13 4/4
🐞 1 real bug found by this contract
Contract Bug Fixed in Regression test
session-receipts Valid histories whose step calls one action without any { … } were rejected: Quint records mbt::actionTaken as step, and the event cross-check refused it
found by the first run of this contract · no mutant re-checks it
#3 tests/test_replay.py
::test_unbranched_step_is_recorded_under_the_step_name_and_still_replays
🧪 4 mutants (planted fake bugs), all caught
Contract Mutant What it breaks Caught by At
session-receipts filtered-counts-as-complete a -k run that skipped cases is judged as if every case ran witness-filteredRunIsNeverPassedTest
samples: 1/4 diverge
state 1, after session(kind='filtered', strict=False)
session-receipts replay-counts-as-complete replaying one saved trace no longer marks the session incomplete witness-replayIsNeverCompleteTest
samples: 2/4 diverge
state 2, after session(kind='replay', strict=True)
session-receipts failed-session-keeps-old-receipt a failed or still-running session leaves the previous results.json in place witness-staleSuccessIsReplacedTest
samples: 4/4 diverge
state 2, after session(kind='noQuint', strict=False)
session-receipts require-complete-ignored --quint-require-complete is accepted but never changes the exit code witness-filteredRunIsNeverPassedTest
samples: 2/4 diverge
state 2, after session(kind='filtered', strict=True)
What session-receipts says

Actions, and the code each one drives:

  • init: copy examples/lru_cache into a fresh project directory; no receipt yet
  • session: run python -m pytest in the project with the installed plugin and the options for this kind; read results.json and the exit code
  • inspect: read results.json and the last exit code without running anything

Invariant honest, checked while sampling histories.

Witnesses, scenarios replayed exactly as written: staleSuccessIsReplacedTest, filteredRunIsNeverPassedTest, replayIsNeverCompleteTest, faultAfterSuccessFailsTest.

Bounds: seed 11 · max_samples 300 · max_steps 3 · n_traces 4.

Witness staleSuccessIsReplacedTest, step by step: the observation the model starts from, then what it expects each action to change.

State Action Model expects
0 init() { exitCode: -1, mode: "none", status: "none" }
1 session(kind='full', strict=True) exitCode: -1 → 0
mode: "none" → "generate-and-replay"
status: "none" → "passed"
2 session(kind='noQuint', strict=False) exitCode: 0 → 1
status: "passed" → "failed"
3 inspect() unchanged

Generated by pytest-quint-connect from contract receipts; what a passing run proves.

session-receipts checks the plugin itself: each step is a real pytest session of the example, and the planted bugs break the plugin's own completeness and receipt logic. CI also runs lru-cache, the teaching example, as a smoke test (the list and OrderedDict implementations pass the same histories, and the stale-read cache fails 4 of 15); it is not reported here, because it checks tutorial code, not code this repository ships.

Adopters measure their own contracts the same way; these figures come from their CI:

Contract Histories Cases Planted bugs (mutants) detected Notes
pytest-obligation merge_reports 21 (5 witnesses, 16 samples) 28 6/6 same 21 histories, state for state, as the runner it replaced
pytest-selective's selection 19 (7 witnesses, 12 samples) 23 3/3 each step is a real Git commit selected by affected(); the mutants drop base-tree edges, stop after direct importers and ignore global inputs
dry-lint's campaign ledger 20 (4 witnesses, 16 samples) 25 4/4 each step drives the real CampaignStore on a SQLite ledger; found a real bug (a reservation could be settled twice, refunding credit again)

Quint 0.33.1, TypeScript backend. See PROVENANCE.md for where the engine came from and how the baseline was reproduced.

Duplicates kept out

Local hooks and the required PR check prevent new copies. The weekly audit records progress against the accepted backlog. Setup and cleanup workflow.

dry-lint in gigaverse-app/pytest-quint-connect: new duplicates kept out of its pull requests, 0 old duplicates cleaned up, 5 remaining

Reviewed duplication debt · Counts from the committed baselines.

Accepted pairs Remaining Retired Dismissed
Functions 5 0 0
Models Not initialized — —

Accepted backlog · Weekly audit

Retired means a side was removed, or (functions only) the judge now finds the pair separate. It is not a count of refactors. Dismissals stay separate; an uninitialized model baseline is unknown.

Impact

What pytest-quint-connect's contracts caught in pull requests, across every repository that shares its totals

Every repository whose report action shares its totals adds its merged pull requests here: the disagreements its contracts caught between the code and its Quint model, and how many were fixed before merge. Repositories are counted pseudonymously, and share-totals: "false" opts out (what is sent).

Meet Quinty

Quinty in a deerstalker, inspecting a contract with a magnifier Quinty in a chef's hat, stamping approval on a passing contract Quinty with a map, tracing the path where the code left the model

Quinty is a starfish: five arms, a quint. On a pull request, Quinty stamps approval when every history matched the model, follows the map to the spot where the code left the model when one did not, and otherwise inspects the contract.

Project What it does
pytest-obligation Conformance proofs for background work that must survive lost messages and dead workers
Due Durable obligations for Python: PostgreSQL remembers what is owed
pytest-selective Explainable test impact analysis for pytest
CI-esta CI observability and honest merge gates
dry-lint Finds code that re-implements what the codebase already does

License

Apache 2.0. See CONTRIBUTING.md to work on pytest-quint-connect itself and RELEASING.md for publishing.


CI measured by CI-esta

Tests selected by pytest-selective

Pull requests run only the test lanes and test files a change can affect, chosen by pytest-selective. CI-esta reports this repository's CI timing, keeps its test durations and owns its required gate. Neither is a dependency of pytest-quint-connect. See how CI runs here.

Metadata

Release files for pytest-quint-connect 1.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-quint-connect 1.4.0
File Size Uploaded Provenance Actions
pytest_quint_connect-1.4.0.tar.gz 7.4 MB With provenance Details for pytest_quint_connect-1.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-quint-connect 1.4.0
File Interpreter ABI Platform Actions
pytest_quint_connect-1.4.0-py3-none-any.whl Python 3 none any Details for pytest_quint_connect-1.4.0-py3-none-any.whl

Total release size: 7.5 MB

Release files / pytest_quint_connect-1.4.0.tar.gz

Download URL pytest_quint_connect-1.4.0.tar.gz
Size 7.4 MB
Tags Source
SHA-256 checksum
How to use checksums
7aaa20b8347cc6a262505d6cc9a25a9778f049a459d9e2e5bf84304d6edd8c37
BLAKE2b-256 checksum
How to use checksums
7918a4b555cc381fb4dbadcb196722281629fa5301d5908b5b479850c3d73738
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Release files / pytest_quint_connect-1.4.0-py3-none-any.whl

Download URL pytest_quint_connect-1.4.0-py3-none-any.whl
Size 88.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9ba93896581b74ea41b9aa5046255c18d152fea7a1c915229bb5f5900280ace2
BLAKE2b-256 checksum
How to use checksums
5f70108e32c8e4020df555ec2c46bcd981c60a2840c0da6fa3b2cb6807a8585d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Security for pytest-quint-connect 1.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_quint_connect-1.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page