pact-python

3.2.1 · active · verified Tue Apr 14

pact-python is an active library (current version 3.2.1) providing consumer-driven contract testing capabilities for Python applications. It builds on the Pact Rust FFI library, offering full support for Pact features and ensuring compatibility with other Pact implementations. It sees regular updates, often aligning with major Pact specification changes and core library enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic consumer-side contract test using `pact-python`. It sets up a mock service, defines an expected interaction, and then verifies that a simple Python client correctly interacts with the mock service based on the defined contract. The mock service URL and consumer/provider names are configurable via environment variables for CI/CD compatibility.

import atexit
import unittest
import requests
import os
from pact import Pact

# Define the client that will interact with the provider
class UserClient:
    def __init__(self, base_url):
        self.base_url = base_url

    def get_user(self, username):
        response = requests.get(f"{self.base_url}/users/{username}")
        response.raise_for_status()
        return response.json()

# Set up Pact for consumer testing
# Use environment variables for consumer/provider names in CI/CD, or hardcode for local dev
PACT_MOCK_HOST = os.environ.get('PACT_MOCK_HOST', 'localhost')
PACT_MOCK_PORT = int(os.environ.get('PACT_MOCK_PORT', '1234'))

# Instantiate Pact with consumer and provider names
pact = Pact(
    consumer=os.environ.get('PACT_CONSUMER', 'MyConsumer'),
    provider=os.environ.get('PACT_PROVIDER', 'UserService')
)

# Start the mock service and register its shutdown
pact.start_service(host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT)
atexit.register(pact.stop_service)

class GetUserInfoContract(unittest.TestCase):
    def test_get_ash_user(self):
        expected_body = {
            'username': 'Ash',
            'id': 123,
            'groups': ['Admin']
        }

        # Define the interaction
        (pact
         .given('User Ash exists and is an administrator')
         .upon_receiving('a request for Ash')
         .with_request('GET', '/users/Ash')
         .will_respond_with(200, headers={'Content-Type': 'application/json'}, body=expected_body))

        # Run the consumer code against the mock service
        with pact:
            client = UserClient(pact.uri)
            result = client.get_user('Ash')
            self.assertEqual(result, expected_body)

if __name__ == '__main__':
    unittest.main()

view raw JSON →