更新
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
"""Medical-assistant names must survive independent list/options loading."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtWidgets import QApplication, QWidget
|
||||
|
||||
from doctor_workstation.core.errors import ApiBusinessError
|
||||
from doctor_workstation.services.repository import RemoteDoctorRepository
|
||||
from doctor_workstation.ui.pages import consultations as module
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self) -> None:
|
||||
self.assistants: Any = [{"id": 66, "name": "周医助"}]
|
||||
self.rows = [
|
||||
{"id": 1, "assistant_id": "66", "patient_name": "测试患者"},
|
||||
{"id": 2, "assistant_id": 66, "assistant_name": "诊单医助"},
|
||||
{"id": 3, "assistant_id": 99},
|
||||
{"id": 4, "assistant_id": 0},
|
||||
{"id": 5, "assistant_id": None},
|
||||
]
|
||||
|
||||
def get(self, endpoint: str, params: Any = None) -> Any:
|
||||
if endpoint == "tcm.diagnosis/lists":
|
||||
return {"lists": deepcopy(self.rows), "count": len(self.rows)}
|
||||
if endpoint == "tcm.diagnosis/getAssistants":
|
||||
if isinstance(self.assistants, Exception):
|
||||
raise self.assistants
|
||||
return deepcopy(self.assistants)
|
||||
return []
|
||||
|
||||
|
||||
class DetailStub(QWidget):
|
||||
saved = Signal()
|
||||
|
||||
def __init__(self, _repository: Any, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(application: QApplication, monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setattr(module, "DiagnosisDialog", DetailStub)
|
||||
jobs = []
|
||||
|
||||
def defer(function: Any, **callbacks: Any) -> None:
|
||||
jobs.append(lambda: callbacks["on_success"](function()))
|
||||
|
||||
monkeypatch.setattr(module, "run_async", defer)
|
||||
client = Client()
|
||||
result = module.ConsultationsPage(RemoteDoctorRepository(client))
|
||||
yield result, client, jobs
|
||||
result.poll_timer.stop()
|
||||
result.close()
|
||||
result.deleteLater()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("options_first", [False, True])
|
||||
def test_names_render_with_either_response_order_without_changing_source(page, options_first):
|
||||
view, client, jobs = page
|
||||
result = view.repository.list_consultations()
|
||||
before = deepcopy(result)
|
||||
view._load_filter_options()
|
||||
if options_first:
|
||||
jobs.pop()()
|
||||
view._apply_result(result, view._generation)
|
||||
model = view.table_host.model
|
||||
model.setData(model.index(0, 0), Qt.CheckState.Checked, Qt.ItemDataRole.CheckStateRole)
|
||||
view.table.selectRow(0)
|
||||
if not options_first:
|
||||
assert model.index(0, 7).data() == "—"
|
||||
changes = []
|
||||
model.dataChanged.connect(lambda first, last, roles: changes.append((first, last, roles)))
|
||||
jobs.pop()()
|
||||
assert any(first.column() == last.column() == 7 for first, last, _ in changes)
|
||||
assert [model.index(row, 7).data() for row in range(5)] == [
|
||||
"周医助", "诊单医助", "—", "—", "—",
|
||||
]
|
||||
assert model.index(0, 7).data(Qt.ItemDataRole.ToolTipRole) == "周医助"
|
||||
assert [row.id for row in model.checked_records()] == [1]
|
||||
assert view.table.current_data().id == 1
|
||||
assert result == before
|
||||
assert "assistant_name" not in client.rows[0]
|
||||
# A later page uses the same lookup; reassignment uses the new ID, not a cached row name.
|
||||
client.rows = [{"id": 1, "assistant_id": 99}, {"id": 6, "assistant_id": 66}]
|
||||
view._apply_result(view.repository.list_consultations(), view._generation)
|
||||
assert [model.index(row, 7).data() for row in range(2)] == ["—", "周医助"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("options", [[], ApiBusinessError("权限不足,无法访问或操作")])
|
||||
def test_server_name_still_displays_when_picker_empty_or_denied(page, options):
|
||||
view, client, jobs = page
|
||||
client.assistants = options
|
||||
view._apply_result(view.repository.list_consultations(), view._generation)
|
||||
view._load_filter_options()
|
||||
jobs.pop()()
|
||||
assert view.table_host.model.index(1, 7).data() == "诊单医助"
|
||||
assert view.table_host.model.index(0, 7).data() == "—"
|
||||
|
||||
|
||||
def test_updated_and_stale_options_do_not_leave_old_assistant_names(page):
|
||||
view, _client, jobs = page
|
||||
view._apply_result(view.repository.list_consultations(), view._generation)
|
||||
view._load_filter_options()
|
||||
jobs.pop()()
|
||||
generation = view._options_generation
|
||||
view._apply_filter_options({"assistants": [{"id": 66, "name": "新医助"}]}, generation)
|
||||
assert view.table_host.model.index(0, 7).data() == "新医助"
|
||||
view._apply_filter_options({"assistants": []}, generation - 1)
|
||||
assert view.table_host.model.index(0, 7).data() == "新医助"
|
||||
view._apply_filter_options({"assistants": []}, generation)
|
||||
assert view.table_host.model.index(0, 7).data() == "—"
|
||||
assert view.table_host.model.index(1, 7).data() == "诊单医助"
|
||||
|
||||
|
||||
def test_long_assistant_name_resizes_both_table_sections(page):
|
||||
view, _client, _jobs = page
|
||||
host = view.table_host
|
||||
view._apply_result(view.repository.list_consultations(), view._generation)
|
||||
original_height = host.main.rowHeight(0)
|
||||
name = "完整医助姓名用于显示换行" * 5
|
||||
host.set_assistant_names({66: name, 0: "不能用于未分配患者", -1: "无效医助"})
|
||||
assert host.model.index(0, 7).data() == name
|
||||
assert host.main.rowHeight(0) > original_height
|
||||
assert host.main.rowHeight(0) == host.fixed.rowHeight(0)
|
||||
assert host.model.index(3, 7).data() == "—"
|
||||
@@ -0,0 +1,352 @@
|
||||
"""COS upload contract tests: real SDK configuration, no external requests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from qcloud_cos import CosClientError, CosConfig, CosS3Client
|
||||
|
||||
from doctor_workstation.core.errors import ApiBusinessError, ApiProtocolError, ApiTransportError
|
||||
from doctor_workstation.services.api_client import ApiClient
|
||||
from doctor_workstation.services.cos_upload import upload_video_to_cos
|
||||
|
||||
BUCKET = "synthetic-video-1234567890"
|
||||
REGION = "ap-guangzhou"
|
||||
PREFIX = "uploads/video/20261105/"
|
||||
_AUTOMATIC = object()
|
||||
|
||||
|
||||
def _credentials() -> dict[str, Any]:
|
||||
now = int(time.time())
|
||||
return {
|
||||
"provider": "qcloud",
|
||||
"fallback": False,
|
||||
"bucket": BUCKET,
|
||||
"region": REGION,
|
||||
"key_prefix": PREFIX,
|
||||
"object_key": "",
|
||||
"host": "https://untrusted-host.example.test",
|
||||
"cdn_domain": "https://cdn.example.test",
|
||||
"max_size": 2 * 1024 * 1024 * 1024,
|
||||
"start_time": now - 10,
|
||||
"expired_time": now + 1800,
|
||||
"credentials": {
|
||||
"tmpSecretId": "synthetic-temporary-id",
|
||||
"tmpSecretKey": "synthetic-temporary-secret",
|
||||
"sessionToken": "synthetic-temporary-token",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Harness:
|
||||
source: Path
|
||||
credentials: Any = field(default_factory=_credentials)
|
||||
confirmation: Any = _AUTOMATIC
|
||||
sdk_error: Exception | None = None
|
||||
sdk_reports_progress: bool = True
|
||||
api_failure: str = ""
|
||||
log_sensitive_sdk_data: bool = False
|
||||
api_requests: list[httpx.Request] = field(default_factory=list)
|
||||
sdk_calls: list[dict[str, Any]] = field(default_factory=list)
|
||||
configs: list[CosConfig] = field(default_factory=list)
|
||||
progress: list[tuple[int, int]] = field(default_factory=list)
|
||||
events: list[str] = field(default_factory=list)
|
||||
|
||||
def handle(self, request: httpx.Request) -> httpx.Response:
|
||||
self.api_requests.append(request)
|
||||
assert request.method == "POST"
|
||||
assert request.headers["token"] == "synthetic-admin-token"
|
||||
endpoint = request.url.path.rsplit("/", 1)[-1]
|
||||
assert endpoint in {"ossCredentials", "ossConfirm"}
|
||||
self.events.append(endpoint)
|
||||
if self.api_failure == endpoint:
|
||||
return httpx.Response(200, json={"code": 0, "msg": "synthetic API rejection"})
|
||||
if endpoint == "ossCredentials":
|
||||
return httpx.Response(200, json={"code": 1, "data": self.credentials})
|
||||
assert request.extensions["timeout"]["read"] == 120.0
|
||||
body = json.loads(request.content)
|
||||
result = self.confirmation
|
||||
if result is _AUTOMATIC:
|
||||
address = "https://cdn.example.test/" + body["key"]
|
||||
result = {"id": 19, "uri": address, "url": address, "type": 20, "cid": 0}
|
||||
return httpx.Response(200, json={"code": 1, "data": result})
|
||||
|
||||
def client(self) -> ApiClient:
|
||||
return ApiClient(
|
||||
"https://api.example.test",
|
||||
token="synthetic-admin-token",
|
||||
max_retries=5,
|
||||
transport=httpx.MockTransport(self.handle),
|
||||
)
|
||||
|
||||
def processing(self) -> None:
|
||||
self.events.append("processing")
|
||||
|
||||
def report(self, sent: int, total: int) -> None:
|
||||
self.progress.append((sent, total))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[_Harness]:
|
||||
source = tmp_path / "synthetic-replay.mp4"
|
||||
source.write_bytes(b"synthetic-video-bytes")
|
||||
state = _Harness(source)
|
||||
|
||||
def sdk_upload(sdk: CosS3Client, **kwargs: Any) -> dict[str, str]:
|
||||
state.configs.append(sdk.get_conf())
|
||||
state.sdk_calls.append(kwargs)
|
||||
state.events.append("sdk-start")
|
||||
if state.log_sensitive_sdk_data:
|
||||
logging.getLogger("qcloud_cos.cos_auth").debug("synthetic-temporary-secret")
|
||||
logging.getLogger("qcloud_cos.cos_client").error("synthetic-temporary-token")
|
||||
if state.sdk_error is not None:
|
||||
raise state.sdk_error
|
||||
if state.sdk_reports_progress:
|
||||
size = source.stat().st_size
|
||||
callback = kwargs["progress_callback"]
|
||||
callback(size // 2, size)
|
||||
callback(size, size)
|
||||
callback(size * 2, size) # Defensive clamping must keep binding pending.
|
||||
state.events.append("sdk-done")
|
||||
return {"ETag": '"synthetic-etag"'}
|
||||
|
||||
def no_external_request(*_args: Any, **_kwargs: Any) -> None:
|
||||
pytest.fail("SDK tests must never make an external request")
|
||||
|
||||
monkeypatch.setattr(CosS3Client, "upload_file", sdk_upload)
|
||||
monkeypatch.setattr("requests.Session.request", no_external_request)
|
||||
# Restore the logger after the test while exercising the helper's choice.
|
||||
monkeypatch.setattr(logging.getLogger("qcloud_cos"), "propagate", True)
|
||||
yield state
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", [1, 1024, 5 * 1024 * 1024])
|
||||
def test_official_sdk_config_and_confirm_order_keep_completion_pending(
|
||||
harness: _Harness, size: int
|
||||
) -> None:
|
||||
harness.source.write_bytes(b"v" * size)
|
||||
harness.sdk_reports_progress = size > 1024 * 1024
|
||||
with harness.client() as client:
|
||||
result = upload_video_to_cos(
|
||||
client,
|
||||
harness.source,
|
||||
mime_type="video/mp4",
|
||||
on_progress=harness.report,
|
||||
on_processing=harness.processing,
|
||||
)
|
||||
|
||||
assert harness.events == ["ossCredentials", "sdk-start", "sdk-done", "processing", "ossConfirm"]
|
||||
assert json.loads(harness.api_requests[0].content) == {
|
||||
"type": "video", "name": harness.source.name
|
||||
}
|
||||
assert len(harness.sdk_calls) == 1
|
||||
config = harness.configs[0]
|
||||
call = harness.sdk_calls[0]
|
||||
assert config._secret_id == "synthetic-temporary-id"
|
||||
assert config._secret_key == "synthetic-temporary-secret"
|
||||
assert config._token == "synthetic-temporary-token"
|
||||
assert config._region == REGION
|
||||
assert config._scheme == "https"
|
||||
assert config._timeout == 120
|
||||
assert config._verify_ssl is True
|
||||
assert config._allow_redirects is False
|
||||
assert config._domain is None
|
||||
assert config._ip is None
|
||||
assert config._port is None
|
||||
assert config.uri(bucket=BUCKET, path=call["Key"]).startswith(
|
||||
f"https://{BUCKET}.cos.{REGION}.myqcloud.com/"
|
||||
)
|
||||
assert call["Bucket"] == BUCKET
|
||||
assert call["LocalFilePath"] == str(harness.source.resolve())
|
||||
assert call["PartSize"] == 1
|
||||
assert call["MAXThread"] == 3
|
||||
assert call["ContentType"] == "video/mp4"
|
||||
assert set(call) == {
|
||||
"Bucket", "Key", "LocalFilePath", "PartSize", "MAXThread", "ContentType", "progress_callback"
|
||||
}
|
||||
assert re.fullmatch(re.escape(PREFIX) + r"[0-9]+-[0-9a-f]{32}\.mp4", call["Key"])
|
||||
assert json.loads(harness.api_requests[1].content) == {
|
||||
"type": "video", "key": call["Key"], "name": harness.source.name,
|
||||
"size": size, "content_type": "video/mp4", "cid": 0,
|
||||
}
|
||||
assert result["id"] == 19
|
||||
assert result["uri"].endswith("/" + call["Key"])
|
||||
assert harness.progress[0] == (0, size)
|
||||
assert harness.progress[-1] == (size - 1, size)
|
||||
assert all(0 <= sent < total == size for sent, total in harness.progress)
|
||||
|
||||
|
||||
def test_fixed_object_key_is_used_without_expanding_its_scope(harness: _Harness) -> None:
|
||||
harness.credentials["object_key"] = PREFIX + "session/fixed.mp4"
|
||||
with harness.client() as client:
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4")
|
||||
assert harness.sdk_calls[0]["Key"] == PREFIX + "session/fixed.mp4"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field_name", "invalid"),
|
||||
[
|
||||
("provider", "local"),
|
||||
("fallback", True),
|
||||
("fallback", "false"),
|
||||
("bucket", "bucket.example.test/escape-1234567890"),
|
||||
("bucket", "bucket@attacker-1234567890"),
|
||||
("bucket", ""),
|
||||
("region", "ap-guangzhou.attacker.test"),
|
||||
("region", "https://attacker.test"),
|
||||
("key_prefix", "uploads/voice/20261105/"),
|
||||
("key_prefix", "uploads/video/20261105/../"),
|
||||
("key_prefix", "uploads/video/20261399/"),
|
||||
("key_prefix", "uploads/video/20261105"),
|
||||
("object_key", "uploads/video/20261106/other.mp4"),
|
||||
("object_key", PREFIX + "../other.mp4"),
|
||||
("object_key", PREFIX + "%2e%2e/other.mp4"),
|
||||
("object_key", PREFIX + "nested\\other.mp4"),
|
||||
("object_key", PREFIX + "other.exe"),
|
||||
("object_key", []),
|
||||
("max_size", 0),
|
||||
("max_size", True),
|
||||
("start_time", 9999999999),
|
||||
("expired_time", 1),
|
||||
("expired_time", False),
|
||||
("credentials", None),
|
||||
("credentials", {"tmpSecretId": "id", "tmpSecretKey": "secret"}),
|
||||
("credentials", {"tmpSecretId": "id", "tmpSecretKey": "", "sessionToken": "token"}),
|
||||
("credentials", {"tmpSecretId": "id", "tmpSecretKey": "secret", "sessionToken": "bad\r\n"}),
|
||||
],
|
||||
)
|
||||
def test_invalid_credentials_fail_before_any_cos_upload(
|
||||
harness: _Harness, field_name: str, invalid: Any
|
||||
) -> None:
|
||||
harness.credentials[field_name] = invalid
|
||||
with harness.client() as client, pytest.raises(ApiProtocolError):
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4")
|
||||
assert harness.sdk_calls == []
|
||||
assert harness.events == ["ossCredentials"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response", [None, [], "invalid"])
|
||||
def test_non_mapping_credentials_are_rejected(harness: _Harness, response: Any) -> None:
|
||||
harness.credentials = response
|
||||
with harness.client() as client, pytest.raises(ApiProtocolError):
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4")
|
||||
assert harness.sdk_calls == []
|
||||
|
||||
|
||||
def test_server_size_limit_is_enforced_before_cos_upload(harness: _Harness) -> None:
|
||||
harness.credentials["max_size"] = harness.source.stat().st_size - 1
|
||||
with harness.client() as client, pytest.raises(ValueError, match="上限"):
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4")
|
||||
assert harness.sdk_calls == []
|
||||
assert harness.events == ["ossCredentials"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("condition", ["missing", "empty", "oversized", "wrong-extension", "bad-mime"])
|
||||
def test_invalid_local_video_fails_before_request(harness: _Harness, condition: str) -> None:
|
||||
mime = "video/mp4"
|
||||
if condition == "missing":
|
||||
harness.source.unlink()
|
||||
elif condition == "empty":
|
||||
harness.source.write_bytes(b"")
|
||||
elif condition == "oversized":
|
||||
with harness.source.open("wb") as stream:
|
||||
stream.truncate(2 * 1024 * 1024 * 1024 + 1)
|
||||
elif condition == "wrong-extension":
|
||||
renamed = harness.source.with_suffix(".exe")
|
||||
harness.source.rename(renamed)
|
||||
harness.source = renamed
|
||||
else:
|
||||
mime = "video/mp4\r\nx-injected: value"
|
||||
with harness.client() as client, pytest.raises(ValueError):
|
||||
upload_video_to_cos(client, harness.source, mime_type=mime)
|
||||
assert harness.api_requests == []
|
||||
assert harness.sdk_calls == []
|
||||
|
||||
|
||||
def test_cos_error_is_sanitized_and_never_confirmed(
|
||||
harness: _Harness, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
harness.sdk_error = CosClientError("synthetic-temporary-secret synthetic-temporary-token")
|
||||
harness.log_sensitive_sdk_data = True
|
||||
caplog.set_level(logging.DEBUG)
|
||||
with harness.client() as client, pytest.raises(ApiTransportError) as caught:
|
||||
upload_video_to_cos(
|
||||
client, harness.source, mime_type="video/mp4",
|
||||
on_progress=harness.report, on_processing=harness.processing,
|
||||
)
|
||||
rendered = "".join(traceback.format_exception(caught.value))
|
||||
assert "synthetic-temporary-secret" not in rendered + caplog.text
|
||||
assert "synthetic-temporary-token" not in rendered + caplog.text
|
||||
assert caught.value.data == {"provider": "cos", "operation": "upload"}
|
||||
assert caught.value.__suppress_context__ is True
|
||||
assert harness.events == ["ossCredentials", "sdk-start"]
|
||||
assert harness.progress == [(0, harness.source.stat().st_size)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["ossCredentials", "ossConfirm"])
|
||||
def test_api_business_errors_keep_their_type_and_are_not_retried(
|
||||
harness: _Harness, endpoint: str
|
||||
) -> None:
|
||||
harness.api_failure = endpoint
|
||||
with harness.client() as client, pytest.raises(ApiBusinessError, match="synthetic API rejection"):
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4", on_progress=harness.report)
|
||||
assert sum(request.url.path.endswith(endpoint) for request in harness.api_requests) == 1
|
||||
assert len(harness.sdk_calls) == (0 if endpoint == "ossCredentials" else 1)
|
||||
assert all(sent < total for sent, total in harness.progress)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"invalid",
|
||||
[
|
||||
None,
|
||||
[],
|
||||
{},
|
||||
{"id": 0},
|
||||
{"id": True},
|
||||
{"id": 19},
|
||||
{"id": 19, "uri": "/uploads/video/local.mp4"},
|
||||
{"id": 19, "uri": "file:///tmp/local.mp4"},
|
||||
{"id": 19, "uri": "https://cdn.example.test/different.mp4"},
|
||||
{"id": 19, "uri": "https://cdn.example.test:bad/" + PREFIX + "fixed.mp4"},
|
||||
{"id": 19, "uri": "https://user:pass@cdn.example.test/" + PREFIX + "fixed.mp4"},
|
||||
],
|
||||
)
|
||||
def test_invalid_confirmation_never_reports_completion(harness: _Harness, invalid: Any) -> None:
|
||||
harness.credentials["object_key"] = PREFIX + "fixed.mp4"
|
||||
harness.confirmation = invalid
|
||||
with harness.client() as client, pytest.raises(ApiProtocolError):
|
||||
upload_video_to_cos(client, harness.source, mime_type="video/mp4", on_progress=harness.report)
|
||||
assert len(harness.sdk_calls) == 1
|
||||
assert harness.events[-1] == "ossConfirm"
|
||||
assert all(sent < total for sent, total in harness.progress)
|
||||
|
||||
|
||||
def test_disposed_ui_callbacks_do_not_interrupt_upload_or_confirmation(harness: _Harness) -> None:
|
||||
processing = []
|
||||
|
||||
def broken_progress(_sent: int, _total: int) -> None:
|
||||
raise RuntimeError("synthetic disposed progress receiver")
|
||||
|
||||
def broken_processing() -> None:
|
||||
processing.append(True)
|
||||
raise RuntimeError("synthetic disposed processing receiver")
|
||||
|
||||
with harness.client() as client:
|
||||
result = upload_video_to_cos(
|
||||
client, harness.source, mime_type="video/mp4",
|
||||
on_progress=broken_progress, on_processing=broken_processing,
|
||||
)
|
||||
assert result["id"] == 19
|
||||
assert processing == [True]
|
||||
assert harness.events == ["ossCredentials", "sdk-start", "sdk-done", "ossConfirm"]
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Exercise the real COS SDK and repository with synthetic HTTP responses."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from doctor_workstation.core.errors import ApiBusinessError, ApiProtocolError
|
||||
from doctor_workstation.services.api_client import ApiClient
|
||||
from doctor_workstation.services.repository import RemoteDoctorRepository
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", [1024, 5 * 1024 * 1024])
|
||||
@pytest.mark.parametrize("record_id", [None, 901])
|
||||
def test_real_sdk_sends_video_only_to_cos_before_confirming_and_binding(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, size: int, record_id: int | None,
|
||||
) -> None:
|
||||
source = tmp_path / "synthetic-replay.mp4"
|
||||
source.write_bytes(b"v" * size)
|
||||
api_calls: list[str] = []
|
||||
cos_requests: list[requests.PreparedRequest] = []
|
||||
uploaded_parts: dict[int, bytes] = {}
|
||||
progress: list[int] = []
|
||||
stages: list[str] = []
|
||||
confirmed_urls: list[str] = []
|
||||
|
||||
def cos_send(_session, request, **kwargs):
|
||||
parsed = urlsplit(request.url)
|
||||
assert parsed.scheme == "https"
|
||||
assert parsed.hostname == "test-bucket-1250000000.cos.ap-guangzhou.myqcloud.com"
|
||||
assert request.headers["x-cos-security-token"] == b"synthetic-sts-token"
|
||||
assert "q-sign-algorithm=sha1" in request.headers["Authorization"]
|
||||
assert "token" not in request.headers
|
||||
cos_requests.append(request)
|
||||
query = parse_qs(parsed.query, keep_blank_values=True)
|
||||
if request.method == "GET":
|
||||
body = b"<ListMultipartUploadsResult><IsTruncated>false</IsTruncated></ListMultipartUploadsResult>"
|
||||
elif request.method == "POST" and "uploads" in query:
|
||||
body = b"<InitiateMultipartUploadResult><UploadId>synthetic-upload</UploadId></InitiateMultipartUploadResult>"
|
||||
elif request.method == "PUT":
|
||||
part = int(query.get("partNumber", ["1"])[0])
|
||||
uploaded_parts[part] = request.body.read() if hasattr(request.body, "read") else request.body
|
||||
body = b""
|
||||
else:
|
||||
assert request.method == "POST" and query.get("uploadId") == ["synthetic-upload"]
|
||||
body = b'<CompleteMultipartUploadResult><ETag>"synthetic-etag"</ETag></CompleteMultipartUploadResult>'
|
||||
response = requests.Response()
|
||||
response.status_code = 200
|
||||
response.url = request.url
|
||||
response.request = request
|
||||
response._content = body
|
||||
response.headers.update({"ETag": '"synthetic-etag"', "Content-Type": "application/xml"})
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(requests.Session, "send", cos_send)
|
||||
|
||||
def api_handler(request: httpx.Request) -> httpx.Response:
|
||||
endpoint = request.url.path.removeprefix("/adminapi/")
|
||||
api_calls.append(endpoint)
|
||||
assert request.method == "POST"
|
||||
assert request.headers["token"] == "synthetic-admin-token"
|
||||
payload = json.loads(request.content)
|
||||
if endpoint == "upload/ossCredentials":
|
||||
assert payload == {"type": "video", "name": source.name}
|
||||
data = {
|
||||
"provider": "qcloud", "fallback": False,
|
||||
"bucket": "test-bucket-1250000000", "region": "ap-guangzhou",
|
||||
"host": "https://test-bucket-1250000000.cos.ap-guangzhou.myqcloud.com",
|
||||
"key_prefix": "uploads/video/20261105/", "max_size": 2 * 1024**3,
|
||||
"expired_time": int(time.time()) + 1800, "start_time": int(time.time()) - 10,
|
||||
"credentials": {"tmpSecretId": "synthetic-id", "tmpSecretKey": "synthetic-key", "sessionToken": "synthetic-sts-token"},
|
||||
}
|
||||
elif endpoint == "upload/ossConfirm":
|
||||
assert b"".join(uploaded_parts[i] for i in sorted(uploaded_parts)) == source.read_bytes()
|
||||
assert stages == ["processing"]
|
||||
assert size not in progress
|
||||
assert payload == {
|
||||
"type": "video", "key": payload["key"], "name": source.name,
|
||||
"size": size, "content_type": "video/mp4", "cid": 0,
|
||||
}
|
||||
assert payload["key"].startswith("uploads/video/20261105/")
|
||||
assert payload["key"].endswith(".mp4")
|
||||
confirmed_urls.append("https://cdn.example.test/" + payload["key"])
|
||||
data = {"id": 101, "uri": confirmed_urls[-1]}
|
||||
elif endpoint == "tcm.diagnosis/createManualCallRecord":
|
||||
assert payload == {"diagnosis_id": 501}
|
||||
assert size not in progress
|
||||
data = {"id": 901}
|
||||
else:
|
||||
assert endpoint == "tcm.diagnosis/attachLocalCallRecording"
|
||||
assert payload == {"diagnosis_id": 501, "call_record_id": 901, "file_url": confirmed_urls[-1]}
|
||||
assert size not in progress
|
||||
data = []
|
||||
return httpx.Response(200, json={"code": 1, "data": data})
|
||||
|
||||
with ApiClient("https://api.example.test", token="synthetic-admin-token", transport=httpx.MockTransport(api_handler)) as client:
|
||||
result = RemoteDoctorRepository(client).upload_call_recording(
|
||||
source, 501, call_record_id=record_id, mime_type="video/mp4",
|
||||
on_progress=lambda sent, total: progress.append(sent),
|
||||
on_processing=lambda: stages.append("processing"),
|
||||
)
|
||||
assert result["completed"] is True and result["call_record_id"] == 901
|
||||
assert result["media_kind"] == "video"
|
||||
assert progress[0] == 0 and progress[-1] == size
|
||||
assert cos_requests
|
||||
assert api_calls == [
|
||||
"upload/ossCredentials", "upload/ossConfirm",
|
||||
*(["tcm.diagnosis/createManualCallRecord"] if record_id is None else []),
|
||||
"tcm.diagnosis/attachLocalCallRecording",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["missing-record", "attach-failed"])
|
||||
def test_video_is_not_complete_until_exact_record_is_bound(tmp_path: Path, monkeypatch, failure):
|
||||
from doctor_workstation.services import repository as repository_module
|
||||
|
||||
source = tmp_path / "synthetic.mp4"
|
||||
source.write_bytes(b"video")
|
||||
monkeypatch.setattr(repository_module, "upload_video_to_cos", lambda *args, **kwargs: {
|
||||
"id": 101, "uri": "https://cdn.example.test/replay.mp4",
|
||||
})
|
||||
calls = []
|
||||
progress = []
|
||||
|
||||
def handler(request):
|
||||
calls.append(request.url.path)
|
||||
if request.url.path.endswith("createManualCallRecord"):
|
||||
return httpx.Response(200, json={"code": 1, "data": {"id": 0 if failure == "missing-record" else 901}})
|
||||
return httpx.Response(200, json={"code": 0, "msg": "绑定失败"})
|
||||
|
||||
with (
|
||||
ApiClient("https://api.example.test", transport=httpx.MockTransport(handler)) as client,
|
||||
pytest.raises(ApiProtocolError if failure == "missing-record" else ApiBusinessError),
|
||||
):
|
||||
RemoteDoctorRepository(client).upload_call_recording(
|
||||
source, 501, on_progress=lambda sent, total: progress.append(sent),
|
||||
)
|
||||
assert source.stat().st_size not in progress
|
||||
assert len(calls) == (1 if failure == "missing-record" else 2)
|
||||
Reference in New Issue
Block a user