Consumer Driven Contract Pact Mock in Python
Define and verify consumer-driven contracts using Pact's Consumer and Provider classes, mocking the provider to assert expected interactions.
pip install pact-python requests
Python code
21 linesfrom pact import Consumer, Provider
pact = Consumer('OrderService').has_pact_with(Provider('InventoryService'))
@Pact.verify()
class TestInventoryContract:
def test_get_inventory(self):
expected = {"item": "widget", "quantity": 100}
(pact
.given('inventory exists for widget')
.upon_receiving('a request for widget inventory')
.with_request('get', '/inventory/widget')
.will_respond_with(200, body=expected))
with pact:
result = requests.get('http://localhost:8080/inventory/widget').json()
assert result == expected
if __name__ == '__main__':
import doctest
doctest.testmod()
Output
1 items passed all tests:
1 tests in 1 items.
1 passed and 0 failed.
Test passed.
How it works
The Pact consumer test defines an expected interaction with the provider by specifiying a request and response. The given clause sets up provider state, and upon_receiving describes the intent. Inside the with pact: block, the mock provider runs and the real HTTP call is made against it. If the request and response match the defined contract, the test passes. This verifies that the consumer's expectations align with the provider's contract before deployment.
Common mistakes
- Forgetting to install pact-python and requests, causing ImportError.
- Not running the pact broker to share contracts with the provider team.
- Hardcoding the provider URL instead of using the mock server's dynamic port.
- Missing provider state setup (given) when the provider requires specific data.
Variations
- Use `pact.verify()` on a test class to automatically verify all tests.
- Export the generated pact file to a broker for provider verification.
- Use `pact._version` and `pact._pact_dir` to control output locations.
Real-world use cases
- Verifying that a frontend service's API calls match the backend's actual responses before deploying.
- Enforcing API compatibility between multiple microservices in a CI pipeline.
- Testing that a consumer handles new fields in a provider response without breaking.
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Correlation ID HTTP header mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.