"""Shared doubles for the session-stream web app suite. Kept out of `conftest.py` on purpose: the rest of the suite imports its doubles from a plain module (`tests/unit/helpers.py`), and `import conftest` by name is fragile across directories. """ from __future__ import annotations import pathlib import sys import threading import time _HERE = pathlib.Path(__file__).resolve().parent _SRC = _HERE.parents[1] / "src" for _path in (str(_HERE), str(_SRC)): if _path not in sys.path: sys.path.insert(0, _path) from fake_jpeg import jpeg_bytes # noqa: E402 #: The one phrase the suite enables. Shape matters, not the words. PHRASE = "amber-otter-lantern-harbor-7k2qp" class StubCapture: """A `Capture` under the test's control: counts grabs, can be told to fail.""" def __init__(self, frames=None, fail_first: int = 0, delay: float = 0.0): self.frames = list(frames) if frames else [jpeg_bytes(i) for i in range(1, 50)] self.fail_first = fail_first self.delay = delay self.calls = 0 self._lock = threading.Lock() def grab(self) -> bytes: with self._lock: self.calls += 1 call = self.calls if self.delay: time.sleep(self.delay) if call <= self.fail_first: raise RuntimeError(f"stub capture failing on purpose (call {call})") return self.frames[(call - 1 - self.fail_first) % len(self.frames)] def read_parts(resp, count: int, timeout: float = 10.0) -> list[bytes]: """Read up to `count` JPEG parts out of a multipart MJPEG response.""" from hhstream_live.server import BOUNDARY boundary = ("--" + BOUNDARY).encode("ascii") parts: list[bytes] = [] buf = b"" deadline = time.monotonic() + timeout while len(parts) < count and time.monotonic() < deadline: chunk = resp.read(4096) if not chunk: break buf += chunk while True: start = buf.find(boundary) if start < 0: break header_end = buf.find(b"\r\n\r\n", start) if header_end < 0: break header = buf[start:header_end].decode("latin-1") length = None for line in header.splitlines(): if line.lower().startswith("content-length:"): length = int(line.split(":", 1)[1].strip()) if length is None: break body_start = header_end + 4 if len(buf) < body_start + length: break parts.append(buf[body_start:body_start + length]) buf = buf[body_start + length + 2:] if len(parts) >= count: break return parts[:count]