py-contract-testing
A complete, runnable example of contract testing in Python with
Pact: both sides of one contract, in one repository,
passing in under a second.
Two services are included. A consumer, user-cli, which reads users over
HTTP. A provider, user-api, a small Flask service that serves them. The
consumer writes down what it needs, and the provider is held to it.
Why contract testing
Integration tests need both services running at once, which is slow, flaky,
and impossible when the two are built by different teams on different
schedules. Mocks are fast but lie: your mock keeps returning name long
after the provider renamed it to full_name, and the tests stay green until
production disagrees.
Contract testing is the middle ground. The consumer's test runs against a
mock, as usual, but that mock writes down what it was asked for. The
result is a contract file. The provider then replays that contract against
its real code. Nobody has to run both services together, and neither side
can drift without a test failing.
Requirements
- Python 3.10 or newer
- Docker, only for the Pact Broker section
Quick start
git clone https://github.com/wmariuss/py-contract-testing.git
cd py-contract-testing
make install
make test
That is the whole cycle. make test runs the consumer tests, which write a
contract into pacts/, and then the provider tests, which replay it against
the real Flask app.
Look at what was produced:
cat pacts/user-cli-user-api.json
It records every request the consumer made and every response it accepted,
including which parts are matched by type rather than by value.
The two halves
1. The consumer says what it needs
In consumer/tests/test_contract.py the
client is pointed at a mock that Pact starts on a local port:
(
pact.upon_receiving("a request for a user")
.given("the user exists", id=3, name="Alice")
.with_request("GET", "/users/3")
.will_respond_with(200)
.with_body({"id": match.int(3), "name": match.str("Alice")})
)
with pact.serve() as mock:
user = UserClient(str(mock.url)).get_user(3)
Two things are worth noticing.
The client is the real client. UserClient is the production code from
consumer/client.py. If it sends the wrong path or
cannot parse the response, this test fails, and nothing is written.
Matchers, not values. match.int(3) means "an integer goes here". The
provider is free to return any integer. Pin values only when the value
itself is part of the agreement.
given(...) names the precondition the provider must arrange. It carries
parameters, so one handler on the provider side can serve many cases.
2. The provider proves it still fits
In provider/tests/test_contract.py the
contract is replayed against the running Flask app:
verifier = (
Verifier("user-api")
.add_transport(url=provider_url)
.add_source(pacts_path)
.state_handler(STATE_HANDLERS, teardown=True)
)
verifier.verify()
The provider never sees the consumer's code. It sees a list of requests and
the responses that were promised. Each given(...) from the contract maps to
a state handler that arranges the world before the request is replayed and
cleans up after it, so no interaction leaks into the next.
See it catch a real break
This is the part worth doing by hand, because it is the whole point.
Open provider/app.py and drop a field from the response
that the consumer relies on:
@app.get("/users/<int:user_id>")
def get_user(user_id: int):
user = USERS.get(user_id)
if user is None:
abort(404)
trimmed = {k: v for k, v in user.items() if k != "description"}
return jsonify(trimmed)
The provider's own tests still pass:
make test-provider # provider/tests/test_api.py: 6 passed
They were written against the provider's own idea of correct, and nothing
there asserts on description. The contract test, in the same run, fails:
Failures:
1) Verifying a pact between user-cli and user-api
Given the user exists - a request for a user
1.1) has a matching body
$ -> Actual map is missing the following keys: description
The consumer's tests pass too, because the consumer has not changed. Only
the contract knows that somebody out there was relying on that field, and it
names the consumer, the interaction, the provider state and the key. Put the
line back and it goes green again.
With a Pact Broker
Passing contract files around by hand does not scale. In practice a broker
sits between the two sides: the consumer publishes its contract, and the
provider fetches whatever contracts name it.
make broker # http://localhost:9292, user pact, password pact
make test-consumer # write the contract
make publish # send it to the broker
make verify-broker # provider fetches it, verifies, publishes the result
Open http://localhost:9292 and you will see the contract, both participants,
and the verification that just passed.
Now the question the broker exists to answer. Record that the provider is
live, then ask whether the consumer can follow it:
make record-deployment PACTICIPANT=user-api
make can-i-deploy
Computer says yes \o/
CONSUMER | C.VERSION | PROVIDER | P.VERSION | SUCCESS? | RESULT#
user-cli | a1605fb | user-api | a1605fb | true | 1
In a pipeline this is the gate between a merge and a deploy: it fails when
the version you are about to ship has no verified contract with what is
actually running in that environment. Once the consumer ships too, record
it: make record-deployment.
Stop the broker and throw its data away with make broker-stop.
Running the services
The example is useful without any tests, if you want to watch the two talk:
make run-provider # Flask on http://localhost:5000
make run-consumer # calls it, in another terminal
Or in containers:
docker compose --profile apps up --build
Set PROVIDER_PORT if 5000 is taken on your machine:
PROVIDER_PORT=5050 docker compose --profile apps up --build.
The provider exposes GET /users, GET /users/{id}, POST /users and
DELETE /users/{id}.
Layout
consumer/
client.py the HTTP client, the code under test
app.py a small program that uses it
tests/test_contract.py writes the contract
provider/
app.py the Flask API
tests/test_api.py the provider's own tests, no contract involved
tests/test_contract.py replays the contract against the API
pacts/ generated contracts, not committed
compose.yaml the Pact Broker
pacts/ is deliberately git-ignored. A contract is a build artifact: it is
generated by the consumer's tests and published to a broker, never edited by
hand and never trusted from a previous run.
Make targets
| Target |
What it does |
make install |
Create the virtualenv and install everything |
make test |
Write the contract, then verify it |
make test-consumer |
Consumer tests only; writes pacts/ |
make test-provider |
Provider tests only; reads pacts/ |
make lint / make format |
Ruff, check or fix |
make run-provider / make run-consumer |
Run the services |
make broker / make broker-stop |
Start or destroy a local Pact Broker |
make publish |
Publish the contract to the broker |
make verify-broker |
Verify against the broker, publish the result |
make can-i-deploy |
Ask the broker whether this version is safe to deploy |
make record-deployment |
Record a deployment; PACTICIPANT=user-api for the provider |
make clean |
Remove generated files |
Version stamps come from git and can be overridden:
make publish GIT_COMMIT=abc123 GIT_BRANCH=main.
How this runs in CI
.github/workflows/ci.yml runs both suites in
one job, so this repository checks itself: change either side incompatibly
and CI fails. Real projects split them, because the two services live in two
repositories and are released on their own schedules. The consumer's build
publishes its contract; the provider's build verifies every contract naming
it, and a webhook from the broker triggers that build when a contract
changes.
Built with
pact-python 3.x, which
wraps the shared Pact Rust core and speaks the
V4 specification.
Older Pact examples in Python used pactman or pact-python 1.x, whose APIs
are gone; if you are coming from one of those, the code here is what the
current API looks like.
Further reading: the Pact docs, and the
5-minute getting started guide.
License
Apache License 2.0.
Author
Marius Stanca