Function/dict state handlers can't supply provider-state injected values (`generate.provider_state`)
维护者通常 9 天内回复
还没有人认领这个 Issue。
评估
调研方向
从 verifier.py 中的 _handler 包装器开始,其中 apply_args(handler, ...) 丢弃了 handler 的返回值,然后在 _server.py 中的 StateCallbackHandler.do_POST 处,它总是以空 body 回复 200 OK。运行 issue 的 repro 或 verifier 的 state-handler 测试,以查看函数形式和 dict 形式发送的是 consumer 的 example id,而不是返回的 task id。完成意味着返回的 mapping 被序列化为 application/json 的 state-change body,并且三种 handler 形式全部通过,同时为新返回类型添加测试。
由索引模型根据 Issue 内容生成。
描述
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.
- 主要语言
- Python
- 星标
- 689
- 派生
- 147
- 平均合并
- 8 天 11 小时
- 30 天内合并 PR
- 27
环境准备
在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
pact-foundation/pact-python 的其他 Issue
-
Post v3 tracking issue可能重新可做 @JP-Ellis 于 412 天前认领,目前没有进行中的 PR。 未关闭type:tracking
pact-foundation/pact-python#1272 · 已指派 1 人 ·
维护者通常 9 天内回复
-
area:documentation difficulty:easy type:chore
难度 3/5 1-2 天 新手友好度 48/100
pact-foundation/pact-python#1267 ·
维护者通常 9 天内回复
-
area:documentation difficulty:easy type:chore
难度 3/5 1-2 天 新手友好度 45/100
pact-foundation/pact-python#1266 · 2 条评论 ·
维护者通常 9 天内回复
-
(V3) Verifying a contract with a missing content field is always successful when it should error可能已有人在做 @JP-Ellis 于 412 天前认领。 未关闭area:core type:bug
pact-foundation/pact-python#1103 · 5 条评论 · 已指派 1 人 ·
维护者通常 9 天内回复
-
Add a complete gRPC example可能已有人在做 @JP-Ellis 于 514 天前认领。 未关闭area:core area:documentation area:examples difficulty:medium smartbear-supported type:chore
pact-foundation/pact-python#1092 · 1 条评论 · 已指派 1 人 ·
维护者通常 9 天内回复
查看 pact-foundation/pact-python 的全部 Issue
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 78/100
huggingface/datasets#9128 ·
维护者通常 1 天内回复
-
priority:low ready-for-dev
难度 2/5 1-3 小时 新手友好度 68/100
OpenHands/extensions#975 ·
维护者通常 1 天内回复
-
documentation
难度 2/5 1-3 小时 新手友好度 82/100
juandresrodca/AdminForge#66 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 68/100
维护者通常 1 天内回复
-
backend/local comp/tools P2 tool/terminal type/bug
难度 2/5 1-3 小时 新手友好度 72/100
NousResearch/hermes-agent#158788 ·
维护者通常 1 天内回复