Files
zyt/app/tests/test_ai_consult_transfer_receipt_ui.py
T
2026-10-23 11:39:56 +08:00

231 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Transfer receipts stay collapsed above the answer throughout its lifecycle."""
from __future__ import annotations
import os
from datetime import datetime
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, 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 GlucoseChartData, GlucoseReading
REPORT = """以下为合成测试资料的核对清单,所有结论需要结合原始记录及记录日期进一步确认。
1. 记录核对
- 来源范围:保留现有资料,逐项确认填写情况与来源,不补写缺失的内容。
2. 后续核对
- 记录日期:继续核对已有记录的完整性,保留最终唯一标记。
"""
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def dialog(application, monkeypatch):
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None),
))
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance.resize(1280, 820)
instance.show()
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def _manifest():
statuses = ["submitted", "prepared", "submitting", "failed", "omitted"]
return {
"source_summary": {"diagnosis_count": 2, "blood_record_count": 3},
"required_sections": [
{"key": key, "status": statuses[index % len(statuses)],
"availability": "empty" if index == 1 else "present"}
for index, (key, _) in enumerate(module._REQUIRED_TRANSFER_SECTIONS)
],
"items": [
{"kind": "image", "label": "图片附件1", "status": "submitted"},
{"kind": "document", "label": "文档附件2", "status": "skipped", "reason": "not_found"},
{"kind": "audio", "label": "音频附件3", "status": "failed"},
{"kind": "custom", "label": "附件4", "status": "omitted"},
],
"attachment_count": 4,
"submitted_attachment_count": 1,
"attachment_transfer": "uploaded_files",
"source_form": "evidence_summary",
"evidence_cache_hit": True,
}
@pytest.mark.parametrize("report", [False, True])
def test_receipt_is_collapsed_above_report_chart_and_body(application, report):
bubble = module._ChatBubble(role="ai", text=REPORT if report else "核对合成记录。")
description = module._transfer_description(_manifest(), "本次回复已完成。")
bubble.set_transfer_status(description)
chart = GlucoseChartData(readings=(GlucoseReading(datetime(2026, 10, 20), fasting=6.2),))
assert bubble.finalize_clinical_analysis(chart_data=chart) is report
bubble.resize(780, 700)
bubble.show()
application.processEvents()
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert bubble.transfer_receipt.isVisible()
assert bubble.transfer_status.isHidden()
assert not bubble.transfer_toggle.isChecked()
assert "展开详情" in bubble.transfer_toggle.text()
assert bubble.transfer_status.text() == description
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isVisible() and bubble.transfer_toggle.isChecked()
assert "收起详情" in bubble.transfer_toggle.text()
assert bubble.transfer_status.textInteractionFlags() & Qt.TextInteractionFlag.TextSelectableByMouse
assert all(f"{label}:" in bubble.transfer_status.text()
for _, label in module._REQUIRED_TRANSFER_SECTIONS)
assert "无(已整理,待提交)" in bubble.transfer_status.text()
assert "血糖血压记录 3 条" in bubble.transfer_status.text()
assert "文件不存在,已跳过" in bubble.transfer_status.text()
assert "音频附件3(音频):提交失败" in bubble.transfer_status.text()
assert "附件4(附件):未提交" in bubble.transfer_status.text()
assert "本请求附件通道:1 项" in bubble.transfer_status.text()
assert "资料栏目提交清单" not in bubble.body.toPlainText()
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isHidden()
bubble.close()
bubble.deleteLater()
def test_receipt_progress_keeps_expansion_and_does_not_reparse_body(application, monkeypatch):
bubble = module._ChatBubble(role="ai", text="合成正文保持完整。")
first = module._transfer_description(_manifest(), "正在提交资料…")
bubble.set_transfer_status(first)
bubble.transfer_toggle.click()
bubble.transfer_status.setSelection(0, 4)
selected = bubble.transfer_status.selectedText()
monkeypatch.setattr(bubble.body, "set_payload", lambda *_: pytest.fail("receipt reparsed answer"))
for _ in range(20):
bubble.set_transfer_status(first)
assert bubble.transfer_status.selectedText() == selected
next_text = module._transfer_description(_manifest(), "已收到 AI 正文,正在生成…")
bubble.set_transfer_status(next_text)
assert bubble.transfer_toggle.isChecked() and not bubble.transfer_status.isHidden()
bubble.transfer_toggle.click()
bubble.set_transfer_status(module._transfer_description(_manifest(), "本次回复已完成。"))
assert not bubble.transfer_toggle.isChecked() and bubble.transfer_status.isHidden()
assert bubble.body.toPlainText() == "合成正文保持完整。"
bubble.deleteLater()
@pytest.mark.parametrize("expanded", [False, True])
@pytest.mark.parametrize("ending", ["done", "error", "cancelled"])
def test_stream_terminal_preserves_receipt_choice_and_skipped_files(dialog, expanded, ending):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
assert bubble.transfer_status.isHidden()
if expanded:
bubble.transfer_toggle.click()
dialog._stream_event(generation, stream, {"event": "progress", "phase": "upstream", **_manifest()})
for chunk in ("首段合成正文。\n\n", "最后唯一标记"):
dialog._stream_event(generation, stream, {"event": "delta", "text": chunk})
dialog._flush_stream_chunks()
if ending == "done":
# A legacy terminal bulk receipt must not relabel the missing file.
stale = _manifest()
stale["items"] = [{**item, "status": "submitted"} for item in stale["items"]]
dialog._stream_event(generation, stream, {"event": "done", **stale})
elif ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("合成连接中断"))
else:
dialog._cancel_stream(reason="合成测试停止")
assert bubble.transfer_toggle.isChecked() is expanded
assert bubble.transfer_status.isHidden() is not expanded
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert "文件不存在,已跳过" in bubble.transfer_status.text()
assert "最后唯一标记" in bubble.body.toPlainText()
assert "资料栏目提交清单" not in bubble._raw_payload
assert "资料栏目提交清单" not in bubble.body.toPlainText()
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
def test_empty_cancel_and_error_keep_collapsed_receipt(dialog):
for ending in ("error", "cancelled"):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
if ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("合成错误"))
else:
dialog._cancel_stream(reason="合成测试停止")
assert bubble.body.isHidden()
assert bubble.transfer_status.isHidden()
assert not bubble.transfer_toggle.isChecked()
bubble.transfer_toggle.click()
assert not bubble.transfer_status.isHidden()
assert "文件不存在,已跳过" in bubble.transfer_status.text()
@pytest.mark.parametrize("expanded", [False, True])
def test_deferred_report_keeps_receipt_at_top_and_preserves_choice(dialog, expanded):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
if expanded:
bubble.transfer_toggle.click()
text = REPORT + "\n\n" + "合成补充记录,核对资料完整性。" * 400
dialog._stream_event(generation, stream, {"event": "delta", "text": text})
dialog._stream_event(generation, stream, {"event": "done"})
assert bubble._report_render_pending
for _ in range(200):
if not bubble._report_render_pending:
break
QTest.qWait(5)
assert not bubble._report_render_pending and bubble._clinical_panel is not None
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert bubble.transfer_toggle.isChecked() is expanded
assert bubble.transfer_status.isHidden() is not expanded
assert bubble._raw_payload == text
def test_opening_receipt_keeps_scroll_position_while_stream_continues(dialog, application):
text = "\n\n".join(["合成记录" * 30] * 35)
bubble = dialog._append_bubble("ai", "")
bubble.append_stream_text(text, text)
bubble.set_transfer_status(module._transfer_description(_manifest(), "正在生成…"))
for _ in range(6):
application.processEvents()
QTest.qWait(5)
bar = dialog.chat_scroll.verticalScrollBar()
bar.setValue(bar.maximum())
before = bar.value()
assert before > 0 and dialog._follow_chat
bubble.transfer_toggle.click()
for _ in range(6):
application.processEvents()
QTest.qWait(5)
assert bar.value() == before
assert not dialog._follow_chat
bubble.append_stream_text("新增合成末行", str(bubble._raw_payload) + "新增合成末行")
bubble.set_transfer_status(module._transfer_description(_manifest(), "本次回复已完成。"))
for _ in range(6):
application.processEvents()
QTest.qWait(5)
assert bar.value() == before and not dialog._follow_chat