Back to snippets

pact_python_consumer_contract_test_with_mock_provider.py

python

A consumer-side contract test that mocks a provider service to verify expect

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 Pact between the Consumer and the Provider
7pact = Consumer('Consumer').has_pact_with(Provider('Provider'))
8pact.start_service()
9
10# Register a cleanup to stop the mock service when the tests are finished
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 not an administrator')
24         .upon_receiving('a request for UserA')
25         .with_request('get', '/users/UserA')
26         .will_respond_with(200, body=expected))
27
28        # Define the actual code that makes the request
29        with pact:
30            # The URL of the mock service is pact.uri
31            result = requests.get(f'{pact.uri}/users/UserA')
32
33        # Verify that the response from the mock service matches what we expected
34        self.assertEqual(result.json(), expected)
35        # pact.verify() is automatically called by the context manager 'with pact'
36
37if __name__ == '__main__':
38    unittest.main()