Files
zyt/app/tests/test_video_room_cycles.py
2026-11-12 16:11:43 +08:00

204 lines
7.2 KiB
Python

"""Exercise room binding across redials without creating a Qt window."""
from __future__ import annotations
import logging
from collections.abc import Iterator
from itertools import count
from queue import Queue
from threading import Event
from types import MethodType
from typing import Any
from unittest.mock import Mock
import pytest
from doctor_workstation.video import window
from doctor_workstation.video.launcher import VideoCallRequest
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
class _QueuedSignal:
"""Keep worker completion separate from delivery on the simulated UI thread."""
def __init__(self) -> None:
self.queue: Queue[tuple[Any, ...]] = Queue()
def emit(self, *args: Any) -> None:
self.queue.put(args)
def take(self) -> tuple[Any, ...]:
return self.queue.get(timeout=2)
class _Repository:
def __init__(self) -> None:
self.events: list[tuple[Any, ...]] = []
self.record_ids = count(701)
self.block_record_id: int | None = None
self.bind_entered = Event()
self.release_bind = Event()
def start_call(self, diagnosis_id: int, patient_id: int, **kwargs: Any) -> dict[str, int]:
assert (diagnosis_id, patient_id, kwargs["call_type"]) == (123, 8, 2)
record_id = next(self.record_ids)
self.events.append(("start", record_id))
return {"call_record_id": record_id}
def bind_call_room(self, diagnosis_id: int, room_id: str, *, call_record_id: int) -> None:
assert diagnosis_id == 123
if call_record_id == self.block_record_id:
self.bind_entered.set()
assert self.release_bind.wait(5), "test did not release the pending room bind"
self.events.append(("bind", call_record_id, room_id))
def end_call(self, diagnosis_id: int, *, call_record_id: int) -> None:
assert diagnosis_id == 123
self.events.append(("end", call_record_id))
class _Host:
def __init__(self) -> None:
self.repository = _Repository()
self.request = VideoCallRequest(
sdk_app_id=1400123456,
user_id="doctor_42",
user_sig="test-ticket",
target_user_id="patient_8",
diagnosis_id=123,
patient_id=8,
)
self.lifecycle = self._lifecycle_factory()
self._lifecycles = [self.lifecycle]
self._closing = False
self._released = False
self._shutdown_requested = False
self._start_requested = False
self._call_cycle_closed = False
self.open_im = True
self._page = Mock()
self.call_ended = Mock()
self._start_completed = _QueuedSignal()
self._room_completed = _QueuedSignal()
for name in (
"_handle_bridge_message", "_prepare_call_cycle", "_start_call_cycle",
"_notify_start_completed", "_on_lifecycle_started",
"_notify_room_completed", "_on_room_completed",
):
setattr(self, name, MethodType(getattr(window._EmbeddedVideoWindow, name), self))
def _lifecycle_factory(self) -> OrderedCallLifecycle:
return OrderedCallLifecycle(self.request, self.repository, logging.getLogger(__name__))
def start(self) -> OrderedCallLifecycle:
self._handle_bridge_message({"event": "call-start-request"})
assert self._start_completed.take() == (True,)
self._on_lifecycle_started(True)
self._page.runJavaScript.assert_called_with(
"window.doctorConsultation?.hostCallReady?.(true, '');"
)
self._page.reset_mock()
return self.lifecycle
def room(self, room_id: str) -> None:
self._handle_bridge_message({"event": "room", "roomId": room_id})
def hangup(self) -> None:
self._handle_bridge_message({"event": "hangup"})
@pytest.fixture
def host() -> Iterator[_Host]:
current = _Host()
try:
yield current
finally:
current.repository.release_bind.set()
for lifecycle in current._lifecycles:
lifecycle.end("test-cleanup").result(timeout=2)
assert lifecycle.wait(2)
def test_three_calls_in_one_im_window_bind_their_own_record_and_room(host: _Host) -> None:
for record_id, room_id in ((701, "r1"), (702, "r2"), (703, "r3")):
lifecycle = host.start()
assert lifecycle.call_record_id == record_id
host.room(room_id)
acknowledgement = host._room_completed.take()
assert acknowledgement[:3] == (lifecycle, room_id, True)
host._on_room_completed(*acknowledgement)
script = host._page.runJavaScript.call_args.args[0]
assert f'roomBindingResult?.("{room_id}", true,' in script
host.hangup()
assert lifecycle.wait(2)
assert len({id(lifecycle) for lifecycle in host._lifecycles}) == 3
assert host.repository.events == [
("start", 701), ("bind", 701, "r1"), ("end", 701),
("start", 702), ("bind", 702, "r2"), ("end", 702),
("start", 703), ("bind", 703, "r3"), ("end", 703),
]
@pytest.mark.parametrize("next_room", ["r1", "r2"])
@pytest.mark.parametrize("worker_finishes_before_redial", [False, True])
def test_old_room_ack_cannot_reach_next_call_even_when_room_is_reused(
host: _Host, next_room: str, worker_finishes_before_redial: bool,
) -> None:
previous = host.start()
if not worker_finishes_before_redial:
host.repository.block_record_id = 701
host.room("r1")
if worker_finishes_before_redial:
old_ack = host._room_completed.take()
else:
assert host.repository.bind_entered.wait(2)
host.hangup()
current = host.start()
assert current is not previous
if not worker_finishes_before_redial:
host.repository.release_bind.set()
old_ack = host._room_completed.take()
assert old_ack[:3] == (previous, "r1", True)
host._on_room_completed(*old_ack)
host._page.runJavaScript.assert_not_called()
host.room(next_room)
current_ack = host._room_completed.take()
assert current_ack[:3] == (current, next_room, True)
host._on_room_completed(*current_ack)
assert host._page.runJavaScript.call_count == 1
assert current.bound_room_id == next_room
assert ("bind", 702, next_room) in host.repository.events
def test_ended_call_drops_room_ack_queued_before_hangup(host: _Host) -> None:
host.start()
host.room("r1")
acknowledgement = host._room_completed.take()
host.hangup()
host._on_room_completed(*acknowledgement)
host._page.runJavaScript.assert_not_called()
@pytest.mark.parametrize("state", ["ready", "ended", "prepared"])
def test_room_event_without_active_call_cannot_create_a_record(host: _Host, state: str) -> None:
if state != "ready":
host.start()
host.hangup()
assert host.lifecycle.wait(2)
if state == "prepared":
# Policy refresh prepares a new lifecycle before call-start-request.
host._prepare_call_cycle()
before = list(host.repository.events)
host.room("late-room")
host.lifecycle.end("test-barrier").result(timeout=2)
assert host.lifecycle.wait(2)
assert host.repository.events == before
assert host.lifecycle.current_room_id is None
assert host._room_completed.queue.empty()