i
This commit is contained in:
gr
2026-10-22 11:12:29 +08:00
480 changed files with 9840 additions and 953 deletions
+431
View File
@@ -0,0 +1,431 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPoint, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.ui.dialogs.ai_consult_charts import (
GlucoseReportCard,
build_glucose_chart_data,
)
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
**changes,
}
def _tracking(*rows: Any, **changes: Any) -> dict[str, Any]:
return {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows), **changes}
def _build(tracking: Any):
return build_glucose_chart_data(tracking, diagnosis_id=501, patient_id=1501)
def test_real_dto_is_immutable_chronological_and_does_not_average_same_day() -> None:
tracking = _tracking(
_row("2026-08-20", record_time="09:10", fasting_blood_sugar="7.2 mmol/L"),
_row("2026-08-18", record_time="09:00", fasting_blood_sugar=6.1),
_row("2026-08-18", record_time="08:00", fasting_blood_sugar=5.9),
_row("2026-08-19", fasting_blood_sugar=None, postprandial_blood_sugar="9.1"),
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before
assert data.available and data.readout_count == 4 and data.record_count == 4
assert [reading.fasting for reading in data.readings] == [5.9, 6.1, None, 7.2]
assert data.readings[2].postprandial == 9.1
assert data.readings[0].recorded_at == datetime(2026, 8, 18, 8)
assert data.readings[0].time_label == "2026-08-18 08:00"
assert data.readings[2].time_label == "2026-08-19"
assert data.date_range is not None
assert tuple(day.isoformat() for day in data.date_range) == ("2026-08-18", "2026-08-20")
assert data.excluded_count == 0
with pytest.raises(FrozenInstanceError):
data.readings[0].fasting = 99 # type: ignore[misc]
tracking["blood_records"][0]["fasting_blood_sugar"] = 99
assert data.readings[-1].fasting == 7.2
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_tracking_root_requires_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(), diagnosis_id=owner))
assert not data.available and data.readings == ()
assert "归属" in data.unavailable_reason
def test_ownerless_root_is_rejected() -> None:
tracking = _tracking(_row())
del tracking["diagnosis_id"]
assert not _build(tracking).available
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_rows_require_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(diagnosis_id=owner), _row("2026-08-19")))
assert data.record_count == 1
assert data.readings[0].recorded_at.day == 19
assert data.excluded_count == 1
@pytest.mark.parametrize("owner", [None, True, 1501.0, "1501", 1502, 0])
def test_declared_patient_owner_is_strict_at_root_and_row(owner: Any) -> None:
assert not _build(_tracking(_row(), patient_id=owner)).available
data = _build(_tracking(_row(patient_id=owner)))
assert not data.available and data.readings == ()
assert data.excluded_count == 1
def test_diagnosis_owned_rows_may_omit_patient_id_but_not_diagnosis_id() -> None:
row = _row()
del row["patient_id"]
assert _build(_tracking(row)).readout_count == 1
del row["diagnosis_id"]
assert not _build(_tracking(row)).available
def test_root_patient_owner_is_used_when_the_caller_has_no_patient_id() -> None:
data = build_glucose_chart_data(_tracking(_row(patient_id=1502)), diagnosis_id=501)
assert not data.available and data.excluded_count == 1
@pytest.mark.parametrize(
"value",
[
True,
False,
float("nan"),
float("inf"),
-float("inf"),
-1,
"-1",
"6-9",
"约 6.8",
"~6.8",
"<6.8",
"6.8±0.2",
"6.8 mg/dL",
"血糖6.8",
{"value": 6.8},
"Infinity",
],
)
def test_ambiguous_readings_stay_gaps_and_are_never_guessed(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert not data.available and data.readout_count == 0
assert len(data.readings) == 1 and data.readings[0].fasting is None
assert data.excluded_count == 1
@pytest.mark.parametrize("value", [None, "", "—", "未填写", 0, 0.0, "0", "0.0 mmol/L"])
def test_daily_zero_and_missing_defaults_are_absent_without_ambiguous_warning(value: Any) -> None:
data = _build(
_tracking(
_row(
fasting_blood_sugar=value,
postprandial_blood_sugar=0,
other_blood_sugar=0,
remark="继续观察",
)
)
)
assert not data.available and data.readout_count == 0
assert data.excluded_count == 0
assert all(reading.readout_count == 0 for reading in data.readings)
@pytest.mark.parametrize("value", ["6.80", "6.8 mmol/L", " 6.8 MMOL / l ", 6.8])
def test_exact_mmol_readings_are_accepted(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert data.readings[0].fasting == 6.8
assert data.excluded_count == 0
def test_partial_ambiguous_row_preserves_verified_series_and_records_one_exclusion() -> None:
data = _build(
_tracking(
_row(fasting_blood_sugar="6-9", postprandial_blood_sugar=9.3, other_blood_sugar="约7")
)
)
assert data.available and data.readout_count == 1
assert data.readings[0].fasting is None
assert data.readings[0].postprandial == 9.3
assert data.excluded_count == 1
@pytest.mark.parametrize(
"day", [None, "", "2026-02-30", "08-18", "2026-8-18", "2026-08-18 大约", 1787040000]
)
def test_missing_or_ambiguous_date_never_becomes_today(day: Any) -> None:
data = _build(_tracking(_row(day)))
assert data.readings == () and data.excluded_count == 1
@pytest.mark.parametrize("clock", ["25:10", "8:30", "上午", True])
def test_invalid_declared_record_time_is_excluded(clock: Any) -> None:
assert _build(_tracking(_row(record_time=clock))).excluded_count == 1
def test_legacy_entries_require_owners_and_keep_periods_distinct() -> None:
tracking = {
"diagnosis_id": 501,
"blood_sugar": {
"entries": [
{"diagnosis_id": 501, "date": "2026-08-18", "value": "6.2", "period": "空腹"},
{"diagnosis_id": 501, "date": "2026-08-19", "value": "9.1", "period": "餐后"},
{
"diagnosis_id": 501,
"measured_at": "2026-08-19T20:10:00",
"value": "7.4",
"period": "睡前",
},
{"date": "2026-08-20", "value": "20.2", "period": "空腹"},
]
},
}
data = _build(tracking)
assert data.readout_count == 3 and data.excluded_count == 1
assert data.readings[0].fasting == 6.2
assert data.readings[1].postprandial == 9.1
assert data.readings[2].other == 7.4
assert data.readings[2].time_label == "2026-08-19 20:10"
tracking["blood_sugar"]["diagnosis_id"] = 502
assert not _build(tracking).available
def test_unit_metadata_cannot_relabel_mg_dl_as_mmol() -> None:
assert not _build(_tracking(_row(), unit="mg/dL")).available
assert not _build(_tracking(_row(unit="mg/dL"))).available
assert _build(_tracking(_row(unit="mmol/L"))).available
def test_production_source_takes_precedence_to_avoid_duplicate_representations() -> None:
tracking = _tracking(
_row(), blood_sugar={"entries": [{"diagnosis_id": 501, "date": "2026-08-18", "value": 9.9}]}
)
assert _build(tracking).readout_count == 1
def test_source_states_are_immutable_and_require_the_same_owned_row() -> None:
tracking = _tracking(
_row(fasting_glucose_status="normal", postprandial_glucose=9.3,
postprandial_glucose_status="low", other_glucose=7.1, other_glucose_status="warning"),
_row("2026-08-19", diagnosis_id=502, fasting_blood_sugar_status="high"),
fasting_blood_sugar_status="high",
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before and data.excluded_count == 1
assert len(data.readings) == 1
reading = data.readings[0]
assert (reading.fasting_status, reading.postprandial_status, reading.other_status) == (
"normal", "low", "warning",
)
tracking["blood_records"][0]["fasting_glucose_status"] = "high"
assert reading.fasting_status == "normal"
with pytest.raises(FrozenInstanceError):
reading.fasting_status = "high" # type: ignore[misc]
@pytest.mark.parametrize("status", [None, True, False, ["normal"], {"status": "normal"}])
def test_untyped_glucose_states_stay_unclassified(status: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar_status=status)))
assert data.readings[0].fasting_status == ""
def test_glucose_points_tables_and_accessibility_share_explicit_states(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=20, fasting_blood_sugar_status="normal",
postprandial_blood_sugar=3, postprandial_blood_sugar_status="low",
other_blood_sugar=12, other_blood_sugar_status="unclassified"),
_row("2026-08-19", fasting_blood_sugar=30),
_row("2026-08-20", fasting_blood_sugar=0, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(650, 420)
card.show()
application.processEvents()
assert card.chart is not None
chart = card.chart
image = chart.grab().toImage()
first = data.readings[0]
for column, field, color, status in (
(1, "fasting", NORMAL_COLOR, "normal"),
(2, "postprandial", ABNORMAL_COLOR, "low"),
(3, "other", UNKNOWN_COLOR, "unclassified"),
):
point = chart._position(first, getattr(first, field))
assert chart._point_color(first, field) == color
assert image.pixelColor(point.toPoint()).name().casefold() == color.casefold()
assert card.table.item(0, column).foreground().color().name().casefold() == color.casefold()
assert status in card.table.item(0, column).toolTip()
assert status in chart._point_tooltip(point)
assert status in chart.accessibleDescription()
assert card.table.item(1, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未标注" in card.table.item(1, 1).toolTip()
assert card.table.item(2, 1).text() == "—"
assert card.table.item(2, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未记录" in card.table.item(2, 1).toolTip()
assert "空腹血糖 — · 状态 未记录" in chart.accessibleDescription()
assert "红色异常、绿色正常、灰色未记录/未标注" in chart.accessibleDescription()
card.close()
def test_glucose_connection_is_gray_between_explicit_normal_points(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
_row("2026-08-20", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(640, 420)
card.show()
application.processEvents()
assert card.chart is not None
left, right = [card.chart._position(reading, 5) for reading in data.readings]
midpoint = (left + right) / 2
image = card.chart.grab().toImage()
center = midpoint.toPoint()
assert UNKNOWN_COLOR.casefold() in {
image.pixelColor(center.x() + dx, center.y() + dy).name()
for dx in (-1, 0, 1) for dy in (-1, 0, 1)
}
assert image.pixelColor(left.toPoint()).name() == NORMAL_COLOR.casefold()
card.close()
def test_explicit_missing_series_preserve_gaps_and_actual_date_spacing(
application: QApplication,
) -> None:
data = _build(
_tracking(
_row("2026-08-01", fasting_blood_sugar=5.8),
_row("2026-08-02", fasting_blood_sugar="6-9"),
_row("2026-08-11", fasting_blood_sugar=7.1),
)
)
assert [reading.fasting for reading in data.readings] == [5.8, None, 7.1]
card = GlucoseReportCard(data)
card.resize(700, 400)
card.show()
application.processEvents()
assert card.chart is not None
first = card.chart._position(data.readings[0], 5.8)
gap = card.chart._position(data.readings[1], 5.8)
last = card.chart._position(data.readings[2], 5.8)
assert (gap.x() - first.x()) / (last.x() - first.x()) == pytest.approx(0.1)
assert not card.grab().isNull()
card.close()
def test_single_point_hover_and_original_records_toggle(
application: QApplication, monkeypatch: pytest.MonkeyPatch
) -> None:
data = _build(_tracking(_row(record_time="08:15", fasting_blood_sugar=6.83)))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.objectName() == "AiConsultGlucoseReport"
assert card.chart is not None and card.chart.data is data
assert card.chart.objectName() == "AiConsultGlucoseChart"
assert card.toggle_button is not None
assert card.table.isHidden()
assert card.table.item(0, 0).text() == "2026-08-18 08:15"
assert card.table.item(0, 1).text() == "6.83"
assert card.table.item(0, 2).text() == "—"
assert "6.83 mmol/L" in card.chart.accessibleDescription()
tooltips: list[str] = []
monkeypatch.setattr(QToolTip, "showText", lambda _position, text, *_args: tooltips.append(text))
point = card.chart._position(data.readings[0], 6.83)
QTest.mouseMove(card.chart, QPoint(round(point.x()), round(point.y())))
application.processEvents()
assert tooltips and "2026-08-18 08:15" in tooltips[-1] and "6.83 mmol/L" in tooltips[-1]
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert not card.table.isHidden() and card.toggle_button.isChecked()
assert card.toggle_button.text() == "收起原始记录"
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert card.table.isHidden()
card.close()
def test_overlapping_observations_remain_separate_in_hover_and_table(
application: QApplication,
) -> None:
data = _build(_tracking(_row(record_time="08:15"), _row(record_time="08:15")))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.chart is not None
tip = card.chart._point_tooltip(card.chart._position(data.readings[0], 6.8))
assert "记录 1" in tip and "记录 2" in tip
assert card.table.rowCount() == 2
card.close()
@pytest.mark.parametrize("width", [320, 580, 880])
def test_report_card_fits_narrow_and_wide_columns(application: QApplication, width: int) -> None:
data = _build(
_tracking(
_row(other_blood_sugar=8.2, postprandial_blood_sugar=9.1),
_row("2026-08-19", fasting_blood_sugar="6-9"),
)
)
card = GlucoseReportCard(data)
card.resize(width, card.sizeHint().height())
card.show()
application.processEvents()
assert card.width() == width
assert card.chart is not None and card.chart.height() >= 210
assert card.chart.geometry().right() < width
for label in card.findChildren(QLabel):
assert label.geometry().right() < width
assert not card.grab().isNull()
assert card.toggle_button is not None
card.toggle_button.click()
application.processEvents()
assert card.table.geometry().right() < width
assert not card.grab().isNull()
card.close()
@pytest.mark.parametrize(
"tracking", [None, {}, _tracking(), _tracking(_row(fasting_blood_sugar=0, remark="仅有备注"))]
)
def test_unavailable_state_has_no_fabricated_chart_or_empty_toggle(
application: QApplication, tracking: Any
) -> None:
card = GlucoseReportCard(_build(tracking))
card.resize(380, card.sizeHint().height())
card.show()
application.processEvents()
assert card.chart is None and card.toggle_button is None and card.table.isHidden()
assert card.height() < 210
assert any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
assert not card.grab().isNull()
card.close()
+407
View File
@@ -0,0 +1,407 @@
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtGui import QTextCursor, QTextDocument
from PySide6.QtWidgets import QApplication
from doctor_workstation.ui.dialogs.ai_consult_metric_text import (
MetricTextState,
metric_text_context,
metric_text_html,
)
@pytest.fixture(scope="module", autouse=True)
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _document(text: str, *, metric_label: str = "") -> QTextDocument:
document = QTextDocument()
document.setHtml(metric_text_html(text, metric_label=metric_label))
assert document.toPlainText() == text.replace("\r\n", "\n").replace("\r", "\n")
return document
def _color(document: QTextDocument, phrase: str, offset: int = 0) -> str:
position = document.toPlainText().index(phrase) + offset
cursor = QTextCursor(document)
cursor.setPosition(position)
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
return cursor.charFormat().foreground().color().name().upper()
@pytest.mark.parametrize(
"text,measurement",
[
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "6-7 mmol/L"),
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "8-9mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖≤ 7.0 mmol/L", "≤ 7.0 mmol/L"),
("血糖<= 7.0 mmol/L", "<= 7.0 mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖3.9~6.1 mmol/L", "3.9~6.1 mmol/L"),
("血糖4.4至7.0 mmol/L", "4.4至7.0 mmol/L"),
("BP140/90mmHg", "140/90mmHg"),
("血压140 / 90 mmHg", "140 / 90 mmHg"),
("HbA1c7.2%", "7.2%"),
("糖化血红蛋白(HbA1c)7.2%", "7.2%"),
("BMI26.1", "26.1"),
("BMI26.1kg/m²", "26.1kg/m²"),
("体质量指数:26.1", "26.1"),
("身高175cm,体重80 kg", "175cm"),
("身高175cm,体重80 kg", "80 kg"),
("身高1.75m", "1.75m"),
("height175cm,weight80kg", "175cm"),
("height175cm,weight80kg", "80kg"),
("LDL-C130mg/dL", "130mg/dL"),
("TC:5.8mmol/L", "5.8mmol/L"),
("eGFR 85 ml/min/1.73m²", "85 ml/min/1.73m²"),
("eGFR:85", "85"),
("eGFR 85 mL/min/1.73 m2", "85 mL/min/1.73 m2"),
("ACR30mg/g", "30mg/g"),
("尿白蛋白肌酐比值30mg/gCr", "30mg/gCr"),
("肌酐88 μmol/L", "88 μmol/L"),
("尿酸300µmol/L", "300µmol/L"),
("heart_rate:72", "72"),
("heart_rate72bpm", "72bpm"),
("心率72次/分", "72次/分"),
("HR72bpm", "72bpm"),
("血氧饱和度98%", "98%"),
("体温36.8℃", "36.8℃"),
("ALT35U/L", "35U/L"),
("血红蛋白130g/L", "130g/L"),
],
)
def test_clinical_values_are_semibold_gray_and_preserve_all_characters(
text: str, measurement: str
) -> None:
document = _document(text)
for offset in range(len(measurement)):
assert _color(document, measurement, offset) == "#697386"
cursor = QTextCursor(document)
cursor.setPosition(document.toPlainText().index(measurement))
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
assert cursor.charFormat().fontWeight() >= 600
@pytest.mark.parametrize("cue", ["目标", "参考", "理想", "阈值"])
def test_targets_and_reference_ranges_stay_gray(cue: str) -> None:
document = _document(f"当前血糖8.2 mmol/L,{cue}:<7.0 mmol/L")
assert _color(document, "8.2 mmol/L") == "#697386"
for offset in range(len("<7.0 mmol/L")):
assert _color(document, "<7.0 mmol/L", offset) == "#697386"
def test_percent_targets_inherit_only_a_clinical_percent_label() -> None:
document = _document("HbA1c7.2%,目标<7.0%;总体完成率80%,风险降低20%")
assert _color(document, "7.2%") == "#697386"
assert _color(document, "<7.0%") == "#697386"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
def test_current_readings_after_targets_do_not_keep_reference_color() -> None:
document = _document("目标<7.0 mmol/L;当前8.2 mmol/L,6.8 mmol/L(参考值)")
assert _color(document, "<7.0 mmol/L") == "#697386"
assert _color(document, "8.2 mmol/L") == "#697386"
assert _color(document, "6.8 mmol/L") == "#697386"
@pytest.mark.parametrize(
"text",
[
"诊单ID:123456;patient_id=1501;流水ABC123456;电话13800138000",
"2026-08-18,2026/08/19,08:30,第1章,1. 检查,2. 处理",
"病程3年,持续2周,随访7天,每次30分钟",
"二甲双胍500mg,每日2次;胰岛素10U;阿司匹林100 mg",
"剂量0.2mg/kg、浓度5mg/mL,外用2%利多卡因",
"统计显示80%的患者改善20%,目标完成率90%,报销比例50%",
"BMI2026-08-18;eGFR2026/08/19;heart_rate2026-08-18",
"not_BMI26.1;abceGFR85;ID7mmol/L;abc72bpm",
],
)
def test_unrelated_numbers_and_drug_doses_remain_unemphasized(text: str) -> None:
rendered = metric_text_html(text)
_document(text)
assert "color:" not in rendered
def test_explicit_statuses_are_emphasized_without_classifying_the_numbers() -> None:
document = _document("血糖6.0 mmol/L未达标;血压140/90mmHg正常;血糖偏高;检查异常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "140/90mmHg") == "#287B65"
assert _color(document, "未达标") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
assert _color(document, "偏高") == "#BD4B58"
assert _color(document, "异常") == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("未达标", "#BD4B58"),
("不达标", "#BD4B58"),
("尚未完全达标", "#BD4B58"),
("未见异常", "#287B65"),
("无异常", "#287B65"),
("未见明显异常", "#287B65"),
("没有显著异常", "#287B65"),
("不正常", "#BD4B58"),
("非正常", "#BD4B58"),
("未恢复正常", "#BD4B58"),
("已达标", "#287B65"),
],
)
def test_negated_statuses_do_not_color_a_misleading_substring(status: str, color: str) -> None:
document = _document(status)
for offset in range(len(status)):
assert _color(document, status, offset) == color
@pytest.mark.parametrize(
"text",
[
"建议复查以排除异常",
"警惕血糖偏低风险",
"可能偏高,需结合进一步检查",
"若仍未达标,应复查",
"不能排除血糖异常",
"是否正常有待检查",
"未见升高;无明显升高;不偏高",
"无法达标;未达到正常;不能完全达标",
"正常值与正常范围;达标率80%",
"如血糖升高或不达标,应随访",
"需使血糖达标",
"建议控制至正常,争取早日达标",
],
)
def test_uncertain_conditional_or_recommended_statuses_stay_neutral(text: str) -> None:
_document(text)
assert "color:" not in metric_text_html(text)
@pytest.mark.parametrize(
"text",
[
"",
" 原文 保留\t制表符\n\n最后 ",
"\n首行前换行\r\n血糖<7.0 mmol/L\r末行\n",
'<script>alert("test")</script>\n<a href="https://example.com">6-7 mmol/L</a>',
'<img src="x" onerror="alert(1)">HbA1c7.2% &lt;7% &nbsp; & custom',
'<span style="color:red">正常</span> & \'" < >',
],
)
def test_html_is_literal_and_plain_text_and_whitespace_are_preserved(text: str) -> None:
document = _document(text)
html = metric_text_html(text)
assert "<script>" not in html
assert "<a " not in html
assert "<img " not in html
assert '<span style="color:red">' not in html
assert not document.find("https://example.com").charFormat().isAnchor()
assert "\n" not in html
@pytest.mark.parametrize(
"label,text,reading",
[
("空腹血糖", "FPG6.0mmol/L", "6.0mmol/L"),
("FPG", "空腹6.0 mmol/L", "6.0 mmol/L"),
("fasting_glucose", "空腹血糖6.0 mmol/L", "6.0 mmol/L"),
("HbA1c", "糖化血红蛋白7.2%", "7.2%"),
("糖化血红蛋白", "glycated hemoglobin 7.2%", "7.2%"),
("glycated haemoglobin", "HbA1c7.2%", "7.2%"),
("血压", "BP140/90mmHg", "140/90mmHg"),
("LDL-C", "低密度脂蛋白胆固醇3.2 mmol/L", "3.2 mmol/L"),
("尿素氮", "尿素氮6.0 mmol/L", "6.0 mmol/L"),
],
)
def test_recorded_states_match_field_aliases(label: str, text: str, reading: str) -> None:
with metric_text_context([MetricTextState(label, reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("high", "#BD4B58"),
("low", "#BD4B58"),
("warning", "#BD4B58"),
("未达标", "#BD4B58"),
("偏低", "#BD4B58"),
("normal", "#287B65"),
("达标", "#287B65"),
("unknown", "#697386"),
("", "#697386"),
("未记录", "#697386"),
("unexpected", "#697386"),
],
)
def test_value_only_widgets_use_the_supplied_field(status: str, color: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", status)]):
document = _document("6.0 mmol/L", metric_label="空腹血糖")
assert _color(document, "6.0 mmol/L") == color
assert _color(_document("6.0 mmol/L"), "6.0 mmol/L") == "#697386"
def test_unitless_value_only_widgets_bind_without_classifying_other_numbers() -> None:
with metric_text_context([MetricTextState("BMI", "26.1", "normal")]):
assert _color(_document("26.1", metric_label="体质指数"), "26.1") == "#287B65"
assert "color:" not in metric_text_html("2026-08-18", metric_label="BMI")
def test_context_restores_outer_state_after_nested_scope_and_exception() -> None:
text = "空腹血糖6.0 mmol/L"
reading = "6.0 mmol/L"
with metric_text_context([MetricTextState("FPG", reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
with (
pytest.raises(RuntimeError),
metric_text_context([MetricTextState("空腹", reading, "normal")]),
):
assert _color(_document(text), reading) == "#287B65"
raise RuntimeError("restore scope")
assert _color(_document(text), reading) == "#BD4B58"
assert _color(_document(text), reading) == "#697386"
def test_context_snapshots_input_sequence() -> None:
states = [MetricTextState("空腹", "6.0 mmol/L", "high")]
with metric_text_context(states):
states.clear()
assert _color(_document("空腹6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize("statuses", [("high", "normal"), ("unknown", "normal"), ("high", "")])
def test_conflicting_same_field_and_reading_states_stay_gray(statuses: tuple[str, str]) -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", statuses[0]),
MetricTextState("空腹血糖", "6.0mmol/L", statuses[1]),
]
):
assert _color(_document("空腹血糖6.0 mmol/L正常"), "6.0 mmol/L") == "#697386"
def test_equivalent_abnormal_source_flags_do_not_conflict() -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", "high"),
MetricTextState("空腹血糖", "6.0mmol/L", "warning"),
]
):
assert _color(_document("空腹血糖6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize(
"text",
[
"餐后血糖6.0 mmol/L",
"血糖6.0 mmol/L",
"空腹血糖6.1 mmol/L",
"空腹血糖6.0 mg/dL",
"空腹血糖<6.0 mmol/L",
"空腹血糖6.0-7.0 mmol/L",
],
)
def test_matching_value_cannot_leak_between_fields_units_or_readings(text: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", "normal")]):
assert "#287B65" not in metric_text_html(text)
def test_range_source_requires_whole_range_and_comparator() -> None:
reading = "≤ 4.4至7.0 mmol/L"
with metric_text_context([MetricTextState("空腹", reading, "warning")]):
assert _color(_document(f"空腹血糖{reading}"), reading) == "#BD4B58"
assert _color(_document("空腹血糖4.4 mmol/L"), "4.4 mmol/L") == "#697386"
def test_known_source_state_takes_precedence_over_ai_assertion() -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("空腹血糖6.0 mmol/L正常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
@pytest.mark.parametrize("hint", ["", "空腹血糖", "空腹血糖目标"])
def test_targets_never_inherit_source_state_even_when_value_matches(hint: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("目标空腹血糖6.0 mmol/L", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
document = _document("6.0 mmol/L(参考值)", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
def test_percent_reference_and_same_value_source_are_separated() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("糖化血红蛋白7.2%,目标7.2%")
assert _color(document, "7.2%") == "#BD4B58"
cursor = document.find("目标7.2%")
cursor.setPosition(cursor.selectionEnd() - 2)
cursor.movePosition(
QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor
)
assert cursor.charFormat().foreground().color().name().upper() == "#697386"
def test_percent_body_uses_its_separate_label_without_coloring_unrelated_percentages() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("7.2%,目标7.2%;完成率80%,风险下降20%", metric_label="HbA1c")
assert _color(document, "7.2%") == "#BD4B58"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
@pytest.mark.parametrize("cue", ["正常范围", "target", "reference range"])
def test_reference_phrases_always_stay_gray(cue: str) -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document(f"HbA1c {cue}: 7.2%")
assert _color(document, "7.2%") == "#697386"
@pytest.mark.parametrize(
"text,reading,color",
[
("血糖6.0 mmol/L未达标", "6.0 mmol/L", "#BD4B58"),
("血压140/90mmHg正常", "140/90mmHg", "#287B65"),
("血糖偏高:6.0 mmol/L", "6.0 mmol/L", "#BD4B58"),
("空腹6.0 mmol/L偏低", "6.0 mmol/L", "#BD4B58"),
("BMI26.1达标", "26.1", "#287B65"),
("FPG6.0mmol/L high", "6.0mmol/L", "#BD4B58"),
("血糖6.0 mmol/L可能偏高", "6.0 mmol/L", "#697386"),
("若血糖6.0 mmol/L未达标", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L无明显升高", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压正常", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压140/90mmHg正常", "6.0 mmol/L", "#697386"),
],
)
def test_local_assertion_colors_only_its_nearby_reading(
text: str, reading: str, color: str
) -> None:
assert _color(_document(text), reading) == color
@pytest.mark.parametrize(
"missing", ["未记录", "未检测", "未知", "暂无数据", "unknown", "N/A", "—", "--", "/"]
)
def test_missing_values_are_gray(missing: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", missing, "normal")]):
assert _color(_document(missing, metric_label="空腹血糖"), missing) == "#697386"
@pytest.mark.parametrize(
"label,color", [("高风险", "#BD4B58"), ("中风险", "#BD4B58"), ("低风险", "#287B65")]
)
def test_asserted_risk_levels_use_the_chart_palette(label: str, color: str) -> None:
assert _color(_document(f"风险评估:{label}"), label) == color
@pytest.mark.parametrize("text", ["可能高风险", "排除高风险", "中风险参考标准", "若为低风险"])
def test_conditional_risk_or_reference_is_not_an_asserted_state(text: str) -> None:
assert "#BD4B58" not in metric_text_html(text)
assert "#287B65" not in metric_text_html(text)
@@ -0,0 +1,413 @@
"""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"),
]
+571
View File
@@ -0,0 +1,571 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError, replace
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPointF, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.core.models import Prescription
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseChartData, GlucoseReportCard
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
from doctor_workstation.ui.dialogs.ai_consult_report_visuals import (
ReportVisualCard,
build_report_visuals,
create_report_visual,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
"systolic_pressure": 146,
"diastolic_pressure": 92,
**changes,
}
def _sections(*rows: Any, **diagnosis: Any) -> dict[str, Any]:
return {
"detail": {"value": {"diagnosis": {"id": 501, "patient_id": 1501, **diagnosis}}},
"tracking": {
"value": {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows)}
},
}
def _build(sections: dict[str, Any], prompt: str = "分析血压", reply: str = ""):
return build_report_visuals(prompt, reply, sections=sections, diagnosis_id=501, patient_id=1501)
def _kind(data: Any) -> str:
return "glucose" if isinstance(data, GlucoseChartData) else data.kind
def test_selects_actual_topics_in_prompt_or_reply_without_unrelated_charts() -> None:
sections = _sections(_row(), weight=60, hba1c=7.2)
assert [_kind(item) for item in _build(sections)] == ["blood_pressure"]
assert [_kind(item) for item in _build(sections, "", "检查空腹血糖")] == ["glucose", "metrics"]
assert _build(sections, "解释睡眠质量") == ()
assert [_kind(item) for item in _build(sections, "综合分析")] == [
"glucose",
"blood_pressure",
"metrics",
]
@pytest.mark.parametrize(
"topic", ["血糖", "血压", "血脂", "体重", "肾功能", "风险", "用药", "运动", "综合分析"]
)
def test_no_actual_data_never_produces_chart_shell(topic: str) -> None:
assert _build({}, topic, "目标血压 120/80,HbA1c 6.5%,每日运动30分钟") == ()
assert _build(_sections(), topic) == ()
def test_ai_prose_goals_and_approximate_numbers_never_become_observations() -> None:
sections = _sections(
_row(systolic_pressure="约146", diastolic_pressure="90-95", fasting_blood_sugar="~6.8")
)
assert _build(sections, "分析血压和血糖", "今天146/92,目标120/80,血糖7.0") == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 0, 502])
def test_tracking_root_and_rows_need_exact_diagnosis_owner(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["diagnosis_id"] = owner
assert _build(root) == ()
rows = _sections(_row(diagnosis_id=owner), _row("2026-08-19"))
visual = _build(rows)[0]
assert len(visual.items) == 2
assert all(item.recorded_at.day == 19 for item in visual.items)
@pytest.mark.parametrize("owner", [None, True, "1501", 1501.0, 0, 1502])
def test_declared_patient_owner_is_checked_at_tracking_root_and_row(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["patient_id"] = owner
assert _build(root) == ()
assert _build(_sections(_row(patient_id=owner))) == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 502])
def test_mismatched_detail_disables_linked_visuals(owner: Any) -> None:
sections = _sections(_row(), id=owner, hba1c=7.2)
assert _build(sections, "综合分析") == ()
def test_detail_patient_conflicts_and_section_errors_fail_closed() -> None:
assert _build(_sections(_row(), patient_id=1502)) == ()
sections = _sections(_row(), weight=60)
sections["detail"]["value"]["patient"] = {"id": 1502}
assert _build(sections, "综合分析") == ()
sections = _sections(_row())
sections["tracking"]["error"] = "接口失败"
assert _build(sections) == ()
def test_dto_snapshot_is_immutable_and_keeps_dates_gaps_and_duplicate_rows() -> None:
sections = _sections(
_row("2026-08-21", systolic_pressure=150),
_row("2026-08-18", systolic_pressure=140),
_row("2026-08-18", systolic_pressure=141),
_row("2026-08-19", systolic_pressure=None, diastolic_pressure=None),
)
before = deepcopy(sections)
data = _build(sections)[0]
assert sections == before
assert [item.value for item in data.items if item.series == "systolic_pressure"] == [
140,
141,
None,
150,
]
assert data.items[0].recorded_at == datetime(2026, 8, 18)
with pytest.raises(FrozenInstanceError):
data.items[0].value = 100 # type: ignore[misc]
sections["tracking"]["value"]["blood_records"][1]["systolic_pressure"] = 999
assert data.items[0].value == 140
@pytest.mark.parametrize(
"value", [True, "约 130", "120-140", "<140", float("nan"), float("inf"), 0, -1]
)
def test_ambiguous_pressure_readings_are_not_plotted(value: Any) -> None:
assert _build(_sections(_row(systolic_pressure=value, diastolic_pressure=None))) == ()
def test_no_dated_pressure_is_replaced_by_a_snapshot_only_when_detail_is_real() -> None:
sections = _sections(_row("不是日期"), systolic_pressure=130, diastolic_pressure=80)
data = _build(sections)[0]
assert data.kind == "metrics"
assert [item.value for item in data.items] == [130, 80]
assert all(item.recorded_at is None and item.reference is None for item in data.items)
def test_status_colors_come_only_from_source_and_units_are_separate() -> None:
data = _build(
_sections(
hba1c=12.5,
hba1c_status="normal",
cholesterol=5.2,
cholesterol_status="high",
microalbumin=12,
microalbumin_status="low",
weight=100,
bmi=35,
),
"综合分析",
)[0]
assert data.kind == "metrics"
metrics = {item.label: item for item in data.items}
assert metrics["糖化血红蛋白"].color == NORMAL_COLOR
assert metrics["总胆固醇"].color == ABNORMAL_COLOR
assert metrics["尿微量白蛋白"].color == ABNORMAL_COLOR
assert metrics["体重"].color == metrics["BMI"].color == UNKNOWN_COLOR
assert [
(metrics[key].unit) for key in ("糖化血红蛋白", "总胆固醇", "尿微量白蛋白", "体重", "BMI")
] == ["%", "mmol/L", "mg/L", "kg", "kg/m²"]
assert all(item.reference is None for item in data.items)
assert metrics["BMI"].value == 35
def test_source_units_override_defaults_without_conversion_or_shared_scale() -> None:
data = _build(
_sections(creatinine="1.1 mg/dL", creatinine_unit="mg/dL", weight="60 kg"), "肾功能与体重"
)[0]
assert [(item.value, item.unit) for item in data.items] == [(1.1, "mg/dL"), (60, "kg")]
assert all(item.reference is None for item in data.items)
def test_recorded_interval_is_distinct_from_exact_points_and_has_no_invented_date() -> None:
data = _build(
_sections(fasting_blood_sugar="6-7", postprandial_blood_sugar="8~9 mmol/L"), "血糖"
)[0]
assert data.kind == "metrics"
assert [item.interval for item in data.items] == [(6, 7), (8, 9)]
assert all(
item.value is None and item.recorded_at is None and item.reference is None
for item in data.items
)
assert data.items[1].value_text == "8~9 mmol/L"
def test_owned_patient_body_measurements_are_used_when_not_repeated_in_diagnosis() -> None:
sections = _sections()
sections["detail"]["value"]["patient"] = {"id": 1501, "weight": 68, "height": 168}
data = _build(sections, "体重与BMI")[0]
assert [(item.label, item.value, item.unit) for item in data.items] == [
("体重", 68, "kg"), ("身高", 168, "cm"),
]
assert all(item.color == UNKNOWN_COLOR and not item.status for item in data.items)
assert not any(item.label == "BMI" for item in data.items)
def test_metric_snapshot_uses_two_columns_on_wide_reports_and_localizes_status(application):
data = _build(_sections(hba1c=7.2, hba1c_status="high", weight=68, bmi=24), "综合分析")[0]
card = create_report_visual(data)
card.resize(760, card.sizeHint().height())
card.show()
application.processEvents()
wide_height = card.chart.height()
assert card.chart._columns == 2
assert "偏高" in card.chart.accessibleDescription()
assert card.table.item(0, 3).text() == "偏高"
assert "体重" in card.chart._point_tooltip(QPointF(card.chart.width() / 2 + 20, 10))
card.resize(320, card.height())
application.processEvents()
assert card.chart._columns == 1
assert card.chart.height() > wide_height
card.close()
card.deleteLater()
def test_reference_scale_requires_actual_stored_limits_and_keeps_zero() -> None:
data = _build(
_sections(
microalbumin=18,
microalbumin_reference_range={"low": 0, "high": 30, "unit": "mg/L"},
hba1c=7.2,
hba1c_reference_range="4-6 %",
weight=60,
),
"综合分析",
)[0]
assert [item.reference for item in data.items] == [(4, 6), (0, 30), None]
incompatible = _build(
_sections(
creatinine=100, creatinine_reference_range={"low": 0, "high": 2, "unit": "mg/dL"}
),
"肾功能",
)[0]
assert incompatible.items[0].reference is None
def test_foreign_nested_lab_values_are_not_adopted() -> None:
sections = _sections()
sections["detail"]["value"]["labs"] = {"diagnosis_id": 502, "hba1c": 7.2}
assert _build(sections, "糖化血红蛋白") == ()
@pytest.mark.parametrize(
("status", "color"),
[("high", ABNORMAL_COLOR), ("low", ABNORMAL_COLOR), ("warning", ABNORMAL_COLOR),
("异常", ABNORMAL_COLOR), ("normal", NORMAL_COLOR), ("正常", NORMAL_COLOR),
("unknown", UNKNOWN_COLOR), ("unclassified", UNKNOWN_COLOR), (None, UNKNOWN_COLOR),
(True, UNKNOWN_COLOR), ({"normal": True}, UNKNOWN_COLOR)],
)
def test_snapshot_flags_use_the_shared_palette_without_thresholds(status, color) -> None:
data = _build(_sections(hba1c=40, hba1c_status=status), "糖化血红蛋白")[0]
assert data.items[0].value == 40
assert data.items[0].color == color
assert "蓝色" not in data.source and "橙" not in data.source
assert "灰色未记录/未标注" in data.source
def test_pressure_points_raw_cells_and_tooltips_keep_only_recorded_states(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=200, systolic_pressure_status="normal",
diastolic_pressure=60, diastolic_status="low"),
_row("2026-08-19", systolic_pressure=220, diastolic_pressure=None,
diastolic_pressure_status="normal"),
_row("2026-08-20", systolic_pressure=210, systolic_status="warning",
diastolic_pressure=70, diastolic_pressure_status="unknown"),
))[0]
assert [(item.status, item.color) for item in data.items] == [
("normal", NORMAL_COLOR), ("low", ABNORMAL_COLOR),
("", UNKNOWN_COLOR), ("normal", UNKNOWN_COLOR),
("warning", ABNORMAL_COLOR), ("unknown", UNKNOWN_COLOR),
]
card = create_report_visual(data)
card.resize(650, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
for index, item in enumerate(data.items):
for column in (2, 3):
cell = card.table.item(index, column)
assert cell.foreground().color().name() == item.color.casefold()
assert "状态" in cell.toolTip()
if item.status:
assert item.status in cell.toolTip()
if item.value is not None:
point = card.chart._position(item)
assert image.pixelColor(point.toPoint()).name() == item.color.casefold()
assert item.status in card.chart._point_tooltip(point)
assert card.table.item(3, 2).text() == "—"
assert card.table.item(3, 3).text() == "未记录"
assert "舒张压 · — · 状态 未记录" in card.chart.accessibleDescription()
assert "收缩压实线圆点,舒张压虚线方点" in card.chart.accessibleDescription()
card.close()
def test_pressure_statuses_cannot_be_borrowed_from_root_or_foreign_rows() -> None:
sections = _sections(
_row(systolic_pressure=200, diastolic_pressure=110),
_row("2026-08-19", diagnosis_id=502, systolic_pressure_status="normal"),
)
sections["tracking"]["value"]["systolic_pressure_status"] = "normal"
items = _build(sections)[0].items
assert len(items) == 2
assert all(item.status == "" and item.color == UNKNOWN_COLOR for item in items)
def test_pressure_connection_is_gray_between_explicit_abnormal_points(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
_row("2026-08-20", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
))[0]
card = create_report_visual(data)
card.resize(640, card.sizeHint().height())
card.show()
application.processEvents()
points = [card.chart._position(item) for item in data.items if item.value is not None]
midpoint = (points[0] + points[1]) / 2
image = card.chart.grab().toImage()
assert image.pixelColor(midpoint.toPoint()).name() == UNKNOWN_COLOR.casefold()
assert image.pixelColor(points[0].toPoint()).name() == ABNORMAL_COLOR.casefold()
card.close()
def test_reference_band_is_neutral_and_never_assigns_normal_status(application) -> None:
data = _build(_sections(hba1c=5, hba1c_reference_range="4-6 %"), "糖化血红蛋白")[0]
assert data.items[0].color == UNKNOWN_COLOR and data.items[0].status == ""
card = create_report_visual(data)
card.resize(400, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
assert image.pixelColor(20, 54).name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 2).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 3).text() == "未标注"
assert "状态 未标注" in card.table.item(0, 2).toolTip()
card.close()
def test_risks_are_exact_categorical_annotations_not_numeric_scores() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"risk_assessment": [
{"label": level, "level": level, "score": 99, "probability": 0.9}
for level in ("high", "medium", "low", "unknown")
]
+ [{"label": "未核验", "level": "severe"}, {"label": "无等级", "level": None}],
}
}
data = _build(sections, "风险评估")[0]
assert data.kind == "risks"
assert [item.status for item in data.items] == ["high", "medium", "low", "unknown"]
assert [item.color for item in data.items] == [
ABNORMAL_COLOR, ABNORMAL_COLOR, NORMAL_COLOR, UNKNOWN_COLOR,
]
assert all(
item.value is None and item.reference is None and "%" not in item.raw_value
for item in data.items
)
assert "定性风险标注" in data.source and "#499、#501" in data.source
@pytest.mark.parametrize(
"metadata",
[
{},
{"patient_id": 1502, "source_diagnosis_ids": [501]},
{"patient_id": 1501, "source_diagnosis_ids": [502]},
{"diagnosis_id": "501"},
{"diagnosis_id": 502},
],
)
def test_unowned_and_foreign_risk_reports_do_not_get_visuals(metadata: Any) -> None:
sections = _sections()
sections["analysis"] = {
"value": {**metadata, "risk_assessment": [{"label": "风险项", "level": "high"}]}
}
assert _build(sections, "风险") == ()
def test_nested_saved_report_uses_its_original_owner_and_levels() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"latest_by_model": {
"qwen": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"diagnosis_id": 499,
"report": {"risk_assessment": [{"label": "血糖波动", "level": "medium"}]},
}
}
}
}
assert _build(sections, "风险")[0].items[0].status == "medium"
sections["analysis"]["value"]["latest_by_model"]["qwen"]["report"]["patient_id"] = 1502
assert _build(sections, "风险") == ()
def test_prescription_timeline_accepts_dto_and_preserves_dates_name_status() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription(
diagnosis_id=501,
prescription_date="2026-08-19",
herbs=[{"name": "黄芪"}],
audit_status=1,
),
{
"diagnosis_id": 501,
"patient_id": 1501,
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
},
{
"diagnosis_id": 502,
"prescription_date": "2026-08-17",
"prescription_name": "外国诊单",
"status_text": "已审核",
},
{"diagnosis_id": 501, "prescription_name": "没有日期", "status_text": "已审核"},
]
}
data = _build(sections, "用药合理性")[0]
assert data.kind == "medications"
assert [(item.time_label, item.label, item.status) for item in data.items] == [
("2026-08-18", "益气方", "已审核"),
("2026-08-19", "黄芪", "已通过"),
]
assert all(item.value is None for item in data.items)
def test_dto_coercion_does_not_hide_invalid_raw_prescription_ownership() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription.from_dict(
{
"diagnosis_id": "501",
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
}
)
]
}
assert _build(sections, "用药") == ()
def test_unitless_bmi_state_remains_a_measurement_instead_of_a_risk_label(application) -> None:
data = _build(_sections(bmi=26.1, bmi_status="high"), "体重")[0]
data = replace(data, items=tuple(replace(item, unit="") for item in data.items))
card = ReportVisualCard(data)
try:
assert card.table.item(0, 3).text() == "偏高"
assert card.table.item(0, 3).foreground().color().name() == "#bd4b58"
finally:
card.deleteLater()
def test_exercise_uses_actual_duration_minutes_with_no_target_bars() -> None:
sections = _sections()
sections["tracking"]["value"]["exercise_records"] = [
_row("2026-08-18", duration=35),
_row("2026-08-19", duration="约40"),
_row("2026-08-20", duration=40, patient_id=1502),
]
data = _build(sections, "建议运动150分钟")[0]
assert data.kind == "exercise"
assert [item.value for item in data.items] == [35, None]
assert data.items[0].unit == "分钟"
def test_charts_render_at_320px_with_exact_hover_and_raw_data(application: QApplication) -> None:
sections = _sections(
_row("2026-08-18"), _row("2026-08-19"), _row("2026-08-21"), hba1c=7.2, hba1c_status="high"
)
sections["analysis"] = {
"value": {
"diagnosis_id": 501,
"risk_assessment": [{"label": "血压波动风险", "level": "medium"}],
}
}
sections["prescriptions"] = {
"value": [
{
"diagnosis_id": 501,
"prescription_date": "2026-08-19",
"prescription_name": "益气方",
"status_text": "已审核",
}
]
}
sections["tracking"]["value"]["exercise_records"] = [_row(duration=35)]
data = _build(sections, "综合分析")
assert {_kind(item) for item in data} == {
"glucose",
"blood_pressure",
"metrics",
"risks",
"medications",
"exercise",
}
for item in data:
card = create_report_visual(item)
card.resize(320, card.sizeHint().height())
card.show()
application.processEvents()
try:
assert card.width() == 320
assert card.minimumSizeHint().width() <= 320
assert not card.grab().isNull()
assert not any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
if isinstance(card, GlucoseReportCard):
continue
assert isinstance(card, ReportVisualCard)
assert (
card.objectName() == "AiConsultReportVisual"
and card.property("visualKind") == item.kind
)
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
application.processEvents()
assert card.table.isVisible() and card.table.rowCount() == len(item.items)
assert card.table.item(0, 1).text() == item.items[0].label
position = card.chart._position(item.items[0]) if card.chart._trend else QPointF(20, 10)
assert item.items[0].label in card.chart._point_tooltip(position)
if item.kind == "blood_pressure":
first, middle, last = [
datum for datum in item.items if datum.series == "systolic_pressure"
]
positions = [card.chart._position(datum).x() for datum in (first, middle, last)]
assert (positions[1] - positions[0]) / (
positions[2] - positions[0]
) == pytest.approx(1 / 3)
QTest.mouseMove(card.chart, position.toPoint())
application.processEvents()
assert "146 mmHg" in QToolTip.text()
finally:
card.close()
card.deleteLater()
+5 -7
View File
@@ -1413,7 +1413,7 @@ def test_ask_sends_only_question_and_relies_on_server_full_context(
if widget.objectName() == "AiConsultBubbleText"
]
assert any("请结合资料分析当前证候" in text for text in all_bubble_texts)
assert any("服务端将按当前诊单实时附带患者全部纵向资料" in text for text in all_bubble_texts)
assert not any("服务端将按当前诊单实时附带患者全部纵向资料" in text for text in all_bubble_texts)
dialog.close()
@@ -1443,11 +1443,11 @@ def _silent_dialog(monkeypatch: pytest.MonkeyPatch) -> AiConsultDialog:
return dialog
def test_full_context_notice_is_shown_once_per_conversation(
def test_full_context_notice_is_not_displayed_in_conversations(
application: QApplication,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# 每轮问答都重复同一句全量上下文说明会把真正的回答挤出可视区。
# 技术性的上下文说明不应占用对话区,包括首次提问和切换患者后。
dialog = _silent_dialog(monkeypatch)
dialog.show()
application.processEvents()
@@ -1458,13 +1458,12 @@ def test_full_context_notice_is_shown_once_per_conversation(
dialog._cancel_stream()
dialog._ask(question)
counts.append(sum(1 for text in _bubble_texts(dialog) if notice in text))
assert counts == [1, 1, 1]
assert counts == [0, 0, 0]
# 换患者视为新会话,需要重新提示一次。
dialog.open_for(diagnosis_id=502, patient_id=302)
application.processEvents()
dialog._ask("新患者的问题")
assert sum(1 for text in _bubble_texts(dialog) if notice in text) == 1
assert sum(1 for text in _bubble_texts(dialog) if notice in text) == 0
dialog.close()
@@ -1710,7 +1709,6 @@ def test_http_stream_paints_before_upstream_finishes_on_the_ui_thread(
)
dialog = AiConsultDialog(RemoteDoctorRepository(client))
dialog.diagnosis_id = 501
dialog._context_notice_shown = True
delivered_on = []
original_event = dialog._stream_event
+2
View File
@@ -11,6 +11,7 @@ from typing import Any
import httpx
import pytest
from doctor_workstation import __version__
from doctor_workstation.core.errors import (
ApiBusinessError,
ApiError,
@@ -47,6 +48,7 @@ def test_get_normalises_adminapi_and_sends_contract_headers() -> None:
)
assert request.headers["token"] == "secret-token"
assert request.headers["version"] == "1.9.4"
assert request.headers["user-agent"] == f"ZytDoctorWorkstation/{__version__}"
assert ApiClient.normalise_base_url("https://example.test/adminapi") == (
"https://example.test/adminapi/"
)
+206
View File
@@ -0,0 +1,206 @@
"""Archived IM events must be readable in the diagnosis drawer and AI history."""
from __future__ import annotations
import json
import os
from copy import deepcopy
from datetime import datetime
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
from doctor_workstation.ui.chat_items import format_chat_time, parse_chat_item
from doctor_workstation.ui.diagnosis_drawer import ChatPanel, _RemoteImageButton
STAMP = 1792454400
def _event(payload, **changes):
return {
"msg_type": "custom",
"content": json.dumps(payload, ensure_ascii=False),
"create_time": STAMP,
**changes,
}
def _rtc(command, *, seconds=None, call_type=2, encoded=True):
body = {
"version": 4,
"call_type": call_type,
"businessID": "rtc_call",
"data": {"cmd": command, "inviter": "doctor_synthetic"},
}
if seconds is not None:
body["call_end"] = seconds
return {
"businessID": 1,
"data": json.dumps(body) if encoded else body,
"actionType": 1,
"inviteID": "synthetic-private-invite",
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def panel(application):
widget = ChatPanel()
widget.resize(1100, 850)
widget.show()
yield widget
widget.close()
widget.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
@pytest.mark.parametrize(
"business,title",
[
("patient_opened_chat", "患者进入在线问诊"),
("patient_left_chat", "患者离开在线问诊"),
("doctor_entered_consult_room", "医生进入在线诊室"),
("consultation_complete", "本次问诊已完成"),
],
)
def test_drawer_recognizes_custom_events_in_content_and_formats_archive_time(
panel, business, title
):
row = _event(
{"businessID": business, "patientName": "示例患者", "patientId": "synthetic-private-id"}
)
before = deepcopy(row)
panel.set_messages([row])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == title
assert panel.findChild(QLabel, "DiagnosisChatMeta").text() == datetime.fromtimestamp(
STAMP
).strftime("%Y-%m-%d %H:%M")
assert not panel.findChildren(QFrame, "DiagnosisChatBubble")
visible_text = " ".join(label.text() for label in panel.findChildren(QLabel))
assert "businessID" not in visible_text and "synthetic-private-id" not in visible_text
assert row == before
@pytest.mark.parametrize("encoded", [False, True])
@pytest.mark.parametrize(
"command,seconds,title,detail",
[
("videoCall", None, "发起视频问诊", "医生已向患者发起视频通话"),
("hangup", "116", "视频问诊已结束", "通话 1 分 56 秒"),
("hangup", "154", "视频问诊已结束", "通话 2 分 34 秒"),
],
)
def test_nested_rtc_signals_prefer_the_command_and_show_duration(
panel, encoded, command, seconds, title, detail
):
panel.set_messages([_event(_rtc(command, seconds=seconds, encoded=encoded))])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == title
assert panel.findChild(QLabel, "DiagnosisChatEventDetail").text() == detail
visible_text = " ".join(label.text() for label in panel.findChildren(QLabel))
assert all(
token not in visible_text
for token in ("rtc_call", "inviteID", "call_end", "synthetic-private-invite")
)
@pytest.mark.parametrize("value", [STAMP, str(STAMP), STAMP * 1000, str(STAMP * 1000)])
def test_seconds_and_milliseconds_have_the_same_display_time(value):
expected = datetime.fromtimestamp(STAMP)
assert format_chat_time(value) == expected.strftime("%H:%M")
assert format_chat_time(value, include_date=True) == expected.strftime("%Y-%m-%d %H:%M")
def test_iso_and_payload_only_times_are_formatted_for_both_views():
assert format_chat_time("2026-10-20T08:30:45Z") == "08:30"
assert format_chat_time("2026-10-20T08:30:45Z", include_date=True) == "2026-10-20 08:30"
row = _event({"businessID": "patient_opened_chat", "time": STAMP * 1000}, create_time=None)
assert parse_chat_item(row, include_date=True).time_text == datetime.fromtimestamp(
STAMP
).strftime("%Y-%m-%d %H:%M")
assert parse_chat_item(
{"text": "普通消息", "timestamp": STAMP}
).time_text == datetime.fromtimestamp(STAMP).strftime("%H:%M")
@pytest.mark.parametrize("value", [None, "", 0, -1, float("nan"), float("inf"), True])
def test_missing_or_invalid_numeric_times_do_not_render_as_epoch_or_raw_numbers(value):
assert format_chat_time(value, include_date=True) == ""
def test_only_typing_signals_show_the_empty_state(panel, application):
panel.set_messages([_event({"businessID": "user_typing_status", "typing": True})])
application.processEvents()
assert panel.empty.isVisible()
assert not panel.findChildren(QFrame, "DiagnosisChatBubble")
assert not panel.findChildren(QFrame, "DiagnosisChatEvent")
def test_unknown_technical_payload_uses_readable_fallback_without_internal_ids(panel):
panel.set_messages([_event({"business_id": "new_private_signal", "inviteID": "private-token"})])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == "系统状态已同步"
assert "private-token" not in " ".join(label.text() for label in panel.findChildren(QLabel))
def test_ordinary_chat_keeps_exact_multiline_content_and_sender_side(panel):
text = " 我已确认以下信息:\n1、本人确认已在线下确诊;\n2、本人已阅读告知书。\n<b>保留原文</b> "
panel.set_messages(
[
{"content": text, "is_from_doctor": "0", "time": STAMP},
{"text": "请补充资料", "from_account": "doctor_synthetic", "time": STAMP},
]
)
bubbles = panel.findChildren(QFrame, "DiagnosisChatBubble")
assert [bubble.property("side") for bubble in bubbles] == ["patient", "doctor"]
body = bubbles[0].findChild(QLabel, "DiagnosisChatText")
assert body.text() == text and body.textFormat() == Qt.TextFormat.PlainText
def test_mixed_events_and_attachments_preserve_image_preview_and_file_actions(panel, monkeypatch):
monkeypatch.setattr(_RemoteImageButton, "load_url", lambda *_args, **_kwargs: None)
image_url = "https://example.invalid/synthetic.jpg"
file_url = "https://example.invalid/synthetic.pdf"
opened = []
panel.open_attachment_requested.connect(opened.append)
panel.set_messages(
[
_event({"businessID": "doctor_entered_consult_room"}),
{"msg_type": "image", "image_url": image_url, "time": STAMP},
{"msg_type": "file", "file_url": file_url, "file_name": "示例报告.pdf", "time": STAMP},
]
)
panel.findChild(_RemoteImageButton, "DiagnosisChatImage").click()
next(
button for button in panel.findChildren(QPushButton) if button.text() == "示例报告.pdf"
).click()
assert opened == [image_url, file_url]
assert len(panel.findChildren(QFrame, "DiagnosisChatEvent")) == 1
def test_nested_duration_and_audio_command_are_not_misclassified():
ended = parse_chat_item(
_event(
{"businessID": "rtc_call", "call_type": 1, "data": {"cmd": "hangup", "call_end": 61}}
)
)
assert ended.title == "语音问诊已结束" and ended.detail == "通话 1 分 1 秒"
started = parse_chat_item(_event({"businessID": "rtc_call", "data": {"cmd": "audioCall"}}))
assert started.title == "发起语音问诊"
def test_text_field_has_the_same_priority_in_both_chat_views():
item = parse_chat_item({"text": "本条正文", "content": "旧字段"})
assert item.text == "本条正文"
def test_invalid_json_is_preserved_without_interrupting_other_messages(panel):
broken = '{"unfinished":'
panel.set_messages([{"content": broken}, _event({"businessID": "patient_opened_chat"})])
assert panel.findChild(QLabel, "DiagnosisChatText").text() == broken
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == "患者进入在线问诊"
+26
View File
@@ -619,6 +619,32 @@ def _select_tab(dialog: DiagnosisDialog, key: str) -> None:
QApplication.processEvents()
def test_chat_tab_recognizes_archived_system_events_in_the_actual_drawer(application: QApplication) -> None:
class ChatRepository(VisualRepository):
def list_im_chat_messages(self, diagnosis_id: int, *, only_archived: bool = True) -> dict[str, Any]:
assert diagnosis_id == 501 and only_archived
return {"lists": [
{"content": '{"businessID":"patient_opened_chat","patientName":"示例患者"}',
"create_time": 1792454400},
{"text": "我已确认问诊信息。", "create_time": 1792454401},
{"text": '{"businessID":"doctor_entered_consult_room"}',
"create_time": 1792454402},
]}
dialog = _open_dialog(application, (1440, 900), mode="edit", repository=ChatRepository())
try:
_select_tab(dialog, "chat")
panel = dialog._chat_panels[1]
assert panel.isVisibleTo(dialog)
assert [label.text() for label in panel.findChildren(QLabel, "DiagnosisChatEventTitle")] == [
"患者进入在线问诊", "医生进入在线诊室",
]
assert panel.findChild(QLabel, "DiagnosisChatText").text() == "我已确认问诊信息。"
assert all("17924544" not in label.text() for label in panel.findChildren(QLabel, "DiagnosisChatMeta"))
finally:
dialog.close()
@pytest.mark.parametrize("size", [(1024, 640), (1440, 900)])
def test_readonly_is_an_independent_vertical_page_flow(
application: QApplication,
+28 -1
View File
@@ -794,6 +794,33 @@ def test_revoked_agreement_cache_discards_flat_comparison_metadata() -> None:
assert value["models"]["qwen"]["reason"] == sentinel
@pytest.mark.parametrize("flag", [False, None, 1, "true"])
def test_unlisted_account_hides_ai_analysis_column_and_keeps_reports(
application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, flag: Any,
) -> None:
repository = Repository()
repository.agreement_visible = flag
opened = []
monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs))
page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1})
try:
page.resize(1366, 800)
page.show()
application.processEvents()
page.table.selectRow(0)
assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12)
# Later status refreshes must not re-expose the analysis column.
page._set_ai_columns(True)
assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12)
assert page.ai_report_button.isVisible() and page.ai_report_button.isEnabled()
assert any(button.accessibleName() == "AI 报告"
for button in page.table.cellWidget(0, 2).findChildren(QPushButton))
page.ai_report_button.click()
assert opened == [{"prescription_id": 801}]
finally:
page.close()
def test_list_capability_failure_revocation_and_late_status_cannot_restore_scores(
application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -810,7 +837,7 @@ def test_list_capability_failure_revocation_and_late_status_cannot_restore_score
page._load_ai_capabilities()
page._ai_statuses_ready(old_statuses, [801, 802], old_token, page._generation)
page._ai_capabilities_ready({"agreement_visible": True}, old_capability_token, page._generation)
assert page.table.isColumnHidden(12) and not page.table.isColumnHidden(11)
assert page.table.isColumnHidden(12) and page.table.isColumnHidden(11)
assert page.ai_statistics_button.isHidden()
assert page.ai_report_button.isVisible()
assert page._ai_statuses
@@ -11,7 +11,7 @@ from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import Qt, QTimer
from PySide6.QtCore import QPoint, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QPushButton
@@ -234,3 +234,60 @@ def test_row_action_permissions_and_foreign_public_management_are_preserved(
assert buttons["删除处方模板"].isEnabled() == can_edit_foreign
else:
assert page.edit_button.isHidden() and page.delete_button.isHidden()
def test_table_fills_viewport_after_window_and_scrollbar_changes(page_factory, application):
page, repository = page_factory()
table = page.table
page.resize(1024, 768)
settle(application)
minimums = [table.columnWidth(column) for column in range(table.columnCount())]
source = deepcopy(repository.rows[0])
for width, count in ((2048, 2), (2048, 70), (1024, 70), (1920, 0),
(1920, 2), (1366, 2), (2048, 2)):
page.resize(width, 768)
table.set_rows([{**deepcopy(source), "id": 10000 + index} for index in range(count)])
settle(application)
viewport = table.viewport()
if count:
assert table.fontMetrics().horizontalAdvance(table.item(0, 0).text()) + 24 <= table.columnWidth(0)
assert table.horizontalHeader().length() == max(sum(minimums), viewport.width())
assert all(table.columnWidth(column) >= minimum for column, minimum in enumerate(minimums))
if viewport.width() >= sum(minimums):
assert table.horizontalScrollBar().maximum() == 0
assert all(table.columnWidth(column) > minimums[column] for column in (1, 4, 5))
if count:
last_cell = table.visualItemRect(table.item(0, 9))
index = table.indexAt(QPoint(viewport.width() - 3, last_cell.center().y()))
assert (index.row(), index.column()) == (0, 9)
else:
assert table.horizontalScrollBar().maximum() > 0
table.horizontalScrollBar().setValue(table.horizontalScrollBar().maximum())
settle(application)
assert table.visualItemRect(table.item(0, 9)).right() < viewport.width()
def test_manual_column_width_survives_resize_and_refresh(page_factory, application):
page, _repository = page_factory()
table = page.table
page.resize(2048, 900)
settle(application)
table.sortItems(0, Qt.SortOrder.DescendingOrder)
table.selectRow(1)
selected_id = record_id(table.current_data())
action_host = table.cellWidget(1, 9)
requested_width = table.columnWidth(1) + 60
table.setColumnWidth(1, requested_width)
settle(application)
for width in (1024, 1920, 1366, 2048):
page.resize(width, 900)
settle(application)
assert table.columnWidth(1) == requested_width
assert record_id(table.current_data()) == selected_id
assert table.cellWidget(1, 9) is action_host
page.refresh()
settle(application)
assert table.columnWidth(1) == requested_width
assert record_id(table.current_data()) == selected_id
assert table.horizontalHeader().sortIndicatorOrder() == Qt.SortOrder.DescendingOrder
assert table.horizontalHeader().length() == table.viewport().width()
+1 -1
View File
@@ -55,7 +55,7 @@ def test_typography_preserves_regular_body_and_distinct_values(page):
body = page.case_labels["present"]
assert body.font().pixelSize() == 14
assert body.font().weight() == 400
assert page.patient_name_label.font().pixelSize() == 22
assert page.patient_name_label.font().pixelSize() == 20
assert page.patient_name_label.font().weight() == 600
assert page.vital_labels["height"].font().pixelSize() == 18
+8 -8
View File
@@ -261,15 +261,15 @@ def test_approved_shell_geometry_and_function_entries_restore(
assert window.centralWidget().layout().contentsMargins().isNull()
assert window.search_host.mapTo(window, QPoint()) == QPoint(234, 15)
assert window.search_host.size() == QSize(384, 44)
assert window.assistant_card.mapTo(window, QPoint()) == QPoint(20, 695)
assert window.assistant_card.size() == QSize(168, 171)
assert window.assistant_button.height() == 46
assert window.brand_name.font().pixelSize() == 18
assert window.brand_subtitle.font().pixelSize() == 13
assert window.assistant_card.mapTo(window, QPoint()) == QPoint(20, 776)
assert window.assistant_card.size() == QSize(168, 132)
assert window.assistant_button.height() == 36
assert window.brand_name.font().pixelSize() == 16
assert window.brand_subtitle.font().pixelSize() == 12
for index, button in enumerate(window.nav_buttons.values()):
assert button.mapTo(window, QPoint()).y() == 99 + 58 * index
assert button.height() == 52
assert button.font().pixelSize() == 15
assert button.mapTo(window, QPoint()).y() == 99 + 48 * index
assert button.height() == 44
assert button.font().pixelSize() == 14
assert button.iconSize() == QSize(20, 20)
assert not window.fold_button.isVisible()
assert not window.ai_top_button.isVisible()
+25 -19
View File
@@ -21,6 +21,7 @@ from PySide6.QtCore import (
QTimer,
)
from PySide6.QtGui import QPalette
from PySide6.QtTest import QTest
from PySide6.QtWidgets import (
QApplication,
QLabel,
@@ -378,7 +379,8 @@ def test_queue_condition_summary_never_exposes_raw_dict(
)
fallback_summary = fallback.findChild(QLabel, "ReceptionQueueSubline")
assert fallback_summary is not None
assert fallback_summary.text() == "暂无病情摘要"
assert fallback_summary.text() == ""
assert fallback_summary.toolTip() == ""
assert "{" not in fallback_summary.text()
row.close()
@@ -1045,14 +1047,17 @@ def test_medication_case_prioritizes_clinical_information_and_keeps_plain_summar
detail["patient"],
diagnosis,
)
application.processEvents()
for _ in range(12):
application.processEvents()
QTest.qWait(5)
assert page.diagnosis_card.objectName() == "ReceptionMedicationCaseCard"
assert page.diagnosis_card.accessibleName() == "完整病例"
assert page.medication_scroll.objectName() == "ReceptionMedicationScroll"
assert page.medication_scroll.accessibleName() == "用药记录与完整病例滚动区域"
assert page.medication_scroll.horizontalScrollBar().maximum() == 0
assert page.medication_scroll.verticalScrollBar().maximum() > 0
case_scrolls = (page.clinical_scroll, page.medication_scroll)
assert any(scroll.verticalScrollBar().maximum() > 0 for scroll in case_scrolls)
assert page.diagnosis_text.isHidden()
assert page.diagnosis_text.textFormat() == Qt.TextFormat.PlainText
@@ -1095,14 +1100,16 @@ def test_medication_case_prioritizes_clinical_information_and_keeps_plain_summar
assert value.textInteractionFlags() & Qt.TextInteractionFlag.TextSelectableByMouse
for _ in range(5):
page.medication_scroll.verticalScrollBar().setValue(
page.medication_scroll.verticalScrollBar().maximum()
)
for scroll in case_scrolls:
scroll.verticalScrollBar().setValue(scroll.verticalScrollBar().maximum())
application.processEvents()
assert (
page.medication_scroll.verticalScrollBar().value()
== page.medication_scroll.verticalScrollBar().maximum()
)
assert all(scroll.verticalScrollBar().value() == scroll.verticalScrollBar().maximum()
for scroll in case_scrolls)
final_note = page.case_section_frames["notes"].findChild(QLabel, "ReceptionCaseFieldValue")
assert final_note is not None
assert "【完整病例末尾】" in final_note.text()
viewport = page.clinical_scroll.viewport()
assert viewport.rect().contains(final_note.mapTo(viewport, final_note.rect().bottomLeft()))
page.close()
application.processEvents()
@@ -1446,12 +1453,14 @@ def test_phone_permission_and_ungated_notify_video_actions(
masked_page = ReceptionPage(Repository(), PermissionSet([]))
masked_page._select_record(detail["appointment"])
assert masked_page.patient_labels["phone"].text() == "138****8000"
assert masked_page.patient_summary_labels["phone"].text() == "138****8000"
assert not masked_page.notify_button.isHidden()
assert not masked_page.video_button.isHidden()
plain_page = ReceptionPage(Repository(), PermissionSet(["tcm.diagnosis/phonePlain"]))
plain_page._select_record(detail["appointment"])
assert plain_page.patient_labels["phone"].text() == "13800138000"
assert plain_page.patient_summary_labels["phone"].text() == "13800138000"
assert plain_page.appointment_labels["doctor"].text() == "张医生"
assert plain_page.appointment_labels["assistant"].text() == "李医助"
assert plain_page.patient_labels["region"].text() == "浙江省杭州市"
@@ -1524,8 +1533,8 @@ def test_notify_assistant_is_a_visible_header_action_not_a_more_menu_item(
for button in buttons:
assert hero.rect().contains(button.geometry())
assert button.width() >= button.sizeHint().width()
right = button.mapTo(page.detail_scroll.viewport(), QPoint(button.width(), 0)).x()
assert right <= page.detail_scroll.viewport().width()
right = button.mapTo(page.detail_stack, QPoint(button.width(), 0)).x()
assert right <= page.detail_stack.width()
for previous, following in zip(buttons, buttons[1:], strict=False):
assert previous.geometry().right() < following.geometry().left()
finally:
@@ -1700,10 +1709,7 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
assert [label.property("riskLevel") for label in chips] == ["high", "medium", "low"]
assert "千问" in page.ai_analysis_title.toolTip()
assert [button.text() for button in page.ai_prompt_buttons] == [
"基于当前病史,下一步检查建议?",
"该患者的用药调整建议?",
"糖尿病教育要点有哪些?",
"并发症筛查建议?",
"检查建议", "用药核对", "健康教育", "并发症筛查",
]
assert page.ai_send_button.text() == ""
assert page.ai_send_button.accessibleName() == "发送 AI 问诊问题"
@@ -1734,9 +1740,9 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
assert page.ai_analysis_card.minimumHeight() == 0
assert page.ai_analysis_card.maximumHeight() > 520
assert page.ai_analysis_card.findChildren(QScrollArea) == []
assert left.height() == right.height()
assert right.left() - left.right() - 1 == 10
assert abs(left.width() / (left.width() + right.width()) - 0.425) < 0.01
assert left.left() == right.left()
assert left.width() == right.width()
assert right.top() - left.bottom() - 1 == 10
assert page.ai_summary_label.width() <= page.ai_analysis_card.contentsRect().width()
assert page.ai_summary_label.minimumSizeHint().width() <= 48
@@ -0,0 +1,324 @@
"""Reachability and data preservation in the real reception shell."""
from __future__ import annotations
import os
import socket
from copy import deepcopy
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QPoint, QRect, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
from doctor_workstation.ui import shell as shell_module
from doctor_workstation.ui.pages import reception as reception_module
from doctor_workstation.ui.pages.reception import QueueRow, ReceptionPage
from doctor_workstation.ui.shell import NavigationItem, ShellWindow
from doctor_workstation.ui.theme import apply_theme
def _settle(application: QApplication) -> None:
for _ in range(12):
application.processEvents()
QTest.qWait(5)
def _mapped_rect(widget, ancestor) -> QRect:
return QRect(widget.mapTo(ancestor, QPoint()), widget.size())
class _LocalRepository:
def __init__(self) -> None:
self.calls: list[str] = []
self.detail = {
"appointment": {
"id": 51, "patient_id": 151, "diagnosis_id": 251,
"patient_name": "本地测试患者", "status": 1,
"doctor_name": "测试医生", "assistant_name": "测试医助",
"appointment_time": "09:30", "appointment_type": "video",
},
"patient": {
"id": 151, "name": "本地测试患者", "gender": 2,
"age": 46, "height": 165, "weight": 60, "phone": "13800138000",
},
"diagnosis": {
"id": 251, "patient_id": 151, "chief_complaint": "反复口渴",
"present_illness": "近期口干,复诊时核对记录。",
"current_medications": "二甲双胍早晚服用,剂量待核对。",
"disease_course_text": "患病十年",
"clinical_diagnosis": "2 型糖尿病", "hba1c": 7.2,
},
}
def list_appointments(self, **_query: Any) -> dict[str, Any]:
self.calls.append("queue")
return {"lists": [deepcopy(self.detail["appointment"])], "count": 1}
def get_reception(self, appointment_id: int) -> dict[str, Any]:
assert appointment_id == 51
self.calls.append("detail")
return deepcopy(self.detail)
def get_diagnosis_ai_analysis(self, diagnosis_id: int, model: str) -> dict[str, Any]:
assert diagnosis_id == 251
self.calls.append(model)
return {
"diagnosis_advice": "结合当前病史复核血糖控制情况。",
"risk_assessment": [{"label": "血糖波动", "level": "medium"}],
"treatment_advice": "核对现有用药及近期检查。", "model_key": model,
}
@pytest.fixture(scope="module")
def application() -> QApplication:
app = QApplication.instance() or QApplication([])
apply_theme(app)
return app
@pytest.fixture
def shell_factory(application: QApplication, monkeypatch: pytest.MonkeyPatch):
def reject_network(*_args, **_kwargs):
pytest.fail("Reception workspace tests must remain local")
def immediate(function, *args, on_success=None, on_error=None, on_finished=None,
pool=None, priority=0, **kwargs):
del pool, priority
try:
result = function(*args, **kwargs)
except Exception as error:
if on_error:
on_error(error)
raise
else:
if on_success:
on_success(result)
finally:
if on_finished:
on_finished()
return object()
monkeypatch.setattr(socket.socket, "connect", reject_network)
monkeypatch.setattr(socket.socket, "connect_ex", reject_network)
monkeypatch.setattr(socket, "create_connection", reject_network)
monkeypatch.setattr(reception_module, "run_async", immediate)
monkeypatch.setattr(shell_module.motion, "reduced_motion", lambda: True)
item = NavigationItem("reception", "接诊台", "", ReceptionPage,
("doctor.appointment/lists",))
monkeypatch.setattr(shell_module, "_resolve_navigation",
lambda *_args, **_kwargs: [(item, item.title)])
opened = []
def create(width=1920, height=1080):
repository = _LocalRepository()
shell = ShellWindow(repository, {"user": {"id": 7, "name": "测试医生"}},
permissions={
"doctor.appointment/lists", "doctor.appointment/complete",
"doctor.appointment/addDoctorNote", "tcm.diagnosis/edit",
"tcm.diagnosis/aiAnalysis", "tcm.diagnosis/aiAssistant",
})
opened.append(shell)
shell.resize(width, height)
shell.show()
_settle(application)
page = shell.pages["reception"]
page.poll_timer.stop()
shell.chat_notifications.stop()
assert page._selected_appointment_id == 51
assert page.detail_stack.currentIndex() == 1
return shell, page, repository
yield create
for shell in opened:
for timer in shell.findChildren(QTimer):
timer.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.mark.parametrize("size", [(1366, 768), (1920, 1080)])
def test_real_shell_prioritizes_patient_facts_while_long_history_scrolls(
application, shell_factory, size,
):
shell, page, repository = shell_factory(*size)
assert (shell.width(), shell.height()) == size
assert not page.workbench.mode_tabs.isVisible()
hero = page.findChild(QFrame, "ReceptionHero")
hero_before = _mapped_rect(hero, page)
actions = (page.notify_button, page.history_button, page.video_button,
page.more_button, page.complete_button)
actions_before = [_mapped_rect(button, page) for button in actions]
for button in actions:
assert button.isVisibleTo(page)
assert hero.rect().contains(_mapped_rect(button, hero))
assert button.width() >= button.minimumSizeHint().width()
insights_viewport = page.insights_scroll.viewport()
summary = page.patient_summary_card
vitals = page.findChild(QFrame, "ReceptionVitalsCard")
labs = page.findChild(QFrame, "ReceptionLabsCard")
assert insights_viewport.rect().contains(_mapped_rect(summary, insights_viewport))
assert insights_viewport.rect().contains(_mapped_rect(vitals, insights_viewport))
assert _mapped_rect(summary, insights_viewport).top() == 0
assert summary.mapTo(page, QPoint()).y() < vitals.mapTo(page, QPoint()).y()
assert vitals.mapTo(page, QPoint()).y() < labs.mapTo(page, QPoint()).y()
assert labs.mapTo(page, QPoint()).y() < page.ai_analysis_card.mapTo(page, QPoint()).y()
assert {key: label.text() for key, label in page.patient_summary_labels.items()} == {
"gender_age": "女 · 46岁", "phone": "138****8000",
"course": "患病十年", "diagnosis": "2 型糖尿病",
}
assistant_title = page.ai_assistant_card.findChild(QPushButton, "ReceptionAiTitle")
insight_scroll_value = page.insights_scroll.verticalScrollBar().value()
fact_positions = [_mapped_rect(card, page) for card in (summary, vitals, labs)]
requests = list(repository.calls)
history = "完整病史:口干持续,携带记录复诊,核对既往用药。\n" * 40
page.case_labels["present"].setText(history)
_settle(application)
assert page.case_labels["present"].text() == history
assert page.case_labels["present"].height() >= page.case_labels["present"].heightForWidth(
page.case_labels["present"].width()
)
scrollbar = page.clinical_scroll.verticalScrollBar()
assert scrollbar.maximum() > 0
scrollbar.setValue(scrollbar.maximum())
_settle(application)
assert scrollbar.value() == scrollbar.maximum()
assert _mapped_rect(hero, page) == hero_before
assert [_mapped_rect(button, page) for button in actions] == actions_before
assert [_mapped_rect(card, page) for card in (summary, vitals, labs)] == fact_positions
assert page.insights_scroll.verticalScrollBar().value() == insight_scroll_value
for title in (page.ai_analysis_title, assistant_title):
page.insights_scroll.ensureWidgetVisible(title)
_settle(application)
assert insights_viewport.rect().contains(_mapped_rect(title, insights_viewport))
assert repository.calls == requests
def test_narrow_workspace_reuses_scrolls_and_preserves_drafts_tabs_and_patient(
application, shell_factory,
):
shell, page, repository = shell_factory()
clinical, insights = page.clinical_scroll, page.insights_scroll
page.detail_tabs.setCurrentIndex(4)
page.note_edit.setPlainText("未保存的本地备注")
page._pending_tongue_images = ["draft-tongue.png"]
page._pending_report_files = ["draft-report.pdf"]
requests = list(repository.calls)
for width in (1024, 1920, 1024, 1366):
shell.resize(width, 768)
_settle(application)
assert page.clinical_scroll is clinical
assert page.insights_scroll is insights
assert page.detail_tabs.currentIndex() == page.clinical_pages.currentIndex() == 4
assert page._selected_appointment_id == 51
assert page.note_edit.toPlainText() == "未保存的本地备注"
assert page._pending_tongue_images == ["draft-tongue.png"]
assert page._pending_report_files == ["draft-report.pdf"]
if width == 1024:
assert page.workbench.mode_tabs.isVisible()
for index, scroll in ((1, insights), (0, clinical)):
page.workbench.mode_tabs.setCurrentIndex(index)
_settle(application)
assert scroll.isVisibleTo(page)
assert page.workbench._narrow_stack.currentWidget() is scroll
else:
assert not page.workbench.mode_tabs.isVisible()
assert clinical.isVisibleTo(page) and insights.isVisibleTo(page)
assert repository.calls == requests
def test_missing_labs_expand_and_collapse_without_losing_recorded_values(
application, shell_factory,
):
_shell, page, _repository = shell_factory()
before = {key: label.text() for key, label in page.lab_labels.items()}
assert before["hba1c"] == "7.2 %"
assert not page.lab_cells["hba1c"].isHidden()
assert all(cell.isHidden() for key, cell in page.lab_cells.items() if key != "hba1c")
assert page.lab_missing_button.text() == "显示 7 项未记录"
page.insights_scroll.ensureWidgetVisible(page.lab_missing_button)
_settle(application)
QTest.mouseClick(page.lab_missing_button, Qt.MouseButton.LeftButton)
_settle(application)
assert all(not cell.isHidden() for cell in page.lab_cells.values())
assert page.lab_missing_button.text() == "收起未记录项"
page.lab_missing_button.click()
_settle(application)
assert {key: label.text() for key, label in page.lab_labels.items()} == before
assert all(cell.isHidden() for key, cell in page.lab_cells.items() if key != "hba1c")
def test_free_text_glucose_keeps_source_without_invented_units_or_status(
application, shell_factory,
):
_shell, page, repository = shell_factory()
description = "近期空腹7至9之间,餐后约12,尚未携带原始记录"
diagnosis = {**repository.detail["diagnosis"], "fasting_blood_sugar": description}
page._render_case(repository.detail["appointment"], repository.detail["patient"], diagnosis)
_settle(application)
assert page.lab_labels["fasting"].text() == description
assert page.lab_labels["fasting"].textFormat() == Qt.TextFormat.PlainText
assert page.lab_cells["fasting"].property("description") is True
assert not page.lab_cells["fasting"].isHidden()
assert page.lab_state_labels["fasting"].isHidden()
assert page.case_metric_labels["fasting_glucose"].text() == description
assert f"空腹血糖:{description}\n" in page.diagnosis_text.text()
assert f"{description} mmol/L" not in page.health_summary_label.text()
row = QueueRow({**repository.detail["appointment"], "diagnosis": diagnosis})
try:
metric = row.findChild(QLabel, "ReceptionQueueMetric")
assert metric.text() == "血糖有描述"
assert metric.toolTip() == description
assert metric.property("tone") == "description"
assert row.glucose_drop.isHidden()
finally:
row.deleteLater()
def test_compact_ai_prompts_keep_full_questions_and_callbacks(shell_factory, monkeypatch):
_shell, page, _repository = shell_factory()
sent = []
monkeypatch.setattr(page, "_open_ai_report_for_prompt", sent.append)
questions = [
"基于当前病史,下一步检查建议?", "该患者的用药调整建议?",
"糖尿病教育要点有哪些?", "并发症筛查建议?",
]
labels = ["检查建议", "用药核对", "健康教育", "并发症筛查"]
assert len(page.ai_prompt_buttons) == len(questions)
for button, label, question in zip(page.ai_prompt_buttons, labels, questions, strict=True):
assert button.text() == label
assert button.toolTip() == button.accessibleName() == question
assert button.isEnabled()
button.click()
assert sent == questions
def test_patient_facts_stay_first_while_ai_is_loading_or_unavailable(application, shell_factory):
_shell, page, repository = shell_factory()
before = {key: label.text() for key, label in page.patient_summary_labels.items()}
requests = list(repository.calls)
for state in ("loading", "error", "permission"):
page._set_ai_analysis_state(state)
_settle(application)
assert {key: label.text() for key, label in page.patient_summary_labels.items()} == before
assert page.patient_summary_card.mapTo(page.insights_scroll.widget(), QPoint()).y() == 0
assert repository.calls == requests
def test_patient_change_returns_to_facts_and_clears_previous_summary(application, shell_factory, monkeypatch):
_shell, page, _repository = shell_factory()
page.insights_scroll.verticalScrollBar().setValue(page.insights_scroll.verticalScrollBar().maximum())
monkeypatch.setattr(page, "_load_detail", lambda record, **_kwargs: page._reset_detail_content(record))
page._select_record({"id": 52, "patient_name": "另一位患者"})
_settle(application)
assert page.insights_scroll.verticalScrollBar().value() == 0
assert all(label.text() == "正在加载…" for label in page.patient_summary_labels.values())
page._render_detail_load_failure("详情暂不可用")
assert all(label.text() == "未记录" for label in page.patient_summary_labels.values())
assert all(label.property("missing") is True for label in page.patient_summary_labels.values())
+85 -4
View File
@@ -2,10 +2,12 @@ from __future__ import annotations
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow
from PySide6.QtCore import QPoint, QRect, Qt, QTimer
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow, QWidget
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import DemoDoctorRepository
@@ -92,7 +94,7 @@ def test_modal_exec_uses_main_window_geometry() -> None:
main.close()
def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> None:
def test_business_windows_and_standalone_readonly_keep_main_window_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
@@ -104,7 +106,6 @@ def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> Non
dialogs = [
AppointmentDrawer({"id": 501, "diagnosis_id": 501}, repository, main, autoload=False),
DiagnosisDialog(repository, main),
OrderDetailDrawer(main),
PrescriptionEditorDialog(repository, parent=main),
]
try:
@@ -121,6 +122,86 @@ def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> Non
main.close()
def _client_geometry(widget):
return QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
def _settle(app):
for _ in range(4):
app.processEvents()
@pytest.mark.parametrize("view_only", [False, True])
def test_diagnosis_drawer_scrim_covers_the_entire_workstation_client_area(view_only) -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1400, 900)
page = QWidget(main)
main.setCentralWidget(page)
main.show()
_settle(app)
dialog = DiagnosisDialog(object(), page, permissions=PermissionSet(["tcm.diagnosis/edit"]))
try:
dialog.open_for(501, editable=not view_only, view_only=view_only,
authoritative_detail={"diagnosis": {"id": 501, "patient_id": 1501}})
_settle(app)
def assert_full_coverage():
assert _client_geometry(dialog) == _client_geometry(main)
assert dialog.drawer_overlay.rect() == dialog.rect()
assert dialog.drawer_panel.width() == round(main.width() * 0.60)
assert dialog.drawer_panel.mapTo(dialog, QPoint(0, 0)).x() + dialog.drawer_panel.width() == dialog.width()
assert dialog.drawer_panel.height() == dialog.height()
image = dialog.grab().toImage()
shade = image.pixelColor(2, 2)
assert shade.alpha() > 0
assert image.pixelColor(2, image.height() - 3) == shade
assert_full_coverage()
main.setGeometry(70, 80, 1200, 780)
_settle(app)
assert_full_coverage()
main.showMaximized()
_settle(app)
assert_full_coverage()
main.showNormal()
_settle(app)
assert_full_coverage()
finally:
dialog.close()
main.close()
@pytest.mark.parametrize("standalone_readonly", [False, True])
def test_order_scrim_covers_its_diagnosis_owner_while_main_window_is_visible(standalone_readonly) -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1400, 900)
main.show()
_settle(app)
owner = DiagnosisDialog(object(), main, permissions=PermissionSet(["tcm.diagnosis/edit"]))
owner.open_for(501, editable=not standalone_readonly,
authoritative_detail={"diagnosis": {"id": 501, "patient_id": 1501}})
drawer = OrderDetailDrawer(owner)
try:
drawer.show()
_settle(app)
assert _client_geometry(drawer) == _client_geometry(owner)
assert drawer.drawer_panel.width() == round(owner.width() * 0.8)
assert drawer.scrim.height() == owner.height()
main.setGeometry(70, 80, 1280, 820)
_settle(app)
assert _client_geometry(drawer) == _client_geometry(owner)
finally:
drawer.close()
owner.close()
main.close()
def test_maximized_workstation_opens_patient_picker_at_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)