from __future__ import annotations import base64 import hashlib import json from types import SimpleNamespace from unittest.mock import Mock from uuid import uuid4 import pytest from PySide6.QtCore import QBuffer, QByteArray, QIODevice from PySide6.QtGui import QColor, QImage from doctor_workstation.video import window from doctor_workstation.video.screenshot import validate_patient_video_frame from doctor_workstation.video.tongue_screenshot import TongueScreenshotController def frame(width=320, height=480, image_format="JPEG"): image = QImage(width, height, QImage.Format.Format_RGB32) image.fill(QColor("#234567")) data = QByteArray() buffer = QBuffer(data) buffer.open(QIODevice.OpenModeFlag.WriteOnly) assert image.save(buffer, image_format, 90) buffer.close() return "data:image/jpeg;base64," + base64.b64encode(bytes(data)).decode() def host(**changes): return SimpleNamespace(**{ "_im_ai_context_is_trusted": lambda: True, "_media_active": True, "_start_requested": True, "_call_cycle_closed": False, "request": SimpleNamespace(target_user_id="patient_42"), "_tongue_ai": Mock(), "web_view": Mock(), "lifecycle": Mock(), **changes, }) @pytest.mark.parametrize("width,height", [(320, 480), (1920, 1080), (1080, 1920), (64, 64)]) def test_patient_frame_keeps_original_jpeg_bytes_and_aspect_ratio(width, height): source = frame(width, height) assert validate_patient_video_frame(source) == source @pytest.mark.parametrize("width,height", [(32, 100), (100, 32), (1921, 64), (64, 1921)]) def test_patient_frame_dimensions_are_bounded_before_decode(width, height): with pytest.raises(ValueError, match="尺寸无效"): validate_patient_video_frame(frame(width, height)) @pytest.mark.parametrize("source", [None, "https://example.test/frame.jpg", "data:image/png;base64,AAAA", "data:image/jpeg;base64,@@@@", "data:image/jpeg;base64,/9j/2Q=="]) def test_invalid_patient_frame_cannot_be_registered(source): with pytest.raises(ValueError): validate_patient_video_frame(source) def test_png_disguised_as_jpeg_and_truncated_jpeg_are_rejected(): with pytest.raises(ValueError): validate_patient_video_frame(frame(image_format="PNG")) content = base64.b64decode(frame().split(",", 1)[1]) with pytest.raises(ValueError, match="不完整"): validate_patient_video_frame("data:image/jpeg;base64," + base64.b64encode(content[:-2]).decode()) def test_preparation_binds_patient_pixels_without_widget_grab_save_or_ai_submission(): target = host() source = frame() events = [] legacy_capture = Mock(side_effect=AssertionError("must never capture the whole widget")) bridge = window._QtVideoBridge(events.append, legacy_capture, lambda user, image: window._EmbeddedVideoWindow._prepare_patient_screenshot(target, user, image)) prepared = json.loads(bridge.preparePatientScreenshot("patient_42", source)) assert prepared == {"dataUrl": source} target._tongue_ai.register_capture.assert_called_once_with(source) target.web_view.grab.assert_not_called() target.lifecycle.save_screenshot.assert_not_called() target._tongue_ai.analyze.assert_not_called() legacy_capture.assert_not_called() assert events == [] bridge.saveScreenshot(prepared["dataUrl"]) assert events == [{"source": "doctor-call", "event": "screenshot", "dataUrl": source}] @pytest.mark.parametrize("changes", [ {"_im_ai_context_is_trusted": lambda: False}, {"_media_active": False}, {"_start_requested": False}, {"_call_cycle_closed": True}, {"request": SimpleNamespace(target_user_id="another_patient")}, ]) def test_wrong_patient_or_inactive_call_cannot_prepare_a_frame(changes): target = host(**changes) with pytest.raises(ValueError): window._EmbeddedVideoWindow._prepare_patient_screenshot(target, "patient_42", frame()) target._tongue_ai.register_capture.assert_not_called() target.web_view.grab.assert_not_called() @pytest.mark.parametrize("user,image", [("", "unused"), ("x" * 257, "unused"), (None, "unused"), ("patient_42", None), ("patient_42", "x" * (14 * 1024 * 1024 + 1))], ids=["empty-user", "oversized-user", "null-user", "null-image", "oversized-image"]) def test_bridge_bounds_inputs_before_native_preparation(user, image): prepare = Mock() bridge = window._QtVideoBridge(Mock(), Mock(), prepare) assert "error" in json.loads(bridge.preparePatientScreenshot(user, image)) prepare.assert_not_called() def test_missing_preparation_handler_and_internal_error_fail_without_fallback(): legacy = Mock() for prepare in (None, Mock(side_effect=ValueError("private patient details"))): bridge = window._QtVideoBridge(Mock(), legacy, prepare) result = json.loads(bridge.preparePatientScreenshot("patient_42", frame())) assert set(result) == {"error"} and "private" not in result["error"] legacy.assert_not_called() def test_registered_patient_frame_is_the_exact_image_received_by_ai(): source = frame() content = base64.b64decode(source.split(",", 1)[1]) calls = [] def analyze(diagnosis_id, jpeg, *, request_id, model="qwen"): calls.append((diagnosis_id, jpeg)) return {"request_id": request_id, "diagnosis_id": diagnosis_id, "image_sha256": hashlib.sha256(jpeg).hexdigest(), "model": model, "model_label": "合成测试", "analysis": {"image_quality": "unusable", "quality_note": "纯色画面未见舌头", "features": [], "limitations": ["无法观察舌头"], "tcm_diagnosis": { "status": "insufficient", "summary": "纯色图片无法辨证", "candidates": [], "missing_information": ["清晰舌象、症状与脉象"]}}} controller = TongueScreenshotController(SimpleNamespace(analyze_tongue_screenshot=analyze), diagnosis_id=42, enabled=True) target = host(_tongue_ai=controller) try: prepared = window._EmbeddedVideoWindow._prepare_patient_screenshot(target, "patient_42", source) assert calls == [] controller.analyze(str(uuid4()), prepared) assert controller.wait(3) result = controller.take_result() assert result["ok"] is True assert result["data"]["image_sha256"] == hashlib.sha256(content).hexdigest() assert calls == [(42, content)] target.web_view.grab.assert_not_called() finally: controller.close()