API Documentation - Pact Python
Pact Python V3.
This package provides contract testing capabilities for Python applications using the Pact specification. Built on the Pact Rust FFI library, it offers full support for all Pact features and maintains compatibility with other Pact implementations.
Package Structure¶
Main Classes¶
The primary entry points for contract testing are:
Pact: For consumer-side contract testing, defining expected interactions and generating contract files.Verifier: For provider-side contract verification, validating that a provider implementation satisfies consumer contracts.
These functions are defined in pact.pact and
pact.verifier and re-exported for convenience.
Matching and Generation¶
For flexible contract definitions, use the matching and generation modules:
from pact import match, generate
# Import modules, not individual functions
# Use functions via module namespace to avoid shadowing built-ins
user_id = match.int(min=1)
user_name = match.str(size=20)
created_at = match.datetime()
# Generators work similarly
response_id = generate.uuid()
score = generate.float(precision=2)
The functions within these modules are designed to align with a number of Python built-in types and functions. As such, the module should be imported as a whole, rather than importing individual functions to avoid potential shadowing of built-ins.
Utility Modules¶
error: Exception classes used throughout the package. Typically not imported directly unless implementing custom error handling.types: Type definitions and protocols. This does not provide much functionality, but will be used by your type-checker.
Basic Usage¶
Consumer Testing¶
from pact import Pact, match
# Create a consumer contract
pact = Pact("consumer", "provider")
# Define expected interactions
(
pact
.upon_receiving("get user")
.given("user exists")
.with_request(method="GET", path="/users/123")
.will_respond_with(
status=200,
body={
"id": match.int(123),
"name": match.str("alice"),
},
)
)
# Use in tests with the mock server
with pact.serve() as server:
# Make requests to server.url
# Test your consumer code
pass
Provider Verification¶
from pact import Verifier
# Verify provider against contracts
verifier = Verifier()
verifier.verify_with_broker(
provider="provider-name",
broker_url="https://my-org.pactflow.io",
)
For more detailed usage examples, see the examples.
Classes¶
Pact(consumer: str, provider: str)
¶
A Pact between a consumer and a provider.
This class defines a Pact between a consumer and a provider. It is the central class in Pact's framework, and is responsible for defining the interactions between the two parties.
One Pact instance should be created for each provider that a consumer
interacts with. The methods on this class are used to define the broader
attributes of the Pact, such as the consumer and provider names, the Pact
specification, any plugins that are used, and any metadata that is attached
to the Pact.
Each interaction between the consumer and the provider is defined through
the upon_receiving method, which
returns a sub-class of Interaction.
| PARAMETER | DESCRIPTION |
|---|---|
consumer
|
Name of the consumer.
TYPE:
|
provider
|
Name of the provider.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the consumer or provider name is empty. |
Source code in src/pact/pact.py
Attributes¶
consumer: str
property
¶
Consumer name.
provider: str
property
¶
Provider name.
specification: pact_ffi.PactSpecification
property
¶
Pact specification version.
Functions¶
interactions(kind: Literal['HTTP', 'Sync', 'Async', 'All'] = 'HTTP') -> Generator[pact_ffi.SynchronousHttp, None, None] | Generator[pact_ffi.SynchronousMessage, None, None] | Generator[pact_ffi.AsynchronousMessage, None, None] | Generator[pact_ffi.PactInteraction, None, None]
¶
Return an iterator over the Pact's interactions.
The kind is used to specify the type of interactions that will be iterated over.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the kind is unknown. |
Source code in src/pact/pact.py
serve(addr: str = 'localhost', port: int = 0, transport: str = 'http', transport_config: str | None = None, *, raises: bool = True, verbose: bool = True) -> PactServer
¶
Return a mock server for the Pact.
This function configures a mock server for the Pact. The mock server
is then started when the Pact is entered into a with block:
| PARAMETER | DESCRIPTION |
|---|---|
addr
|
Address to bind the mock server to. Defaults to
TYPE:
|
port
|
Port to bind the mock server to. Defaults to
TYPE:
|
transport
|
Transport to use for the mock server. Defaults to
TYPE:
|
transport_config
|
Configuration for the transport. This is specific to the transport being used and should be a JSON string.
TYPE:
|
raises
|
Whether to raise an exception if there are mismatches between
the Pact and the server. If set to
TYPE:
|
verbose
|
Whether or not to print the mismatches to the logger. This works
independently of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PactServer
|
PactServer instance. |
Source code in src/pact/pact.py
upon_receiving(description: str, interaction: Literal['HTTP', 'Sync', 'Async'] = 'HTTP') -> HttpInteraction | AsyncMessageInteraction | SyncMessageInteraction
¶
Create a new Interaction.
| PARAMETER | DESCRIPTION |
|---|---|
description
|
Description of the interaction. This must be unique within the Pact.
TYPE:
|
interaction
|
Type of interaction. Defaults to
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the interaction type is invalid. |
Source code in src/pact/pact.py
using_plugin(name: str, version: str | None = None) -> Self
¶
Add a plugin to be used by the test.
Plugins extend the functionality of Pact.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the plugin.
TYPE:
|
version
|
Version of the plugin. This is optional and can be
TYPE:
|
Source code in src/pact/pact.py
verify(handler: Callable[[str | bytes | None, dict[str, object]], None], kind: Literal['Async', 'Sync'], *, raises: bool = True) -> list[InteractionVerificationError] | None
¶
Verify message interactions.
This function is used to ensure that the consumer is able to handle the
messages that are defined in the Pact. The handler function is called
for each message in the Pact.
The end-user is responsible for defining the handler function and
verifying that the messages are handled correctly. For example, if the
handler is meant to call an API, then the API call should be mocked out
and once the verification is complete, the mock should be verified. Any
exceptions raised by the handler will be caught and reported as
mismatches.
| PARAMETER | DESCRIPTION |
|---|---|
handler
|
The function that will be called for each message in the Pact. The first argument to the function is the message body, either as a string or byte array. The second argument is the metadata for the message. If there is no metadata, then this will be an empty dictionary.
TYPE:
|
kind
|
The type of message interaction. This must be one of
TYPE:
|
raises
|
Whether or not to raise an exception if the handler fails to
process a message. If set to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[InteractionVerificationError] | None
|
|
list[InteractionVerificationError] | None
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the message type is unknown. |
PactVerificationError
|
If raises is True and there are errors. |
Source code in src/pact/pact.py
with_metadata(namespace: str, metadata: dict[str, str]) -> Self
¶
Set additional metadata for the Pact.
A common use for this function is to add information about the client library (name, version, hash, etc.) to the Pact.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Namespace for the metadata. This is used to group the metadata together.
TYPE:
|
metadata
|
Key-value pairs of metadata to add to the Pact. |
Source code in src/pact/pact.py
with_specification(version: str | pact_ffi.PactSpecification) -> Self
¶
Set the Pact specification version.
The Pact specification version indicates the features which are supported by the Pact, and certain default behaviours.
If this method is not called, then the Pact will use version 4 of the specification by default.
| PARAMETER | DESCRIPTION |
|---|---|
version
|
Pact specification version. This can be either a string or a
The version string is case insensitive and has an optional
TYPE:
|
Source code in src/pact/pact.py
write_file(directory: Path | str | None = None, *, overwrite: bool = False) -> None
¶
Write out the pact to a file.
This function should be called once all of the consumer tests have been run. It writes the Pact to a file, which can then be used to validate the provider.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
The directory to write the pact to. If the directory does not exist, it will be created. The filename will be automatically generated from the underlying Pact. |
overwrite
|
If set to True, the file will be overwritten if it already exists. Otherwise, the contents of the file will be merged with the existing file.
TYPE:
|
Source code in src/pact/pact.py
Verifier(name: str, host: str | None = None)
¶
A Verifier between a consumer and a provider.
This class encapsulates the logic for verifying that a provider meets the expectations of a consumer. This is done by replaying interactions from the consumer against the provider, and ensuring that the provider's responses match the expectations set by the consumer.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The name of the provider to verify. This is used to identify which interactions the provider is involved in, and then Pact will replay these interactions against the provider.
TYPE:
|
host
|
The host on which the Pact verifier is running. This is used to
communicate with the provider. If not specified, the default
value is
TYPE:
|
Source code in src/pact/verifier.py
Attributes¶
logs: str
property
¶
Get the logs.
results: dict[str, Any]
property
¶
Get the results.
Functions¶
Add a customer header to the request.
These headers are added to every request made to the provider.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The key of the header.
TYPE:
|
value
|
The value of the header.
TYPE:
|
Source code in src/pact/verifier.py
Add multiple customer headers to the request.
These headers are added to every request made to the provider.
| PARAMETER | DESCRIPTION |
|---|---|
headers
|
The headers to add. The value can be: - a dictionary of header key-value pairs - an iterable of (key, value) tuples |
Source code in src/pact/verifier.py
add_source(source: str | Path | URL, *, username: str | None = None, password: str | None = None, token: str | None = None) -> Self
¶
Adds a source to the verifier.
This will use one or more Pact files as the source of interactions to verify.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The source of the interactions. This may be either of the following:
If using a URL, the |
username
|
The username to use for basic HTTP authentication. This is only used when the source is a URL.
TYPE:
|
password
|
The password to use for basic HTTP authentication. This is only used when the source is a URL.
TYPE:
|
token
|
The token to use for bearer token authentication. This is only
used when the source is a URL. Note that this is mutually
exclusive with
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source scheme is invalid. |
Source code in src/pact/verifier.py
add_transport(*, url: str | URL | None = None, protocol: str | None = None, port: int | None = None, path: str | None = None, scheme: str | None = None) -> Self
¶
Add a provider transport method.
If the provider supports multiple transport methods, or non-HTTP(S) methods, this method allows these additional transport methods to be added. It can be called multiple times to add multiple transport methods.
As some transport methods may not use ports, paths or schemes, these
parameters are optional. Note that while optional, these may still be
used during testing as Pact uses HTTP(S) to communicate with the
provider. For example, if you are implementing your own message
verification, it needs to be exposed over HTTP and the port and path
arguments are used for this testing communication.
| PARAMETER | DESCRIPTION |
|---|---|
url
|
A convenient way to set the provider transport. This option is mutually exclusive with the other options.
TYPE:
|
protocol
|
The protocol to use. This will typically be one of:
Any other protocol will be treated as a custom protocol and will be handled by a plugin. If
TYPE:
|
port
|
The provider port. If the protocol does not use ports, this parameter should be
TYPE:
|
path
|
The provider context path. For protocols which do not use paths, this parameter should be
For protocols which do use paths, this parameter should be specified to avoid any ambiguity, though if left unspecified, the root path will be used. If a non-root path is used, the path given here will be
prepended to the path in the interaction. For example, if the
path is
TYPE:
|
scheme
|
The provider scheme, if applicable to the protocol. This is typically only used for the
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If mutually exclusive parameters are provided, or required parameters are missing, or host/protocol mismatches. |
Source code in src/pact/verifier.py
broker_source(url: str | URL | None | Unset = UNSET, *, username: str | None | Unset = UNSET, password: str | None | Unset = UNSET, token: str | None | Unset = UNSET, selector: bool = False, use_env: bool = True) -> BrokerSelectorBuilder | Self
¶
broker_source(
url: str | URL | Unset = UNSET,
*,
username: str | Unset = UNSET,
password: str | Unset = UNSET,
selector: Literal[False] = False,
use_env: bool = True,
) -> Self
broker_source(
url: str | URL | None | Unset = UNSET,
*,
token: str | None | Unset = UNSET,
selector: Literal[False] = False,
use_env: bool = True,
) -> Self
Adds a broker source to the verifier.
If any of the values are None, the value will be read from the
environment variables unless the use_env parameter is set to False.
The known variables are:
PACT_BROKER_BASE_URLfor theurlparameter.PACT_BROKER_USERNAMEfor theusernameparameter.PACT_BROKER_PASSWORDfor thepasswordparameter.PACT_BROKER_TOKENfor thetokenparameter.
By default, or if selector=False, this function returns the verifier
instance to allow for method chaining. If selector=True is given, this
function returns a BrokerSelectorBuilder
instance which allows for further configuration of the broker source in
a fluent interface. The build() call is
then used to finalise the broker source and return the verifier instance
for further configuration.
| PARAMETER | DESCRIPTION |
|---|---|
url
|
The broker URL. The URL may contain a username and password for basic HTTP authentication. |
username
|
The username to use for basic HTTP authentication. If the source
is a URL containing a username, this parameter must be |
password
|
The password to use for basic HTTP authentication. If the source
is a URL containing a password, this parameter must be |
token
|
The token to use for bearer token authentication. This is
mutually exclusive with |
selector
|
Whether to return a
BrokerSelectorBuilder instance. The
builder instance allows for further configuration of the broker
source and must be finalised with a call to
TYPE:
|
use_env
|
Whether to read missing values from the environment variables.
This is
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If mutually exclusive authentication parameters are provided. |
Source code in src/pact/verifier.py
disable_ssl_verification() -> Self
¶
Disable SSL verification.
Source code in src/pact/verifier.py
filter(description: str | None = None, *, state: str | None = None, no_state: bool = False) -> Self
¶
Set the filter for the interactions.
This method can be used to filter interactions based on their description and state. Repeated calls to this method will replace the previous filter.
| PARAMETER | DESCRIPTION |
|---|---|
description
|
The interaction description. This should be a regular expression. If unspecified, no filtering will be done based on the description.
TYPE:
|
state
|
The interaction state. This should be a regular expression. If unspecified, no filtering will be done based on the state.
TYPE:
|
no_state
|
Whether to include interactions with no state.
TYPE:
|
Source code in src/pact/verifier.py
filter_consumers(*filters: str) -> Self
¶
Filter the consumers.
| PARAMETER | DESCRIPTION |
|---|---|
filters
|
Filters to apply to the consumers.
TYPE:
|
logs_for_provider(provider: str) -> str
classmethod
¶
message_handler(handler: Callable[..., Message] | dict[str, Callable[..., Message] | Message | bytes]) -> Self
¶
Set the message handler.
This method sets a custom message handler for the verifier. The handler can be called to produce a specific message to send to the provider.
This can be provided in one of two ways:
-
A fully fledged function that will be called for all messages. This is the most powerful option as it allows for full control over the message generation. The function's signature must be compatible with the
MessageProducerArgstype. -
A dictionary mapping message names to either (a) producer functions, (b)
Messagedictionaries, or © raw bytes. If using a producer function, it must be compatible with theMessageProducerArgstype.
Implementation¶
There are a large number of ways to send messages, and the specifics of the transport methods are not specifically relevant to Pact. As such, Pact abstracts the transport layer away and uses a lightweight HTTP server to handle messages.
Pact Python is capable of setting up this server and handling the
messages internally using user-provided handlers. It is possible to use
your own HTTP server to handle messages by using the add_transport
method. It is not possible to use both this method and add_transport
to handle messages.
| PARAMETER | DESCRIPTION |
|---|---|
handler
|
The message handler. This should be a callable or a dictionary mapping message names to callables, Message dicts, or bytes.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the handler or its values are invalid. |
Source code in src/pact/verifier.py
output(*, strip_ansi: bool = False) -> str
¶
set_coloured_output(*, enabled: bool = True) -> Self
¶
set_error_on_empty_pact(*, enabled: bool = True) -> Self
¶
Toggle error on empty pact.
If enabled, a Pact file with no interactions will cause the verifier to return an error. If disabled, a Pact file with no interactions will be ignored.
Source code in src/pact/verifier.py
set_publish_options(version: str, url: str | None = None, branch: str | None = None, tags: list[str] | None = None) -> Self
¶
Set options used when publishing results to the Broker.
| PARAMETER | DESCRIPTION |
|---|---|
version
|
The provider version.
TYPE:
|
url
|
URL to the build which ran the verification.
TYPE:
|
tags
|
Collection of tags for the provider. |
branch
|
Name of the branch used for verification. The first time a branch is set here or through
TYPE:
|
Source code in src/pact/verifier.py
set_request_timeout(timeout: int) -> Self
¶
Set the request timeout.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
The request timeout in milliseconds.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the timeout is negative. |
Source code in src/pact/verifier.py
state_handler(handler: Callable[..., None] | Mapping[str, Callable[..., None]] | StateHandlerUrl, *, teardown: bool = False, body: bool | None = None) -> Self
¶
state_handler(
handler: Callable[..., None],
*,
teardown: bool = False,
body: None = None,
) -> Self
Set the state handler.
In many interactions, the consumer will assume that the provider is in a
certain state. For example, a consumer requesting information about a
user with ID 123 will have specified given("user with ID 123
exists").
The state handler is responsible for changing the provider's internal state to match the expected state before the interaction is replayed.
This can be done in one of three ways:
- By providing a single function that will be called for all state changes.
- By providing a mapping of state names to functions.
- By providing the URL endpoint to which the request should be made.
The last option is more complicated as it requires the provider to be able to handle the state change requests. The first two options handle this internally and are the preferred options if the provider is written in Python.
The function signature must be compatible with the
StateHandlerArgs. If the function has
additional arguments, these must either have default values, or be
filled by using the partial function.
Pact also uses a special state denoted with the empty string "". This
is used as a generic test setup/teardown handler. This key is optional
in dictionaries, but other implementation should ensure they can handle
(or safely ignore) this state name.
| PARAMETER | DESCRIPTION |
|---|---|
handler
|
The handler for the state changes. This can be one of the following:
See above for more information on the function signature.
TYPE:
|
teardown
|
Whether to teardown the provider state after an interaction is validated.
TYPE:
|
body
|
Whether to include the state change request in the body (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the handler/body combination is invalid. |
TypeError
|
If the handler type is invalid. |
Source code in src/pact/verifier.py
verify() -> Self
¶
Verify the interactions.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
Whether the interactions were verified successfully. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If no transports have been set. |