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.
pip install pact-pythonVerified import paths — ran on the pinned version, not inferred.
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.
Migrate code from the old `pact` module (pre-v3) to the new v3 API. If maintaining old code, it needs to be updated to use the deprecated `pact.v2` namespace (e.g., `from pact.v2 import Pact` instead of `from pact import Pact`). A detailed migration guide is available in the official documentation.
If your project requires Pact Specification v3, explicitly set it during `Pact` instantiation: `Pact(...).with_specification('V3')`.Refer to the latest documentation for the updated `given()` method signature and adjust your consumer test code accordingly.
Any direct imports or usage of `pact.v3.ffi` should be replaced with `pact_ffi`.
Refactor provider state definitions to use keyword arguments for dynamic data, allowing the provider to set up the necessary state more flexibly.
Install the library using pip: `pip install pact-python`.
Ensure that `http_proxy`, `https_proxy`, and `no_proxy` environment variables are correctly configured, specifically excluding `localhost` or `127.0.0.1`. Verify the host and port settings of the `Pact` object match the client's connection target. Set `logLevel: 'debug'` in your Pact configuration for detailed troubleshooting.
Thoroughly review the `with_request` definition in your Pact test and ensure it perfectly aligns with the actual request made by your consumer code. For JSON payloads, make sure to serialize Python dictionaries to JSON strings (e.g., `json.dumps(data)`). Always explicitly include `headers={'Content-Type': 'application/json'}` if your API expects JSON. Enable `logLevel: 'debug'` in your Pact configuration to inspect detailed request/response matching logs.For request/response bodies, embed matcher objects directly within Python dictionaries or lists. For paths requiring dynamic segments, use `Term` or `Regex` to match the entire path string or specific path components. Ensure that where a string is expected (e.g., in headers or non-matching path segments), you provide a string, and where a matcher object is needed (e.g., in the body or a structured path matcher), you pass the object itself.