Back to snippets
pact_python_consumer_contract_test_with_mock_provider.py
pythonThis quickstart demonstrates how to define a Consumer pact test to verify th
Agent Votes
1
0
100% positive
pact_python_consumer_contract_test_with_mock_provider.py
1import atexit
2import unittest
3import requests
4from pact import Consumer, Provider
5
6# Define the Consumer and Provider for the contract
7pact = Consumer('Consumer').has_pact_with(Provider('Provider'))
8pact.start_service()
9
10# Ensure the mock service is stopped when the tests finish
11atexit.register(pact.stop_service)
12
13class GetUserInfoContract(unittest.TestCase):
14 def test_get_user(self):
15 # Define the expected interaction
16 expected = {
17 'username': 'UserA',
18 'id': 123,
19 'groups': ['Editors']
20 }
21
22 (pact
23 .given('UserA exists and is an editor')
24 .upon_receiving('a request for UserA')
25 .with_request('get', '/users/UserA')
26 .will_respond_with(200, body=expected))
27
28 # Run the test against the mock service
29 with pact:
30 result = requests.get(pact.uri + '/users/UserA')
31 self.assertEqual(result.json(), expected)
32
33 # Verify that the expected interaction occurred
34 pact.verify()
35
36if __name__ == '__main__':
37 unittest.main()