更新
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
"""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"]
|
||||
@@ -0,0 +1,430 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import FrozenInstanceError
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import shiboken6
|
||||
from PySide6.QtCore import QBuffer, QIODevice, QMimeData, QUrl
|
||||
from PySide6.QtGui import QImage, QPixmap
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.ui import image_drop
|
||||
from doctor_workstation.ui.image_drop import (
|
||||
can_drop_images,
|
||||
capture_image_drop,
|
||||
materialize_image_drop,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
def _image(width: int = 12, height: int = 8) -> QImage:
|
||||
image = QImage(width, height, QImage.Format.Format_RGB32)
|
||||
image.fill(0xFF668877)
|
||||
return image
|
||||
|
||||
|
||||
def _image_bytes(image_format: str, width: int = 12, height: int = 8) -> bytes:
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert _image(width, height).save(buffer, image_format)
|
||||
return bytes(buffer.data())
|
||||
|
||||
|
||||
def _png(width: int = 12, height: int = 8) -> bytes:
|
||||
return _image_bytes("PNG", width, height)
|
||||
|
||||
|
||||
def _local_mime(*paths: Path) -> QMimeData:
|
||||
mime = QMimeData()
|
||||
mime.setUrls([QUrl.fromLocalFile(str(path)) for path in paths])
|
||||
return mime
|
||||
|
||||
|
||||
def _raw_mime(payload: bytes, media_type: str = "image/png") -> QMimeData:
|
||||
mime = QMimeData()
|
||||
mime.setData(media_type, payload)
|
||||
return mime
|
||||
|
||||
|
||||
def _mock_download(monkeypatch: pytest.MonkeyPatch, handler: object) -> None:
|
||||
monkeypatch.setattr(
|
||||
image_drop,
|
||||
"_new_download_client",
|
||||
lambda: httpx.Client(transport=httpx.MockTransport(handler), follow_redirects=False),
|
||||
)
|
||||
|
||||
|
||||
def test_local_images_are_validated_by_content_and_copied_without_touching_originals(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
first = tmp_path / "第一张 图片.jpg"
|
||||
second = tmp_path / "second.png"
|
||||
first.write_bytes(_png())
|
||||
second.write_bytes(_png(10, 20))
|
||||
mime = _local_mime(first, second)
|
||||
assert can_drop_images(mime)
|
||||
drop = capture_image_drop(mime)
|
||||
assert drop.count == 2
|
||||
with materialize_image_drop(drop) as paths:
|
||||
assert len(paths) == 2
|
||||
assert all(path.suffix == ".png" for path in paths)
|
||||
assert paths[0].read_bytes() == first.read_bytes()
|
||||
assert paths[1].read_bytes() == second.read_bytes()
|
||||
assert all(path.parent != tmp_path for path in paths)
|
||||
assert all(not path.exists() for path in paths)
|
||||
assert first.exists() and second.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source_kind", ["local", "raw"])
|
||||
def test_bmp_is_converted_to_server_supported_png(tmp_path: Path, source_kind: str) -> None:
|
||||
original = tmp_path / "image.bmp"
|
||||
content = _image_bytes("BMP")
|
||||
original.write_bytes(content)
|
||||
mime = _local_mime(original) if source_kind == "local" else _raw_mime(content, "image/bmp")
|
||||
with materialize_image_drop(capture_image_drop(mime)) as paths:
|
||||
assert paths[0].suffix == ".png"
|
||||
assert paths[0].read_bytes().startswith(b"\x89PNG\r\n\x1a\n")
|
||||
converted = QImage(str(paths[0]))
|
||||
assert converted.size() == _image().size()
|
||||
assert converted.pixelColor(0, 0) == _image().pixelColor(0, 0)
|
||||
assert original.read_bytes() == content
|
||||
assert not paths[0].exists()
|
||||
|
||||
|
||||
def test_conversion_rechecks_byte_limit_and_cleans_up(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# A genuine 1-pixel BMP is smaller than its genuine PNG representation.
|
||||
content = _image_bytes("BMP", 1, 1)
|
||||
assert len(content) < len(_png(1, 1))
|
||||
monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", len(content))
|
||||
monkeypatch.setattr(
|
||||
image_drop, "TemporaryDirectory",
|
||||
lambda prefix: TemporaryDirectory(prefix=prefix, dir=tmp_path),
|
||||
)
|
||||
drop = capture_image_drop(_raw_mime(content, "image/bmp"))
|
||||
with pytest.raises(ValueError, match="10 MiB"), materialize_image_drop(drop):
|
||||
pytest.fail("converted image exceeded upload limit")
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_hover_never_reads_files_downloads_or_decodes(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
def unexpected(*args: object, **kwargs: object) -> None:
|
||||
pytest.fail("hover must not access images")
|
||||
|
||||
monkeypatch.setattr(Path, "is_file", unexpected)
|
||||
monkeypatch.setattr(image_drop, "_download_image", unexpected)
|
||||
monkeypatch.setattr(image_drop, "QImageReader", unexpected)
|
||||
assert can_drop_images(_local_mime(tmp_path / "not-yet-existing.png"))
|
||||
assert can_drop_images(_raw_mime(b"undecodable"))
|
||||
mime = QMimeData()
|
||||
mime.setHtml('<a href="https://site.invalid"><img src="https://img.invalid/a.png"></a>')
|
||||
assert can_drop_images(mime)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pixmap", [False, True])
|
||||
def test_memory_snapshot_survives_mime_deletion_and_works_in_worker(
|
||||
application: QApplication, pixmap: bool,
|
||||
) -> None:
|
||||
original = _image()
|
||||
mime = QMimeData()
|
||||
mime.setImageData(QPixmap.fromImage(original) if pixmap else original)
|
||||
drop = capture_image_drop(mime)
|
||||
original.fill(0)
|
||||
shiboken6.delete(mime)
|
||||
assert drop.count == 1
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
drop.sources = ()
|
||||
|
||||
def resolve() -> bytes:
|
||||
with materialize_image_drop(drop) as paths:
|
||||
return paths[0].read_bytes()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as worker:
|
||||
content = worker.submit(resolve).result(timeout=10)
|
||||
assert content == _png()
|
||||
|
||||
|
||||
def test_local_files_take_precedence_over_duplicate_memory_picture(tmp_path: Path) -> None:
|
||||
path = tmp_path / "image.png"
|
||||
path.write_bytes(_png())
|
||||
mime = _local_mime(path)
|
||||
mime.setImageData(_image(3, 3))
|
||||
drop = capture_image_drop(mime)
|
||||
assert drop.count == 1
|
||||
with materialize_image_drop(drop) as paths:
|
||||
assert paths[0].read_bytes() == path.read_bytes()
|
||||
|
||||
|
||||
def test_raw_image_snapshot_keeps_no_mime_reference() -> None:
|
||||
payload = _png()
|
||||
mime = _raw_mime(payload)
|
||||
drop = capture_image_drop(mime)
|
||||
mime.setData("image/png", b"modified")
|
||||
shiboken6.delete(mime)
|
||||
with materialize_image_drop(drop) as paths:
|
||||
assert paths[0].read_bytes() == payload
|
||||
|
||||
|
||||
def test_browser_image_src_wins_over_enclosing_link_and_uri_list(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
urls: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
urls.append(str(request.url))
|
||||
assert "authorization" not in request.headers
|
||||
assert "cookie" not in request.headers
|
||||
return httpx.Response(200, content=_png(), headers={"Content-Type": "image/png"})
|
||||
|
||||
_mock_download(monkeypatch, handler)
|
||||
mime = QMimeData()
|
||||
mime.setUrls([QUrl("https://site.invalid/article")])
|
||||
mime.setHtml(
|
||||
'<a href="https://site.invalid/article">'
|
||||
'<img src="https://cdn.invalid/a.png?width=2&height=3"></a>'
|
||||
)
|
||||
with materialize_image_drop(capture_image_drop(mime)) as paths:
|
||||
assert len(paths) == 1
|
||||
assert urls == ["https://cdn.invalid/a.png?width=2&height=3"]
|
||||
|
||||
|
||||
def test_multiple_html_images_and_base64_data_are_preserved() -> None:
|
||||
payload = _png()
|
||||
encoded = base64.b64encode(payload).decode("ascii")
|
||||
mime = QMimeData()
|
||||
mime.setHtml(f'<img src="data:image/png;base64,{encoded}">' * 2)
|
||||
drop = capture_image_drop(mime)
|
||||
assert drop.count == 2
|
||||
with materialize_image_drop(drop) as paths:
|
||||
assert [path.read_bytes() for path in paths] == [payload, payload]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("representation", ["text", "url"])
|
||||
def test_remote_image_url_can_be_dropped(
|
||||
monkeypatch: pytest.MonkeyPatch, representation: str,
|
||||
) -> None:
|
||||
_mock_download(monkeypatch, lambda _: httpx.Response(200, content=_png()))
|
||||
mime = QMimeData()
|
||||
if representation == "url":
|
||||
mime.setUrls([QUrl("https://cdn.invalid/image?id=123")])
|
||||
else:
|
||||
mime.setText("https://cdn.invalid/image?id=123")
|
||||
assert can_drop_images(mime)
|
||||
with materialize_image_drop(capture_image_drop(mime)) as paths:
|
||||
assert paths[0].read_bytes() == _png()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["C:/private/photo.png", "file:///C:/private/photo.png", "hello"])
|
||||
def test_plain_text_is_not_interpreted_as_local_file(text: str) -> None:
|
||||
mime = QMimeData()
|
||||
mime.setText(text)
|
||||
assert not can_drop_images(mime)
|
||||
with pytest.raises(ValueError, match="请拖入图片"):
|
||||
capture_image_drop(mime)
|
||||
|
||||
|
||||
def test_mixed_valid_and_invalid_files_fail_before_yield_and_clean_up(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
good, bad = tmp_path / "good.png", tmp_path / "fake.png"
|
||||
good.write_bytes(_png())
|
||||
bad.write_text("not a real image", encoding="utf-8")
|
||||
monkeypatch.setattr(
|
||||
image_drop, "TemporaryDirectory",
|
||||
lambda prefix: TemporaryDirectory(prefix=prefix, dir=tmp_path),
|
||||
)
|
||||
with (
|
||||
pytest.raises(ValueError, match="不是受支持的图片"),
|
||||
materialize_image_drop(capture_image_drop(_local_mime(good, bad))),
|
||||
):
|
||||
pytest.fail("must validate the full batch before uploading anything")
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == ["fake.png", "good.png"]
|
||||
|
||||
|
||||
def test_temp_files_are_cleaned_when_upload_raises() -> None:
|
||||
with (
|
||||
pytest.raises(RuntimeError, match="upload failed"),
|
||||
materialize_image_drop(capture_image_drop(_raw_mime(_png()))) as paths,
|
||||
):
|
||||
raise RuntimeError("upload failed")
|
||||
assert not paths[0].parent.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["local", "html"])
|
||||
def test_batch_limit_is_checked_without_io(tmp_path: Path, kind: str) -> None:
|
||||
if kind == "local":
|
||||
mime = _local_mime(*(tmp_path / f"{index}.png" for index in range(21)))
|
||||
else:
|
||||
mime = QMimeData()
|
||||
mime.setHtml('<img src="https://cdn.invalid/a.png">' * 21)
|
||||
with pytest.raises(ValueError, match="20"):
|
||||
capture_image_drop(mime)
|
||||
|
||||
|
||||
def test_exactly_twenty_images_are_allowed(tmp_path: Path) -> None:
|
||||
path = tmp_path / "image.png"
|
||||
path.write_bytes(_png())
|
||||
with materialize_image_drop(capture_image_drop(_local_mime(*([path] * 20)))) as paths:
|
||||
assert len(paths) == 20
|
||||
|
||||
|
||||
def test_local_byte_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 100)
|
||||
path = tmp_path / "large.png"
|
||||
path.write_bytes(b"a" * 101)
|
||||
with (
|
||||
pytest.raises(ValueError, match="10 MiB"),
|
||||
materialize_image_drop(capture_image_drop(_local_mime(path))),
|
||||
):
|
||||
pytest.fail("oversized image accepted")
|
||||
|
||||
|
||||
def test_raw_byte_limit_is_checked_during_capture(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 10)
|
||||
with pytest.raises(ValueError, match="10 MiB"):
|
||||
capture_image_drop(_raw_mime(b"a" * 11))
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_for_encoded_and_memory_images(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(image_drop, "MAX_IMAGE_PIXELS", 50)
|
||||
with (
|
||||
pytest.raises(ValueError, match="像素过大"),
|
||||
materialize_image_drop(capture_image_drop(_raw_mime(_png()))),
|
||||
):
|
||||
pytest.fail("large raster accepted")
|
||||
mime = QMimeData()
|
||||
mime.setImageData(_image())
|
||||
with pytest.raises(ValueError, match="像素过大"):
|
||||
capture_image_drop(mime)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
b'<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>',
|
||||
b"<html><body>login</body></html>",
|
||||
b"not an image",
|
||||
])
|
||||
def test_non_raster_content_cannot_masquerade_as_png(payload: bytes) -> None:
|
||||
with (
|
||||
pytest.raises(ValueError, match="不是受支持的图片"),
|
||||
materialize_image_drop(capture_image_drop(_raw_mime(payload))),
|
||||
):
|
||||
pytest.fail("invalid image accepted")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"data:image/svg+xml;base64,PHN2Zy8+",
|
||||
"data:image/png;base64,not-base64!",
|
||||
"data:image/png,not-base64",
|
||||
])
|
||||
def test_invalid_data_images_fail(value: str) -> None:
|
||||
mime = QMimeData()
|
||||
mime.setText(value)
|
||||
with pytest.raises(ValueError), materialize_image_drop(capture_image_drop(mime)):
|
||||
pytest.fail("invalid data image accepted")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("redirect", ["file:///C:/private/image.png", "javascript:alert(1)"])
|
||||
def test_unsafe_redirects_are_never_requested(
|
||||
monkeypatch: pytest.MonkeyPatch, redirect: str,
|
||||
) -> None:
|
||||
requests: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(str(request.url))
|
||||
return httpx.Response(302, headers={"Location": redirect})
|
||||
|
||||
_mock_download(monkeypatch, handler)
|
||||
mime = QMimeData()
|
||||
mime.setText("https://cdn.invalid/a.png")
|
||||
with (
|
||||
pytest.raises(ValueError, match="HTTP/HTTPS"),
|
||||
materialize_image_drop(capture_image_drop(mime)),
|
||||
):
|
||||
pytest.fail("unsafe redirect accepted")
|
||||
assert requests == ["https://cdn.invalid/a.png"]
|
||||
|
||||
|
||||
def test_redirects_do_not_forward_cookies(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
requests: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(str(request.url))
|
||||
assert "cookie" not in request.headers
|
||||
assert "authorization" not in request.headers
|
||||
if len(requests) == 1:
|
||||
return httpx.Response(302, headers={"Location": "/b.png", "Set-Cookie": "token=secret"})
|
||||
return httpx.Response(200, content=_png())
|
||||
|
||||
_mock_download(monkeypatch, handler)
|
||||
mime = QMimeData()
|
||||
mime.setText("https://cdn.invalid/a.png")
|
||||
with materialize_image_drop(capture_image_drop(mime)) as paths:
|
||||
assert paths[0].read_bytes() == _png()
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,headers", [
|
||||
(401, {}),
|
||||
(403, {}),
|
||||
(200, {"Content-Type": "text/html"}),
|
||||
])
|
||||
def test_login_and_webpage_sources_explain_save_locally(
|
||||
monkeypatch: pytest.MonkeyPatch, status: int, headers: dict[str, str],
|
||||
) -> None:
|
||||
_mock_download(monkeypatch, lambda _: httpx.Response(status, headers=headers, content=b"login"))
|
||||
mime = QMimeData()
|
||||
mime.setText("https://site.invalid/private.png")
|
||||
with (
|
||||
pytest.raises(ValueError, match="先保存本地再拖入"),
|
||||
materialize_image_drop(capture_image_drop(mime)),
|
||||
):
|
||||
pytest.fail("login page accepted")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("declared_length", [True, False])
|
||||
def test_download_size_limit_uses_headers_and_actual_stream(
|
||||
monkeypatch: pytest.MonkeyPatch, declared_length: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 100)
|
||||
|
||||
class OversizedStream(httpx.SyncByteStream):
|
||||
def __iter__(self):
|
||||
yield b"a" * 60
|
||||
yield b"b" * 60
|
||||
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
headers = {"Content-Length": "120"} if declared_length else {}
|
||||
return httpx.Response(200, headers=headers, stream=OversizedStream())
|
||||
|
||||
_mock_download(monkeypatch, handler)
|
||||
mime = QMimeData()
|
||||
mime.setText("https://cdn.invalid/a.png")
|
||||
with (
|
||||
pytest.raises(ValueError, match="10 MiB"),
|
||||
materialize_image_drop(capture_image_drop(mime)),
|
||||
):
|
||||
pytest.fail("oversized response accepted")
|
||||
|
||||
|
||||
def test_embedded_url_credentials_are_rejected() -> None:
|
||||
mime = QMimeData()
|
||||
mime.setText("https://token:secret@cdn.invalid/a.png")
|
||||
with pytest.raises(ValueError, match="HTTP/HTTPS"):
|
||||
capture_image_drop(mime)
|
||||
@@ -342,7 +342,7 @@ def test_local_audio_dialog_lists_status_and_retry_controls(tmp_path: Path) -> N
|
||||
application.processEvents()
|
||||
try:
|
||||
assert dialog.objectName() == "LocalAudioQueueDialog"
|
||||
assert dialog.table.columnCount() == 8
|
||||
assert dialog.table.columnCount() == 9
|
||||
assert dialog.table.rowCount() == 2
|
||||
assert dialog.summary_failed.text() == "失败 1"
|
||||
assert dialog.summary_uploaded.text() == "已上传 1"
|
||||
@@ -350,7 +350,8 @@ def test_local_audio_dialog_lists_status_and_retry_controls(tmp_path: Path) -> N
|
||||
assert dialog.table.horizontalHeaderItem(1).text() == "通话记录 ID"
|
||||
assert dialog.table.horizontalHeaderItem(2).text() == "房间号"
|
||||
assert dialog.table.horizontalHeaderItem(5).text() == "上传状态"
|
||||
assert dialog.table.horizontalHeaderItem(6).text() == "失败原因"
|
||||
assert dialog.table.horizontalHeaderItem(6).text() == "文字状态"
|
||||
assert dialog.table.horizontalHeaderItem(7).text() == "失败原因"
|
||||
assert dialog.table.columnWidth(dialog._room_column) == 180
|
||||
rooms = {
|
||||
dialog.table.item(row, 2).text() for row in range(dialog.table.rowCount())
|
||||
@@ -400,7 +401,7 @@ def test_global_local_audio_dialog_lists_all_diagnoses_and_outcomes(
|
||||
application.processEvents()
|
||||
try:
|
||||
assert dialog.title_label.text() == "本机录音上传管理"
|
||||
assert dialog.table.columnCount() == 9
|
||||
assert dialog.table.columnCount() == 10
|
||||
assert dialog.table.rowCount() == 2
|
||||
assert dialog.table.horizontalHeaderItem(1).text() == "诊单 ID"
|
||||
assert dialog.table.horizontalHeaderItem(2).text() == "通话记录 ID"
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QLabel, QPushButton
|
||||
|
||||
from doctor_workstation.ui.dialogs.local_audio_queue import LocalAudioQueueDialog
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def application() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
def _record(
|
||||
tmp_path: Path,
|
||||
*,
|
||||
status: str = "uploaded",
|
||||
transcription_status: str = "pending",
|
||||
transcription_error: str = "",
|
||||
) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
id=1,
|
||||
diagnosis_id=8169,
|
||||
call_record_id=901,
|
||||
room_id="12345678",
|
||||
file_path=tmp_path / "synthetic-recording.webm",
|
||||
size_bytes=2048,
|
||||
status=status,
|
||||
error_text="",
|
||||
uploaded_url="cos://recordings/synthetic.webm" if status == "uploaded" else "",
|
||||
attempts=1,
|
||||
created_at="2026-11-06T01:00:00+00:00",
|
||||
exists=False,
|
||||
transcription_status=transcription_status,
|
||||
transcription_error=transcription_error,
|
||||
)
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self, record: SimpleNamespace) -> None:
|
||||
self.record = record
|
||||
self.upload_retries: list[int] = []
|
||||
|
||||
def list_records(self, *, diagnosis_id: int | None) -> list[Any]:
|
||||
if diagnosis_id is None or diagnosis_id == self.record.diagnosis_id:
|
||||
return [self.record]
|
||||
return []
|
||||
|
||||
def retry(self, record_id: int) -> None:
|
||||
self.upload_retries.append(record_id)
|
||||
|
||||
|
||||
class _LegacyManager:
|
||||
def __init__(self, store: _Store) -> None:
|
||||
self.store = store
|
||||
self.uploads: list[int] = []
|
||||
self.pending_upload_scopes: list[int | None] = []
|
||||
|
||||
def submit_pending(self, *, diagnosis_id: int | None) -> list[Future[bool]]:
|
||||
self.pending_upload_scopes.append(diagnosis_id)
|
||||
return []
|
||||
|
||||
def submit(self, record_id: int) -> Future[bool]:
|
||||
self.uploads.append(record_id)
|
||||
return Future()
|
||||
|
||||
|
||||
class _Manager(_LegacyManager):
|
||||
def __init__(self, store: _Store) -> None:
|
||||
super().__init__(store)
|
||||
self.transcriptions: list[int] = []
|
||||
self.pending_transcription_scopes: list[int | None] = []
|
||||
|
||||
def submit_pending_transcriptions(
|
||||
self, *, diagnosis_id: int | None
|
||||
) -> list[Future[bool]]:
|
||||
self.pending_transcription_scopes.append(diagnosis_id)
|
||||
return []
|
||||
|
||||
def submit_transcription(self, record_id: int) -> Future[bool]:
|
||||
self.transcriptions.append(record_id)
|
||||
self.store.record.transcription_status = "transcribing"
|
||||
self.store.record.transcription_error = ""
|
||||
return Future()
|
||||
|
||||
|
||||
def _buttons(dialog: LocalAudioQueueDialog) -> dict[str, QPushButton]:
|
||||
host = dialog.table.cellWidget(0, dialog._action_column)
|
||||
assert host is not None
|
||||
return {button.text(): button for button in host.findChildren(QPushButton)}
|
||||
|
||||
|
||||
def test_uploaded_record_with_failed_text_can_retry_without_uploading_again(
|
||||
application: QApplication, tmp_path: Path
|
||||
) -> None:
|
||||
record = _record(
|
||||
tmp_path,
|
||||
transcription_status="failed",
|
||||
transcription_error="文字保存失败,请稍后重试",
|
||||
)
|
||||
store = _Store(record)
|
||||
manager = _Manager(store)
|
||||
dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager)
|
||||
dialog.show()
|
||||
application.processEvents()
|
||||
try:
|
||||
assert dialog.table.item(0, dialog._status_column).text() == "已上传"
|
||||
assert dialog.table.item(0, dialog._transcription_column).text() == "生成失败"
|
||||
assert dialog.table.item(0, dialog._error_column).text() == (
|
||||
"文字:文字保存失败,请稍后重试"
|
||||
)
|
||||
assert dialog.summary_uploaded.text() == "已上传 1"
|
||||
assert dialog.summary_failed.text() == "失败 0"
|
||||
assert dialog.summary_transcription.text() == "文字未完成 1"
|
||||
assert not dialog.retry_failed_button.isEnabled()
|
||||
|
||||
QTest.mouseClick(_buttons(dialog)["重试文字"], Qt.MouseButton.LeftButton)
|
||||
application.processEvents()
|
||||
|
||||
assert manager.transcriptions == [record.id]
|
||||
assert manager.uploads == []
|
||||
assert store.upload_retries == []
|
||||
assert record.status == "uploaded"
|
||||
assert dialog.table.item(0, dialog._status_column).text() == "已上传"
|
||||
assert dialog.table.item(0, dialog._transcription_column).text() == "生成中"
|
||||
assert not _buttons(dialog)["文字生成中"].isEnabled()
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_transcribing_controls_are_disabled_and_polling_detects_completion(
|
||||
application: QApplication, tmp_path: Path
|
||||
) -> None:
|
||||
record = _record(tmp_path, transcription_status="transcribing")
|
||||
store = _Store(record)
|
||||
manager = _Manager(store)
|
||||
dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager)
|
||||
try:
|
||||
assert not _buttons(dialog)["文字生成中"].isEnabled()
|
||||
QTest.mouseClick(_buttons(dialog)["文字生成中"], Qt.MouseButton.LeftButton)
|
||||
assert manager.transcriptions == []
|
||||
|
||||
record.transcription_status = "completed"
|
||||
dialog.refresh_records()
|
||||
|
||||
assert dialog.table.item(0, dialog._transcription_column).text() == "已保存"
|
||||
assert dialog.summary_transcription.text() == "文字未完成 0"
|
||||
assert _buttons(dialog) == {}
|
||||
hint = dialog.findChild(QLabel, "LocalAudioQueueHint")
|
||||
assert hint is not None
|
||||
assert "视频录制回放 → 查看文字" in hint.text()
|
||||
assert "未分离说话人" in hint.text()
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("diagnosis_id", [8169, None])
|
||||
def test_pending_text_resumes_for_dialog_scope_and_has_separate_action(
|
||||
application: QApplication, tmp_path: Path, diagnosis_id: int | None
|
||||
) -> None:
|
||||
record = _record(tmp_path)
|
||||
store = _Store(record)
|
||||
manager = _Manager(store)
|
||||
dialog = LocalAudioQueueDialog(object(), diagnosis_id, store=store, manager=manager)
|
||||
try:
|
||||
assert manager.pending_transcription_scopes == [diagnosis_id]
|
||||
assert dialog.table.horizontalHeaderItem(dialog._transcription_column).text() == (
|
||||
"文字状态"
|
||||
)
|
||||
assert dialog.table.item(0, dialog._transcription_column).text() == "待生成"
|
||||
assert _buttons(dialog)["补全文字"].isEnabled()
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_unuploaded_record_waits_for_upload_and_keeps_upload_retry(
|
||||
application: QApplication, tmp_path: Path
|
||||
) -> None:
|
||||
record = _record(tmp_path, status="failed")
|
||||
record.error_text = "上传连接中断"
|
||||
store = _Store(record)
|
||||
dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=_Manager(store))
|
||||
try:
|
||||
assert dialog.table.item(0, dialog._transcription_column).text() == "等待上传"
|
||||
assert dialog.table.item(0, dialog._error_column).text() == "上传:上传连接中断"
|
||||
assert set(_buttons(dialog)) == {"重试"}
|
||||
assert dialog.summary_transcription.text() == "文字未完成 0"
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_polling_detects_text_error_changes_without_upload_changes(
|
||||
application: QApplication, tmp_path: Path
|
||||
) -> None:
|
||||
record = _record(tmp_path, transcription_status="failed", transcription_error="请求失败")
|
||||
store = _Store(record)
|
||||
dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=_Manager(store))
|
||||
try:
|
||||
record.transcription_error = "转写服务暂不可用"
|
||||
dialog.refresh_records()
|
||||
assert dialog.table.item(0, dialog._error_column).text() == "文字:转写服务暂不可用"
|
||||
assert dialog.table.item(0, dialog._transcription_column).toolTip() == (
|
||||
"转写服务暂不可用"
|
||||
)
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_dialog_accepts_legacy_manager_without_transcription_methods(
|
||||
application: QApplication, tmp_path: Path
|
||||
) -> None:
|
||||
store = _Store(_record(tmp_path))
|
||||
manager = _LegacyManager(store)
|
||||
dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager)
|
||||
try:
|
||||
assert manager.pending_upload_scopes == [8169]
|
||||
assert not _buttons(dialog)["补全文字"].isEnabled()
|
||||
finally:
|
||||
dialog.close()
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Synthetic recording recovery: durable text, exact call binding, no duplicate upload."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
import wave
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.core.errors import ApiTransportError
|
||||
from doctor_workstation.services import local_audio_queue as queue_module
|
||||
from doctor_workstation.services.api_client import ApiClient
|
||||
from doctor_workstation.services.local_audio_queue import (
|
||||
LocalAudioQueueStore,
|
||||
LocalAudioUploadManager,
|
||||
)
|
||||
from doctor_workstation.services.repository import RemoteDoctorRepository
|
||||
from doctor_workstation.video import recording_transcription as recording
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self):
|
||||
self.call = {
|
||||
"id": 71, "caller_id": 5, "caller_type": "doctor", "status": 2,
|
||||
"local_audio_status": 2, "transcription_status": "partial",
|
||||
"local_audio_urls_list": ["https://audio.example.test/recording.webm"],
|
||||
"transcription_session_id": "live-session", "transcript_text": "旧的片段",
|
||||
}
|
||||
self.uploads = 0
|
||||
self.saves = []
|
||||
self.fail_save = False
|
||||
self.ack_id = 71
|
||||
|
||||
def get_current_user(self):
|
||||
return SimpleNamespace(id=5)
|
||||
|
||||
def list_call_records(self, _diagnosis_id):
|
||||
return [self.call.copy()]
|
||||
|
||||
def upload_call_recording(self, **kwargs):
|
||||
self.uploads += 1
|
||||
return {"file_url": "https://audio.example.test/recording.webm"}
|
||||
|
||||
def save_local_audio_transcript(self, **payload):
|
||||
self.saves.append(payload)
|
||||
if self.fail_save:
|
||||
raise ApiTransportError("synthetic network failure")
|
||||
return {"call_record_id": self.ack_id, "transcription_status": "completed", "saved": True}
|
||||
|
||||
|
||||
def ready(store, *, uploaded=True):
|
||||
record = store.begin_recording(
|
||||
session_id="synthetic-local", diagnosis_id=9, call_record_id=71, mime_type="audio/webm"
|
||||
)
|
||||
record.file_path.write_bytes(b"synthetic audio")
|
||||
store.finalize_recording(record.id, size_bytes=15)
|
||||
if uploaded:
|
||||
store.mark_uploaded(record.id, "https://audio.example.test/recording.webm")
|
||||
return record.id
|
||||
|
||||
|
||||
def test_upload_automatically_recovers_missing_text_without_reupload(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store, uploaded=False)
|
||||
repository = Repository()
|
||||
saved = threading.Event()
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成测试文字")
|
||||
manager.add_upload_listener(
|
||||
lambda row: saved.set() if row.transcription_status == "completed" else None
|
||||
)
|
||||
assert manager.submit(record_id).result(3)
|
||||
assert saved.wait(3)
|
||||
assert repository.uploads == 1
|
||||
assert repository.saves[0]["call_record_id"] == 71
|
||||
assert repository.saves[0]["expected_session_id"] == "live-session"
|
||||
assert repository.saves[0]["expected_status"] == "partial"
|
||||
assert store.require(record_id).transcription_status == "completed"
|
||||
assert store.require(record_id).exists
|
||||
|
||||
|
||||
def test_failed_save_keeps_draft_and_id_across_restart(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
repository.fail_save = True
|
||||
recognized = []
|
||||
|
||||
def transcribe(path):
|
||||
recognized.append(path)
|
||||
return "保留原始文字,0.5 毫克。"
|
||||
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=transcribe)
|
||||
assert not manager.submit_transcription(record_id).result(3)
|
||||
first = store.require(record_id)
|
||||
assert first.status == "uploaded"
|
||||
assert first.transcription_status == "failed"
|
||||
assert store.transcription_draft(record_id) == "保留原始文字,0.5 毫克。"
|
||||
repository.fail_save = False
|
||||
restarted = LocalAudioQueueStore(tmp_path)
|
||||
retry = LocalAudioUploadManager(repository, restarted, transcriber=transcribe)
|
||||
assert retry.submit_transcription(record_id).result(3)
|
||||
assert len(recognized) == 1
|
||||
assert repository.uploads == 0
|
||||
assert repository.saves[0]["recovery_id"] == repository.saves[1]["recovery_id"]
|
||||
assert not restarted.transcription_draft(record_id)
|
||||
|
||||
|
||||
def test_existing_complete_text_skips_recognition_and_save(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
repository.call["transcription_status"] = "completed"
|
||||
|
||||
def forbidden(_path):
|
||||
pytest.fail("must not overwrite an existing completed transcript")
|
||||
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=forbidden)
|
||||
assert manager.submit_transcription(record_id).result(3)
|
||||
assert not repository.saves
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [
|
||||
{"caller_id": 6}, {"status": 0}, {"local_audio_status": 0}, {"id": 72},
|
||||
{"local_audio_urls_list": ["https://audio.example.test/other-call.webm"]},
|
||||
])
|
||||
def test_wrong_owner_active_or_missing_call_does_not_transcribe(tmp_path, changes):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
repository.call.update(changes)
|
||||
recognized = []
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda path: recognized.append(path))
|
||||
assert not manager.submit_transcription(record_id).result(3)
|
||||
assert not recognized
|
||||
assert not repository.saves
|
||||
assert store.require(record_id).status == "uploaded"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", "x" * 100_001], ids=["empty", "blank", "oversized"])
|
||||
def test_empty_or_oversized_asr_is_never_marked_saved(tmp_path, text):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: text)
|
||||
assert not manager.submit_transcription(record_id).result(3)
|
||||
assert store.require(record_id).transcription_status == "failed"
|
||||
assert not repository.saves
|
||||
|
||||
|
||||
def test_wrong_call_ack_preserves_draft_as_failed(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
repository.ack_id = 72
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成文字")
|
||||
assert not manager.submit_transcription(record_id).result(3)
|
||||
assert store.transcription_draft(record_id) == "合成文字"
|
||||
assert store.require(record_id).transcription_status == "failed"
|
||||
|
||||
|
||||
def test_duplicate_submit_recognizes_once(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def transcribe(_path):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return "合成文字"
|
||||
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=transcribe)
|
||||
first = manager.submit_transcription(record_id)
|
||||
assert entered.wait(3)
|
||||
assert manager.submit_transcription(record_id) is first
|
||||
release.set()
|
||||
assert first.result(3)
|
||||
assert len(repository.saves) == 1
|
||||
|
||||
|
||||
def test_interrupted_work_resumes_with_saved_draft(tmp_path):
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
claimed = store.claim_transcription(record_id)
|
||||
store.save_transcription_draft(record_id, "识别已完成但进程意外退出")
|
||||
queue_module._RECOVERED_DATABASES.discard(store.database_path)
|
||||
restarted = LocalAudioQueueStore(tmp_path)
|
||||
assert restarted.require(record_id).transcription_status == "pending"
|
||||
assert restarted.require(record_id).transcription_recovery_id == claimed.transcription_recovery_id
|
||||
manager = LocalAudioUploadManager(Repository(), restarted)
|
||||
assert manager.submit_pending_transcriptions(diagnosis_id=9)[0].result(3)
|
||||
assert restarted.require(record_id).transcription_status == "completed"
|
||||
|
||||
|
||||
def test_upload_finishes_before_call_end_then_text_recovers_automatically(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(queue_module, "_TRANSCRIPTION_END_RETRY_DELAYS", (0.01, 0.01))
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store, uploaded=False)
|
||||
repository = Repository()
|
||||
calls = []
|
||||
saved = threading.Event()
|
||||
|
||||
def call_state(_diagnosis_id):
|
||||
calls.append(True)
|
||||
return [{**repository.call, "status": 1 if len(calls) == 1 else 2}]
|
||||
|
||||
repository.list_call_records = call_state
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成文字")
|
||||
manager.add_upload_listener(
|
||||
lambda row: saved.set() if row.transcription_status == "completed" else None
|
||||
)
|
||||
assert manager.submit(record_id).result(3)
|
||||
assert saved.wait(3)
|
||||
assert len(calls) == 2
|
||||
assert repository.uploads == 1
|
||||
assert len(repository.saves) == 1
|
||||
|
||||
|
||||
def test_waiting_for_call_end_is_bounded_and_retry_remains_available(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(queue_module, "_TRANSCRIPTION_END_RETRY_DELAYS", (0.01, 0.01))
|
||||
store = LocalAudioQueueStore(tmp_path)
|
||||
record_id = ready(store)
|
||||
repository = Repository()
|
||||
repository.call["status"] = 1
|
||||
recognized = []
|
||||
manager = LocalAudioUploadManager(repository, store, transcriber=lambda path: recognized.append(path))
|
||||
assert not manager.submit_transcription(record_id).result(3)
|
||||
assert not recognized
|
||||
assert store.require(record_id).transcription_status == "failed"
|
||||
repository.call["status"] = 2
|
||||
manager._transcriber = lambda _path: "合成文字"
|
||||
assert manager.submit_transcription(record_id).result(3)
|
||||
|
||||
|
||||
def wav(path: Path, samples: int, *, rate=16_000, channels=1):
|
||||
with wave.open(str(path), "wb") as output:
|
||||
output.setnchannels(channels)
|
||||
output.setsampwidth(2)
|
||||
output.setframerate(rate)
|
||||
output.writeframes(b"\x10\x00" * samples * channels)
|
||||
|
||||
|
||||
def test_decoder_keeps_tail_and_resamples_stereo(tmp_path):
|
||||
pytest.importorskip("av")
|
||||
source = tmp_path / "synthetic.wav"
|
||||
wav(source, 48_000 * 25, rate=48_000, channels=2)
|
||||
chunks = list(recording.recording_pcm(source))
|
||||
assert [len(chunk) for chunk in chunks] == [384_000, 384_000, 32_000]
|
||||
|
||||
|
||||
def test_decoder_rejects_corrupt_or_overlong_audio(tmp_path, monkeypatch):
|
||||
pytest.importorskip("av")
|
||||
source = tmp_path / "synthetic.wav"
|
||||
source.write_bytes(b"not audio")
|
||||
with pytest.raises(recording.RecordingTranscriptionError, match="解码失败"):
|
||||
list(recording.recording_pcm(source))
|
||||
wav(source, 32_000)
|
||||
monkeypatch.setattr(recording, "MAX_RECORDING_SECONDS", 1)
|
||||
with pytest.raises(recording.RecordingTranscriptionError, match="超过"):
|
||||
list(recording.recording_pcm(source))
|
||||
|
||||
|
||||
def test_recording_transcriber_preserves_text_and_never_labels_speakers(tmp_path):
|
||||
pytest.importorskip("av")
|
||||
source = tmp_path / "synthetic.wav"
|
||||
wav(source, 16_000 * 13)
|
||||
responses = iter(["沒有過敏,0.5 mg。", "不是 5 mg。"])
|
||||
engine = SimpleNamespace(transcribe=lambda _pcm: next(responses))
|
||||
assert recording.RecordingTranscriber(engine)(source) == "没有过敏,0.5 mg。\n不是 5 mg。"
|
||||
|
||||
|
||||
def test_repository_sends_exact_binding_and_compare_state():
|
||||
calls = []
|
||||
|
||||
def handle(request):
|
||||
assert request.url.path == "/adminapi/tcm.diagnosis/saveLocalAudioTranscript"
|
||||
calls.append(json.loads(request.content))
|
||||
return httpx.Response(200, json={"code": 1, "data": {
|
||||
"call_record_id": 71, "transcription_status": "completed", "saved": True,
|
||||
}})
|
||||
|
||||
client = ApiClient("https://example.test/adminapi/", transport=httpx.MockTransport(handle))
|
||||
repository = RemoteDoctorRepository(client)
|
||||
payload = dict(
|
||||
diagnosis_id=9, call_record_id=71, recovery_id="audio-" + "a" * 32,
|
||||
expected_session_id="live-session", expected_status="partial",
|
||||
audio_url="https://audio.example.test/recording.webm", transcript_text="合成测试文字",
|
||||
)
|
||||
assert repository.save_local_audio_transcript(**payload)["saved"]
|
||||
assert calls == [payload]
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Finalization retries retain one sealed capture session and one call identity."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video.launcher import VideoCallRequest
|
||||
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self, outcomes=(), block_attempt=0):
|
||||
self.outcomes = list(outcomes)
|
||||
self.block_attempt = block_attempt
|
||||
self.attempts = []
|
||||
self.events = []
|
||||
self.entered = threading.Event()
|
||||
self.release = threading.Event()
|
||||
|
||||
def start_call(self, **_payload):
|
||||
return {"call_record_id": 71}
|
||||
|
||||
def start_call_transcription(self, **_payload):
|
||||
return True
|
||||
|
||||
def upsert_call_transcript_segments(self, **_payload):
|
||||
return True
|
||||
|
||||
def finish_call_transcription(self, **payload):
|
||||
self.attempts.append(payload)
|
||||
self.events.append("finish")
|
||||
if len(self.attempts) == self.block_attempt:
|
||||
self.entered.set()
|
||||
assert self.release.wait(3), "test did not release finalization"
|
||||
outcome = self.outcomes.pop(0) if self.outcomes else True
|
||||
if isinstance(outcome, Exception):
|
||||
raise outcome
|
||||
return outcome
|
||||
|
||||
def end_call(self, **_payload):
|
||||
self.events.append("end")
|
||||
return True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_lifecycle():
|
||||
lifecycles = []
|
||||
|
||||
def make(**options):
|
||||
repository = Repository(**options)
|
||||
request = VideoCallRequest(
|
||||
sdk_app_id=1400123456,
|
||||
user_id="doctor-test",
|
||||
user_sig="test-ticket",
|
||||
target_user_id="patient-test",
|
||||
diagnosis_id=12,
|
||||
)
|
||||
lifecycle = OrderedCallLifecycle(request, repository, logging.getLogger(__name__))
|
||||
lifecycles.append((lifecycle, repository))
|
||||
assert lifecycle.start_transcription("tr-finish-retry").result(timeout=2)
|
||||
assert lifecycle.save_transcript_segment(
|
||||
{"segment_id": "synthetic-1", "text": "synthetic fixture"}
|
||||
).result(timeout=2)
|
||||
return lifecycle, repository
|
||||
|
||||
yield make
|
||||
for lifecycle, repository in lifecycles:
|
||||
repository.release.set()
|
||||
lifecycle.end("test-cleanup").result(timeout=3)
|
||||
assert lifecycle.wait(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [
|
||||
RuntimeError("temporary storage failure"), False,
|
||||
{"status": "failed", "segment_count": 0},
|
||||
{"status": "partial", "segment_count": 1},
|
||||
])
|
||||
def test_failed_finish_retries_same_snapshot_without_reopening_capture(make_lifecycle, failure):
|
||||
lifecycle, repository = make_lifecycle(outcomes=[failure, True])
|
||||
failed = lifecycle.finish_transcription()
|
||||
with pytest.raises(RuntimeError):
|
||||
failed.result(timeout=2)
|
||||
with pytest.raises(RuntimeError, match="already stopped"):
|
||||
lifecycle.start_transcription("tr-finish-retry")
|
||||
with pytest.raises(RuntimeError, match="already stopped"):
|
||||
lifecycle.save_transcript_segment({"segment_id": "late", "text": "synthetic fixture"})
|
||||
|
||||
retry = lifecycle.finish_transcription()
|
||||
assert retry is not failed
|
||||
assert retry.result(timeout=2)
|
||||
assert lifecycle.finish_transcription() is retry
|
||||
assert repository.attempts == [
|
||||
{"diagnosis_id": 12, "call_record_id": 71,
|
||||
"transcription_session_id": "tr-finish-retry",
|
||||
"expected_segment_count": 1, "status": "completed"},
|
||||
] * 2
|
||||
|
||||
|
||||
def test_concurrent_finish_retries_share_one_running_write(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(
|
||||
outcomes=[RuntimeError("temporary storage failure"), True], block_attempt=2,
|
||||
)
|
||||
with pytest.raises(RuntimeError):
|
||||
lifecycle.finish_transcription().result(timeout=2)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=4) as callers:
|
||||
futures = list(callers.map(lambda _: lifecycle.finish_transcription(), range(4)))
|
||||
assert repository.entered.wait(2)
|
||||
assert all(future is futures[0] for future in futures)
|
||||
assert len(repository.attempts) == 2
|
||||
finally:
|
||||
repository.release.set()
|
||||
assert futures[0].result(timeout=2)
|
||||
|
||||
|
||||
def test_cancelled_finish_can_retry_without_reopening_capture(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def occupy_worker():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
|
||||
lifecycle._worker.submit("test-block", occupy_worker)
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
cancelled = lifecycle.finish_transcription()
|
||||
assert cancelled.cancel()
|
||||
retry = lifecycle.finish_transcription()
|
||||
assert retry is not cancelled
|
||||
finally:
|
||||
release.set()
|
||||
assert retry.result(timeout=2)
|
||||
assert len(repository.attempts) == 1
|
||||
|
||||
|
||||
def test_end_retries_failed_finish_before_ending_exact_call(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(outcomes=[RuntimeError("temporary failure"), True])
|
||||
with pytest.raises(RuntimeError):
|
||||
lifecycle.finish_transcription().result(timeout=2)
|
||||
assert lifecycle.end("synthetic-hangup").result(timeout=2)
|
||||
assert repository.events == ["finish", "finish", "end"]
|
||||
assert repository.attempts[-1]["status"] == "partial"
|
||||
assert repository.attempts[-1]["transcription_session_id"] == "tr-finish-retry"
|
||||
assert lifecycle.finish_transcription().result(timeout=2)
|
||||
assert len(repository.attempts) == 2
|
||||
|
||||
|
||||
def test_failed_finish_cannot_submit_after_end_worker_has_stopped(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(
|
||||
outcomes=[RuntimeError("first failure"), RuntimeError("fallback failure")],
|
||||
)
|
||||
with pytest.raises(RuntimeError):
|
||||
lifecycle.finish_transcription().result(timeout=2)
|
||||
assert lifecycle.end("synthetic-hangup").result(timeout=2)
|
||||
with pytest.raises(RuntimeError, match="already ended"):
|
||||
lifecycle.finish_transcription()
|
||||
assert len(repository.attempts) == 2
|
||||
Reference in New Issue
Block a user