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

Offen Anfängerfreundlich
#1,789 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 9 Tagen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
78/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
python
Bereich
testing

Rechercherichtung

Beginne in verifier.py bei den _handler-Wrappern, wo apply_args(handler, ...) den Rückgabewert des Handlers verwirft, dann in _server.py bei StateCallbackHandler.do_POST, der immer 200 OK mit leerem Body antwortet. Führe das Repro des Issues oder die Verifier-State-Handler-Tests aus, um zu sehen, dass die Funktions- und Dict-Formen die Beispiel-ID des Consumers statt der zurückgegebenen Task-ID senden. Fertig bedeutet, dass ein zurückgegebenes Mapping als application/json-State-Change-Body serialisiert wird und alle drei Handler-Formen bestehen, mit Tests für den neuen Rückgabetyp.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

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.

Vorherrschende Sprache
Python
Sterne
689
Forks
147
Ø Merge
8 T. 11 Std.
Gemergte PRs (30 T.)
27

Entwicklungsumgebung

In Codespaces öffnen

Startet den Dev-Container des Projekts im Browser, mit Ihrem eigenen GitHub-Konto.

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus pact-foundation/pact-python

Alle Issues in pact-foundation/pact-python

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.