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

207 lines
8.1 KiB
Python

"""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() == "患者进入在线问诊"