Registry / testing / pact-python

pact-python

JSON →
library3.4.0pypypi✓ verified 20d ago

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-python
INSTALL
IMPORT
SIG · PACT-PYTHON
P
pact-python
testingpythonv3.4.0
Install
5.2s avg
Import
557ms
Disk
68MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.574s · 74.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 5.2s · import 0.540s · 40MB
68MB installed
● package 68MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Pact
from pact import Pact
from pact.v3 import Pact
The `pact.v3` namespace was a temporary module during the transition to v3; the main `pact` module now exposes the v3 API directly.
Consumer, Provider
from pact import Consumer, Provider
from pact.v2 import Consumer, Provider
While `Consumer` and `Provider` classes exist, `Pact(consumer='...', provider='...')` is the recommended v3 approach. The old v2 API moved to `pact.v2` (which is deprecated).
Verifier
from pact.verifier import Verifier
Used for verifying pacts against a provider service.

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()
pact --version
Debug
Known issues
breakingVersion 3.x introduces significant breaking changes due to a re-architecture leveraging the Pact Rust FFI library, replacing the older Ruby-based executables and API. The primary `pact` module now exposes the v3 API.
fix
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.
affects: 3.0.0 and later
breakingThe default Pact specification version for new `Pact` instances changed from v3 to v4. While largely backward-compatible, explicitly setting the specification might be necessary if your project relies on specific v3 behaviors.
fix
If your project requires Pact Specification v3, explicitly set it during `Pact` instantiation: `Pact(...).with_specification('V3')`.
affects: 3.0.0 and later
breakingThe signature of the `Interaction.given()` method has been simplified, which may require updates to consumer test definitions.
fix
Refer to the latest documentation for the updated `given()` method signature and adjust your consumer test code accordingly.
affects: 3.0.0 and later
deprecatedThe `pact.v3.ffi` module has been removed as of v3.0.0 and is replaced by the standalone `pact_ffi` package.
fix
Any direct imports or usage of `pact.v3.ffi` should be replaced with `pact_ffi`.
affects: 3.0.0 and later
gotchaWhen defining provider states using `given()`, it's recommended to parameterize the state (e.g., `given("user exists", id=123)`) rather than embedding values directly in the state description (e.g., `given("user 123 exists")`). This makes provider state handlers more reusable and robust.
fix
Refactor provider state definitions to use keyword arguments for dynamic data, allowing the provider to set up the necessary state more flexibly.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pact'
The 'pact-python' library is either not installed in the current Python environment, or the environment is not correctly activated, preventing Python from finding the required 'pact' module during import.
fix
Install the library using pip: `pip install pact-python`.
The pact mock service doesn't appear to be running
The Pact mock service failed to start, or the consumer client was unable to establish a connection to it, frequently due to network issues such as corporate proxies, firewalls, or misconfigured host/port settings.
fix
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.
Missing requests
This error, or similar messages like 'Actual interactions do not match expected interactions,' indicates that the HTTP request sent by the consumer's code did not precisely match the expectations defined in the `pact-python` interaction, often due to discrepancies in the request method, URL path, headers (e.g., missing `Content-Type`), or body format.
fix
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.
TypeError: Object of type Like is not JSON serializable
Pact matchers like `Like`, `Term`, or `EachLike` are objects that should be passed directly to `body()` or used within dictionaries/lists for request/response bodies, not embedded as strings (e.g., in f-strings) in parts like the URL path or header values where a string is expected.
fix
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.
Upgrade
Version history
3.4.0latest on PyPI · released May 4, 2026
Audit
Dependencies
PythonrequiredRequires Python 3.10 or newer.
Agent activity
18 hits · last 30 days
node
14
Amazon
1
Resources
pact-python — pip install pact-python · libregistry