450 lines
18 KiB
Python
450 lines
18 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, Qt
|
|
from PySide6.QtTest import QTest
|
|
from PySide6.QtWidgets import QApplication, QPushButton
|
|
|
|
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
|
|
from doctor_workstation.ui.visuals.aurora_sheet import CollapsibleObsidianSheet
|
|
|
|
|
|
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.patient_name == ""
|
|
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.aurora.patient_name == 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
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("state", "status", "message"),
|
|
[
|
|
("reading", "正在读取", "正在读取"),
|
|
("error", "读取失败", "读取失败"),
|
|
("permission", "无查看权限", "无权查看"),
|
|
("missing", "暂无报告", "暂无已保存"),
|
|
],
|
|
)
|
|
def test_saved_report_status_covers_every_analysis_card(state: str, status: str, message: str) -> None:
|
|
vm = derive_cockpit_snapshot(
|
|
diagnosis={"id": 17, "patient_name": "孙芳"},
|
|
ai_state=state,
|
|
active_ai_model="openai",
|
|
ai_payload={
|
|
"diagnosis_advice": "此前缓存的诊断建议",
|
|
"risk_assessment": ["此前缓存的风险"],
|
|
"generated_at": "2026-11-12",
|
|
},
|
|
).aurora
|
|
assert "孙芳" in vm.ai_summary_line and "OpenAI" in vm.ai_summary_line
|
|
assert message in vm.ai_summary_line
|
|
assert dict(vm.params)["报告状态"] == status
|
|
assert dict(vm.params)["快照时间"] == "—"
|
|
for card, section in zip(vm.cards, ("诊断建议", "治疗建议", "风险评估"), strict=True):
|
|
assert card.badge_text == status
|
|
assert message in card.body_text and section in card.body_text
|
|
assert card.foot_right == ""
|
|
assert not card.risk_items
|
|
assert "此前缓存" not in repr(vm)
|
|
|
|
|
|
def test_report_read_failure_reason_reaches_cards_when_summary_is_hidden() -> None:
|
|
reason = "读取病历报告失败,请检查网络连接。"
|
|
vm = derive_cockpit_snapshot(
|
|
patient={"id": 32, "name": "孙芳"}, ai_state="error", ai_message=reason
|
|
).aurora
|
|
assert vm.ai_summary_line == reason
|
|
assert all(card.body_text == reason for card in vm.cards)
|
|
|
|
|
|
@pytest.mark.parametrize("width", [610, 1250])
|
|
def test_analysis_sheet_heading_tracks_patient_in_both_states(application: QApplication, width: int) -> None:
|
|
sheet = CollapsibleObsidianSheet()
|
|
sheet.resize(width, sheet.height())
|
|
sheet.show()
|
|
try:
|
|
saved = derive_cockpit_snapshot(
|
|
appointment={"patient_name": "—"},
|
|
diagnosis={"id": 702, "patient_name": "阿依古丽·买买提"},
|
|
ai_payload={"diagnosis_advice": "已保存的报告正文"},
|
|
).aurora
|
|
sheet.set_view_model(saved)
|
|
assert saved.patient_name == "阿依古丽·买买提"
|
|
for expanded in (False, True):
|
|
sheet.set_expanded(expanded)
|
|
application.processEvents()
|
|
assert sheet.width() == width
|
|
assert sheet.title_label.isVisible()
|
|
assert saved.patient_name in sheet.title_label.text()
|
|
assert sheet.title_label.width() >= sheet.title_label.sizeHint().width()
|
|
assert sheet.summary_label.text() == "已保存的报告正文"
|
|
|
|
second = derive_cockpit_snapshot(patient={"id": 33, "name": "孙芳"}).aurora
|
|
sheet.set_view_model(second)
|
|
assert "孙芳" in sheet.title_label.text()
|
|
assert saved.patient_name not in sheet.title_label.text()
|
|
assert "已保存的报告正文" not in sheet.summary_label.text()
|
|
|
|
unnamed = derive_cockpit_snapshot(patient={"id": 33}).aurora
|
|
assert unnamed.has_patient and not unnamed.patient_name
|
|
sheet.set_view_model(unnamed)
|
|
assert "姓名未记录" in sheet.title_label.text()
|
|
sheet.set_view_model(derive_cockpit_snapshot().aurora)
|
|
assert "未选择患者" in sheet.title_label.text()
|
|
assert "孙芳" not in sheet.title_label.text()
|
|
finally:
|
|
sheet.close()
|
|
|
|
|
|
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)
|
|
|
|
# Switch patients first so a reset to the default queue row cannot pass.
|
|
patient_store = shell.patient_context_store
|
|
initial_patient = patient_store.current_patient
|
|
second_row = rec_page.cockpit_view.timeline_layout.itemAt(1).widget()
|
|
QTest.mouseClick(second_row, Qt.MouseButton.LeftButton)
|
|
_settle(application, 8)
|
|
selected_patient = patient_store.current_patient
|
|
assert selected_patient.has_patient
|
|
assert selected_patient.patient_id != initial_patient.patient_id
|
|
|
|
classic_button = shell.classic_reception_button
|
|
assert classic_button.isVisible()
|
|
assert classic_button.text() == "原版接诊台"
|
|
QTest.mouseClick(classic_button, Qt.MouseButton.LeftButton)
|
|
_settle(application, 4)
|
|
assert rec_page._workspace_mode == "chart"
|
|
assert rec_page.queue_list.isVisible()
|
|
assert rec_page.queue_list.currentRow() == 1
|
|
assert rec_page.detail_tabs.isVisible()
|
|
assert rec_page.patient_name_label.isVisible()
|
|
assert rec_page.patient_name_label.text() == selected_patient.patient_name
|
|
assert patient_store.current_patient.appointment_id == selected_patient.appointment_id
|
|
|
|
back_button = rec_page._return_to_cockpit_bar.findChild(QPushButton)
|
|
assert back_button is not None and back_button.isVisible()
|
|
assert back_button.text() == "← 返回临床接诊总览"
|
|
QTest.mouseClick(back_button, Qt.MouseButton.LeftButton)
|
|
_settle(application, 4)
|
|
assert rec_page.cockpit_view.isVisible()
|
|
assert classic_button.isVisible()
|
|
assert patient_store.current_patient.appointment_id == selected_patient.appointment_id
|
|
|
|
# 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()
|
|
assert not classic_button.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()
|
|
assert not classic_button.isVisible()
|
|
|
|
assert shell.navigate("reception")
|
|
_settle(application, 4)
|
|
assert classic_button.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()
|