249 lines
11 KiB
Python
249 lines
11 KiB
Python
"""Saved patient reports remain distinct from the current request in real Qt."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from types import SimpleNamespace
|
|
|
|
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
|
|
|
import pytest
|
|
from PySide6.QtCore import QCoreApplication, QEvent, 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
|
|
|
|
|
|
class Deferred:
|
|
def __init__(self):
|
|
self.pending = []
|
|
|
|
def __call__(self, function, *args, on_success=None, **_kwargs):
|
|
self.pending.append((function, args, on_success))
|
|
|
|
def complete(self, index):
|
|
function, args, success = self.pending[index]
|
|
success(function(*args))
|
|
|
|
|
|
class Repository:
|
|
def __init__(self):
|
|
self.foreign_owner = False
|
|
self.report_text = {
|
|
1501: "甲患者保存报告开头。\n" + "甲患者完整历史依据。\n" * 60 + "4. 免责声明:甲患者历史报告结尾。",
|
|
1502: "乙患者保存报告开头。\n" + "乙患者完整历史依据。\n" * 60 + "乙患者历史报告结尾。",
|
|
}
|
|
|
|
def get_diagnosis_detail(self, diagnosis_id, **_kwargs):
|
|
return {"diagnosis": {"id": diagnosis_id, "patient_id": diagnosis_id + 1000,
|
|
"patient_name": "甲患者" if diagnosis_id == 501 else "乙患者"}}
|
|
|
|
def list_patient_ai_reports(self, patient_id):
|
|
return {"patient_id": 9999 if self.foreign_owner else patient_id,
|
|
"reports": [{"patient_id": patient_id, "model_label": "离线测试模型",
|
|
"created_at": "2026-10-20 08:00:00",
|
|
"report": {"diagnosis_advice": self.report_text[patient_id],
|
|
"treatment_advice": "保存的用药复核依据。"}}]}
|
|
|
|
def list_im_chat_messages(self, *_args, **_kwargs):
|
|
return []
|
|
|
|
|
|
class OfflineWorker(module._AiStreamWorker):
|
|
def cancel(self):
|
|
# Exercise UI cancellation and ownership without starting control HTTP
|
|
# threads; worker transport cancellation has its own regression suite.
|
|
self._cancelled.set()
|
|
return self.take_events()
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def application():
|
|
return QApplication.instance() or QApplication([])
|
|
|
|
|
|
@pytest.fixture
|
|
def workspace(application, monkeypatch):
|
|
deferred = Deferred()
|
|
monkeypatch.setattr(module, "run_async", deferred)
|
|
monkeypatch.setattr(module, "_AiStreamWorker", OfflineWorker)
|
|
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
|
|
globalInstance=lambda: SimpleNamespace(start=lambda _: None)))
|
|
repository = Repository()
|
|
dialog = module.AiConsultDialog(repository, PermissionSet(["tcm.diagnosis/aiAssistant"]))
|
|
dialog.open_for(diagnosis_id=501, patient_id=1501)
|
|
dialog.show()
|
|
application.processEvents()
|
|
yield dialog, repository, deferred
|
|
bubbles = dialog.findChildren(module._ChatBubble)
|
|
dialog.close()
|
|
assert dialog._session_closed
|
|
assert not any(timer.isActive() for timer in dialog.findChildren(QTimer))
|
|
assert not any(bubble._presentation_timer.isActive() for bubble in bubbles)
|
|
dialog.deleteLater()
|
|
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
|
application.processEvents()
|
|
|
|
|
|
def insight_text(dialog):
|
|
return "\n".join(label.text() for label in dialog.side_scroll.findChildren(QLabel)
|
|
if label.objectName() == "AiConsultInsightText")
|
|
|
|
|
|
def emit(dialog, event):
|
|
dialog._stream_event(dialog._generation, dialog._stream_generation, event)
|
|
|
|
|
|
def test_long_saved_report_preserves_content_and_has_explicit_source(workspace, application):
|
|
dialog, repository, deferred = workspace
|
|
deferred.complete(0)
|
|
application.processEvents()
|
|
assert "历史" in dialog.insight_source.text()
|
|
assert "2026-10-20 08:00:00" in dialog.insight_source.text()
|
|
assert "离线测试模型" in dialog.insight_source.text()
|
|
report_bubble = next(bubble for bubble in dialog.findChildren(module._ChatBubble)
|
|
if "甲患者保存报告开头" in str(bubble._raw_payload))
|
|
assert report_bubble._provenance["diagnosis_advice"] == repository.report_text[1501]
|
|
assert "已保存报告(历史)" in report_bubble.stamp.text()
|
|
assert insight_text(dialog).count("甲患者完整历史依据") == 60
|
|
assert "甲患者历史报告结尾" in insight_text(dialog)
|
|
assert dialog.side_scroll.verticalScrollBar().maximum() > 0
|
|
assert len(dialog.findChildren(module._ClickCard, "AiConsultToolCard")) == 6
|
|
|
|
|
|
def test_current_request_is_visible_above_scrolled_history_and_keeps_task_owner(workspace, application):
|
|
dialog, _repository, deferred = workspace
|
|
deferred.complete(0)
|
|
application.processEvents()
|
|
bar = dialog.side_scroll.verticalScrollBar()
|
|
bar.setValue(bar.maximum())
|
|
dialog._ask("无模板合成问题", task="medication_review")
|
|
worker = dialog._stream_worker
|
|
dialog._stream_started_at -= 42
|
|
emit(dialog, {"event": "progress", "phase": "upstream"})
|
|
status = dialog.side_request_status
|
|
assert "用药评估" in status.text() and "已等待 42 秒" in status.text()
|
|
assert "等待 AI 正文" in status.text()
|
|
assert status.property("diagnosisId") == 501
|
|
assert status.property("requestId") == worker.request_id
|
|
assert status.property("task") == "medication_review"
|
|
assert not dialog.side_scroll.isAncestorOf(status)
|
|
assert status.isVisible() and status.visibleRegion().boundingRect().height() > 0
|
|
assert "甲患者历史报告结尾" in insight_text(dialog)
|
|
assert "甲患者保存报告" not in dialog._stream_bubble._raw_payload
|
|
assert not dialog._stream_text
|
|
|
|
|
|
def test_late_saved_report_during_wait_does_not_become_current_reply(workspace, application):
|
|
dialog, _repository, deferred = workspace
|
|
dialog._ask("合成实时问题", task="summary")
|
|
worker = dialog._stream_worker
|
|
emit(dialog, {"event": "progress", "phase": "upstream"})
|
|
expected_status = dialog.side_request_status.text()
|
|
deferred.complete(0)
|
|
application.processEvents()
|
|
assert dialog.side_request_status.text() == expected_status
|
|
assert dialog.side_request_status.property("requestId") == worker.request_id
|
|
assert dialog._stream_bubble._raw_payload == "资料已提交,正在等待 AI 正文…"
|
|
assert not dialog._stream_text and not dialog._stream_completed
|
|
assert "历史" in dialog.insight_source.text()
|
|
|
|
|
|
def test_request_status_tracks_submission_wait_and_first_body_without_substitution(workspace):
|
|
dialog, _repository, deferred = workspace
|
|
deferred.complete(0)
|
|
saved_source = dialog.insight_source.text()
|
|
dialog._ask("合成无模板问题", task="complication_risk")
|
|
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
|
|
"attachment_count": 0})
|
|
assert "资料正文已提交,等待 AI 正文" in dialog.side_request_status.text()
|
|
emit(dialog, {"event": "progress", "phase": "upstream"})
|
|
assert "等待 AI 正文" in dialog.side_request_status.text()
|
|
emit(dialog, {"event": "delta", "text": "模型批准的原始片段🩺"})
|
|
assert "已收到 AI 正文,正在生成" in dialog.side_request_status.text()
|
|
assert "已用时" in dialog.side_request_status.text()
|
|
assert "已等待" not in dialog.side_request_status.text()
|
|
assert dialog._stream_text == "模型批准的原始片段🩺"
|
|
assert dialog.insight_source.text() == saved_source
|
|
assert dialog._asking and not dialog._stream_completed
|
|
|
|
|
|
def test_patient_switch_resets_scroll_and_late_old_owner_cannot_change_sidebar(workspace, application):
|
|
dialog, _repository, deferred = workspace
|
|
deferred.complete(0)
|
|
application.processEvents()
|
|
bar = dialog.side_scroll.verticalScrollBar()
|
|
bar.setValue(bar.maximum())
|
|
assert bar.value() > 0
|
|
dialog._ask("甲患者旧问题", task="case_analysis")
|
|
old_generation, old_stream = dialog._generation, dialog._stream_generation
|
|
dialog.open_for(diagnosis_id=502, patient_id=1502)
|
|
assert bar.value() == 0
|
|
assert dialog.side_request_status.text() == "本次尚未发起 AI 请求。"
|
|
assert dialog.side_request_status.property("requestId") == ""
|
|
deferred.complete(0) # A duplicated late callback still belongs to patient A.
|
|
dialog._stream_event(old_generation, old_stream, {"event": "delta", "text": "甲患者迟到正文"})
|
|
assert "甲患者" not in insight_text(dialog)
|
|
deferred.complete(1)
|
|
application.processEvents()
|
|
assert bar.value() == 0
|
|
assert "乙患者历史报告结尾" in insight_text(dialog)
|
|
assert "甲患者" not in insight_text(dialog)
|
|
assert dialog.side_request_status.property("diagnosisId") == 502
|
|
|
|
|
|
def test_report_with_wrong_owner_is_rejected_before_display(workspace, application):
|
|
dialog, repository, deferred = workspace
|
|
repository.foreign_owner = True
|
|
deferred.complete(0)
|
|
application.processEvents()
|
|
assert "甲患者保存报告开头" not in insight_text(dialog)
|
|
assert "加载失败" in dialog.insight_source.text()
|
|
|
|
|
|
@pytest.mark.parametrize("ending", ["done", "error", "eof", "cancel"])
|
|
def test_terminal_request_status_is_truthful_and_preserves_history(workspace, application, ending):
|
|
dialog, _repository, deferred = workspace
|
|
deferred.complete(0)
|
|
dialog._ask("合成终态问题", task="glucose_trend")
|
|
worker = dialog._stream_worker
|
|
generation, stream = dialog._generation, dialog._stream_generation
|
|
emit(dialog, {"event": "delta", "text": "本次收到的真实片段。"})
|
|
if ending == "done":
|
|
emit(dialog, {"event": "done"})
|
|
expected = "本次回复已完成"
|
|
elif ending == "error":
|
|
dialog._stream_failed(generation, stream, RuntimeError("离线合成错误"))
|
|
expected = "本次请求失败"
|
|
elif ending == "eof":
|
|
dialog._stream_finished(generation, stream, worker)
|
|
expected = "未收到回复完成确认"
|
|
else:
|
|
dialog._cancel_stream(reason="离线合成取消")
|
|
expected = "已停止本次等待"
|
|
QTest.qWait(40)
|
|
assert expected in dialog.side_request_status.text()
|
|
assert "血糖趋势" in dialog.side_request_status.text()
|
|
assert "甲患者历史报告结尾" in insight_text(dialog)
|
|
assert not dialog._asking
|
|
assert not dialog._stream_elapsed_timer.isActive()
|
|
assert not dialog._delivery_timer.isActive()
|
|
assert not dialog._stream_timeout_timer.isActive()
|
|
|
|
|
|
def test_replacement_request_rejects_previous_status_and_text(workspace):
|
|
dialog, _repository, deferred = workspace
|
|
deferred.complete(0)
|
|
dialog._ask("合成旧请求", task="case_analysis")
|
|
generation, stream = dialog._generation, dialog._stream_generation
|
|
old_id = dialog._stream_worker.request_id
|
|
dialog._ask("合成新请求", replace_active=True, task="lifestyle_advice")
|
|
expected = dialog.side_request_status.text()
|
|
dialog._stream_event(generation, stream, {"event": "progress", "phase": "upstream"})
|
|
dialog._stream_event(generation, stream, {"event": "done", "answer": "过期答案"})
|
|
assert dialog.side_request_status.text() == expected
|
|
assert "健康建议" in expected
|
|
assert dialog.side_request_status.property("requestId") != old_id
|
|
assert not dialog._stream_text
|