Function/dict state handlers can't supply provider-state injected values (`generate.provider_state`)
Los mantenedores suelen responder en 9 días
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 78/100
Línea de trabajo
Empieza en verifier.py en los wrappers de _handler, donde apply_args(handler, ...) descarta el valor de retorno del handler, luego en _server.py en StateCallbackHandler.do_POST, que siempre responde 200 OK con un cuerpo vacío. Ejecuta el repro del issue o las pruebas del state-handler del verifier para ver que las formas de función y dict envían el id de ejemplo del consumidor en lugar del id de la tarea devuelta. Hecho significa que un mapping devuelto se serializa como un cuerpo de cambio de estado application/json y que las tres formas de handler pasan, con pruebas para el nuevo tipo de retorno.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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.
- Lenguaje dominante
- Python
- Estrellas
- 689
- Forks
- 147
- Merge medio
- 8 d 11 h
- PR fusionados (30 d)
- 27
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de pact-foundation/pact-python
-
Post v3 tracking issueQuizá libre de nuevo @JP-Ellis la tomó hace 412 días y no hay ningún pull request abierto. Abiertotype:tracking
pact-foundation/pact-python#1272 · 1 asignado ·
Los mantenedores suelen responder en 9 días
-
area:documentation difficulty:easy type:chore
Dificultad 3/5 1-2 días Aptitud para principiantes 48/100
pact-foundation/pact-python#1267 ·
Los mantenedores suelen responder en 9 días
-
Create message Pact docsAbiertoarea:documentation difficulty:easy type:chore
Dificultad 3/5 1-2 días Aptitud para principiantes 45/100
pact-foundation/pact-python#1266 · 2 comentarios ·
Los mantenedores suelen responder en 9 días
-
(V3) Verifying a contract with a missing content field is always successful when it should errorPosiblemente ocupada @JP-Ellis la tomó hace 412 días. Abiertoarea:core type:bug
pact-foundation/pact-python#1103 · 5 comentarios · 1 asignado ·
Los mantenedores suelen responder en 9 días
-
Add a complete gRPC examplePosiblemente ocupada @JP-Ellis la tomó hace 514 días. Abiertoarea:core area:documentation area:examples difficulty:medium smartbear-supported type:chore
pact-foundation/pact-python#1092 · 1 comentario · 1 asignado ·
Los mantenedores suelen responder en 9 días
Todos los issues de pact-foundation/pact-python
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
huggingface/datasets#9128 ·
Los mantenedores suelen responder en 1 día
-
priority:low ready-for-dev
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
OpenHands/extensions#975 ·
Los mantenedores suelen responder en 1 día
-
documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
juandresrodca/AdminForge#66 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
-
backend/local comp/tools P2 tool/terminal type/bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
NousResearch/hermes-agent#158788 ·
Los mantenedores suelen responder en 1 día