igengx
This commit is contained in:
@@ -367,14 +367,31 @@ def test_prescription_action_with_write_permission_but_without_ai_grant_is_block
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership(
|
||||
@pytest.mark.parametrize("esign_enabled", [False, True])
|
||||
def test_prescription_action_opens_upload_once_with_current_diagnosis_ownership(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
esign_enabled: bool,
|
||||
) -> None:
|
||||
created: list[dict[str, Any]] = []
|
||||
editor_seeds: list[dict[str, Any]] = []
|
||||
upload_receipts: list[dict[str, Any]] = []
|
||||
current_user = {"id": 12, "name": "甄医生"}
|
||||
receipt = {
|
||||
"id": 9001,
|
||||
"esign": {
|
||||
"enabled": esign_enabled,
|
||||
"required": esign_enabled,
|
||||
"environment": "sandbox",
|
||||
"status": "pending" if esign_enabled else "legacy",
|
||||
"can_sign": False,
|
||||
"can_download": False,
|
||||
"review_submitted_at": 0,
|
||||
"awaiting_upload": True,
|
||||
"can_submit_for_review": True,
|
||||
},
|
||||
}
|
||||
|
||||
class Repository:
|
||||
def get_diagnosis_detail(
|
||||
@@ -419,7 +436,10 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
|
||||
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append(prescription)
|
||||
return {"id": 9001, **prescription}
|
||||
return receipt
|
||||
|
||||
def submit_prescription_for_review(self, prescription_id: int) -> None:
|
||||
raise AssertionError(f"uploading {prescription_id} requires a separate click")
|
||||
|
||||
def list_prescriptions_by_diagnosis(
|
||||
self,
|
||||
@@ -427,10 +447,6 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
) -> list[dict[str, Any]]:
|
||||
return [{"id": 9001, "diagnosis_id": diagnosis_id, "sn": "RX-9001"}]
|
||||
|
||||
class FakeSignal:
|
||||
def connect(self, _slot: Any) -> None:
|
||||
return None
|
||||
|
||||
class FakeEditor:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -441,9 +457,12 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
editor_seeds.append(seed)
|
||||
assert kwargs["mode"] == "add"
|
||||
assert kwargs["current_user"] == current_user
|
||||
self.diagnosis_requested = FakeSignal()
|
||||
self.save_draft = kwargs["save_draft"]
|
||||
self.saved_draft = None
|
||||
|
||||
def exec(self) -> Any:
|
||||
if esign_enabled:
|
||||
self.saved_draft = self.save_draft(self.payload())
|
||||
return ai_consult_module.QDialog.DialogCode.Accepted
|
||||
|
||||
@staticmethod
|
||||
@@ -452,17 +471,32 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
"diagnosis_id": 999,
|
||||
"appointment_id": 998,
|
||||
"case_record": {"forged": True},
|
||||
"patient_id": 997,
|
||||
"phone": "13900000000",
|
||||
"doctor_name": "甄医生",
|
||||
"herbs": [{"name": "茯苓", "dosage": 10, "unit": "g"}],
|
||||
}
|
||||
|
||||
from doctor_workstation.ui.dialogs import prescription as prescription_module
|
||||
class FakeUploadDialog:
|
||||
def __init__(self, _repository: Any, prescription: dict[str, Any], **_kwargs: Any) -> None:
|
||||
assert prescription is receipt
|
||||
self.state = prescription["esign"]
|
||||
upload_receipts.append(prescription)
|
||||
|
||||
def exec(self) -> None:
|
||||
return None
|
||||
|
||||
from doctor_workstation.ui.dialogs import (
|
||||
prescription as prescription_module,
|
||||
prescription_esign as prescription_esign_module,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
prescription_module,
|
||||
"PrescriptionEditorDialog",
|
||||
FakeEditor,
|
||||
)
|
||||
monkeypatch.setattr(prescription_esign_module, "PrescriptionEsignDialog", FakeUploadDialog)
|
||||
host = QWidget()
|
||||
host.current_user = current_user # type: ignore[attr-defined]
|
||||
dialog = AiConsultDialog(
|
||||
@@ -484,7 +518,9 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
assert editor_seeds[0]["diagnosis_id"] == 501
|
||||
assert editor_seeds[0]["appointment_id"] == 801
|
||||
assert editor_seeds[0]["herbs"][0]["name"] == "茯苓"
|
||||
assert created and created[0]["diagnosis_id"] == 501
|
||||
assert len(created) == 1
|
||||
assert upload_receipts == [receipt]
|
||||
assert created[0]["diagnosis_id"] == 501
|
||||
assert created[0]["appointment_id"] == 801
|
||||
assert created[0]["case_record"] == {"chief_complaint": "性功能下降"}
|
||||
assert created[0]["patient_id"] == 301
|
||||
@@ -495,7 +531,7 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
browser.toPlainText()
|
||||
for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
|
||||
]
|
||||
assert any("处方已开具并提交审核" in body for body in bodies)
|
||||
assert any("处方草稿已保存" in body and "上传处方" in body for body in bodies)
|
||||
dialog.close()
|
||||
host.close()
|
||||
|
||||
|
||||
@@ -98,6 +98,26 @@ def test_invalid_identity_or_action_cannot_read_patient_context(changes):
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,forwarded", [(None, None), ("qwen", None), ("openai", "openai"), ("doubao", "doubao")])
|
||||
def test_selected_model_is_forwarded_only_when_not_the_task_default(model, forwarded):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert service.handle(request(service, **({} if model is None else {"model": model})))
|
||||
assert service.wait()
|
||||
assert service.take_result()["status"] == "success"
|
||||
_diagnosis_id, _prompt, options = repository.stream_calls[0]
|
||||
assert options.get("model") == forwarded
|
||||
assert ("model" in options) is (forwarded is not None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["deepseek", "", "Doubao", 1, ["doubao"]])
|
||||
def test_unknown_model_cannot_start_a_request(model):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert not service.handle(request(service, model=model))
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
def test_permission_default_denied_and_each_host_has_unique_session():
|
||||
repository = Repository()
|
||||
disabled = im_ai.ImAiController(
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from time import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
@@ -11,6 +14,7 @@ import pytest
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiProtocolError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
RepositoryNotFoundError,
|
||||
)
|
||||
@@ -415,6 +419,8 @@ class _StubApiClient:
|
||||
self.token = ""
|
||||
self.get_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.post_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.deadline = int(time()) + 3600
|
||||
self.post_tokens: list[str] = []
|
||||
|
||||
def set_token(self, token: str) -> None:
|
||||
"""Retain the synthetic login token."""
|
||||
@@ -445,13 +451,17 @@ class _StubApiClient:
|
||||
return {"appointment": {"id": params["id"]}, "doctor_notes": []}
|
||||
return {"lists": [], "count": 0, "extend": {}}
|
||||
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None) -> Any:
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None, *,
|
||||
headers: dict[str, str] | None = None, timeout: float | None = None) -> Any:
|
||||
"""Return synthetic mutation data and record the exact JSON payload."""
|
||||
|
||||
body = dict(payload or {})
|
||||
self.post_calls.append((endpoint, body))
|
||||
self.post_tokens.append((headers or {}).get("token", self.token))
|
||||
if endpoint == "login/account":
|
||||
return {"token": "remote-token", "is_paw": 1}
|
||||
return {"token": "remote-token", "is_paw": 1, "desktop_expires_at": self.deadline}
|
||||
if endpoint == "login/desktopHeartbeat":
|
||||
return {"desktop_expires_at": self.deadline}
|
||||
if endpoint == "tcm.prescriptionLibrary/add":
|
||||
return {"id": 9}
|
||||
if endpoint == "tcm.diagnosis/getCallSignature":
|
||||
@@ -473,6 +483,8 @@ def test_remote_repository_uses_all_confirmed_endpoints_without_network() -> Non
|
||||
repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
|
||||
|
||||
session = repository.login(" doctor ", "secret")
|
||||
assert client.post_calls == [("login/account", {"account": "doctor", "password": "secret", "terminal": 21})]
|
||||
assert session.desktop_expires_at == client.deadline
|
||||
assert session.token == "remote-token"
|
||||
assert repository.get_current_user().name == "远程医生"
|
||||
assert [path for path, _ in client.get_calls].count("auth.admin/mySelf") == 1
|
||||
@@ -588,6 +600,8 @@ def test_remote_login_persists_only_after_session_validation(
|
||||
)
|
||||
|
||||
assert saved == []
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
|
||||
@@ -604,6 +618,10 @@ def test_remote_login_applies_remember_account_to_token_store(tmp_path: Path) ->
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
|
||||
repository.logout()
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
repository.login("doctor", "secret", remember_account=False)
|
||||
assert store.load_account() is None
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
@@ -614,7 +632,8 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
|
||||
client = _FailingProfileClient(AuthenticationExpiredError("expired", code=-1))
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url,
|
||||
desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
@@ -625,6 +644,101 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deadline", [0, 1])
|
||||
def test_old_web_or_past_cutoff_token_is_discarded_without_network(tmp_path: Path, deadline: int) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("saved-token", account="doctor", scope=client.base_url, desktop_expires_at=deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
repository.restore_session()
|
||||
repository.logout()
|
||||
assert client.post_calls == client.get_calls == []
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
|
||||
|
||||
def test_restore_requires_live_heartbeat_and_keeps_earlier_cutoff(tmp_path: Path) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline - 10)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
session = repository.restore_session()
|
||||
assert session and session.desktop_expires_at == client.deadline - 10
|
||||
assert client.post_calls == [("login/desktopHeartbeat", {})]
|
||||
assert client.post_tokens == ["desktop-token"]
|
||||
assert client.get_calls == [("auth.admin/mySelf", {})]
|
||||
|
||||
|
||||
def test_network_loss_during_restore_preserves_token_for_retry(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
def offline(*_args: Any, **_kwargs: Any) -> Any:
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
with pytest.raises(ApiTransportError):
|
||||
repository.restore_session()
|
||||
assert client.token == ""
|
||||
assert client.get_calls == []
|
||||
assert store.load_token() == "desktop-token"
|
||||
|
||||
|
||||
def test_logout_after_network_loss_clears_credentials_and_never_retries(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
repository.login("doctor", "secret", remember_account=True)
|
||||
attempts = []
|
||||
|
||||
def offline(endpoint: str, _payload: dict, **kwargs: Any) -> Any:
|
||||
attempts.append((endpoint, kwargs["headers"]["token"]))
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
repository.logout()
|
||||
repository.logout()
|
||||
assert attempts == [("login/logout", "remote-token")]
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
def test_app_close_during_login_retires_issued_token_before_transport_close(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
profile_started = Event()
|
||||
finish_profile = Event()
|
||||
get_profile = client.get
|
||||
closes = []
|
||||
|
||||
def pending_profile(endpoint: str) -> Any:
|
||||
profile_started.set()
|
||||
assert finish_profile.wait(3)
|
||||
return get_profile(endpoint)
|
||||
|
||||
monkeypatch.setattr(client, "get", pending_profile)
|
||||
monkeypatch.setattr(client, "close", lambda: closes.append(client.token), raising=False)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
login = pool.submit(repository.login, "doctor", "secret", remember_account=True)
|
||||
assert profile_started.wait(3)
|
||||
shutdown = pool.submit(repository.close)
|
||||
finish_profile.set()
|
||||
assert login.result(timeout=3).token == "remote-token"
|
||||
shutdown.result(timeout=3)
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
assert closes == [""]
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
|
||||
|
||||
def test_restore_never_sends_token_to_a_different_api_scope(tmp_path: Path) -> None:
|
||||
"""Changing the configured server invalidates automatic token reuse."""
|
||||
|
||||
|
||||
@@ -81,13 +81,13 @@ def _detail(appointment_id: int, patient_id: int, diagnosis_id: int) -> dict[str
|
||||
|
||||
|
||||
def _snapshot(model: str, version: int, stamp: str) -> dict[str, Any]:
|
||||
label = "OpenAI" if model == "openai" else "千问"
|
||||
label = {"openai": "OpenAI", "doubao": "豆包"}.get(model, "千问")
|
||||
return {
|
||||
"id": version * 10 + (2 if model == "openai" else 1),
|
||||
"id": version * 10 + {"openai": 2, "doubao": 3}.get(model, 1),
|
||||
"patient_id": 301,
|
||||
"model_key": model,
|
||||
"model_label": label,
|
||||
"model_name": "gpt-demo" if model == "openai" else "qwen-demo",
|
||||
"model_name": {"openai": "gpt-demo", "doubao": "doubao-demo"}.get(model, "qwen-demo"),
|
||||
"version": version,
|
||||
"generated_at": stamp,
|
||||
"report": {
|
||||
@@ -211,7 +211,7 @@ def test_saved_history_is_rendered_without_automatic_generation(
|
||||
page.close()
|
||||
|
||||
|
||||
def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
def test_empty_database_and_manual_refresh_append_every_model_in_order(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -254,18 +254,20 @@ def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
page._select_record(detail["appointment"])
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls == [("list", 302), ("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [1, 1]
|
||||
assert repository.calls == [
|
||||
("list", 302), ("generate", "qwen"), ("generate", "openai"), ("generate", "doubao"),
|
||||
]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [1, 1, 1]
|
||||
|
||||
page.ai_analysis_regenerate_button.click()
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls[-2:] == [("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [2, 2]
|
||||
assert repository.calls[-3:] == [("generate", "qwen"), ("generate", "openai"), ("generate", "doubao")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [2, 2, 2]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def test_openai_failure_keeps_new_qwen_snapshot_and_still_generates_doubao(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -281,7 +283,7 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def generate_patient_ai_report(self, patient_id: int, *, model: str) -> dict[str, Any]:
|
||||
if model == "openai":
|
||||
raise RuntimeError("OpenAI 暂时不可用")
|
||||
row = _snapshot("qwen", 1, "2026-08-14 10:30:00")
|
||||
row = _snapshot(model, 1, "2026-08-14 10:30:00")
|
||||
row["patient_id"] = patient_id
|
||||
return {
|
||||
"patient_id": patient_id,
|
||||
@@ -305,7 +307,11 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
assert page.ai_summary_label.text() == "千问第 1 版诊断建议"
|
||||
assert len(page._ai_analysis_histories["qwen"]) == 1
|
||||
assert page._ai_analysis_model_states["openai"] == "error"
|
||||
assert "千问新快照已保留" in page.ai_analysis_secondary_status.text()
|
||||
# 第二个模型失败不阻断第三个模型补齐。
|
||||
assert page._ai_analysis_model_states["doubao"] == "success"
|
||||
assert len(page._ai_analysis_histories["doubao"]) == 1
|
||||
assert "千问结果已保留" in page.ai_analysis_secondary_status.text()
|
||||
assert "OpenAI新快照生成失败" in page.ai_analysis_secondary_status.text()
|
||||
page.close()
|
||||
|
||||
|
||||
|
||||
@@ -528,6 +528,10 @@ def test_order_action_matrix_requires_exact_permissions_and_states(
|
||||
"ddcode",
|
||||
"withdraw",
|
||||
]
|
||||
for submission_time, review_ready in ((0, False), (1_760_000_000, False), (1_760_000_000, True)):
|
||||
current = {**pending, "review_submitted_at": submission_time, "can_review_prescription": review_ready}
|
||||
available = {key for key, _label, _danger in workspace._available_actions(current)}
|
||||
assert ("audit_prescription" in available) is review_ready
|
||||
assert [key for key, _label, _danger in workspace._available_actions(shipped)] == [
|
||||
"revoke_pay_audit",
|
||||
"ddcode",
|
||||
@@ -618,6 +622,37 @@ def test_order_approval_routes_unsigned_prescription_before_audit(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("review_signed", [False, True])
|
||||
def test_order_approval_requires_pharmacist_signature_when_enabled(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
review_signed: bool,
|
||||
) -> None:
|
||||
signed_at = 1_760_000_000
|
||||
status = {
|
||||
"enabled": True, "required": True, "environment": "sandbox", "status": "signed",
|
||||
"can_sign": False, "can_download": True, "review_submitted_at": signed_at - 10,
|
||||
"review_required": True, "review_signature_time": signed_at if review_signed else 0,
|
||||
"can_review_prescription": False,
|
||||
}
|
||||
row = {
|
||||
"id": 70, "prescription_id": 52, "prescription_audit_status": 0, "fulfillment_status": 1,
|
||||
"review_submitted_at": signed_at - 10, "can_review_prescription": True,
|
||||
}
|
||||
approved = []
|
||||
repository = SimpleNamespace(get_prescription_esign_status=lambda _id: status)
|
||||
page = PatientsPage(repository, PermissionSet(["tcm.prescriptionOrder/auditPrescription"]))
|
||||
monkeypatch.setattr(page, "_submit_order_audit", lambda order_id, **_kwargs: approved.append(order_id))
|
||||
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
|
||||
page._handle_order_action("audit_prescription", row)
|
||||
assert approved == ([70] if review_signed else [])
|
||||
if not review_signed:
|
||||
assert "管理后台" in page.order_workspace.banner.label.text()
|
||||
page.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_shell_uses_demo_session_menu_and_fits_minimum_window(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
@@ -13,8 +13,8 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtCore import QBuffer, QIODevice, Qt, Signal
|
||||
from PySide6.QtGui import QColor, QDesktopServices, QImage
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QWidget
|
||||
|
||||
@@ -714,7 +714,9 @@ def test_authentication_stays_embedded_and_only_server_readiness_can_sign(
|
||||
)
|
||||
dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state()})
|
||||
dialog.show()
|
||||
assert [label.text() for label in dialog.step_labels] == ["处方草稿已保存", "验证医生身份", "签名并完成"]
|
||||
assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
|
||||
"保存草稿", "验证医生身份", "医生签署",
|
||||
]
|
||||
assert dialog.start_button.isEnabled()
|
||||
assert not dialog.sign_button.isVisible()
|
||||
dialog.start_button.click()
|
||||
@@ -896,6 +898,75 @@ def test_signing_and_detail_display_archived_issue_and_signature_times(
|
||||
detail.close()
|
||||
|
||||
|
||||
def test_verified_pharmacist_updates_both_copies_signing_steps_and_log(
|
||||
immediate: None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
repository = Repository()
|
||||
repository.status = state(
|
||||
"signed", review_required=True, signature_time=1795000007, signature_time_source="tsa",
|
||||
)
|
||||
detail = prescription_module.PrescriptionDetailDialog({"id": 7}, repository=repository)
|
||||
signing = esign_module.PrescriptionEsignDialog(repository, {"id": 7})
|
||||
assert "待药师签署" in detail.esign_banner.label.text()
|
||||
assert "待药师签署" in signing.status_label.text()
|
||||
assert signing.review_step_label.accessibleDescription() == "当前步骤"
|
||||
assert not signing.review_step_label.isHidden() and signing.refresh_button.isEnabled()
|
||||
assert "管理后台" in signing.banner.label.text()
|
||||
assert "审核药师" not in detail.user_document.toPlainText()
|
||||
detail._saved_original = signing._saved_original = tmp_path / "doctor-only.pdf"
|
||||
|
||||
image = QImage(160, 60, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor("red"))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly) and image.save(buffer, "PNG")
|
||||
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
|
||||
repository.status.update(
|
||||
doctor_signer_name="签名医生",
|
||||
review_signer_name="张药师",
|
||||
review_signature_time=1795000017,
|
||||
review_signature=signature,
|
||||
signing_log=[
|
||||
{"event": "doctor_signed", "time": 1795000007, "source": "tsa",
|
||||
"label": "医生已签署", "actor_name": "签名医生"},
|
||||
{"event": "pharmacist_signed", "time": 1795000017, "source": "tsa",
|
||||
"label": "药师已签署", "actor_name": "张药师", "message": "<b>签章验签成功</b>"},
|
||||
{"event": "invalid", "time": -1, "source": "system", "label": "无效记录"},
|
||||
],
|
||||
)
|
||||
detail.refresh_esign()
|
||||
signing.refresh()
|
||||
assert signing.review_step_label.accessibleDescription() == "已完成"
|
||||
assert "药师签署时间:2026-11-18 19:06:57(北京时间 · 可信时间戳)" in signing.signature_time_label.text()
|
||||
assert "医生与药师已签署" in detail.esign_banner.label.text()
|
||||
assert detail._saved_original is None and signing._saved_original is None
|
||||
assert detail.tabs.tabText(1) == "处方联"
|
||||
for document in (detail.document, detail.user_document):
|
||||
assert "审核药师" in document.toPlainText()
|
||||
assert "签名医生" in document.toPlainText()
|
||||
assert f'src="{signature}"' in document.toHtml()
|
||||
|
||||
log_views = []
|
||||
monkeypatch.setattr(
|
||||
esign_module.SigningLogDialog, "exec", lambda dialog: log_views.append(dialog.entries.toPlainText()),
|
||||
)
|
||||
detail.signing_log_button.click()
|
||||
signing.signing_log_button.click()
|
||||
assert len(log_views) == 2 and log_views[0] == log_views[1]
|
||||
assert "医生已签署 · 签名医生" in log_views[0]
|
||||
assert "药师已签署 · 张药师" in log_views[0]
|
||||
assert "2026-11-18 19:06:57(北京时间 · 可信时间戳)" in log_views[0]
|
||||
assert "<b>签章验签成功</b>" in log_views[0]
|
||||
assert "无效记录" not in log_views[0]
|
||||
|
||||
repository.status["review_signature"] = "https://example.test/forged.png"
|
||||
detail.refresh_esign()
|
||||
for document in (detail.document, detail.user_document):
|
||||
assert "张药师" in document.toPlainText()
|
||||
assert "forged.png" not in document.toHtml()
|
||||
detail.close()
|
||||
signing.close()
|
||||
|
||||
|
||||
def test_download_validates_original_and_hash_before_writing(
|
||||
immediate: None, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -1124,6 +1195,187 @@ def test_reviewer_without_signing_authority_gets_doctor_instruction(
|
||||
page.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("previously_signed", [False, True])
|
||||
def test_issued_prescription_requires_upload_and_verified_doctor_signature_for_audit(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch, previously_signed: bool,
|
||||
) -> None:
|
||||
signed = state("signed", review_required=False)
|
||||
pending = state("pending", review_required=False, can_sign=True)
|
||||
upload_attempts = []
|
||||
audit_calls = []
|
||||
row = {
|
||||
"id": 7, "audit_status": 0, "esign": signed if previously_signed else pending,
|
||||
"review_submitted_at": 0, "can_review_prescription": False,
|
||||
}
|
||||
|
||||
def upload(prescription_id: int) -> dict[str, Any]:
|
||||
upload_attempts.append(prescription_id)
|
||||
if len(upload_attempts) == 1:
|
||||
raise ApiBusinessError("上传失败,请重试")
|
||||
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
row.update(receipt)
|
||||
row["can_review_prescription"] = previously_signed
|
||||
return receipt
|
||||
|
||||
def repository(owner: bool) -> Any:
|
||||
def status() -> dict[str, Any]:
|
||||
awaiting_upload = row["review_submitted_at"] == 0
|
||||
return {
|
||||
**row["esign"], "review_submitted_at": row["review_submitted_at"],
|
||||
"awaiting_upload": awaiting_upload, "can_submit_for_review": owner and awaiting_upload,
|
||||
"can_review_prescription": row["can_review_prescription"],
|
||||
}
|
||||
|
||||
return SimpleNamespace(
|
||||
list_prescriptions=lambda **_filters: {"lists": [Prescription.from_dict({**row, "esign": status()})], "count": 1},
|
||||
get_prescription_esign_status=lambda _id: status(),
|
||||
submit_prescription_for_review=upload,
|
||||
audit_prescription=lambda prescription_id, **audit: audit_calls.append((prescription_id, audit)),
|
||||
)
|
||||
|
||||
def approve(dialog: Any) -> int:
|
||||
dialog._choose("approve")
|
||||
return dialog.result()
|
||||
|
||||
monkeypatch.setattr(page_module, "show_toast", lambda *_args: None)
|
||||
monkeypatch.setattr(page_module.AuditPrescriptionDialog, "exec", approve)
|
||||
doctor = page_module.PrescriptionsPage(repository(True), PermissionSet("cf.prescription/edit"))
|
||||
reviewer = page_module.PrescriptionsPage(repository(False), PermissionSet("cf.prescription/audit"))
|
||||
doctor.refresh()
|
||||
reviewer.refresh()
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待上传处方", "warning")
|
||||
assert doctor.audit_button.isHidden()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
assert not reviewer.audit_button.isEnabled()
|
||||
assert reviewer.upload_button.isHidden()
|
||||
reviewer._audit_selected()
|
||||
assert not audit_calls
|
||||
|
||||
upload_button = doctor.upload_button
|
||||
assert upload_button.isEnabled() and not upload_button.isHidden()
|
||||
upload_button.click()
|
||||
assert "上传失败" in doctor.banner.label.text()
|
||||
assert upload_button.isEnabled()
|
||||
row_action = doctor.table.cellWidget(0, 2)
|
||||
row_upload = next(button for button in row_action.findChildren(type(upload_button)) if button.text() == "上传处方")
|
||||
row_upload.click()
|
||||
assert upload_attempts == [7, 7]
|
||||
assert upload_button.isHidden()
|
||||
if not previously_signed:
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待签名", "warning")
|
||||
assert doctor.audit_button.text() == "继续签署" and doctor.audit_button.isEnabled()
|
||||
reviewer.refresh()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
row.update(esign=signed)
|
||||
reviewer.refresh()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
row["can_review_prescription"] = True
|
||||
doctor.refresh()
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待审核", "warning")
|
||||
assert page_module.can_audit(doctor.table.current_data())
|
||||
|
||||
reviewer.refresh()
|
||||
assert not reviewer.audit_button.isHidden()
|
||||
assert reviewer.audit_button.isEnabled()
|
||||
reviewer.audit_button.click()
|
||||
assert audit_calls == [(7, {"action": "approve", "remark": ""})]
|
||||
doctor.close()
|
||||
reviewer.close()
|
||||
|
||||
|
||||
def test_saved_draft_offers_explicit_upload_before_doctor_signing(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
repository = Repository()
|
||||
repository.status = state(
|
||||
"pending", review_submitted_at=0, awaiting_upload=True, can_submit_for_review=True,
|
||||
can_review_prescription=False, review_required=True,
|
||||
)
|
||||
record = {
|
||||
"id": 7, "audit_status": 0, "esign": repository.status,
|
||||
"patient_name": "测试患者", "herbs": [{"name": "样例药材甲", "dosage": 1}],
|
||||
}
|
||||
|
||||
def upload(prescription_id: int) -> dict[str, Any]:
|
||||
assert prescription_id == 7
|
||||
repository.calls.append("upload")
|
||||
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
if repository.calls.count("upload") == 1:
|
||||
raise ApiBusinessError("上传失败,请重试")
|
||||
repository.status = {**repository.status, **receipt, "awaiting_upload": False}
|
||||
return receipt
|
||||
|
||||
def finish(dialog: esign_module.PrescriptionEsignDialog) -> None:
|
||||
dialog.resize(dialog.minimumSize())
|
||||
dialog.show()
|
||||
preview = dialog.prescription_preview
|
||||
assert dialog.workspace_splitter.widget(0) is preview
|
||||
assert dialog.workspace_splitter.widget(1) is dialog.workflow_panel
|
||||
assert preview.geometry().right() < dialog.workflow_panel.geometry().left()
|
||||
assert "样例药材甲" in preview.paper.toPlainText()
|
||||
assert dialog.workflow_panel.isAncestorOf(dialog.upload_button)
|
||||
assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
|
||||
"保存草稿", "上传处方", "验证医生身份", "医生签署", "药师审核签署",
|
||||
]
|
||||
assert dialog.step_labels[1].accessibleDescription() == "当前步骤"
|
||||
assert dialog.upload_button.isVisible() and not dialog.start_button.isEnabled()
|
||||
assert repository.calls == ["status"]
|
||||
dialog.start()
|
||||
assert repository.calls == ["status"]
|
||||
dialog.upload_button.click()
|
||||
assert "上传失败" in dialog.banner.label.text()
|
||||
assert dialog.upload_button.isEnabled() and not dialog.start_button.isEnabled()
|
||||
dialog.upload_button.click()
|
||||
assert repository.calls == ["status", "upload", "upload", "status"]
|
||||
assert dialog.step_labels[1].accessibleDescription() == "已完成"
|
||||
assert dialog.step_labels[2].accessibleDescription() == "当前步骤"
|
||||
assert dialog.upload_button.isHidden() and dialog.start_button.isEnabled()
|
||||
dialog.close()
|
||||
|
||||
monkeypatch.setattr(repository, "submit_prescription_for_review", upload, raising=False)
|
||||
monkeypatch.setattr(esign_module.PrescriptionEsignDialog, "exec", finish)
|
||||
assert esign_module.saved_prescription_message(record, "已提交审核") == (
|
||||
"处方草稿已保存。" + esign_module.PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, "success",
|
||||
)
|
||||
assert not esign_module.resume_saved_prescription(repository, record, None)
|
||||
|
||||
|
||||
def test_review_submission_repository_uses_prescription_id_and_validates_receipt() -> None:
|
||||
calls = []
|
||||
response = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
|
||||
def post(endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
calls.append((endpoint, payload))
|
||||
return response.copy()
|
||||
|
||||
repository = RemoteDoctorRepository(SimpleNamespace(post=post))
|
||||
assert repository.submit_prescription_for_review(7) == response
|
||||
assert calls == [("tcm.prescription/submitForReview", {"id": 7})]
|
||||
response["review_submitted_at"] = 0
|
||||
with pytest.raises(ApiProtocolError, match="处方上传结果格式不正确"):
|
||||
repository.submit_prescription_for_review(7)
|
||||
|
||||
|
||||
def test_signed_prescription_details_show_upload_before_pharmacist_signing(immediate: None) -> None:
|
||||
signature = Repository()
|
||||
signature.status = state("signed", review_required=True, review_submitted_at=0)
|
||||
record = {"id": 7, "audit_status": 0, "esign": signature.status, "review_submitted_at": 0}
|
||||
assert esign_module.saved_prescription_message(record, "已提交审核") == (
|
||||
"处方已保存,医生已签署。" + esign_module.PRESCRIPTION_UPLOAD_PROMPT, "success",
|
||||
)
|
||||
signing = esign_module.PrescriptionEsignDialog(signature, record)
|
||||
detail = prescription_module.PrescriptionDetailDialog(record, repository=signature)
|
||||
assert "待上传处方" in signing.status_label.text()
|
||||
assert "待上传处方" in detail.status_banner.label.text()
|
||||
signature.status = {**signature.status, "review_submitted_at": 1_760_000_000}
|
||||
signing.refresh()
|
||||
detail.refresh_esign()
|
||||
assert "待药师签署" in signing.status_label.text()
|
||||
assert "待审核" in detail.status_banner.label.text()
|
||||
signing.close()
|
||||
detail.close()
|
||||
|
||||
|
||||
def test_saved_response_without_state_warns_without_claiming_completion(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -10,6 +10,7 @@ import pytest
|
||||
from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
|
||||
from PySide6.QtPdf import QPdfDocument
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget
|
||||
|
||||
from doctor_workstation import app as app_module
|
||||
@@ -21,6 +22,7 @@ from doctor_workstation.ui.dialogs.prescription import (
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
PrescriptionOrderDialog,
|
||||
PrescriptionSigningPreview,
|
||||
PrescriptionTemplateDialog,
|
||||
RemoteMedicineComboBox,
|
||||
build_prescription_clinical_diagnosis,
|
||||
@@ -479,6 +481,47 @@ def test_editor_builds_complete_add_payload(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved_dietary_taboo", [["辛辣食物", "浓茶"], "辛辣食物, 浓茶"])
|
||||
def test_editor_dietary_taboo_popup_supports_consecutive_selections(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
saved_dietary_taboo: list[str] | str,
|
||||
) -> None:
|
||||
editor = PrescriptionEditorDialog(
|
||||
SimpleNamespace(), prescription={"dietary_taboo": saved_dietary_taboo}, mode="edit"
|
||||
)
|
||||
editor.show()
|
||||
editor.body_scroll.ensureWidgetVisible(editor.dietary_taboo)
|
||||
application.processEvents()
|
||||
|
||||
selector = editor.dietary_taboo
|
||||
field = selector.lineEdit()
|
||||
assert field.text() == "辛辣食物、浓茶"
|
||||
QTest.mouseClick(field, Qt.MouseButton.LeftButton)
|
||||
view = selector.view()
|
||||
assert view.isVisible()
|
||||
|
||||
for row, expected in (
|
||||
(1, "辛辣食物、生冷食物、浓茶"),
|
||||
(2, "辛辣食物、生冷食物、油腻食物、浓茶"),
|
||||
(0, "生冷食物、油腻食物、浓茶"),
|
||||
):
|
||||
point = view.visualRect(selector.model().index(row, 0)).center()
|
||||
QTest.mouseClick(view.viewport(), Qt.MouseButton.LeftButton, pos=point)
|
||||
assert view.isVisible()
|
||||
assert field.text() == expected
|
||||
|
||||
QTest.keyClick(view, Qt.Key.Key_Down)
|
||||
QTest.keyClick(view, Qt.Key.Key_Space)
|
||||
assert view.isVisible()
|
||||
QTest.keyClick(view, Qt.Key.Key_Escape)
|
||||
assert not view.isVisible()
|
||||
assert field.text() == "油腻食物、浓茶"
|
||||
assert editor.payload()["dietary_taboo"] == ["油腻食物", "浓茶"]
|
||||
editor.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_esign_draft_save_retries_without_discarding_form(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
@@ -645,29 +688,146 @@ def test_prescription_window_footer_preserves_draft_on_void_failure(
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["internal", "user"])
|
||||
def test_prescription_preview_scales_signature_proportionately(
|
||||
application: QApplication, variant: str,
|
||||
@pytest.mark.parametrize("print_layout", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("image_size", "expected_size"),
|
||||
[((300, 150), (40, 20)), ((384, 60), (64, 10)), ((20, 10), (20, 10))],
|
||||
)
|
||||
def test_prescription_slip_scales_both_signatures_proportionately(
|
||||
application: QApplication,
|
||||
variant: str,
|
||||
print_layout: bool,
|
||||
image_size: tuple[int, int],
|
||||
expected_size: tuple[int, int],
|
||||
) -> None:
|
||||
image = QImage(300, 150, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor("black"))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
|
||||
signatures = []
|
||||
for color in ("black", "red"):
|
||||
image = QImage(*image_size, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor(color))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signatures.append("data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii"))
|
||||
|
||||
doctor_signature, review_signature = signatures
|
||||
rendered = render_prescription_html({
|
||||
"doctor_signature": doctor_signature,
|
||||
"esign": {
|
||||
"status": "signed",
|
||||
"review_signer_name": "张药师",
|
||||
"review_signature_time": 1795000017,
|
||||
"review_signature": review_signature,
|
||||
},
|
||||
}, variant=variant, print_layout=print_layout)
|
||||
width, height = expected_size
|
||||
for signature in signatures:
|
||||
assert f'src="{signature}" width="{width}" height="{height}"' in rendered
|
||||
|
||||
document = QTextDocument()
|
||||
document.setHtml(render_prescription_html({"doctor_signature": signature}, variant=variant))
|
||||
signature_sizes = []
|
||||
document.setHtml(rendered)
|
||||
signature_sizes = {}
|
||||
block = document.begin()
|
||||
while block.isValid():
|
||||
fragments = block.begin()
|
||||
while not fragments.atEnd():
|
||||
image_format = fragments.fragment().charFormat().toImageFormat()
|
||||
if image_format.name() == signature:
|
||||
signature_sizes.append((image_format.width(), image_format.height()))
|
||||
if image_format.name() in signatures:
|
||||
signature_sizes[image_format.name()] = (image_format.width(), image_format.height())
|
||||
fragments += 1
|
||||
block = block.next()
|
||||
expected_size = (72, 36) if variant == "internal" else (48, 24)
|
||||
assert signature_sizes == [expected_size]
|
||||
assert signature_sizes == dict.fromkeys(signatures, expected_size)
|
||||
|
||||
|
||||
def test_signing_preview_uses_full_seed_and_updates_visible_signatures(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
def unexpected_detail(prescription_id: int) -> None:
|
||||
pytest.fail(f"Complete prescription {prescription_id} should not be reloaded")
|
||||
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 71,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "测试诊断",
|
||||
"prescription_type": "饮片",
|
||||
"dosage_amount": 20,
|
||||
"dosage_unit": "ml",
|
||||
"dose_count": 3,
|
||||
"herbs": [{"name": "白术", "dosage": 6}],
|
||||
"esign": {"status": "pending"},
|
||||
})
|
||||
preview = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), prescription)
|
||||
assert preview.paper is not None and preview.paper.isReadOnly()
|
||||
document = preview.paper.document()
|
||||
for text in ("虚构患者", "测试诊断", "白术 (6克)", "18克", "一次20ml"):
|
||||
assert text in document.toPlainText()
|
||||
|
||||
revision = document.revision()
|
||||
preview.set_esign_state({"status": "pending", "message": "等待核验"})
|
||||
assert document.revision() == revision
|
||||
signed = {
|
||||
"status": "signed",
|
||||
"doctor_signer_name": "签名医生",
|
||||
"review_signer_name": "审核药师姓名",
|
||||
"review_signature_time": 1795000017,
|
||||
}
|
||||
preview.set_esign_state(signed)
|
||||
for text in ("签名医生", "审核药师姓名", "白术 (6克)"):
|
||||
assert text in document.toPlainText()
|
||||
revision = document.revision()
|
||||
preview.set_esign_state(signed | {"review_signature_time": 1795000020})
|
||||
assert document.revision() == revision
|
||||
|
||||
|
||||
def test_signing_preview_retries_wrong_detail_and_ignores_stale_response(
|
||||
application: QApplication,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
requests = []
|
||||
|
||||
def defer_detail(function: Any, prescription_id: int, *, on_success: Any, on_error: Any) -> None:
|
||||
requests.append((prescription_id, on_success))
|
||||
|
||||
monkeypatch.setattr(dialog_module, "run_async", defer_detail)
|
||||
seed = {"id": 72, "esign": {"status": "pending"}}
|
||||
repository = SimpleNamespace(get_prescription=lambda _prescription_id: None)
|
||||
preview = PrescriptionSigningPreview(repository, seed)
|
||||
assert "正在加载" in preview.status_label.text()
|
||||
assert requests[0][0] == 72
|
||||
preview.set_esign_state({"status": "signed", "doctor_signer_name": "签名医生"})
|
||||
|
||||
herbs = [{"name": "甘草", "dosage": 3}]
|
||||
requests[0][1]({"id": 73, "patient_name": "其他患者", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
assert "不匹配" in preview.status_label.text() and not preview.retry_button.isHidden()
|
||||
preview.retry_button.click()
|
||||
assert requests[1][0] == 72
|
||||
requests[0][1](seed | {"patient_name": "过时结果", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
requests[1][1](seed | {"patient_name": "当前患者", "herbs": herbs})
|
||||
assert preview.paper is not None
|
||||
text = preview.paper.toPlainText()
|
||||
assert "当前患者" in text and "甘草 (3克)" in text and "签名医生" in text
|
||||
|
||||
|
||||
def test_signing_preview_renders_an_intentionally_empty_saved_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 73,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "系统代开诊断",
|
||||
"is_system_auto": 1,
|
||||
"herbs": [],
|
||||
})
|
||||
preview = PrescriptionSigningPreview(
|
||||
SimpleNamespace(get_prescription=lambda _prescription_id: prescription),
|
||||
{"id": 73},
|
||||
)
|
||||
assert preview.paper is not None
|
||||
for text in ("虚构患者", "系统代开诊断", "暂无药材明细"):
|
||||
assert text in preview.paper.toPlainText()
|
||||
|
||||
|
||||
def test_unsigned_draft_shows_signing_state_before_audit() -> None:
|
||||
|
||||
@@ -740,7 +740,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
|
||||
|
||||
assert repository.queue_calls == 4
|
||||
assert repository.detail_calls == 1
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")]
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
|
||||
assert page.queue_list.item(0) is first_item
|
||||
assert page.queue_list.itemWidget(first_item) is first_row
|
||||
assert first_item.data(Qt.ItemDataRole.UserRole)["server_revision"] == 4
|
||||
@@ -748,7 +748,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
|
||||
|
||||
page.refresh()
|
||||
assert repository.detail_calls == 2
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")]
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
|
||||
assert page.queue_list.item(0) is first_item
|
||||
|
||||
page.close()
|
||||
@@ -1683,14 +1683,14 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
|
||||
page._select_record(detail["appointment"])
|
||||
application.processEvents()
|
||||
|
||||
assert analysis_calls == [(233, "qwen"), (233, "openai")]
|
||||
assert analysis_calls == [(233, "qwen"), (233, "openai"), (233, "doubao")]
|
||||
assert [
|
||||
(
|
||||
page.ai_analysis_model_selector.itemText(index),
|
||||
page.ai_analysis_model_selector.itemData(index),
|
||||
)
|
||||
for index in range(page.ai_analysis_model_selector.count())
|
||||
] == [("千问", "qwen"), ("OpenAI", "openai")]
|
||||
] == [("千问", "qwen"), ("OpenAI", "openai"), ("豆包", "doubao")]
|
||||
assert page.ai_analysis_model_selector.currentData() == "qwen"
|
||||
assert page._ai_analysis_state == "success"
|
||||
assert page.ai_analysis_stack.currentWidget() is page.ai_analysis_content_page
|
||||
@@ -1798,7 +1798,7 @@ def test_reception_dual_ai_queues_openai_only_after_qwen_is_visible(
|
||||
assert len(queued_async) == 2
|
||||
assert calls == []
|
||||
assert page.ai_analysis_model_selector.currentData() == "qwen"
|
||||
assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting"}
|
||||
assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting", "doubao": "waiting"}
|
||||
|
||||
qwen_result = queued_async[1]["function"](*queued_async[1]["args"])
|
||||
assert calls == [(283, "qwen")]
|
||||
@@ -2009,6 +2009,7 @@ def test_reception_ai_analysis_permission_error_retry_states(
|
||||
(234, "qwen"),
|
||||
(234, "qwen"),
|
||||
(234, "openai"),
|
||||
(234, "doubao"),
|
||||
]
|
||||
assert page._ai_analysis_state == "success"
|
||||
assert page.ai_analysis_expand_button.isEnabled()
|
||||
@@ -2063,14 +2064,16 @@ def test_saved_diagnosis_forces_a_fresh_structured_ai_analysis(
|
||||
PermissionSet(["tcm.diagnosis/aiAnalysis"]),
|
||||
)
|
||||
page.refresh()
|
||||
assert repository.analysis_calls == [(238, "qwen"), (238, "openai")]
|
||||
assert repository.analysis_calls == [(238, "qwen"), (238, "openai"), (238, "doubao")]
|
||||
|
||||
page._diagnosis_saved()
|
||||
assert repository.analysis_calls == [
|
||||
(238, "qwen"),
|
||||
(238, "openai"),
|
||||
(238, "doubao"),
|
||||
(238, "qwen"),
|
||||
(238, "openai"),
|
||||
(238, "doubao"),
|
||||
]
|
||||
assert "第 2 次qwen分析" in page.ai_risk_label.text()
|
||||
|
||||
@@ -2172,7 +2175,7 @@ def test_ai_analysis_dialog_switches_complete_cached_payloads_without_requests(
|
||||
calls_before_dialog = list(repository.analysis_calls)
|
||||
page.ai_analysis_expand_button.click()
|
||||
|
||||
assert calls_before_dialog == [(239, "qwen"), (239, "openai")]
|
||||
assert calls_before_dialog == [(239, "qwen"), (239, "openai"), (239, "doubao")]
|
||||
assert repository.analysis_calls == calls_before_dialog
|
||||
assert len(dialogs) == 1
|
||||
dialog = dialogs[0]
|
||||
|
||||
@@ -782,6 +782,24 @@ def test_remote_diagnosis_ai_stream_normalises_chunks_in_order() -> None:
|
||||
assert client.post_calls == []
|
||||
|
||||
|
||||
def test_remote_diagnosis_ai_stream_sends_only_a_whitelisted_selected_model() -> None:
|
||||
payloads: list[dict[str, Any]] = []
|
||||
|
||||
class StreamingClient(RecordingClient):
|
||||
def post_event_stream(self, endpoint: str, payload: dict[str, Any], **kwargs: Any):
|
||||
payloads.append(dict(payload))
|
||||
yield {"event": "done", "data": {"model_label": "豆包", "answer": "完成"}}
|
||||
|
||||
repository = RemoteDoctorRepository(StreamingClient())
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", task="summary", model="doubao"))
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", task="summary"))
|
||||
assert payloads[0]["model"] == "doubao"
|
||||
assert "model" not in payloads[1]
|
||||
with pytest.raises(ValueError, match="qwen, openai or doubao"):
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", model="deepseek"))
|
||||
assert len(payloads) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status_code", [404, 405])
|
||||
def test_remote_diagnosis_ai_stream_falls_back_for_missing_route(status_code: int) -> None:
|
||||
class MissingStreamClient(RecordingClient):
|
||||
@@ -915,7 +933,7 @@ def test_remote_diagnosis_ai_analysis_uses_exact_post_contract() -> None:
|
||||
|
||||
calls_before_validation = list(client.post_calls)
|
||||
timeouts_before_validation = list(client.timeouts)
|
||||
with pytest.raises(ValueError, match="qwen or openai"):
|
||||
with pytest.raises(ValueError, match="qwen, openai or doubao"):
|
||||
repository.get_diagnosis_ai_analysis(501, model="invalid") # type: ignore[arg-type]
|
||||
with pytest.raises(ValueError, match="positive"):
|
||||
repository.get_diagnosis_ai_analysis(0)
|
||||
|
||||
@@ -167,6 +167,18 @@ def shell_window(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_minimize_preserves_session_and_close_requests_application_exit(
|
||||
shell_window: ShellWindow, application: QApplication
|
||||
) -> None:
|
||||
exits = []
|
||||
shell_window.close_requested.connect(lambda: exits.append(True))
|
||||
shell_window.showMinimized()
|
||||
application.processEvents()
|
||||
assert exits == []
|
||||
shell_window.close()
|
||||
assert exits == [True]
|
||||
|
||||
|
||||
def test_legacy_shell_matches_reference_geometry_at_both_acceptance_sizes(
|
||||
application: QApplication,
|
||||
shell_window: ShellWindow,
|
||||
|
||||
@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (
|
||||
from doctor_workstation import app as app_module
|
||||
from doctor_workstation.app import ApplicationController
|
||||
from doctor_workstation.config import AppConfig
|
||||
from doctor_workstation.core import Session
|
||||
from doctor_workstation.core.errors import AuthenticationExpiredError
|
||||
from doctor_workstation.services import DemoDoctorRepository
|
||||
from doctor_workstation.ui import login as login_module
|
||||
@@ -186,6 +187,65 @@ def test_controller_session_expiry_returns_to_login_once() -> None:
|
||||
assert messages == ["登录状态已失效,请重新登录。"]
|
||||
|
||||
|
||||
def test_idle_heartbeat_is_single_flight_and_offline_wake_observes_cutoff(monkeypatch: Any) -> None:
|
||||
now = [100.0]
|
||||
queued = []
|
||||
messages = []
|
||||
timer_delays = []
|
||||
session = Session(token="first", desktop_expires_at=200)
|
||||
repository = SimpleNamespace(desktop_heartbeat=lambda _token: 200)
|
||||
controller = SimpleNamespace(
|
||||
current_repository=repository, _desktop_session=session, _shutting_down=False,
|
||||
_heartbeat_pending=False, _next_heartbeat_at=100, _session_workers=object(),
|
||||
_desktop_timer=SimpleNamespace(start=timer_delays.append),
|
||||
_logout=lambda *, message: messages.append(message),
|
||||
)
|
||||
controller._check_desktop_session = lambda: ApplicationController._check_desktop_session(controller)
|
||||
monkeypatch.setattr(app_module, "time", SimpleNamespace(time=lambda: now[0]))
|
||||
monkeypatch.setattr(app_module, "run_async", lambda fn, token, **opts: queued.append((fn, token, opts)))
|
||||
|
||||
controller._check_desktop_session()
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 1 and queued[0][:2] == (repository.desktop_heartbeat, "first")
|
||||
queued[0][2]["on_error"](RuntimeError("offline"))
|
||||
now[0] = 114
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 1
|
||||
now[0] = 115
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 2
|
||||
queued[1][2]["on_success"](400)
|
||||
assert session.desktop_expires_at == 200
|
||||
now[0] = 199.75
|
||||
controller._check_desktop_session()
|
||||
assert timer_delays[-1] == 250
|
||||
assert not messages
|
||||
now[0] = 205 # Resume with a heartbeat still in flight.
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 3
|
||||
assert messages == ["已到北京时间 05:00,请重新登录医生工作站。"]
|
||||
|
||||
|
||||
def test_old_worker_expiry_cannot_log_out_new_account() -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
errors: list[Exception] = []
|
||||
workers = []
|
||||
pool = SimpleNamespace(start=lambda worker, _priority: workers.append(worker))
|
||||
|
||||
def expired() -> None:
|
||||
raise AuthenticationExpiredError("first session expired", code=-1)
|
||||
|
||||
try:
|
||||
set_authentication_expired_handler(lambda error: errors.append(error) is None)
|
||||
widget_module.run_async(expired, on_error=errors.append, pool=pool)
|
||||
set_authentication_expired_handler(lambda error: errors.append(error) is None)
|
||||
workers[0].run()
|
||||
application.processEvents()
|
||||
assert not errors
|
||||
finally:
|
||||
set_authentication_expired_handler(None)
|
||||
|
||||
|
||||
def test_persisted_session_restore_blocks_manual_submit_before_worker_start(
|
||||
monkeypatch: Any,
|
||||
) -> None:
|
||||
|
||||
Reference in New Issue
Block a user