Files
zyt/app/tests/test_spatial_cockpit_v3.py
T
2026-12-01 17:27:49 +08:00

338 lines
13 KiB
Python

"""End-to-end verification of Clinical OS 3.0 Real-Data Cockpit & Spatial Shell."""
from __future__ import annotations
import os
from datetime import date, timedelta
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from doctor_workstation.core.permissions import PermissionSet
from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository
from doctor_workstation.ui.shell_spatial import SpatialShellWindow
from doctor_workstation.ui.state import PatientContextStore
from doctor_workstation.ui.theme import apply_theme
from doctor_workstation.ui.viewmodels import derive_cockpit_snapshot
def _settle(app: QApplication, rounds: int = 16) -> None:
for _ in range(rounds):
app.processEvents()
QTest.qWait(8)
@pytest.fixture(scope="module")
def application() -> QApplication:
app = QApplication.instance() or QApplication([])
apply_theme(app)
return app
def test_patient_context_store_broadcasts_snapshots_and_modes() -> None:
store = PatientContextStore()
seen_names: list[str] = []
sheet_states: list[bool] = []
store.active_patient_changed.connect(lambda snap: seen_names.append(snap.patient_name))
store.bottom_sheet_mode_changed.connect(sheet_states.append)
snap = store.update_from_reception(
{"id": 101, "patient_name": "林晓岚", "status": 1, "appointment_time": "09:30"},
{"id": 201, "gender": 2, "age": 46, "phone": "13800138000"},
{"id": 501, "clinical_diagnosis": "2型糖尿病", "disease_course_text": "8年"},
)
assert snap.has_patient
assert snap.patient_name == "林晓岚"
assert snap.appointment_id == 101
assert snap.diagnosis_id == 501
assert "46岁" in snap.subtitle_line
assert seen_names == ["林晓岚"]
assert store.toggle_bottom_sheet() is True
assert store.toggle_bottom_sheet() is False
assert sheet_states == [True, False]
store.clear()
assert not store.current_patient.has_patient
assert seen_names[-1] == "未选择患者"
def test_empty_cockpit_snapshot_contains_zero_fabricated_metrics() -> None:
empty_vm = derive_cockpit_snapshot(active_ai_model="doubao")
assert empty_vm.has_patient is False
assert empty_vm.progression.primary_value == "—"
assert all(not bar.recorded for bar in empty_vm.progression.bars)
assert empty_vm.diurnal.primary_value == "—"
assert empty_vm.diurnal.has_marker is False
assert all(slot.state == "empty" for slot in empty_vm.diurnal.slots)
assert all(vital.value == "—" for vital in empty_vm.diurnal.vitals)
assert empty_vm.journey.primary_metric_text == "—"
assert empty_vm.aurora.active_model_key == "doubao"
assert empty_vm.aurora.gauge_value in {"0", "0/6", "—"}
# Ensure zero legacy fake texts leak into empty state
serialized = repr(empty_vm)
for forbidden in ("76%", "84%", "92%", "-24%", "76 bpm", "舌红少津", "清热生津期"):
assert forbidden not in serialized
def test_cockpit_viewmodel_maps_real_clinical_records_and_ai_payload() -> None:
today = date.today()
d_minus_2 = (today - timedelta(days=2)).isoformat()
d_minus_1 = (today - timedelta(days=1)).isoformat()
today_iso = today.isoformat()
vm = derive_cockpit_snapshot(
{"id": 11, "patient_name": "张建国", "status": 1},
{"height": 172, "weight": 78},
{
"id": 511,
"clinical_diagnosis": "2型糖尿病(气阴两虚证)",
"fasting_blood_sugar": 7.8,
"postprandial_blood_sugar": 10.6,
"glycated_hemoglobin": 7.4,
"systolic_pressure": 136,
"diastolic_pressure": 84,
"chief_complaint": "口干多饮半年,加重两周",
"sleep_condition_text": "入睡困难、易醒",
"eye_condition_text": "视物模糊",
"water_intake_text": "2500ml以上",
"fatty_liver_degree_text": "中度脂肪肝",
"urine_condition_text": "夜尿3次",
"body_feeling_text": "双足末梢麻木",
"past_history_text": "高血压5年",
"current_medications": "二甲双胍缓释片 0.5g bid",
"allergy_history_text": "青霉素过敏",
"tongue": "舌质暗红苔薄黄",
"pulse": "脉弦细数",
"revisit_due": {
"visit_count": 2,
"medication_days": 14,
"medication_end_date": (today + timedelta(days=5)).isoformat(),
"days_offset": 5,
"status": "upcoming",
},
},
daily_window={
"blood_records": [
{
"record_date": d_minus_2,
"fasting_blood_sugar": 8.4,
"postprandial_blood_sugar": 11.8,
},
{
"record_date": d_minus_1,
"fasting_blood_sugar": 7.2,
"postprandial_blood_sugar": 9.6,
},
{
"record_date": today_iso,
"fasting_blood_sugar": 6.6,
"postprandial_blood_sugar": 8.9,
"systolic_pressure": 128,
"diastolic_pressure": 78,
},
],
"diet_records": [{"record_date": d_minus_1, "breakfast_foods": ["燕麦", "鸡蛋"]}],
"exercise_records": [{"record_date": today_iso, "exercise_type": "快走", "duration": 35}],
},
doctor_notes=[
{
"content": "嘱晚间控主食,复查空腹。",
"tongue_images": ["/uploads/tongue1.jpg"],
"report_files": ["/uploads/lab1.pdf"],
}
],
prescriptions=[
{
"prescription_name": "生脉玉女煎加减",
"dosage_count": 14,
"audit_status_desc": "已双签通过",
}
],
ai_payload={
"diagnosis_advice": "患者口干多饮、夜尿频伴双足麻木,属气阴两虚夹瘀阻络。",
"treatment_advice": "益气养阴、活血通络,配合餐后30分钟中等强度步行。",
"risk_assessment": [
{"label": "青霉素过敏史,严禁相关制剂", "level": "high"},
{"label": "合并中度脂肪肝与周围神经麻木", "level": "medium"},
],
"generated_at": f"{today_iso} 09:20:00",
},
ai_state="success",
active_ai_model="doubao",
)
assert vm.has_patient is True
assert vm.patient_name == "张建国"
assert vm.progression.primary_value == "6.6"
assert vm.progression.unit == "mmol/L"
recorded_bars = [b for b in vm.progression.bars if b.recorded]
unrecorded_bars = [b for b in vm.progression.bars if not b.recorded]
assert len(recorded_bars) == 3
assert len(unrecorded_bars) == 0
assert all(bool(b.label) and bool(b.value_text) for b in recorded_bars)
assert recorded_bars[-1].highlight is True
assert vm.diurnal.primary_value == "8.9"
assert vm.diurnal.has_marker is True
assert vm.diurnal.vitals[0].value == "128/78"
assert vm.diurnal.vitals[1].value == "26.4"
assert "二甲双胍" in vm.diurnal.vitals[2].value
symptoms_stage = vm.twin_for_mode("sanjiao")
assert len(symptoms_stage.nodes) == 4
assert any("双足末梢麻木" in n.detail for n in symptoms_stage.nodes)
history_stage = vm.twin_for_mode("organ")
assert any("青霉素过敏" in n.detail for n in history_stage.nodes)
tcm_stage = vm.twin_for_mode("tcm")
assert any("生脉玉女煎加减" in n.detail for n in tcm_stage.nodes)
assert "3" in vm.journey.primary_metric_text
assert "第2诊" in vm.journey.end_capsule_text or "药尽" in vm.journey.end_capsule_text
assert vm.aurora.active_model_key == "doubao"
assert "6" in vm.aurora.gauge_value
assert "气阴两虚" in vm.aurora.cards[0].body_text
assert len(vm.aurora.cards[2].risk_items) == 2
def test_spatial_shell_auto_fallback_to_consultations_when_appointments_empty(
application: QApplication,
) -> None:
"""Verify admin account with 0 appointments automatically loads real clinic consultations."""
class AdminNoAppointmentsRepo(DemoDoctorRepository):
def list_appointments(self, *, page_no: int = 1, page_size: int = 20, **filters: Any): # type: ignore[override]
del filters
from doctor_workstation.core.models import PageResult
return PageResult(items=(), total=0, page_no=page_no, page_size=page_size)
repo = AdminNoAppointmentsRepo()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = SpatialShellWindow(
repo,
{"session": session, "user": session.user, "demo_mode": True},
PermissionSet(DEMO_PERMISSIONS),
)
shell.resize(1440, 900)
shell.show()
_settle(application, 28)
try:
rec_page = shell.pages["reception"]
assert rec_page._cockpit_queue_scope == "consultations"
assert len(rec_page._queue_records) > 0
assert shell.patient_context_store.current_patient.has_patient
assert shell.patient_context_store.current_patient.diagnosis_id > 0
# Switch AI model tabs on bottom sheet and confirm immediate synchronization
shell.ai_bottom_sheet.model_selected.emit("doubao")
_settle(application, 6)
assert rec_page._ai_analysis_active_model == "doubao"
finally:
for page in shell.pages.values():
poll = getattr(page, "poll_timer", None)
if poll is not None:
poll.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow(
application: QApplication,
) -> None:
repo = DemoDoctorRepository()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = SpatialShellWindow(
repo,
{"session": session, "user": session.user, "demo_mode": True},
PermissionSet(DEMO_PERMISSIONS),
)
shell.resize(1440, 920)
shell.show()
_settle(application, 24)
try:
assert not hasattr(shell, "sidebar")
assert shell._active_page_key == "reception"
assert shell.nav_buttons["reception"].isChecked()
# Verify AI 辨证师 button has full sizeHint width & never overlaps search_capsule
assert shell.ai_nav_button.width() >= shell.ai_nav_button.sizeHint().width()
assert shell.nav_island.geometry().right() < shell.search_capsule.geometry().left()
rec_page = shell.pages["reception"]
assert rec_page._workspace_mode == "cockpit"
assert rec_page.view_mode_stack.currentWidget() is rec_page.cockpit_view
assert shell.patient_context_store.current_patient.has_patient
cockpit_img = shell.grab().toImage()
assert not cockpit_img.isNull()
# Switch Twin Stage modes (sanjiao -> organ -> tcm)
rec_page.cockpit_view.twin_stage.set_mode("organ")
rec_page.cockpit_view.twin_stage.set_mode("tcm")
rec_page.cockpit_view.twin_stage.set_mode("sanjiao")
_settle(application, 4)
# Open Structured Chart in Right Companion Wing without leaving Cockpit
rec_page._open_structured_chart_tab(3)
_settle(application, 4)
assert rec_page._workspace_mode == "cockpit"
assert shell.wing_manager.is_open
shell.wing_manager.close_wing()
_settle(application, 2)
# Explicit legacy chart mode round-trip still works cleanly when invoked directly
rec_page.set_workspace_mode("chart")
_settle(application, 4)
assert rec_page._workspace_mode == "chart"
assert rec_page._return_to_cockpit_bar.isVisible()
rec_page.set_workspace_mode("cockpit")
_settle(application, 4)
assert rec_page._workspace_mode == "cockpit"
# Expand Obsidian Aurora-Glass Bottom Sheet
assert not shell.ai_bottom_sheet.is_expanded
shell.toggle_ai_bottom_sheet()
_settle(application, 6)
assert shell.ai_bottom_sheet.is_expanded
assert shell.ai_bottom_sheet.height() > 200
expanded_img = shell.grab().toImage()
assert not expanded_img.isNull()
shell.toggle_ai_bottom_sheet()
_settle(application, 4)
assert not shell.ai_bottom_sheet.is_expanded
# Navigate to Schedule & other spatial routes
assert shell.navigate("appointments")
_settle(application, 14)
appt_page = shell.pages["appointments"]
assert appt_page.spatial_week_card.isVisible()
for route_key in ("patients", "prescription_library", "prescriptions", "consultations"):
assert shell.navigate(route_key)
_settle(application, 10)
page = shell.pages[route_key]
assert hasattr(page, "spatial_bridge")
assert page.spatial_bridge.isVisible()
finally:
for page in shell.pages.values():
poll = getattr(page, "poll_timer", None)
if poll is not None:
poll.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()