Function/dict state handlers can't supply provider-state injected values (`generate.provider_state`)
Les mainteneurs répondent en général sous 9 jours
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 78/100
Piste de recherche
Commence dans verifier.py au niveau des wrappers _handler, où apply_args(handler, ...) ignore la valeur de retour du handler, puis dans _server.py au niveau de StateCallbackHandler.do_POST, qui répond toujours 200 OK avec un corps vide. Exécute le repro de l'issue ou les tests du state-handler du verifier pour voir que les formes fonction et dict envoient l'id d'exemple du consumer au lieu de l'id de tâche retourné. Terminé signifie qu'un mapping retourné est sérialisé comme corps de changement d'état application/json et que les trois formes de handler passent, avec des tests pour le nouveau type de retour.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
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_handlerand_state_handler_function/_state_handler_dict
type the handler asCallable[..., None].- The internal wrappers (
_handlerinverifier.py) call
apply_args(handler, ...)and throw away the result. StateCallbackHandler.do_POSTin_server.pyalways answers
200 OKwith 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:
- 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 - The
state_handlerdocs 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.
- Langage dominant
- Python
- Étoiles
- 689
- Forks
- 147
- Merge moyen
- 8 j 11 h
- PR mergées (30 j)
- 27
Préparer son environnement
Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.
- Aucun Dockerfile ni fichier Docker Compose
- Propose un modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de pact-foundation/pact-python
-
Post v3 tracking issuePeut-être à nouveau libre @JP-Ellis l’a pris il y a 412 jours, et aucune pull request n’est ouverte. Ouvertetype:tracking
pact-foundation/pact-python#1272 · 1 personne assignée ·
Les mainteneurs répondent en général sous 9 jours
-
area:documentation difficulty:easy type:chore
Difficulté 3/5 1-2 jours Accessibilité débutants 48/100
pact-foundation/pact-python#1267 ·
Les mainteneurs répondent en général sous 9 jours
-
Create message Pact docsOuvertearea:documentation difficulty:easy type:chore
Difficulté 3/5 1-2 jours Accessibilité débutants 45/100
pact-foundation/pact-python#1266 · 2 commentaires ·
Les mainteneurs répondent en général sous 9 jours
-
(V3) Verifying a contract with a missing content field is always successful when it should errorPeut-être pris @JP-Ellis l’a pris il y a 412 jours. Ouvertearea:core type:bug
pact-foundation/pact-python#1103 · 5 commentaires · 1 personne assignée ·
Les mainteneurs répondent en général sous 9 jours
-
Add a complete gRPC examplePeut-être pris @JP-Ellis l’a pris il y a 514 jours. Ouvertearea:core area:documentation area:examples difficulty:medium smartbear-supported type:chore
pact-foundation/pact-python#1092 · 1 commentaire · 1 personne assignée ·
Les mainteneurs répondent en général sous 9 jours
Toutes les issues de pact-foundation/pact-python
Issues similaires
-
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
huggingface/datasets#9128 ·
Les mainteneurs répondent en général sous 1 jour
-
priority:low ready-for-dev
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
OpenHands/extensions#975 ·
Les mainteneurs répondent en général sous 1 jour
-
documentation
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
juandresrodca/AdminForge#66 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
Les mainteneurs répondent en général sous 1 jour
-
backend/local comp/tools P2 tool/terminal type/bug
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
NousResearch/hermes-agent#158788 ·
Les mainteneurs répondent en général sous 1 jour