"""OS drag events use the existing note upload/save path and stay patient-scoped.""" from __future__ import annotations import json from pathlib import Path import httpx import pytest from PySide6.QtCore import QMimeData, QPoint, QPointF, Qt, QUrl from PySide6.QtGui import QDragEnterEvent, QDropEvent, QImage from PySide6.QtWidgets import QApplication from test_diagnosis_drawer_visual import ActionRepository, _open_dialog, _select_tab from doctor_workstation.services.api_client import ApiClient from doctor_workstation.services.repository import RemoteDoctorRepository from doctor_workstation.ui.dialogs import diagnosis as diagnosis_module from doctor_workstation.ui.image_drop import capture_image_drop @pytest.fixture(scope="module") def application(): return QApplication.instance() or QApplication([]) @pytest.fixture(autouse=True) def immediate_async(monkeypatch): def run(function, *args, on_success=None, on_error=None, on_finished=None, **_kwargs): try: result = function(*args) except Exception as error: if on_error: on_error(error) else: if on_success: on_success(result) finally: if on_finished: on_finished() return object() monkeypatch.setattr(diagnosis_module, "run_async", run) class UploadRepository(ActionRepository): def __init__(self): super().__init__() self.uploads = [] self.fail_at = 0 def get_doctor_notes(self, diagnosis_id): self.notes_calls += 1 return [] def upload_material(self, path, material_type): assert Path(path).is_file() assert not QImage(path).isNull() self.uploads.append((path, material_type)) if len(self.uploads) == self.fail_at: raise RuntimeError("图片上传失败") return f"https://media.example.invalid/{len(self.uploads)}.png" @pytest.fixture def workspace(application): repository = UploadRepository() dialog = _open_dialog(application, (1280, 900), mode="edit", repository=repository) _select_tab(dialog, "notes") try: yield dialog, repository finally: dialog.close() application.processEvents() def image_mime(tmp_path, count=1): paths = [] for index in range(count): path = tmp_path / f"image-{index}.png" picture = QImage(12, 12, QImage.Format.Format_RGB32) picture.fill(Qt.GlobalColor.blue) assert picture.save(str(path)) paths.append(path) mime = QMimeData() mime.setUrls([QUrl.fromLocalFile(str(path)) for path in paths]) return mime, paths def send_drop(target, mime): actions = Qt.DropAction.CopyAction | Qt.DropAction.MoveAction enter = QDragEnterEvent(QPoint(8, 8), actions, mime, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) QApplication.sendEvent(target, enter) if not enter.isAccepted(): return False event = QDropEvent(QPointF(8, 8), actions, mime, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) event.setDropAction(Qt.DropAction.MoveAction) QApplication.sendEvent(target, event) QApplication.processEvents() assert event.dropAction() == Qt.DropAction.CopyAction return event.isAccepted() @pytest.mark.parametrize("kind", ["tongue_images", "report_files"]) def test_drop_multiple_files_on_button_uploads_then_saves_one_note(workspace, tmp_path, kind): dialog, repository = workspace mime, original_paths = image_mime(tmp_path, 2) timeline = dialog.drawer_notes_timeline target = timeline.tongue_button if kind == "tongue_images" else timeline.report_button assert send_drop(target, mime) assert [item[1] for item in repository.uploads] == ["image", "image"] note = [payload for name, payload in repository.action_calls if name == "note"] assert note == [(501, "", {kind: [ "https://media.example.invalid/1.png", "https://media.example.invalid/2.png", ]})] assert all(path.exists() for path in original_paths) assert all(not Path(path).exists() for path, _kind in repository.uploads) assert not dialog._notes_mutation_busy assert repository.notes_calls >= 2 def test_drop_memory_image_on_blank_scroll_area_chooses_report(workspace, monkeypatch): dialog, repository = workspace selected = [] monkeypatch.setattr(dialog, "_choose_dropped_image_type", lambda count: selected.append(count) or "report_files") mime = QMimeData() image = QImage(10, 10, QImage.Format.Format_RGB32) image.fill(Qt.GlobalColor.red) mime.setImageData(image) assert send_drop(dialog._tab_pages["notes"].viewport(), mime) assert selected == [1] assert repository.uploads[0][1] == "image" assert any("report_files" in payload[2] for name, payload in repository.action_calls if name == "note") def test_cancel_category_does_not_upload_or_save(workspace, tmp_path, monkeypatch): dialog, repository = workspace mime, _paths = image_mime(tmp_path) monkeypatch.setattr(dialog, "_choose_dropped_image_type", lambda _count: "") assert send_drop(dialog.drawer_notes_timeline, mime) assert not repository.uploads assert not any(name == "note" for name, _payload in repository.action_calls) def test_readonly_or_missing_note_permission_rejects_drop(workspace, tmp_path): dialog, repository = workspace mime, _paths = image_mime(tmp_path) timeline = dialog.drawer_notes_timeline for editable, permitted in ((False, True), (True, False)): dialog._editable, dialog._can_note_add = editable, permitted timeline.set_editable(editable and permitted) assert not timeline.acceptDrops() assert not send_drop(timeline, mime) dialog._drop_doctor_note_images(capture_image_drop(mime), "tongue_images") QApplication.processEvents() assert not repository.uploads def test_upload_busy_rejects_second_drop_and_does_not_cross_patient(workspace, tmp_path, monkeypatch): dialog, repository = workspace mime, _paths = image_mime(tmp_path) pending = [] monkeypatch.setattr(diagnosis_module, "run_async", lambda operation, **callbacks: pending.append((operation, callbacks))) assert send_drop(dialog.drawer_notes_timeline.tongue_button, mime) assert dialog._notes_mutation_busy assert not send_drop(dialog.drawer_notes_timeline, mime) assert len(pending) == 1 operation, callbacks = pending[0] dialog._diagnosis_id = 777 dialog._generation += 1 dialog._notes_mutation_generation += 1 result = operation() callbacks["on_success"](result) callbacks["on_finished"]() notes = [payload for name, payload in repository.action_calls if name == "note"] assert notes[0][0] == 501 assert dialog._diagnosis_id == 777 def test_queued_drop_does_not_attach_after_patient_switch(workspace, tmp_path): dialog, repository = workspace mime, _paths = image_mime(tmp_path) dialog._drop_doctor_note_images(capture_image_drop(mime), "tongue_images") dialog._diagnosis_id = 777 dialog._generation += 1 QApplication.processEvents() assert not repository.uploads def test_later_upload_failure_saves_prior_images_and_reports_partial_result(workspace, tmp_path): dialog, repository = workspace repository.fail_at = 2 mime, _paths = image_mime(tmp_path, 3) assert send_drop(dialog.drawer_notes_timeline.tongue_button, mime) notes = [payload for name, payload in repository.action_calls if name == "note"] assert notes == [(501, "", {"tongue_images": ["https://media.example.invalid/1.png"]})] assert len(repository.uploads) == 2 assert "已保存 1/3 张" in dialog.drawer_banner.label.text() assert "只重试未成功" in dialog.drawer_banner.label.text() assert not dialog._notes_mutation_busy def test_move_only_drag_is_rejected_to_preserve_original(workspace, tmp_path): dialog, repository = workspace mime, paths = image_mime(tmp_path) target = dialog.drawer_notes_timeline.tongue_button enter = QDragEnterEvent(QPoint(8, 8), Qt.DropAction.MoveAction, mime, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) QApplication.sendEvent(target, enter) assert not enter.isAccepted() event = QDropEvent(QPointF(8, 8), Qt.DropAction.MoveAction, mime, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) assert dialog.drawer_notes_timeline.eventFilter(target, event) assert not event.isAccepted() QApplication.processEvents() assert not repository.uploads assert paths[0].exists() def test_report_picture_uses_image_upload_endpoint_but_saves_as_report(workspace, tmp_path): dialog, _repository = workspace calls = [] def api(request): endpoint = request.url.path.removeprefix("/adminapi/") calls.append(endpoint) if endpoint == "upload/image": assert request.method == "POST" assert b"image/png" in request.content result = {"uri": "https://media.example.invalid/report.png"} elif endpoint == "doctor.appointment/addDoctorNote": assert json.loads(request.content) == { "diagnosis_id": 501, "content": "", "report_files": ["https://media.example.invalid/report.png"], } result = {"id": 123} else: assert endpoint == "doctor.appointment/doctorNotes" result = [] return httpx.Response(200, json={"code": 1, "data": result}) client = ApiClient("https://example.test/adminapi/", transport=httpx.MockTransport(api)) dialog.repository = RemoteDoctorRepository(client) mime, _paths = image_mime(tmp_path) assert send_drop(dialog.drawer_notes_timeline.report_button, mime) assert calls == ["upload/image", "doctor.appointment/addDoctorNote", "doctor.appointment/doctorNotes"]