Function/dict state handlers can't supply provider-state injected values (`generate.provider_state`)

Open Beginner friendly
#1,789 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 9 days

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
testing

Research direction

Start in verifier.py at the _handler wrappers, where apply_args(handler, ...) discards the handler's return value, then in _server.py at StateCallbackHandler.do_POST, which always replies 200 OK with an empty body. Run the issue's repro or the verifier state-handler tests to see the function and dict forms send the consumer's example id instead of the returned task id. Done means a returned mapping is serialized as an application/json state-change body and all three handler forms pass, with tests for the new return type.

Written by the indexing model from the issue text.

Description

Summary

A consumer can write generate.provider_state("${taskId}"), which tells the
verifier to fill the value in from the provider state. Pact core takes that
value from the JSON body of the state-change response. With a Python function
or dict state handler, nothing the handler returns gets back to Pact core:

  • Verifier.state_handler and _state_handler_function / _state_handler_dict
    type the handler as Callable[..., None].
  • The internal wrappers (_handler in verifier.py) call
    apply_args(handler, ...) and throw away the result.
  • StateCallbackHandler.do_POST in _server.py always answers
    200 OK with an empty body.

So the verifier quietly falls back to the consumer's example value. The only
way to inject values is to run a separate HTTP endpoint and pass it as a URL
state handler, even though the docstring calls the function and dict forms
"the preferred options if the provider is written in Python".

Checked against pact-python 4.2.0 (latest on PyPI) and main as of 2026-11-22.

Reproduction

Self-contained; needs only pact-python (4.2.0, Python 3.13, Windows 11). The provider only knows a task once the state handler has created it, and the consumer's path uses generate.provider_state("/tasks/${taskId}"). The same pact is verified with all three handler forms.

"""Minimal repro: Python function/dict state handlers cannot supply
provider-state injected values; a URL state handler can.

Requires only `pact-python` (tested with 4.2.0). Run: python repro.py
"""

from __future__ import annotations

import json
import tempfile
import threading
import urllib.request
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from pact import Pact, Verifier, generate, match

STATE = "a task exists"
EXAMPLE_ID = "example-id"


def serve(handler_cls: type[BaseHTTPRequestHandler]) -> tuple[ThreadingHTTPServer, str]:
    srv = ThreadingHTTPServer(("127.0.0.1", 0), handler_cls)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv, f"http://127.0.0.1:{srv.server_address[1]}"


# --- consumer: write the pact -------------------------------------------------
def write_pact(out: Path) -> Path:
    pact = Pact("task-consumer", "task-provider").with_specification("V4")
    (
        pact.upon_receiving("a request for an existing task")
        .given(STATE)
        .with_request(
            "GET",
            match.like(
                f"/tasks/{EXAMPLE_ID}",
                generator=generate.provider_state("/tasks/${taskId}"),
            ),
        )
        .will_respond_with(200)
    )
    with pact.serve() as srv:
        urllib.request.urlopen(f"{srv.url}/tasks/{EXAMPLE_ID}").read()
    pact.write_file(out)
    return out / "task-consumer-task-provider.json"


# --- provider: tasks only exist once the state handler creates them ----------
TASKS: set[str] = set()
SEEN_PATHS: list[str] = []


class Provider(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        SEEN_PATHS.append(self.path)
        task_id = self.path.removeprefix("/tasks/")
        self.send_response(200 if task_id in TASKS else 404)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def log_message(self, *args: object) -> None:
        pass


def create_task() -> dict[str, str]:
    task_id = str(uuid.uuid4())
    TASKS.add(task_id)
    return {"taskId": task_id}


# --- the three state-handler forms -------------------------------------------
def function_handler(state: str, action: str, parameters: dict | None = None):
    if action == "setup":
        return create_task()  # return value is discarded by pact-python
    return None


def dict_handler(parameters: dict | None = None):
    return create_task()  # return value is discarded by pact-python


class UrlStateHandler(BaseHTTPRequestHandler):
    def do_POST(self) -> None:
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])) or b"{}")
        out = create_task() if body.get("action", "setup") == "setup" else {}
        data = json.dumps(out).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args: object) -> None:
        pass


def verify(pact_file: Path, provider_url: str, configure) -> str:
    SEEN_PATHS.clear()
    verifier = (
        Verifier("task-provider", host="127.0.0.1")
        .add_transport(url=provider_url)
        .add_source(str(pact_file))
    )
    configure(verifier)
    try:
        verifier.verify()
        verdict = "PASS"
    except Exception as exc:  # noqa: BLE001
        first = next((l.strip() for l in str(exc).splitlines() if "status" in l.lower()), "")
        verdict = f"FAIL ({first or type(exc).__name__})"
    return f"{verdict}; provider saw {SEEN_PATHS}"


def main() -> None:
    pact_file = write_pact(Path(tempfile.mkdtemp()))
    provider, provider_url = serve(Provider)
    url_srv, url_base = serve(UrlStateHandler)

    print("function handler:", verify(pact_file, provider_url,
          lambda v: v.state_handler(function_handler, teardown=True)))
    print("dict handler:    ", verify(pact_file, provider_url,
          lambda v: v.state_handler({STATE: dict_handler})))
    print("URL handler:     ", verify(pact_file, provider_url,
          lambda v: v.state_handler(f"{url_base}/state", teardown=True, body=True)))

    provider.shutdown()
    url_srv.shutdown()


if __name__ == "__main__":
    main()

Output on 4.2.0:

function handler: FAIL (RuntimeError); provider saw ['/tasks/example-id']
dict handler:     FAIL (RuntimeError); provider saw ['/tasks/example-id']
URL handler:      PASS; provider saw ['/tasks/efa298f0-7f09-490d-a52a-b2d78ac3d21f']

The function and dict handlers both return {"taskId": ...}, but the verifier sends the consumer's example id and gets a 404 (expected 200 but was 404).

Expected

Either:

  1. A handler that returns a mapping gets it serialised as the state-change
    response body (JSON), so injected values work. The return type would become
    dict[str, Any] | None. Or
  2. The state_handler docs say plainly that function and dict handlers
    can't supply provider-state values, and point to the URL form.

Option 1 is small. I tried it locally: return apply_args(...) in the two
_handler wrappers in verifier.py, plus writing a dict result as an
application/json body in StateCallbackHandler.do_POST. With that change all
three handler forms in the repro pass. Happy to open a PR with tests if you'd
take it.

Dominant language
Python
Stars
689
Forks
147
Avg merge
8d 11h
Merged PRs (30d)
27

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from pact-foundation/pact-python

All issues in pact-foundation/pact-python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.