Skip to content

Test provider

Provider verification for binary payloads with matching rules.

This test runs a small FastAPI provider which stores opaque binary blobs, and verifies it against the contract generated by test_consumer.py.

The interesting part of provider verification for binary payloads is that the contract does not contain an exact byte sequence: the contentType matching rule only requires the payload to be of the declared type. The provider state handler below therefore seeds the store with a payload which differs from the example bytes in the contract, and verification still passes.

The provider must still return the correct Content-Type; the matching rule constrains the content type of the payload, so returning application/json or omitting the header will cause a mismatch.

Attributes

BLOBS: dict[str, bytes] = {} module-attribute

PROVIDER_BLOB = bytes([0, 66, 19, 55, 255, 127, 1]) module-attribute

RECEIVED_SIZES: list[int] = [] module-attribute

SERVED_SIZES: list[int] = [] module-attribute

app = FastAPI() module-attribute

FastAPI application serving a binary blob store.

Classes

Functions:

app_server() -> str

Run the FastAPI server for provider verification.

RETURNS DESCRIPTION
str

The base URL of the running FastAPI server.

Source code in examples/catalog/binary_payloads/test_provider.py
@pytest.fixture(scope="session")
def app_server() -> str:
    """
    Run the FastAPI server for provider verification.

    Returns:
        The base URL of the running FastAPI server.
    """
    hostname = "localhost"
    port = pact._util.find_free_port()  # noqa: SLF001
    Thread(
        target=uvicorn.run,
        args=(app,),
        kwargs={"host": hostname, "port": port},
        daemon=True,
    ).start()
    time.sleep(0.1)  # Allow server time to start
    return f"http://{hostname}:{port}"

download_blob(blob_id: str) -> Response async

Return a stored binary payload.

PARAMETER DESCRIPTION
blob_id

The ID of the blob to return.

TYPE: str

RETURNS DESCRIPTION
Response

The raw payload, served as application/octet-stream.

RAISES DESCRIPTION
HTTPException

If no blob exists with the given ID.

Source code in examples/catalog/binary_payloads/test_provider.py
@app.get("/blobs/{blob_id}")
async def download_blob(blob_id: str) -> Response:
    """
    Return a stored binary payload.

    Args:
        blob_id:
            The ID of the blob to return.

    Returns:
        The raw payload, served as `application/octet-stream`.

    Raises:
        HTTPException:
            If no blob exists with the given ID.
    """
    if blob_id not in BLOBS:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Blob not found",
        )
    payload = BLOBS[blob_id]
    SERVED_SIZES.append(len(payload))
    return Response(content=payload, media_type="application/octet-stream")

seed_blob(action: Literal['setup', 'teardown'], parameters: dict[str, Any]) -> None

Populate the blob store before an interaction which needs a stored blob.

PARAMETER DESCRIPTION
action

Either "setup" (before the interaction) or "teardown" (after).

TYPE: Literal['setup', 'teardown']

parameters

State parameters from the consumer contract. Must contain the "id" of the blob to create.

TYPE: dict[str, Any]

Source code in examples/catalog/binary_payloads/test_provider.py
def seed_blob(
    action: Literal["setup", "teardown"],
    parameters: dict[str, Any],
) -> None:
    """
    Populate the blob store before an interaction which needs a stored blob.

    Args:
        action:
            Either `"setup"` (before the interaction) or `"teardown"` (after).
        parameters:
            State parameters from the consumer contract. Must contain the
            `"id"` of the blob to create.
    """
    if "id" not in parameters:
        msg = "State must contain an 'id' field to seed a binary blob"
        raise ValueError(msg)

    blob_id = str(parameters["id"])

    if action == "setup":
        BLOBS[blob_id] = PROVIDER_BLOB
        return

    if action == "teardown":
        BLOBS.pop(blob_id, None)
        return

    msg = f"Unknown action: {action}"
    raise ValueError(msg)

test_provider(app_server: str) -> None

Verify the provider against the binary payload contract.

The verifier replays the interactions from the contract generated by the consumer tests. Binary request bodies are compared using the matching rules from the contract, and binary response bodies are verified the same way, so the provider may return any payload of the declared content type.

The "a binary blob exists" provider state seeds the store with PROVIDER_BLOB, whose bytes differ from the example in the contract. Verification passes because the contract only requires application/octet-stream.

Source code in examples/catalog/binary_payloads/test_provider.py
def test_provider(app_server: str) -> None:
    """
    Verify the provider against the binary payload contract.

    The verifier replays the interactions from the contract generated by the
    consumer tests. Binary request bodies are compared using the matching rules
    from the contract, and binary response bodies are verified the same way, so
    the provider may return any payload of the declared content type.

    The `"a binary blob exists"` provider state seeds the store with
    `PROVIDER_BLOB`, whose bytes differ from the example in the contract.
    Verification passes because the contract only requires
    `application/octet-stream`.
    """
    verifier = (
        Verifier("binary-provider")
        .add_source(Path(__file__).parents[1] / "pacts")
        .add_transport(url=app_server)
        .state_handler(
            {"a binary blob exists": seed_blob},
            teardown=True,
        )
    )

    verifier.verify()

    assert RECEIVED_SIZES, "The provider did not receive any binary payload"
    assert SERVED_SIZES, "The provider did not serve any binary payload"
    assert SERVED_SIZES[0] == len(PROVIDER_BLOB), (
        "Expected the provider to serve its own payload rather than the "
        "contract example"
    )

upload_blob(request: Request) -> dict[str, str | int] async

Store an uploaded binary payload and return its metadata.

PARAMETER DESCRIPTION
request

The incoming request. Its raw body is read without any parsing, as the payload is opaque binary data.

TYPE: Request

RETURNS DESCRIPTION
dict[str, str | int]

The ID of the stored blob and the size of the payload in bytes.

Source code in examples/catalog/binary_payloads/test_provider.py
@app.post("/blobs", status_code=status.HTTP_201_CREATED)
async def upload_blob(request: Request) -> dict[str, str | int]:
    """
    Store an uploaded binary payload and return its metadata.

    Args:
        request:
            The incoming request. Its raw body is read without any parsing, as
            the payload is opaque binary data.

    Returns:
        The ID of the stored blob and the size of the payload in bytes.
    """
    content = await request.body()
    RECEIVED_SIZES.append(len(content))
    blob_id = f"blob-{len(BLOBS) + 1}"
    BLOBS[blob_id] = content
    return {"id": blob_id, "size": len(content)}