TST-14Recommended
Check the contract between services
When two services you own talk to each other, test the shape of their messages on both sides with a shared contract. This covers events sent through a queue or broker as well as requests.
How to do it
Let the consumer write down the requests it sends and the answers it needs, with a tool such as Pact or a shared schema. Run that contract against the provider in its own build. A provider change that breaks a consumer fails before it ships. Skip this when both sides live in one codebase and always deploy together. For events, the consumer writes down the smallest message it can handle, and the producer's build proves it still sends that message. Pact calls these message pacts, and an AsyncAPI file can serve as the shared schema. Version each event as Version event payloads says. To test one API against its OpenAPI file, see test the API against its contract.
Examples
JavaScript example
// Consumer side, Pact JS
await provider.addInteraction({
states: [{ description: 'order 1042 exists' }],
uponReceiving: 'a request for order 1042',
withRequest: { method: 'GET', path: '/orders/1042' },
willRespondWith: { status: 200, body: { id: 1042, total: 4200 } },
});
Python example
# Consumer side, pact-python 3 or later
pact = Pact("shop-web", "orders-api").with_specification("V4")
(pact.upon_receiving("a request for order 1042")
.given("order 1042 exists")
.with_request("GET", "/orders/1042")
.will_respond_with(200)
.with_body({"id": 1042, "total": 4200}, content_type="application/json"))
How to check
Remove a field that a consumer uses from the provider's answer, or from an event the producer sends. The provider's build fails on the contract test.
Sources
Related rules
- EVT-3 Version event payloads in Integration and events
- API-46 Test the API against its contract in API design
- API-27 Make only additive changes in API design
- API-45 Write the contract first in API design
- EVT-1 Describe every channel in an AsyncAPI document in Integration and events
- EVT-5 Treat each source schema as a contract in Integration and events
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/testing/integration-and-contract-tests/contract-tests">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.