"""Offline contract tests for the existing Qwen text/vision service.""" from __future__ import annotations import base64 from contextlib import contextmanager from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from io import BytesIO import json import os from pathlib import Path import subprocess import sys import tempfile import threading import unittest from unittest.mock import patch from PIL import Image PROJECT_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PROJECT_ROOT)) @contextmanager def fake_endpoint(reply=None, status=200): """Run an actual local HTTP boundary; never contact the deployed service.""" captured = [] default_reply = { "id": "chatcmpl-offline", "object": "chat.completion", "created": 1, "model": "Qwen/Qwen3.8-27B-FP8", "choices": [{"index": 0, "message": { "role": "assistant", "content": "5", "reasoning_content": "2 plus 3 is 5." }, "finish_reason": "stop"}], "usage": {"prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15}, } class Handler(BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) captured.append({"path": self.path, "headers": dict(self.headers), "body": body}) payload = reply(body) if callable(reply) else (reply if reply is not None else default_reply) encoded = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(encoded))) self.end_headers() self.wfile.write(encoded) def log_message(self, *_args): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) worker = threading.Thread(target=lambda: server.serve_forever(poll_interval=0.01), daemon=True) worker.start() try: yield f"http://127.0.0.1:{server.server_port}/v1", captured, default_reply finally: server.shutdown() server.server_close() worker.join(timeout=2) def assistant_reply(content, **message_fields): return { "id": "chatcmpl-fixture", "object": "chat.completion", "created": 1, "model": "Qwen/Qwen3.8-27B-FP8", "choices": [{"index": 0, "message": { "role": "assistant", "content": content, **message_fields }, "finish_reason": "stop"}], "usage": {"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30}, } class QwenClientTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.workspace = Path(self.temp.name) / "workspace" self.workspace.mkdir() def client(self, base_url, **options): from llm_services.qwen_client import QwenClient return QwenClient(base_url=base_url, workspace_root=self.workspace, **options) def image(self, name="sample.png"): path = self.workspace / name path.parent.mkdir(parents=True, exist_ok=True) Image.new("RGB", (8, 8), "red").save(path) return path def test_math_uses_existing_fp8_chat_endpoint_and_preserves_sglang_response(self): with fake_endpoint() as (url, captured, raw): result = self.client(url).solve_math("2 + 3 = ?") self.assertEqual(captured[0]["path"], "/v1/chat/completions") payload = captured[0]["body"] self.assertEqual(payload["model"], "Qwen/Qwen3.8-27B-FP8") self.assertEqual(payload["messages"][-1], {"role": "user", "content": "2 + 3 = ?"}) self.assertEqual(payload["chat_template_kwargs"]["enable_thinking"], False) self.assertFalse(payload["stream"]) self.assertEqual(result["content"], "5") self.assertEqual(result["reasoning_content"], "2 plus 3 is 5.") self.assertEqual(result["usage"]["total_tokens"], 15) self.assertEqual(result["raw_response"], raw) def test_dedicated_environment_configures_endpoint_model_and_optional_key(self): with fake_endpoint() as (url, captured, _raw): with patch.dict(os.environ, { "QWEN_API_BASE": url + "/", "QWEN_MODEL": "local-qwen-alias", "QWEN_API_KEY": "qwen-only-test-key", "OPENAI_API_KEY": "unrelated-secret" }, clear=True): from llm_services.qwen_client import QwenClient QwenClient(workspace_root=self.workspace, enable_thinking=True).solve_math("2+3") self.assertEqual(captured[0]["path"], "/v1/chat/completions") self.assertEqual(captured[0]["body"]["model"], "local-qwen-alias") self.assertTrue(captured[0]["body"]["chat_template_kwargs"]["enable_thinking"]) self.assertEqual(captured[0]["headers"].get("Authorization"), "Bearer qwen-only-test-key") def test_unrelated_service_keys_are_never_sent(self): with fake_endpoint() as (url, captured, _raw): with patch.dict(os.environ, { "OPENAI_API_KEY": "not-for-qwen", "VLLM_API_KEY": "not-for-qwen-either", "HTTP_PROXY": "http://127.0.0.1:1", "ALL_PROXY": "http://127.0.0.1:1" }, clear=True): self.client(url).solve_math("2+3") self.assertNotIn("Authorization", captured[0]["headers"]) def test_image_is_sent_as_data_uri_with_structuring_prompt(self): image_path = self.image("assets/first.png") structured = {"subjects": ["blue square"], "scene": "red background", "ocr": []} with fake_endpoint(assistant_reply("```json\n" + json.dumps(structured) + "\n```")) as (url, captured, _): result = self.client(url).describe_image("assets/first.png") parts = captured[0]["body"]["messages"][-1]["content"] image_url = next(part["image_url"]["url"] for part in parts if part["type"] == "image_url") prefix, encoded = image_url.split(",", 1) self.assertEqual(prefix, "data:image/png;base64") self.assertEqual(base64.b64decode(encoded), image_path.read_bytes()) text = next(part["text"] for part in parts if part["type"] == "text") for field in ("subjects", "scene", "ocr"): self.assertIn(field, text) self.assertEqual(result["structured"], structured) def test_custom_visual_prompt_and_sglang_text_blocks_are_supported(self): response = assistant_reply([{"type": "text", "text": '{"scene":"room",'}, {"type": "text", "text": '"subjects":[],"ocr":[]}'}]) with fake_endpoint(response) as (url, captured, _): result = self.client(url).describe_image(self.image(), "Return these fields as JSON.") self.assertEqual(result["structured"]["scene"], "room") self.assertEqual(captured[0]["body"]["messages"][-1]["content"][-1]["text"], "Return these fields as JSON.") def test_inline_thinking_is_separated_from_final_json(self): with fake_endpoint(assistant_reply('Inspect the actual image.\n{"subjects":[],"scene":"room","ocr":[]}')) as (url, _, _): result = self.client(url, enable_thinking=True).describe_image(self.image()) self.assertEqual(result["reasoning_content"], "Inspect the actual image.") self.assertEqual(result["structured"]["scene"], "room") def test_visual_non_json_answer_is_retained_without_claiming_structured_success(self): with fake_endpoint(assistant_reply("I cannot see a clear object.")) as (url, _, _): result = self.client(url).describe_image(self.image()) self.assertIsNone(result["structured"]) self.assertEqual(result["raw_response"]["choices"][0]["message"]["content"], result["content"]) def test_images_outside_workspace_are_rejected_before_http(self): outside = self.workspace.parent / "outside.png" Image.new("RGB", (8, 8), "green").save(outside) with fake_endpoint() as (url, captured, _): for path in (outside, "../outside.png"): with self.subTest(path=str(path)), self.assertRaises(ValueError): self.client(url).describe_image(path) self.assertEqual(captured, []) def test_symlink_escape_is_rejected_before_http(self): outside = self.workspace.parent / "private.png" Image.new("RGB", (8, 8), "green").save(outside) link = self.workspace / "link.png" try: link.symlink_to(outside) except (OSError, NotImplementedError): self.skipTest("symlinks are unavailable on this host") with fake_endpoint() as (url, captured, _): with self.assertRaises(ValueError): self.client(url).describe_image(link) self.assertEqual(captured, []) def test_invalid_image_is_rejected_before_http(self): path = self.workspace / "not-image.png" path.write_text("not a picture", encoding="utf-8") with fake_endpoint() as (url, captured, _): with self.assertRaises(ValueError): self.client(url).describe_image(path) self.assertEqual(captured, []) def test_http_failure_and_missing_choices_are_not_treated_as_model_success(self): from llm_services.qwen_client import QwenClientError with fake_endpoint({"error": {"message": "not available"}}, status=503) as (url, _, _): with self.assertRaises(QwenClientError): self.client(url).solve_math("2+3") with fake_endpoint({"id": "invalid-response", "choices": []}) as (url, _, _): with self.assertRaises(QwenClientError): self.client(url).solve_math("2+3") def run_verification(self, reply): output = self.workspace / "outputs" / "verification" with fake_endpoint(reply) as (url, captured, _): process = subprocess.run([ sys.executable, str(PROJECT_ROOT / "scripts" / "verify_existing_qwen.py"), "--base-url", url, "--workspace-root", str(self.workspace), "--output-dir", str(output), "--timeout", "5", ], cwd=PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", timeout=20, env={**os.environ, "PYTHONIOENCODING": "utf-8"}) report = json.loads((output / "report.json").read_text(encoding="utf-8")) return process, report, captured @staticmethod def verification_reply(body, wrong_visual=False): parts = body["messages"][-1]["content"] if isinstance(parts, str): return assistant_reply("5") image_parts = [part for part in parts if part["type"] == "image_url"] if not image_parts: return assistant_reply("5") encoded = image_parts[0]["image_url"]["url"].split(",", 1)[1] image = Image.open(BytesIO(base64.b64decode(encoded))) is_red = image.convert("RGB").getpixel((0, 0))[0] > 200 if is_red or wrong_visual: structured = {"background_color": "red", "shape": "square", "shape_color": "blue", "subjects": ["blue square"], "scene": "red background", "ocr": []} else: structured = {"background_color": "green", "shape": "circle", "shape_color": "yellow", "subjects": ["yellow circle"], "scene": "green background", "ocr": []} return assistant_reply(json.dumps(structured)) def test_verifier_records_actual_math_and_two_visual_responses(self): process, report, captured = self.run_verification(self.verification_reply) self.assertEqual(process.returncode, 0, process.stderr + process.stdout) self.assertTrue(report["passed"]) self.assertEqual(len(captured), 3) self.assertEqual(len(report["results"]), 3) self.assertTrue(all(item["raw_response"]["id"] == "chatcmpl-fixture" for item in report["results"])) self.assertTrue(report["checks"]["visual_outputs_differ"]) def test_verifier_fails_identical_wrong_visual_answers_even_with_http_200(self): process, report, captured = self.run_verification(lambda body: self.verification_reply(body, wrong_visual=True)) self.assertNotEqual(process.returncode, 0) self.assertFalse(report["passed"]) self.assertEqual(len(captured), 3) self.assertFalse(report["checks"]["second_image_matches"]) self.assertFalse(report["checks"]["visual_outputs_differ"]) if __name__ == "__main__": unittest.main()