#!/usr/bin/env python3 """Deterministic local HTTP fixture for marqdo-ext-ai integration tests. This is a test double for an OpenAI-compatible Chat Completions endpoint, not a second product protocol. One process serves one scenario on an ephemeral loopback port and records every request it receives to a JSONL file so the test runner can count requests and inspect what the CLI actually sent. Security: the fixture never prints request headers and records `Authorization` as a redacted marker only. Tests use synthetic data exclusively. """ from __future__ import annotations import argparse import json import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path REDACTED = "" VALID_SELECT = {"status": "selected", "keys": ["k1", "k2"], "reason": "两个候选与任务相关"} VALID_CLASSIFY = {"label": "方法A"} VALID_PROCUREMENT = { "assessments": [ {"supplier_id": "A", "assessment": "match", "evidence_ids": ["e1"], "reason": "材料描述了所需资质"}, {"supplier_id": "D", "assessment": "match", "evidence_ids": ["e4"], "reason": "材料声称拥有资质"}, {"supplier_id": "E", "assessment": "unknown", "evidence_ids": ["e5"], "reason": "材料描述模糊"}, ], } SCENARIOS = { "valid_select": {"content": json.dumps(VALID_SELECT, ensure_ascii=False)}, "valid_classify": {"content": json.dumps(VALID_CLASSIFY, ensure_ascii=False)}, "valid_yes": {"content": json.dumps({"label": "是"}, ensure_ascii=False)}, "valid_procurement": {"content": json.dumps(VALID_PROCUREMENT, ensure_ascii=False)}, "valid_text": {"content": "好的"}, "usage_meta": { "content": json.dumps(VALID_SELECT, ensure_ascii=False), "model": "fixture-model-2", "id": "chatcmpl-fixture-1", "usage": {"prompt_tokens": 12, "completion_tokens": 7}, }, "extra_field": {"content": json.dumps({"label": "方法A", "extra": 1}, ensure_ascii=False)}, "bad_enum": {"content": json.dumps({"label": "方法X"}, ensure_ascii=False)}, "tool_calls": { "content": None, "tool_calls": [ {"id": "call_1", "type": "function", "function": {"name": "run_shell", "arguments": "{}"}} ], }, "trailing_text": {"content": json.dumps(VALID_CLASSIFY, ensure_ascii=False) + " extra"}, "duplicate_keys": {"content": '{"label":"方法A","label":"方法B"}'}, "not_json": {"content": "抱歉,我无法按要求返回。"}, "finish_length": { "content": json.dumps({"label": "方法A"}, ensure_ascii=False), "finish_reason": "length", }, "null_content_length": { "content": None, "finish_reason": "length", }, "finish_filter": { "content": json.dumps({"label": "方法A"}, ensure_ascii=False), "finish_reason": "content_filter", }, "http_429": {"status": 429, "content": "rate limited"}, "http_500": {"status": 500, "content": "server error"}, "http_401": {"status": 401, "content": "bad credential"}, "missing_choices": {"envelope": {"id": "x", "object": "chat.completion"}}, "multi_choice": {"envelope": {"choices": [{"message": {"content": "a"}, "finish_reason": "stop"}, {"message": {"content": "b"}, "finish_reason": "stop"}]}}, "chunked_valid": {"content": json.dumps(VALID_SELECT, ensure_ascii=False), "chunked": True}, "non_finite": {"content": '{"score":1e400}'}, "unsafe_int": {"content": '{"score":123456789012345678901234567890}'}, "oversize_output": {"content": "x" * 300000}, "long_json": {"content": '{"label":"' + "x" * 2000 + '", "note": "' + "y" * 100 + '"}'}, "oversize_response": {"content": '{"label":"' + "x" * 5000 + '"}'}, "empty_content": {"content": ""}, "malformed_http": {"raw": b"not an http response"}, "delay_2s": {"content": json.dumps(VALID_CLASSIFY, ensure_ascii=False), "delay": 2.0}, } CONTRACT_OBJECT = { "schema": "object", "properties": {"label": {"schema": "string", "enum": ["方法A", "方法B"]}}, "required": ["label"], } def build_envelope(scenario: dict) -> bytes: if "raw" in scenario: return scenario["raw"] if "envelope" in scenario: return json.dumps(scenario["envelope"], ensure_ascii=False).encode() content = scenario.get("content") if content is None: message: dict = {"role": "assistant", "content": None} else: message = {"role": "assistant", "content": content} if "tool_calls" in scenario: message["tool_calls"] = scenario["tool_calls"] choice = {"index": 0, "message": message, "finish_reason": scenario.get("finish_reason", "stop")} envelope = { "id": scenario.get("id", "chatcmpl-fixture"), "object": "chat.completion", "model": scenario.get("model", "fixture-model"), "choices": [choice], } if "usage" in scenario: envelope["usage"] = scenario["usage"] return json.dumps(envelope, ensure_ascii=False).encode() class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "marqdo-ai-fixture/1" sys_version = "" def _record(self, body: bytes) -> None: record = { "method": self.command, "path": self.path, "headers": { key: (REDACTED if key.lower() == "authorization" else value) for key, value in self.headers.items() }, "body": body.decode("utf-8", errors="replace"), } with self.server.record_path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record, ensure_ascii=False) + "\n") def do_POST(self) -> None: # noqa: N802 - http.server API length = int(self.headers.get("Content-Length", "0")) body = self.rfile.read(length) self._record(body) scenario = self.server.scenario delay = scenario.get("delay", 0.0) if delay: import time time.sleep(delay) if "raw" in scenario: self.wfile.write(scenario["raw"]) self.close_connection = True return payload = build_envelope(scenario) status = scenario.get("status", 200) self.send_response(status) self.send_header("Content-Type", "application/json") if scenario.get("chunked"): self.send_header("Transfer-Encoding", "chunked") self.end_headers() # Deliberately split the payload into small chunks, including a # chunk boundary inside a multi-byte UTF-8 character. encoded = payload cuts = [1, 7, 19] position = 0 for cut in cuts: piece = encoded[position : position + cut] position += cut if not piece: continue self.wfile.write(f"{len(piece):x}\r\n".encode() + piece + b"\r\n") rest = encoded[position:] if rest: self.wfile.write(f"{len(rest):x}\r\n".encode() + rest + b"\r\n") self.wfile.write(b"0\r\n\r\n") else: self.send_header("Content-Length", str(len(payload))) self.send_header("Connection", "close") self.end_headers() self.wfile.write(payload) self.close_connection = True def log_message(self, fmt: str, *args) -> None: # noqa: A003 return def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, default=0) parser.add_argument("--scenario", required=True) parser.add_argument("--record", required=True) args = parser.parse_args() if args.scenario not in SCENARIOS: print(f"unknown scenario: {args.scenario}", file=sys.stderr) return 2 record = Path(args.record) record.parent.mkdir(parents=True, exist_ok=True) record.write_text("", encoding="utf-8") server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) server.scenario = SCENARIOS[args.scenario] server.record_path = record sys.stdout.write(f"PORT={server.server_port}\n") sys.stdout.flush() try: server.serve_forever() except KeyboardInterrupt: pass return 0 if __name__ == "__main__": raise SystemExit(main())