This commit is contained in:
Your Name
2026-12-01 17:27:49 +08:00
parent 4cc37531a1
commit 4e0c2daf5c
29 changed files with 6622 additions and 1515 deletions
+194 -48
View File
@@ -1,9 +1,10 @@
"""End-to-end verification of Clinical OS 3.0 Spatial Shell & Digital Twin Cockpit."""
"""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")
@@ -20,7 +21,7 @@ from doctor_workstation.ui.theme import apply_theme
from doctor_workstation.ui.viewmodels import derive_cockpit_snapshot
def _settle(app: QApplication, rounds: int = 14) -> None:
def _settle(app: QApplication, rounds: int = 16) -> None:
for _ in range(rounds):
app.processEvents()
QTest.qWait(8)
@@ -61,45 +62,190 @@ def test_patient_context_store_broadcasts_snapshots_and_modes() -> None:
assert seen_names[-1] == "未选择患者"
def test_cockpit_viewmodel_derives_three_jiao_journey_and_aurora_cards() -> None:
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,
"hba1c": 7.6,
"clinical_diagnosis": "2型糖尿病(气阴两虚证)",
"fasting_blood_sugar": 7.8,
"chief_complaint": "晨起口渴多饮,伴乏力夜尿频",
"tongue": "舌红少津",
"pulse": "脉弦细",
"diagnosis_date": (date.today() - timedelta(days=11)).isoformat(),
"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": "玉女煎合生脉散加减",
"risk_assessment": [{"label": "黎明血糖抬升", "level": "medium"}],
"diagnosis_advice": "患者口干多饮、夜尿频伴双足麻木,属气阴两虚夹瘀阻络。",
"treatment_advice": "益气养阴、活血通络,配合餐后30分钟中等强度步行。",
"risk_assessment": [
{"label": "青霉素过敏史,严禁相关制剂", "level": "high"},
{"label": "合并中度脂肪肝与周围神经麻木", "level": "medium"},
],
"generated_at": f"{today_iso} 09:20:00",
},
active_ai_model="qwen",
ai_state="success",
active_ai_model="doubao",
)
assert vm.has_patient is True
assert vm.patient_name == "张建国"
assert len(vm.progression.bars) == 12
assert vm.progression.bars[-1].highlight is True
assert len(vm.diurnal.slots) == 16
assert any(s.state == "alert" for s in vm.diurnal.slots)
assert len(vm.diurnal.vitals) == 3
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
sanjiao = vm.twin_for_mode("sanjiao")
assert sanjiao.upper_heat_intensity > 0.5
assert sanjiao.middle_heat_intensity > 0.5
assert sanjiao.lower_heat_intensity > 0.5
assert len(vm.twin_for_mode("organ").nodes) == 2
assert len(vm.twin_for_mode("tcm").nodes) == 2
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
assert vm.journey.total_days == 21
assert vm.journey.current_day == 12
assert sum(1 for d in vm.journey.days if d.state == "today") == 1
assert len(vm.aurora.cards) == 3
assert "气阴两虚" in vm.aurora.ai_summary_line
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(
@@ -112,44 +258,50 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow(
{"session": session, "user": session.user, "demo_mode": True},
PermissionSet(DEMO_PERMISSIONS),
)
shell.resize(1600, 940)
shell.resize(1440, 920)
shell.show()
_settle(application, 24)
try:
# 1. Zero-sidebar floating capsule nav defaults to reception Digital Twin Cockpit
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
active_name = shell.patient_context_store.current_patient.patient_name
assert active_name in shell.context_patient_name.text()
# Paint-test all custom QPainter widgets via grab()
cockpit_img = shell.grab().toImage()
assert not cockpit_img.isNull()
assert cockpit_img.width() >= 1600
# 2. Switch Twin Stage modes (sanjiao -> organ -> tcm)
# 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)
# 3. Switch to 6-tab Structured Chart and back to Digital Twin Cockpit
rec_page._open_structured_chart_tab(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()
assert rec_page.detail_tabs.currentIndex() == 4
rec_page.set_workspace_mode("cockpit")
_settle(application, 4)
assert rec_page._workspace_mode == "cockpit"
# 4. Expand Serene.ai Obsidian Aurora-Glass Bottom Sheet
# Expand Obsidian Aurora-Glass Bottom Sheet
assert not shell.ai_bottom_sheet.is_expanded
shell.toggle_ai_bottom_sheet()
_settle(application, 6)
@@ -161,21 +313,15 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow(
_settle(application, 4)
assert not shell.ai_bottom_sheet.is_expanded
# 5. Navigate to Schedule (AppointmentsPage) & verify 7-day WeekCalendarStripWidget
# Navigate to Schedule & other spatial routes
assert shell.navigate("appointments")
_settle(application, 16)
_settle(application, 14)
appt_page = shell.pages["appointments"]
assert appt_page.spatial_week_card.isVisible()
assert not appt_page.header.isVisible()
tomorrow_iso = (date.today() + timedelta(days=1)).isoformat()
appt_page.week_strip.set_selected_date(date.today() + timedelta(days=1), emit_signal=True)
_settle(application, 10)
assert appt_page._start_date == tomorrow_iso
# 6. Navigate across Patients, Prescription Library, Prescriptions, Consultations
for route_key in ("patients", "prescription_library", "prescriptions", "consultations"):
assert shell.navigate(route_key)
_settle(application, 12)
_settle(application, 10)
page = shell.pages[route_key]
assert hasattr(page, "spatial_bridge")
assert page.spatial_bridge.isVisible()
+500
View File
@@ -0,0 +1,500 @@
"""End-to-end verification of Clinical OS 4.0 Dual-Wing Companion & Split-Stage Engine."""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QDialog
from doctor_workstation.core.permissions import PermissionSet
from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository
from doctor_workstation.ui.dialogs.appointment_complete import AppointmentCompleteDialog
from doctor_workstation.ui.dialogs.prescription import PrescriptionEditorDialog
from doctor_workstation.ui.shell_spatial import SpatialShellWindow
from doctor_workstation.ui.theme import apply_theme
from doctor_workstation.ui.visuals.ai_report_wing import (
ClinicalAiReportWingPanel,
_extract_key_takeaways,
_split_evidence_rows,
)
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_ai_report_wing_extracts_tcm_takeaways_and_evidence_rows() -> None:
sample_advice = (
"四诊:望诊见舌质偏红,舌苔黄腻(部分区域可见剥落),舌体略胖大,边有齿痕\n"
"闻诊未见异常记录\n"
"问诊见口干口苦,手脚偶发麻木,近期视物模糊、重影,腰酸\n"
"切诊脉象未采集\n"
"八纲:里证(病在脏腑)、热证(苔黄、口干口苦)、虚实夹杂\n"
"气血津液与脏腑定位:气阴两虚,湿热内蕴,病位主要在脾、肾、肝\n"
"证名:消渴病,气阴两虚兼湿热证"
)
takeaways = _extract_key_takeaways(sample_advice)
assert len(takeaways) == 3
assert takeaways[0][0] == "辨证证名"
assert "消渴病" in takeaways[0][1]
assert takeaways[1][0] == "八纲属性"
assert takeaways[2][0] == "病位病机"
assert "脾、肾、肝" in takeaways[2][1]
rows = _split_evidence_rows(sample_advice)
badges = [r[0] for r in rows]
assert "望诊" in badges
assert "闻诊" in badges
assert "问诊" in badges
assert "切诊" in badges
assert "辨证结论" in badges
# Also verify inline OpenAI bracketed wall-of-text splits into distinct structured sections
openai_wall = (
"【已知事实】56岁男性,身高186 cm、体重70 kg,初诊空腹血糖11.00 mmol/L。"
"【合理推断】总体符合长期糖尿病伴血糖控制不稳定。"
"【信息缺口】缺少糖尿病明确分型、HbA1c及眼底检查。"
)
o_rows = _split_evidence_rows(openai_wall)
o_badges = [r[0] for r in o_rows]
assert o_badges == ["已知事实", "临床推断", "待补信息"]
def test_spatial_wing_ai_report_left_right_dock_and_magnetic_sidecar(
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(1520, 920)
shell.show()
_settle(application, 24)
try:
# 1. Open AI Report Companion Wing via bottom sheet button (replaces ugly modal dialog!)
shell._open_active_patient_ai_report()
_settle(application, 8)
wm = shell.wing_manager
assert wm.is_open
assert wm.side == "right"
assert wm.mode == "docked"
assert shell.right_wing_dock.isVisible()
assert not shell.left_wing_dock.isVisible()
assert isinstance(wm.active_widget, ClinicalAiReportWingPanel)
# Copy report uses clean inline feedback without giant center overlay
wm.active_widget._copy_current_report()
assert "已复制" in wm.active_widget.copy_btn.text()
# 2. Switch wing to LEFT dock
wm.set_side("left")
_settle(application, 6)
assert wm.side == "left"
assert shell.left_wing_dock.isVisible()
assert not shell.right_wing_dock.isVisible()
# Switch back to RIGHT dock
wm.set_side("right")
_settle(application, 6)
assert wm.side == "right"
assert shell.right_wing_dock.isVisible()
# 3. Detach to external Magnetic Companion Sidecar Window & prove ZERO overlap!
wm.set_mode("sidecar")
_settle(application, 8)
assert wm.mode == "sidecar"
assert wm._sidecar is not None and wm._sidecar.isVisible()
assert not shell.right_wing_dock.isVisible()
assert shell.geometry().right() < wm._sidecar.geometry().left()
# 4. Re-dock back into main window & verify clean restoration
wm.set_mode("docked")
_settle(application, 6)
assert wm.mode == "docked"
assert shell.right_wing_dock.isVisible()
assert not wm._sidecar.isVisible()
wm.close_wing()
_settle(application, 4)
assert not wm.is_open
finally:
for page in shell.pages.values():
if hasattr(page, "poll_timer"):
page.poll_timer.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_qdialogs_and_exec_callers_mount_non_modally_in_spatial_wing(
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(1520, 920)
shell.show()
_settle(application, 24)
try:
wm = shell.wing_manager
# 1. Open DiagnosisDialog ('四诊病历') -> mounts full-bleed inside Right Wing!
shell._open_active_patient_diagnosis()
_settle(application, 12)
assert wm.is_open
assert wm.active_widget is shell._global_diagnosis_dialog
assert shell._global_diagnosis_dialog.property("hostedInSpatialWing") is True
assert shell.right_wing_dock.isVisible()
# Close and reopen cached DiagnosisDialog -> must cleanly re-mount!
wm.close_wing()
_settle(application, 4)
assert not wm.is_open
shell._open_active_patient_diagnosis()
_settle(application, 8)
assert wm.is_open
assert wm.active_widget is shell._global_diagnosis_dialog
# 2. Open PrescriptionEditorDialog via synchronous `.exec()` and reject asynchronously!
rx_dlg = PrescriptionEditorDialog(
repo,
{"diagnosis_id": 501, "patient_id": 301, "patient_name": "林晓岚"},
mode="add",
current_user=session.user,
permissions=PermissionSet(DEMO_PERMISSIONS),
parent=shell,
)
rx_errors: list[BaseException] = []
def _verify_and_close_rx() -> None:
try:
assert wm.is_open
assert wm.active_widget is rx_dlg
assert rx_dlg.property("hostedInSpatialWing") is True
assert not rx_dlg.isModal()
except BaseException as exc: # noqa: BLE001
rx_errors.append(exc)
finally:
rx_dlg.reject()
QTimer.singleShot(40, _verify_and_close_rx)
code = rx_dlg.exec()
if rx_errors:
raise rx_errors[0]
assert code == int(QDialog.DialogCode.Rejected)
assert not wm.is_open
# 3. Test AppointmentCompleteDialog `.exec()` returning Accepted via Spatial Wing!
comp_dlg = AppointmentCompleteDialog(can_note=True, parent=shell)
QTimer.singleShot(30, comp_dlg.accept)
res = comp_dlg.exec()
assert res == int(QDialog.DialogCode.Accepted)
finally:
for page in shell.pages.values():
if hasattr(page, "poll_timer"):
page.poll_timer.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_125dpi_rapid_switching_zero_overlap_and_fast_open(
application: QApplication,
) -> None:
"""Reproduce 1920x1080 @ 125% DPI (1536x864) rapid wing switching & verify zero overlap."""
import time
from PySide6.QtWidgets import QScrollArea, QWidget
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(1536, 864)
shell.show()
_settle(application, 28)
try:
rec = shell.pages["reception"]
wm = shell.wing_manager
# Expand bottom sheet first, then open AI report wing -> bottom sheet must auto-collapse!
shell.set_ai_bottom_sheet_expanded(True)
assert shell.ai_bottom_sheet.is_expanded
rec.open_ai_report_wing()
_settle(application, 6)
assert not shell.ai_bottom_sheet.is_expanded
# Rapidly alternate between AI Report Wing and Edit Diagnosis 4 times
for _ in range(2):
t0 = time.perf_counter()
rec._edit_diagnosis()
dt_diag_ms = (time.perf_counter() - t0) * 1000.0
_settle(application, 6)
visible_body_children = [
c
for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly)
if c.isVisible() and c is not wm.card.glide_veil
]
assert len(visible_body_children) == 1
assert visible_body_children[0] is shell._global_diagnosis_dialog
assert wm.card.header.title_label.text() == "编辑诊单"
t1 = time.perf_counter()
rec.open_ai_report_wing()
dt_ai_ms = (time.perf_counter() - t1) * 1000.0
_settle(application, 6)
visible_body_children = [
c
for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly)
if c.isVisible() and c is not wm.card.glide_veil
]
assert len(visible_body_children) == 1
assert isinstance(visible_body_children[0], ClinicalAiReportWingPanel)
assert dt_diag_ms < 180.0
assert dt_ai_ms < 120.0
# Open Edit Diagnosis at 1536x864 and verify cockpit columns & past_history do NOT clip/overlap
rec._edit_diagnosis()
_settle(application, 10)
cockpit = rec.cockpit_view
twin_right = cockpit.twin_stage.mapTo(cockpit, cockpit.twin_stage.rect().topRight()).x()
plan_left = cockpit.plan_card.mapTo(cockpit, cockpit.plan_card.rect().topLeft()).x()
assert twin_right <= plan_left, f"TwinStage ({twin_right}) overlapped PlanCard ({plan_left})!"
diag = shell._global_diagnosis_dialog
basic_scroll = diag.findChild(QScrollArea, "DiagnosisDrawerBody")
assert basic_scroll is not None
past_editor = diag._choice_fields["past_history"]
assert past_editor.width() <= basic_scroll.viewport().width()
# Verify clicking '原始详单 ↗' opens DiagnosisDialog in Wing WITHOUT leaving Cockpit view!
wm.close_wing()
_settle(application, 4)
cockpit.open_chart_tab_requested.emit(0)
_settle(application, 8)
assert rec.view_mode_stack.currentWidget() is rec.cockpit_view
assert wm.is_open and wm.active_widget is shell._global_diagnosis_dialog
finally:
for page in shell.pages.values():
if hasattr(page, "poll_timer"):
page.poll_timer.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_v4_3_calendar_density_patient_switch_sync_and_video_diagnosis_btn(
application: QApplication,
) -> None:
"""Verify: (1) spacious 14d/7d calendar, (2) live Wing refresh on patient switch, (3) video 4-exam button."""
from PySide6.QtWidgets import QPushButton
repo = DemoDoctorRepository()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = SpatialShellWindow(
repo,
{"session": session, "demo_mode": True},
session.permissions,
)
shell.resize(1536, 864)
shell.show()
_settle(application, 22)
try:
rec = shell.pages["reception"]
wm = shell.wing_manager
journey_card = rec.cockpit_view.journey_card
# 1. Full width: spacious 14-day rounded cards (every card >= 32px wide)
_ = shell.grab()
assert len(journey_card._day_rects) == 14
assert all(r.width() >= 32.0 for r, _ in journey_card._day_rects)
# 2. Open Edit Diagnosis for first patient (林晓岚, diagnosis_id=501)
rec._edit_diagnosis()
_settle(application, 14)
diag = shell._global_diagnosis_dialog
assert wm.is_open and wm.active_widget is diag
first_diag_id = diag._diagnosis_id
assert first_diag_id > 0
# When Right Wing narrows stage at 1536x864, calendar adapts to 7 spacious cards!
_ = shell.grab()
assert len(journey_card._day_rects) == 7
assert all(r.width() >= 36.0 for r, _ in journey_card._day_rects)
# Switch to the 2nd patient in queue while DiagnosisDialog stays open in Right Wing!
assert len(rec._queue_records) >= 2
second_record = rec._queue_records[1]
second_name = str(
getattr(second_record, "patient_name", None)
or (second_record.get("patient_name") if isinstance(second_record, dict) else "")
or ""
)
rec._select_record_from_cockpit(second_record)
_settle(application, 18)
assert diag._diagnosis_id != first_diag_id
assert second_name and second_name in wm.card.header.context_badge.toolTip()
name_widget = diag.edit_fields.get("name") or diag.display_fields.get("name")
if name_widget is not None:
rendered_name = (
name_widget.text() if hasattr(name_widget, "text") else name_widget.toPlainText()
)
assert second_name in rendered_name
# 3. Video/IM '四诊病历' QPushButton.clicked(bool=False) MUST NOT clobber diagnosis_id!
wm.close_wing()
_settle(application, 4)
target_diag_id = diag._diagnosis_id
callback = lambda *_args, current_id=target_diag_id: shell.open_diagnosis_by_id( # noqa: E731
current_id, modeless=True
)
fake_hud_btn = QPushButton("四诊病历")
fake_hud_btn.clicked.connect(lambda _checked=False: callback())
fake_hud_btn.click()
_settle(application, 10)
assert wm.is_open and wm.active_widget is diag
assert diag._diagnosis_id == target_diag_id
# Also verify open_diagnosis_by_id(False) safely falls back to active patient's diagnosis_id
wm.close_wing()
_settle(application, 4)
recovered = shell.open_diagnosis_by_id(False, modeless=True)
_settle(application, 8)
assert recovered is diag
assert diag._diagnosis_id == target_diag_id
finally:
for page in shell.pages.values():
if hasattr(page, "poll_timer"):
page.poll_timer.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_v4_4_locus_deep_links_and_real_dated_data_only(
application: QApplication,
) -> None:
"""Verify: (1) sparse patient renders ONLY real dated values (zero empty '—' or 11 blank bars),
(2) clicking each TwinStage card jumps straight to its matching tab & field in DiagnosisDialog."""
from doctor_workstation.ui.viewmodels.cockpit_vm import derive_cockpit_snapshot
# 1. Sparse patient payload matching real-machine '王进花' screenshot
sparse_vm = derive_cockpit_snapshot(
appointment={
"id": 88,
"diagnosis_id": 608,
"patient_name": "王进花",
"appointment_date": "2026-11-27",
"appointment_time": "17:30:00",
"diagnosis_type_text": "复诊",
},
patient={"name": "王进花", "age": 67},
diagnosis={
"id": 608,
"patient_name": "王进花",
"diagnosis_date": 0, # Unset 0 timestamp must NEVER display '诊断日期 · 0'
"chief_complaint": "姓名:王进花\n年龄:67\n患者空腹血糖:空腹18\n在用药物:没有吃药\n患病时长:一年多",
},
)
assert sparse_vm.twin_sanjiao.scan_badge == "诊断日期 · 2026-11-27"
assert len(sparse_vm.progression.bars) == 1
assert sparse_vm.progression.bars[0].value_text == "18"
assert sparse_vm.progression.bars[0].label == "11-27"
assert len(sparse_vm.diurnal.slots) == 0
assert len(sparse_vm.diurnal.vitals) >= 2
assert all(v.value != "—" and bool(v.date_label) for v in sparse_vm.diurnal.vitals)
assert any("没有吃药" in v.value for v in sparse_vm.diurnal.vitals)
assert any("一年多" in v.value for v in sparse_vm.diurnal.vitals)
# 2. End-to-end Deep-Link Navigation across TwinStage cards & Glycemic cards
repo = DemoDoctorRepository()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = SpatialShellWindow(
repo,
{"session": session, "demo_mode": True},
session.permissions,
)
shell.resize(1536, 864)
shell.show()
_settle(application, 22)
try:
rec = shell.pages["reception"]
cockpit = rec.cockpit_view
# Click '下焦 · 腰肾二便与四肢' -> opens 'basic' tab & scrolls down to urine_condition
cockpit.locus_selected.emit("kidney_limbs")
_settle(application, 16)
diag = shell._global_diagnosis_dialog
assert shell.wing_manager.is_open and shell.wing_manager.active_widget is diag
assert diag._current_tab_key() == "basic"
assert diag._basic_scroll.verticalScrollBar().value() > 120
# Click '既往史与合并症' -> stays on 'basic' & scrolls down to past_history
cockpit.locus_selected.emit("past_history")
_settle(application, 10)
assert diag._current_tab_key() == "basic"
assert diag._basic_scroll.verticalScrollBar().value() > 180
# Click '医生备注与影像附件' -> switches directly to 'notes' tab
cockpit.locus_selected.emit("notes_media")
_settle(application, 8)
assert diag._current_tab_key() == "notes"
# Click '本诊单电子处方记录' -> switches directly to 'prescription' tab
cockpit.locus_selected.emit("rx_summary")
_settle(application, 8)
assert diag._current_tab_key() == "prescription"
# Click '空腹血糖监测' -> switches directly to 'daily' tab
cockpit.progression_card.open_daily_requested.emit()
_settle(application, 8)
assert diag._current_tab_key() == "daily"
finally:
for page in shell.pages.values():
if hasattr(page, "poll_timer"):
page.poll_timer.stop()
shell.chat_notifications.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()