### Run Example Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Run the project's example to verify its functionality. This requires Docker or a similar containerization tool to be installed and running. ```shell hatch run example ``` -------------------------------- ### Install Pact Python Source: https://github.com/pact-foundation/pact-python/blob/main/README.md Install the latest version of Pact Python from PyPi. This command is used to set up the library for use in your project. ```console pip install pact-python # 🚀 now write some tests! ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/requests_and_fastapi/README.md Install project dependencies, including test-specific packages, using pip. Ensure pip is up-to-date before installing. ```console pip install -U pip # Pip 25.1 is required pip install --group test -e . ``` -------------------------------- ### Install pact-python Source: https://github.com/pact-foundation/pact-python/blob/main/pact-python-cli/README.md Install the pact-python library using pip. This command installs the latest stable version. ```bash pip install pact-python ``` -------------------------------- ### Run Catalog Entry Tests Source: https://github.com/pact-foundation/pact-python/blob/main/examples/catalog/README.md Command to run tests for a specific catalog entry within the Pact Python examples directory. Ensure you have uv installed and are in the correct directory. ```console cd examples/catalog uv run --group test pytest ``` -------------------------------- ### Run Pact Mock Service Source: https://github.com/pact-foundation/pact-python/blob/main/pact-python-cli/README.md Start a Pact mock service for a given consumer and provider. This is essential for running consumer-driven contract tests. ```bash pact-mock-service -p 1234 -l logs/mock-service.log --pact-dir pacts/ consumer localhost:8000 ``` -------------------------------- ### Define a Pact in v2.x Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md This example shows the v2.x approach to defining a pact using separate Consumer and Provider classes. ```python from pact.v2 import Consumer, Provider consumer = Consumer('my-web-front-end') provider = Provider('my-backend-service') pact = consumer.has_pact_with(provider, pact_dir='/path/to/pacts') ``` -------------------------------- ### Pact Python v2 Consumer Test Example Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2025/12-04 pact-python-v3-release.md Example of a consumer-side Pact test written using Pact Python v2. This demonstrates the setup, request, and verification steps. ```python from pact.v2 import Consumer, Provider import requests consumer = Consumer('my-web-front-end') provider = Provider('my-backend-service') pact = consumer.has_pact_with(provider, pact_dir='/path/to/pacts') ( pact .given('user exists') # (1) .upon_receiving('a request for user data') .with_request( 'GET', '/users/123', headers={'Accept': 'application/json'}, query={'include': 'profile'} ) .will_respond_with( 200, headers={'Content-Type': 'application/json'}, body={'id': 123, 'name': 'Alice'} ) ) pact.start_service() # (2) pact.setup() response = requests.get(pact.uri + '/users/123') assert response.json() == {'id': 123, 'name': 'Alice'} pact.verify() # (3) pact.stop_service() # (4) ``` -------------------------------- ### Dictionary-Based State Handler Example Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Use a dictionary to map provider state names to specific Python functions for setup and teardown. This is recommended for managing states directly within your Python test suite. ```python from pact import Verifier from typing import Literal, Any def mock_user_exists( action: Literal["setup", "teardown"], parameters: dict[str, Any] | None, ) -> None: """Mock the provider state where a user exists.""" parameters = parameters or {} user_id = parameters.get("id", 123) if action == "setup": # Set up the user in your test database/mock return UserDb.create(User( id=user_id, name=parameters.get("name", "Test User"), email=parameters.get("email", "test@example.com"), )) if action == "teardown": # Clean up after the test return UserDb.delete(user_id) def mock_user_does_not_exist( action: Literal["setup", "teardown"], parameters: dict[str, Any] | None, ) -> None: """Mock the provider state where a user does not exist.""" parameters = parameters or {} user_id = parameters.get("id", 123) if action == "setup" and user_id: # Ensure the user doesn't exist if UserDb.get(user_id): UserDb.delete(user_id) # Map state names to handler functions state_handlers = { "user exists": mock_user_exists, "user 123 exists": mock_user_exists, "user does not exist": mock_user_does_not_exist, } verifier = ( Verifier("my-provider") .add_transport(url="http://localhost:8080") .add_source("./pacts/") .state_handler(state_handlers, teardown=True) ) verifier.verify() ``` -------------------------------- ### Pact Python v3 Example Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2025/12-04 pact-python-v3-release.md Demonstrates setting up a Pact interaction with parameterized provider states and using the serve() method for mock service management. The pact file is written explicitly. ```python from pact import Pact import requests pact = Pact('my-web-front-end', 'my-backend-service') ( pact .upon_receiving('a request for user data') .given('user exists', id=123, name='Alice') .with_request('GET', '/users/123') .with_header('Accept', 'application/json') .with_query_parameter('include', 'profile') .will_respond_with(200) .with_body({'id': 123, 'name': 'Alice'}, content_type='application/json') ) with pact.serve() as srv: response = requests.get(f"{srv.url}/users/123") assert response.json() == {'id': 123, 'name': 'Alice'} pact.write_file('/path/to/pacts') ``` -------------------------------- ### Install pact-python-ffi via pip Source: https://github.com/pact-foundation/pact-python/blob/main/pact-python-ffi/README.md Install the package using pip. This command installs the pact-python-ffi library and its dependencies. ```console pip install pact-python-ffi ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Install prek to automate the process of catching simple formatting or linting issues during git commits and pushes. ```sh prek install ``` -------------------------------- ### Handle Provider States with a Function Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Implement a single function to handle all provider state setup and teardown actions. This function receives the state name, action (setup/teardown), and parameters. Ensure handlers run in the same process if using mocking libraries. ```python from pact import Verifier from typing import Literal, Any def handle_provider_state( state: str, action: Literal["setup", "teardown"], parameters: dict[str, Any] | None, ) -> None: """Handle all provider state changes.""" parameters = parameters or {} if state == "user exists": if action == "setup": return create_user( parameters.get("id", 123), name=parameters.get("name", "Alice"), ) if action == "teardown": return delete_user(parameters.get("id", 123)) if state == "no users exist": if action == "setup": return clear_all_users() msg = f"Unknown state/action: {state}/{action}" raise ValueError(msg) verifier = ( Verifier("my-provider") .add_transport(url="http://localhost:8080") .add_source("./pacts/") .state_handler(handle_provider_state, teardown=True) ) verifier.verify() ``` -------------------------------- ### Serve Mock Service on Custom Host and Port Source: https://github.com/pact-foundation/pact-python/blob/main/docs/consumer.md Start the mock service using a specific host and port. The mock service acts as a real HTTP server, asserting incoming requests against defined expectations and returning predefined responses. ```python with pact.serve(host="localhost", port=1234) as srv: client = UserClient(str(srv.url)) user = client.get_user(123) ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/aiohttp_and_flask/README.md Install required dependencies for the project using pip within an activated virtual environment. Pip version 25.1 or higher is required. ```console pip install -U pip pip install --group test -e . ``` -------------------------------- ### Provider State Handler with Full Parameters Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md Use this when your provider state requires setup and teardown actions with detailed parameters. The callback function receives the state name, action, and parameters. ```python from pact import Verifier def provider_state_callback( name: str, # (1) action: Literal["setup", "teardown"], # (2) parameters: dict[str, Any] | None, # (3) ) -> None: """ Callback to set up and tear down the provider state. Args: name: The name of the provider state. For example, "a user with ID 123 exists" or "no users exist". action: The action to perform. Either "setup" or "teardown". The setup action should create the provider state, and the teardown action should remove it. parameters: If the provider state has additional parameters, they will be passed here. For example, instead of "a user with ID 123 exists", the provider state might be "a user with the given ID exists" and the specific ID would be passed in the params. """ ... def test_provider(): verifier = Verifier("provider_name") verifier.state_handler(provider_state_callback, teardown=True) ``` -------------------------------- ### Activate Development Environment Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md After cloning the repository, run this command to install all project dependencies within a Python virtual environment and activate it. This prepares your environment for development. ```shell hatch shell ``` -------------------------------- ### Install Hatch Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Install Hatch, a tool for managing Python development environments and dependencies. This is a prerequisite for setting up the Pact Python development environment. ```shell python -m pip install --user pipx # If you don't have pipx pipx install hatch ``` -------------------------------- ### URL-Based State Handler Example Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Configure the Verifier to use an external HTTP endpoint for managing provider states. This is useful when the provider is not written in Python or state management logic is external. ```python verifier = ( Verifier("my-provider") .add_transport(url="http://localhost:8080") .add_source("./pacts/") .state_handler( "http://localhost:8080/_pact/setup", # Your state setup endpoint teardown=True, body=True, # Send state info in request body ) ) ``` -------------------------------- ### Python Consumer Client Example Source: https://github.com/pact-foundation/pact-python/blob/main/docs/consumer.md This Python code defines a User dataclass and a UserClient class to interact with a user provider service. It demonstrates how to define the data model from the consumer's perspective and initialize the client with a hostname for testing against a mock service. ```python from dataclasses import dataclass from datetime import datetime from typing import Any import requests @dataclass() class User: id: int name: str created_on: datetime class UserClient: """Simple HTTP client for interacting with a user provider service.""" def __init__(self, hostname: str) -> None: self._hostname = hostname def get_user(self, user_id: int) -> User: """Get a user by ID from the provider.""" response = requests.get(f"{self._hostname}/users/{user_id}") response.raise_for_status() data: dict[str, Any] = response.json() return User( id=data["id"], name=data["name"], created_on=datetime.fromisoformat(data["created_on"]), ) ``` -------------------------------- ### Install pact-python-cli Source: https://github.com/pact-foundation/pact-python/blob/main/pact-python-cli/README.md Install the pact-python-cli package using pip. This command is typically run in a terminal or command prompt. ```console pip install pact-python-cli ``` -------------------------------- ### Run Consumer Tests with v2 Manual Service Management Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Manage the mock service manually in v2 by starting, setting up, verifying, and stopping the service explicitly. ```python pact = Consumer("my-consumer").has_pact_with( Provider("my-provider"), host_name="localhost", port=1234, ) # Manually start the mock service pact.start_service() pact.setup() # Configure interactions # Make requests response = requests.get(pact.uri + '/users/123') # Assertions... # Verify and stop pact.verify() # Writes pact file pact.stop_service() ``` -------------------------------- ### Install pact-python with compat-v2 feature Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md To use the v2 compatibility module, install pact-python with the 'compat-v2' feature enabled. This is a temporary solution for gradual migration. ```bash pip install pact-python[compat-v2] ``` -------------------------------- ### Python Consumer Pact Test Setup Source: https://github.com/pact-foundation/pact-python/blob/main/docs/consumer.md Sets up a Pytest fixture for a Pact mock provider. It defines the consumer and provider names and the Pact specification version. The fixture yields the Pact object for use in tests and writes the pact file upon completion. ```python from pathlib import Path import pytest from pact import Pact, match @pytest.fixture def pact() -> Generator[Pact, None, None]: # (1) """Set up a Pact mock provider for consumer tests.""" pact = Pact("user-consumer", "user-provider").with_specification("V4") # (2) yield pact pact.write_file(Path(__file__).parent / "pacts") ``` -------------------------------- ### Run Tests with uv Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/aiohttp_and_flask/README.md Execute tests using pytest within a virtual environment managed by uv. This is the recommended method for setting up and running the example. ```console uv run --group test pytest ``` -------------------------------- ### Run Consumer Tests with v2 Context Manager Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Use the v2 context manager for running consumer tests, which automatically handles mock service setup and pact file verification. ```python pact = Consumer("my-consumer").has_pact_with( Provider("my-provider"), host_name="localhost", port=1234, ) # Context manager automatically calls setup() and verify() with pact: response = requests.get(pact.uri + '/users/123') # Pact file written automatically on exit ``` -------------------------------- ### Consumer Version Selector: Main Branch Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Example of using the `consumer_version` method to select pacts from the consumer's main branch. ```python # Verify pacts from main branch .consumer_version(main_branch=True) ``` -------------------------------- ### Consumer Version Selector: Specific Environment Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Example of using the `consumer_version` method to select pacts from a consumer version deployed to a specific environment. ```python # Verify pacts from a specific environment .consumer_version(deployed=True, environment="production") ``` -------------------------------- ### Consumer Version Selector: Specific Branch Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Example of using the `consumer_version` method to select pacts from a specific consumer branch for verification. ```python # Verify pacts from a specific branch .consumer_version(branch="feature/new-api") ``` -------------------------------- ### Consumer Version Selector: Deployed or Released Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Example of using the `consumer_version` method to select pacts from consumer versions that are deployed or released. ```python # Verify pacts from deployed or released versions .consumer_version(deployed_or_released=True) ``` -------------------------------- ### Consumer Version Selector: Specific Consumer and Branch Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md Example of using the `consumer_version` method to select pacts from a specific consumer by name and branch. ```python # Verify pacts from a specific consumer only .consumer_version(consumer="mobile-app", branch="main") ``` -------------------------------- ### Run Tests with pip Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/aiohttp_and_flask/README.md Execute tests using pytest after installing dependencies with pip. This command assumes a virtual environment has been created and activated. ```console pytest ``` -------------------------------- ### HTTP Request to Trigger Message Generation Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/07-26 asynchronous message support.md This is an example of an HTTP POST request used to trigger the provider to generate a specific message. It includes a JSON payload describing the action. ```http POST /_pact/message HTTP/1.1 Content-Type: application/json { "description": "a request to delete a user", } ``` -------------------------------- ### Message Producer Callback with Typing Hints Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md Implement a message producer callback using `pact.types.Message` for type safety. This example shows how to define the message content and metadata with explicit types. ```python from pact.types import Message def message_producer_callback( name: str, params: dict[str, Any] | None, ) -> Message: assert name == "request to delete a user" return Message( contents=json.dumps({ "action": "delete_user", "user_id": "123", }).encode("utf-8"), metadata=None, content_type="application/json", ) ``` -------------------------------- ### Provider Test Setup for Asynchronous Messages Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/07-26 asynchronous message support.md This Python code demonstrates how to configure a Pact Verifier for asynchronous message contracts. It sets provider information, the source of pacts, provider state, and adds a message transport. ```python from pact import Verifier class Provider: """ A simple HTTP provider that sends messages to the consumer. This would typically use the same underlying functions that would generate messages, except that instead of being sent into the message queue, they are sent to the consumer's HTTP server. """ provider = Provider() ( Verifier() .set_info("someProvider", url=provider.url) # (1) .set_source("/path/to/pacts") .set_state(provider.state_url) # (2) .add_transport( protocol="message", path="/_pact/message", ) ) ``` -------------------------------- ### Provider state handling via URL (v2) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Sets up provider states using a dedicated URL in v2. ```python success, logs = verifier.verify_pacts( './pacts/consumer-provider.json', provider_states_setup_url='http://localhost:8080/_pact/provider_states' ) ``` -------------------------------- ### Create Provider and Verifier instances (v2) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Instantiates separate Provider and Verifier objects for verification. ```python from pact import Provider, Verifier # Create separate Provider and Verifier instances provider = Provider('my-provider') verifier = Verifier(provider, 'http://localhost:8080') ``` -------------------------------- ### Run Consumer Tests with v3 Serve Method Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Use the v3 `serve()` method for a single, consistent way to run consumer tests with an in-process mock service. ```python pact = Pact("my-consumer", "my-provider") with pact.serve() as srv: response = requests.get(f"{srv.url}/users/123") ``` -------------------------------- ### Python Consumer Pact Test for GET User Source: https://github.com/pact-foundation/pact-python/blob/main/docs/consumer.md Tests the GET request for a user by defining an interaction with a mock provider. It specifies the expected response body structure using matchers and verifies the client's response. ```python def test_get_user(pact: Pact) -> None: """Test the GET request for a user.""" response: dict[str, object] = { # (3) "id": match.int(123), "name": match.str("Alice"), "created_on": match.datetime(), } ( pact.upon_receiving("A user request") # (4) .given("the user exists", id=123, name="Alice") # (5) .with_request("GET", "/users/123") # (6) .will_respond_with(200) # (7) .with_body(response, content_type="application/json") # (8) ) with pact.serve() as srv: # (9) client = UserClient(str(srv.url)) # (10) user = client.get_user(123) assert user.name == "Alice" ``` -------------------------------- ### Verifier instance with provider and URL (v2) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Configures a Verifier with a provider and its base URL in v2. ```python verifier = Verifier(provider, 'http://localhost:8080') ``` -------------------------------- ### Initialize Verifier with Provider Name (Before) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md Before version 2.3.0, the provider name was set using the `set_info` method. ```python verifier = Verifier() verifier.set_info("provider_name", ...) ``` -------------------------------- ### Set Provider Info and Transport URL (Before) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md Previously, provider name and transport URL were set using `set_info`. ```python verifier = Verifier() verifier.set_info( "provider_name", url="http://localhost:8123", ) ``` -------------------------------- ### Verify Provider Against Local Pacts Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md This snippet demonstrates how to verify a provider against pact files stored in a local directory. Ensure the provider name, pact directory, and provider URL are correctly specified. ```python from pact import Verifier def test_provider(): """Test the provider against the consumer contract.""" verifier = ( Verifier("my-provider") # Provider name .add_source("./pacts/") # Directory containing Pact files .add_transport(url="http://localhost:8080") # Provider URL ) verifier.verify() ``` -------------------------------- ### Add pact sources from Pact Broker (v3) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Configures pact sources from a Pact Broker using broker_source in v3. ```python verifier = ( Verifier('my-provider') .broker_source( 'https://pact-broker.example.com', username='username', password='password' ) ) ``` -------------------------------- ### Recommended Pytest Fixture for Session-Scoped Logging Source: https://github.com/pact-foundation/pact-python/blob/main/docs/logging.md Configures FFI logging once at the start of a pytest test session using an autouse fixture. This ensures all tests benefit from logging without re-initialization errors. ```python import pytest import pact_ffi @pytest.fixture(autouse=True, scope="session") def pact_logging(): """Configure Pact FFI logging for the test session.""" pact_ffi.log_to_stderr("INFO") ``` -------------------------------- ### Generate Pactfile from Requests Source: https://github.com/pact-foundation/pact-python/blob/main/pact-python-cli/README.md Generate a Pact file by recording requests made to a mock service. This is an alternative way to create pact files. ```bash pact-mock-service --port 1234 --pact-dir pacts/ --log-dir logs/ --provider-base-url http://localhost:8000 ``` -------------------------------- ### Verify pacts from local files (v2) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Verifies pacts using file paths in v2. ```python success, logs = verifier.verify_pacts( './pacts/consumer1-provider.json', './pacts/consumer2-provider.json' ) ``` -------------------------------- ### Create Provider Verifier with v2 Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Illustrates the creation of a Provider and Verifier object in Pact Python v2. ```python from pact.v2 import Provider, Verifier ``` -------------------------------- ### Create Virtual Environment with venv Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/aiohttp_and_flask/README.md Steps to create and activate a Python virtual environment using the venv module. This is an alternative to using uv for dependency management. ```console python -m venv .venv source .venv/bin/activate # On macOS/Linux .venv\Scripts\activate # On Windows ``` -------------------------------- ### Python Consumer Processing SQS Messages Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/07-26 asynchronous message support.md This Python code defines functions to process asynchronous messages from an SQS queue. It includes message parsing, user deletion logic, and message retrieval/deletion from the queue. Ensure boto3 is installed and configured for AWS access. ```python from typing import Any import boto3 QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue" def delete_user(user_id: str) -> bool: # Delete user from database # Delete associated files return True def process_message(message: dict[str, Any]) -> bool: if message.get("action") == "delete_user": user_id = message["user_id"] return delete_user(user_id) return False def main(): sqs = boto3.client("sqs") response = sqs.receive_message(QueueUrl=queue_url) for message in response.get("Messages", []): if process_message(message): sqs.delete_message( QueueUrl=queue_url, ReceiptHandle=message["ReceiptHandle"], ) ``` -------------------------------- ### Run All Tests Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Execute the project's test suite to ensure everything is functioning correctly. This command runs tests within the activated Hatch environment. ```shell hatch run test ``` -------------------------------- ### Add pact sources from local files or directories (v3) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Configures pact sources using add_source for directories or individual files in v3. ```python verifier = ( Verifier('my-provider') # It can discover all Pact files in a directory .add_source('./pacts/') # Or read individual files .add_source('./pacts/specific-consumer.json') ) ``` -------------------------------- ### Verify Provider With Advanced Broker Selectors Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md This snippet demonstrates advanced configuration for verifying pacts from a Pact Broker using selectors. It includes options to include pending pacts, WIP pacts since a specific date, and filter by provider and consumer branches. ```python from pact import Verifier def test_provider_with_selectors(): """Test with advanced broker selectors.""" verifier = ( Verifier("my-provider") .add_transport(url="http://localhost:8080") .broker_source( "https://my-broker.example.com", token="bearer-token", selector=True, # Enable selector builder ) .include_pending() # Include pending pacts .include_wip_since("2023-01-01") # Include WIP pacts since date .provider_branch("main") .consumer_version(branch="main") # Specific consumer version selectors .consumer_version(branch="develop") # Can be called multiple times .build() # Build the selector ) verifier.verify() ``` -------------------------------- ### Publishing Pacts to Pact Broker CLI Source: https://github.com/pact-foundation/pact-python/blob/main/docs/consumer.md Use the `pact-broker publish` command to upload pact files to the Pact Broker. Ensure environment variables like `PACT_BROKER_BASE_URL` are set for authentication and broker location. ```console pact-broker publish \ /path/to/pacts/consumer-provider.json \ --consumer-app-version 1.0.0 \ --auto-detect-version-properties ``` -------------------------------- ### Single Verifier instance with provider name (v3) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Initializes a Verifier with just the provider name in v3. ```python from pact import Verifier # Single Verifier instance with provider name verifier = Verifier('my-provider') ``` -------------------------------- ### Provider State Handler with Functions Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md Demonstrates how to define and use functional callbacks for provider states when verifying pacts. The `teardown=False` option is shown, indicating that the state handler should not perform cleanup. ```python from pact import Verifier def user_state_callback( parameters: dict[str, Any] | None, ) -> None: ... def no_users_state_callback( parameters: dict[str, Any] | None, ) -> None: ... def test_provider(): verifier = Verifier("provider_name") verifier.state_handler( { "a user with ID 123 exists": user_state_callback, "no users exist": no_users_state_callback, }, teardown=False, ) ``` -------------------------------- ### Provider state handling via URL with state_handler (v3) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Configures provider state handling using a URL with the state_handler method in v3, supporting POST requests with body. ```python # Option 1: URL-based (similar to v2) verifier = ( Verifier('my-provider') .add_transport(url='http://localhost:8080') .state_handler( 'http://localhost:8080/_pact/provider_states', body=True # (1) ) .add_source('./pacts/') ) ``` -------------------------------- ### Initialize Verifier with Provider Name (After) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md In version 2.3.0, the provider name is passed directly to the `Verifier` constructor. ```python verifier = Verifier(name="provider_name") ``` -------------------------------- ### Building Rust FFI Extension with CFFI Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/05-02 integrating rust ffi with pact python.md This snippet shows how to use CFFI to define and compile a Python extension module that links against a Rust library. ```python ffibuilder = cffi.FFI() with (self.tmpdir / "pact.h").open("r", encoding="utf-8") as f: ffibuilder.cdef(f.read()) # (1) ffibuilder.set_source( "_ffi", # (2) "\n".join([*includes, '#include "pact.h"']), libraries=["pact_ffi", *extra_libs], # (3) library_dirs=[str(self.tmpdir)], # (4) ) output = Path(ffibuilder.compile(verbose=True, tmpdir=str(self.tmpdir))) # (5) shutil.copy(output, PACT_ROOT_DIR / "v3") ``` -------------------------------- ### Matcher Usage in v2 Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Demonstrates the usage of limited matcher classes available in Pact Python v2. ```python from pact.v2.matchers import Like, EachLike, Regex, Term # Usage: Like({'id': 123}) EachLike({'item': 'value'}) Regex('hello world', r'^hello') ``` -------------------------------- ### Verify pacts from Pact Broker (v2) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Verifies pacts by fetching them from a Pact Broker using credentials in v2. ```python success, logs = verifier.verify_with_broker( broker_url='https://pact-broker.example.com', broker_username='username', broker_password='password' ) ``` -------------------------------- ### FFI Logging to a File (Future Implementation) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/logging.md This snippet demonstrates how FFI logs would be directed to a specified file with a given log level. Note: This function is not yet implemented in the Python bindings. ```python import pact_ffi # This will be available in a future release pact_ffi.log_to_file("/path/to/logfile.log", pact_ffi.LevelFilter.DEBUG) ``` -------------------------------- ### Verify Provider From Pact Broker Source: https://github.com/pact-foundation/pact-python/blob/main/docs/provider.md This snippet shows how to verify a provider against pacts fetched from a Pact Broker. It includes basic authentication using username and password. ```python from pact import Verifier def test_provider_from_broker(): """Test the provider against contracts from a Pact Broker.""" verifier = ( Verifier("my-provider") .add_transport(url="http://localhost:8080") .broker_source( "https://my-broker.example.com", username="broker-username", # or use token="bearer-token" password="broker-password", ) ) verifier.verify() ``` -------------------------------- ### v3 - Function State Handler Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Use a function to handle provider states for HTTP verification. This function receives the state name and parameters, and should set up the necessary provider state. ```python def handler(name, params=None): if name == 'user exists': # Set up user in database/mock create_user(params.get('id', 123)) elif name == 'no users exist': # Clear users clear_users() verifier = ( Verifier('my-provider') .add_transport(url='http://localhost:8080') .state_handler(handler) .add_source('./pacts/') ) ``` -------------------------------- ### Advanced Pact Broker source selection (v3) Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Uses BrokerSelectorBuilder for granular control over pact selection from a Pact Broker in v3. ```python # Or with selectors for more control broker_builder = ( verifier .broker_source( 'https://pact-broker.example.com', selector=True ) .include_pending() .provider_branch('main') .consumer_version(branch='main') .consumer_version(branch='develop') .build() ) ``` -------------------------------- ### v3 Verification Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md In v3, verification is simplified. The `verify()` method raises an exception on failure, eliminating the need for manual success checks and error handling. ```python verifier.verify() ``` -------------------------------- ### v3 - Mapping State Handler Source: https://github.com/pact-foundation/pact-python/blob/main/MIGRATION.md Use a dictionary to map provider state names to handler functions for HTTP verification. This provides a concise way to define multiple state handlers. ```python state_handlers = { 'user exists': lambda name, params: create_user(params.get('id', 123)), 'no users exist': lambda name, params: clear_users(), } verifier = ( Verifier('my-provider') .add_transport(url='http://localhost:8080') .state_handler(state_handlers) .add_source('./pacts/') ) ``` -------------------------------- ### Set Provider Name and Transport URL (After) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md After version 2.3.0, the provider name is set in the constructor, and transport information is added via `add_transport`. ```python verifier = Verifier("provider_name") verifier.add_transport(url="http://localhost:8123") ``` -------------------------------- ### Converting String Argument to Rust FFI Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/05-02 integrating rust ffi with pact python.md Illustrates the pattern for converting Python strings (or None) into C-compatible types for Rust FFI functions, including encoding and null pointer handling. ```python def foobar(value: str | None) -> bool: return lib.foobar(value.encode("utf-8") if value else ffi.NULL) # (1) ``` -------------------------------- ### Set Provider State Handler Endpoint (After) Source: https://github.com/pact-foundation/pact-python/blob/main/docs/blog/posts/2024/12-30 functional arguments.md In version 2.3.0, `set_state` is renamed to `state_handler`, and the `body` argument must be explicitly set to indicate if the endpoint expects data in the query string or POST body. ```python verifier = Verifier() verifier.state_handler( "http://localhost:8123/provider-states", body=False, # the previous default must be explicitly set ) ``` -------------------------------- ### Run Tests Across All Supported Python Versions Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Execute the test suite against all Python versions supported by the project. This ensures compatibility across different Python environments. ```shell hatch run test:all ``` -------------------------------- ### Define XML with Repeating Elements and Matchers Source: https://github.com/pact-foundation/pact-python/blob/main/examples/http/xml_example/README.md Shows how to define XML structures with repeating elements and apply Pact matchers using the `.each()` method. This is suitable for contracts involving lists or collections of XML elements. ```python ( xml.element( "items", xml.element("item", xml.element("id", match.int(1))).each(min=1, examples=2), ) ) ``` -------------------------------- ### Run Linters and Formatters Source: https://github.com/pact-foundation/pact-python/blob/main/CONTRIBUTING.md Commands to run Ruff for linting and formatting code locally. These commands help catch stylistic problems and ensure code consistency. ```sh hatch run lint ``` ```sh hatch run format ```