Test consumer
Consumer tests demonstrating binary payloads with matching rules.
Binary payloads (images, archives, compiled artefacts, etc.) cannot be
represented as JSON or XML, so Pact stores them as raw bytes and encodes them
as base64 within the generated contract. This means the contract cannot express
matching rules inside the payload. Instead, matching rules are applied to the
payload as a whole, and the most useful of these is the contentType matcher:
The contract then requires that the payload be of the declared content type, rather than an exact byte-for-byte match, so the provider may return (or accept) any payload of that type. Exact byte matching is the default when no matching rule is defined, which in practice makes binary contracts extremely brittle.
The example below models a small blob store: the consumer uploads an opaque
binary payload and later downloads it again. Both directions use
with_binary_body to declare the payload, with a contentType matching rule
on the body root ($).
The payloads here are arbitrary bytes with no meaning of their own, so the
declared type is application/octet-stream. A payload known to be a specific
format should declare that format (for example image/png) instead: the
matching rule constrains the type the provider must return.
Attributes¶
ACTUAL_BLOB = bytes([222, 173, 190, 239, 0, 17, 34, 51, 68, 85])
module-attribute
¶
CONTRACT_BLOB = bytes([0, 1, 2, 3, 255, 254, 16, 32])
module-attribute
¶
Classes¶
Functions:¶
pact() -> Generator[Pact, None, None]
¶
Set up Pact for consumer contract testing.
The generated contract is written to the pacts directory shared by all
catalog entries, where the provider test picks it up for verification.
Source code in examples/catalog/binary_payloads/test_consumer.py
test_download_binary_blob(pact: Pact) -> None
¶
Test downloading a binary payload with a matching rule.
The response body is declared in the same way as the request body above:
raw bytes via with_binary_body, plus a contentType matching rule on
$. The mock server returns the example bytes from the contract, so the
consumer can assert on the exact payload it receives.
Source code in examples/catalog/binary_payloads/test_consumer.py
test_upload_binary_blob(pact: Pact) -> None
¶
Test uploading a binary payload with a matching rule.
The request body is declared with with_binary_body() and a
contentType matching rule on $. The test then sends a payload
with different contents and a different length, which the mock server
accepts because the rule only constrains the content type.
The response is JSON and is matched field-by-field in the usual way, which
shows that a binary request can be combined with a structured response.
The size field uses match.int() so the provider is free to report the
real size of whatever payload it received.