Files
zyt/app/tests/test_ai_consult_report_charts_ui.py
T
2026-10-22 11:02:57 +08:00

414 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Recorded glucose charts inside the actual AI report and streaming lifecycle."""
from __future__ import annotations
import os
from copy import deepcopy
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QPoint, QTimer
from PySide6.QtGui import QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QComboBox, QLabel
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
REPORT = """以下依据已加载的血糖记录梳理变化情况,请结合原始测量时间与当前病历逐项核对。
1. 血糖记录与趋势
- 记录核对:请区分空腹和餐后记录,并结合实际测量日期阅读图表,缺失的记录不能作为零值。
- 资料说明:文字中提及的数值仅用于说明,图表只能采用健康档案中的实际测量记录。
2. 随访资料核对
- 本次复诊:请保留完整记录,核对服药时间、进食时间与居家测量方式,补充尚未填写的资料。
"""
CLINICAL_REPORT = """基于当前病历,患者有血糖波动的描述,需结合完整的测量记录与四诊信息进一步核对。
### 1. 可能证候分析
- 病史待核对:现有记录反映的变化需与实际测量条件相互核对,尚不足以确认具体证候。
### 2. 关键矛盾与不足
- 资料缺口:需区分空腹及餐后记录,核对测量日期,保留未记录的部分而不补写数值。
### 3. 建议下一步
- 核对原始记录:将历史血糖记录与用药、进食情况一起核对,由医生结合资料作进一步判断。
"""
def _tracking(diagnosis_id=501, patient_id=1501):
return {
"diagnosis_id": diagnosis_id,
"blood_records": [
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-17", "record_time": "07:30",
"fasting_blood_sugar": 6.2, "postprandial_blood_sugar": 8.4},
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-18", "record_time": "07:40",
"fasting_blood_sugar": 6.8, "postprandial_blood_sugar": None},
],
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
def _settle(application):
for _ in range(6):
application.processEvents()
QTest.qWait(5)
@pytest.fixture
def dialog(application, monkeypatch):
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _generation: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance._workspace_sections = {"tracking": {"value": _tracking()}}
instance.resize(1280, 820)
instance.show()
_settle(application)
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.mark.parametrize("reply, panel_type", [
(REPORT, module._StructuredReportPanel),
(CLINICAL_REPORT, module._ClinicalAnalysisPanel),
])
def test_completed_report_formats_use_observed_measurements(dialog, reply, panel_type):
bubble = dialog._append_bubble("ai", reply)
before = deepcopy(dialog._workspace_sections)
dialog._finalize_ai_bubble(bubble)
panel = bubble.findChild(panel_type)
assert panel is not None
card = panel.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.data.readout_count == 3
assert [row.fasting for row in card.chart.data.readings] == [6.2, 6.8]
assert [row.postprandial for row in card.chart.data.readings] == [8.4, None]
assert dialog._workspace_sections == before
# The chart is above the textual interpretation, not a separate chat reply.
assert panel.layout().itemAt(1).widget() is card
assert bubble.body is not None and bubble.body.isHidden()
assert bubble._raw_payload == reply
def test_stream_builds_chart_on_done_once_and_keeps_timing_and_snapshot(dialog, application):
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "请评估该患者的血糖控制情况与趋势。"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": REPORT})
dialog._flush_stream_chunks()
assert bubble.findChild(GlucoseReportCard) is None
dialog._stream_event(generation, stream, {"event": "done", "model_label": "千问"})
_settle(application)
cards = bubble.findChildren(GlucoseReportCard)
assert len(cards) == 1 and cards[0].chart is not None
assert cards[0].chart.data.readout_count == 3
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
dialog._stream_finished(generation, stream, object())
assert "千问" in panel.meta_label.text()
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 22
assert cards[0].chart.data.readings[0].fasting == 6.2
assert dialog.send_button.isEnabled()
def test_archived_and_saved_reports_receive_the_same_chart(dialog):
dialog._render_messages([{"diagnosis_id": 501, "role": "ai", "content": REPORT}])
archived = dialog.findChildren(GlucoseReportCard)
assert len(archived) == 1 and archived[0].chart is not None
dialog._render_analysis({"diagnosis_advice": "血糖记录需与实际进食时间核对。"})
charts = [card.chart for card in dialog.findChildren(GlucoseReportCard)]
assert len(charts) == 2
assert all(chart is not None and chart.data.readout_count == 3 for chart in charts)
def test_no_measurements_keeps_full_report_without_fabricated_prose_values(dialog):
dialog._workspace_sections = {"tracking": {"value": None, "error": "记录不可用"}}
reply = REPORT + "\nAI 文本举例:空腹血糖 5.6 mmol/L,餐后 8.2 mmol/L。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
assert bubble._raw_payload == reply
assert bubble.findChild(module._StructuredReportPanel) is not None
assert bubble.findChild(module.QFrame, "AiConsultReportVisual") is None
def test_plain_answer_gets_chart_but_irrelevant_answer_stays_text_only(dialog):
bubble = dialog._append_bubble("ai", "请核对原始血糖记录。")
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is not None
assert bubble.body is not None and not bubble.body.isHidden()
unrelated = dialog._append_bubble("ai", "请携带既往处方核对具体药物名称。")
dialog._finalize_ai_bubble(unrelated)
assert unrelated.findChild(GlucoseReportCard) is None
def test_switching_patient_clears_chart_context_before_loading_and_ignores_old_stream(dialog):
old_generation, old_stream = dialog._generation, dialog._stream_generation
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert dialog._workspace_sections == {}
assert dialog._detail == {}
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
dialog._stream_bubble = bubble
dialog._stream_event(old_generation, old_stream, {"event": "done", "answer": REPORT})
assert bubble.findChild(GlucoseReportCard) is card
# A delayed response for the previous diagnosis cannot repopulate data.
dialog._workspace_loaded(old_generation, {"diagnosis_id": 501, "tracking": {"value": _tracking()}})
assert dialog._workspace_sections == {}
def test_changed_authoritative_patient_cannot_enable_old_chart_data(dialog):
dialog.patient_id = 1999
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
@pytest.mark.parametrize("width", [1080, 1600])
def test_report_chart_and_end_of_report_remain_reachable(dialog, application, width):
dialog.resize(width, 820)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
_settle(application)
card = bubble.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.width() > 200 and card.chart.height() > 150
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert card.chart.width() <= card.width()
assert bubble._clinical_panel is not None
final_label = bubble._clinical_panel.findChildren(QLabel, "AiConsultReportBody")[-1]
dialog.chat_scroll.verticalScrollBar().setValue(dialog.chat_scroll.verticalScrollBar().maximum())
_settle(application)
bottom = final_label.mapTo(dialog.chat_scroll.viewport(), QPoint(0, final_label.height() - 1))
assert dialog.chat_scroll.viewport().rect().contains(bottom)
def test_blood_pressure_answer_automatically_chooses_pressure_instead_of_glucose(dialog):
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
reply = """以下根据本诊单实际录入的血压记录梳理近期变化,需结合原始测量时间核对。
1. 血压记录与变化
- 记录核对:当前已有连续日期的收缩压和舒张压记录,图表应按实际日期显示,保留原有测量单位。
2. 随访资料核对
- 测量条件:请核对测量时的休息状态、服药时间与设备,结合完整资料由医生进一步评估。
"""
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble, prompt="请分析血压变化。")
assert bubble.findChild(GlucoseReportCard) is None
cards = bubble.findChildren(module.QFrame, "AiConsultReportVisual")
assert cards and any(card.property("visualKind") == "blood_pressure" for card in cards)
assert all(card.data.kind == card.property("visualKind") for card in cards)
def test_numeric_ranges_and_status_are_colored_without_changing_report_text(dialog):
reply = """以下根据患者描述核对现有血糖记录,本段数字范围需要保留原文,不能自动改成精确测量点。
1. 当前控制水平:未达标
- 空腹血糖:记录为 6-7 mmol/L,需结合原始测量时间核对。
- 餐后血糖:记录为 8-9 mmol/L,当前资料尚需进一步核对。
2. 参考目标与复诊资料
- 目标说明:目标 <7.0 mmol/L 仅为报告中引用的参考内容,应与实际记录区分。
"""
dialog._workspace_sections = {}
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is None
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
documents = []
for label in panel.findChildren(QLabel):
doc = QTextDocument()
doc.setHtml(label.text())
documents.append(doc)
for value in ("6-7 mmol/L", "8-9 mmol/L", "<7.0 mmol/L"):
document = next(doc for doc in documents if value in doc.toPlainText())
color = document.find(value).charFormat().foreground().color().name()
assert color not in {"#000000", "#1a1c1f"}
heading = next(doc for doc in documents if "当前控制水平" in doc.toPlainText())
assert heading.find("未达标").charFormat().foreground().color().name() == "#bd4b58"
assert bubble._raw_payload == reply
def test_refinalizing_answer_replaces_visuals_without_duplicate_cards(dialog, application):
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections = {}
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert bubble.findChild(GlucoseReportCard) is None
def test_short_answer_colors_values_without_replacing_markdown_or_original_payload(dialog):
reply = "**复核记录**:血压 142/90 mmHg,HbA1c 7.2%,请结合实际资料核对。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.body is not None
document = bubble.body.document()
assert document.find("142/90 mmHg").charFormat().foreground().color().name() == "#697386"
assert document.find("复核记录").charFormat().fontWeight() >= 600
assert bubble._raw_payload == reply
def test_clinical_evidence_keeps_ranges_and_does_not_shorten_approximate_readings():
evidence = module._clinical_evidence("患者空腹血糖 6-7 mmol/L,其他资料待补充。")
assert evidence[0].value == "6-7 mmol/L"
approximate = module._clinical_evidence("患者空腹血糖有时6点多,尚未携带原始记录。")
assert not any(item.label == "空腹血糖" for item in approximate)
def test_multitopic_reports_switch_charts_without_hiding_or_rebuilding_analysis(dialog, application):
dialog._workspace_sections["detail"] = {"value": {"diagnosis": {
"id": 501, "patient_id": 1501, "hba1c": 7.2, "hba1c_status": "high",
}, "patient": {"id": 1501, "weight": 68, "height": 168}}}
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble, prompt="请综合分析血糖、血压和体重。")
_settle(application)
selector = bubble.findChild(QComboBox, "AiConsultReportVisualSelector")
assert selector is not None and selector.count() == 3
group = selector.parentWidget()
cards = [item.widget() for index in range(1, group.layout().count())
if (item := group.layout().itemAt(index)).widget() is not None]
assert len(cards) == 3
identities = [id(card) for card in cards]
for index in range(selector.count()):
selector.setCurrentIndex(index)
_settle(application)
assert not cards[index].isHidden()
assert all(card.isHidden() for position, card in enumerate(cards) if position != index)
assert [id(card) for card in cards] == identities
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert bubble._raw_payload == REPORT
assert bubble.findChild(module._StructuredReportPanel) is not None
def _label_color(widget, reading, object_name=""):
documents = []
for label in widget.findChildren(QLabel, object_name):
document = QTextDocument()
document.setHtml(label.text())
if reading in document.toPlainText():
documents.append(document)
assert documents, f"No rendered label contains {reading!r}"
return {doc.find(reading).charFormat().foreground().color().name() for doc in documents}
def _colored_snapshot():
return {"detail": {"value": {"diagnosis": {
"id": 501, "patient_id": 1501,
"fasting_blood_sugar": "6-7", "fasting_blood_sugar_status": "high",
"postprandial_blood_sugar": "8-9", "postprandial_blood_sugar_status": "normal",
"hba1c": 7.2, "bmi": 26.1, "bmi_status": "high",
}, "patient": {"id": 1501}}}}
def test_streamed_snapshot_uses_same_colors_in_body_chart_and_raw_records(dialog):
dialog._workspace_sections = _colored_snapshot()
before = deepcopy(dialog._workspace_sections)
reply = """以下根据本诊单录入的指标核对资料,范围保留原文,由医生结合原始记录评估。
1. 本次指标记录
- 空腹血糖:记录为 6-7 mmol/L,保留原始范围。
- 餐后血糖:记录为 8-9 mmol/L,保留原始范围。
- 糖化血红蛋白:7.2%,记录未标注状态。
2. 补充资料
- 参考目标:空腹血糖目标 6-7 mmol/L,仅供核对报告中的参考内容。
"""
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "综合分析血糖"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": reply})
dialog._stream_event(generation, stream, {"event": "done"})
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
assert _label_color(panel, "6-7 mmol/L", "AiConsultReportBody") == {"#bd4b58", "#697386"}
assert _label_color(panel, "8-9 mmol/L", "AiConsultReportBody") == {"#287b65"}
assert _label_color(panel, "7.2%", "AiConsultReportBody") == {"#697386"}
card = next(card for card in panel.findChildren(module.QFrame, "AiConsultReportVisual")
if card.data.kind == "metrics")
for label, color in [("空腹血糖", "#bd4b58"), ("餐后血糖", "#287b65"), ("糖化血红蛋白", "#697386")]:
index, item = next((i, item) for i, item in enumerate(card.data.items) if item.label == label)
assert item.color.lower() == color
assert card.table.item(index, 2).foreground().color().name() == color
assert bubble._raw_payload == reply
assert dialog._workspace_sections == before
def test_trend_states_also_color_short_markdown_and_combined_pressure(dialog):
rows = dialog._workspace_sections["tracking"]["value"]["blood_records"]
rows[0].update(fasting_blood_sugar_status="high", postprandial_blood_sugar_status="normal",
systolic_pressure=142, diastolic_pressure=90,
systolic_pressure_status="normal", diastolic_pressure_status="high")
reply = "**核对记录**:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
document = bubble.body.document()
for reading, color in [("6.2 mmol/L", "#bd4b58"), ("8.4 mmol/L", "#287b65"), ("142/90 mmHg", "#bd4b58")]:
assert document.find(reading).charFormat().foreground().color().name() == color
assert document.toPlainText() == "核对记录:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
assert document.find("核对记录").charFormat().fontWeight() >= 600
# Rendering a different record cannot inherit the previous report's source flags.
dialog._workspace_sections = {}
other = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(other)
assert other.body.document().find("6.2 mmol/L").charFormat().foreground().color().name() == "#697386"
assert document.find("6.2 mmol/L").charFormat().foreground().color().name() == "#bd4b58"
def test_saved_summary_and_key_facts_share_source_state_and_missing_palette(dialog):
dialog._workspace_sections = _colored_snapshot()
dialog._workspace_sections["detail"]["value"]["diagnosis"]["hba1c_status"] = "high"
dialog._apply_header(dialog._workspace_sections["detail"]["value"])
facts = dialog.findChildren(QLabel, "AiConsultKeyValue")
assert next(label for label in facts if label.text() == "26.1").styleSheet() == "color: #bd4b58;"
assert all(label.styleSheet() == "color: #697386;" for label in facts if label.text() == "未记录")
dialog._render_analysis({
"diagnosis_advice": "空腹血糖 6-7 mmol/L,餐后血糖 8-9 mmol/L。HbA1c 7.2%。",
"risk_assessment": [{"label": "随访风险", "level": "medium"}],
})
assert _label_color(dialog, "6-7 mmol/L", "AiConsultInsightText") == {"#bd4b58"}
assert _label_color(dialog, "8-9 mmol/L", "AiConsultInsightText") == {"#287b65"}
assert _label_color(dialog, "7.2%", "AiConsultInsightText") == {"#bd4b58"}
badge = next(label for label in dialog.findChildren(QLabel, "AiConsultTag") if label.text() == "中风险")
assert "#BD4B58" in badge.styleSheet()
@pytest.mark.parametrize("text", ["HbA1c 7.2%", "7.2 mmol/L 为原始记录", "指标:7.2%"])
def test_sidebar_does_not_split_decimal_measurements_into_list_markers(text):
segments = module._split_insight_segments(text)
assert len(segments) == 1
assert segments[0].kind != "list" and "7.2" in segments[0].text
def test_numbered_sidebar_summary_preserves_decimals_and_actual_list_structure():
segments = module._split_insight_segments("建议:1. 复核 HbA1c 7.2% 2. 核对空腹血糖 6.8 mmol/L")
numbered = [item for item in segments if item.kind == "list"]
assert [(item.marker, item.text) for item in numbered] == [
("1.", "复核 HbA1c 7.2%"), ("2.", "核对空腹血糖 6.8 mmol/L"),
]