"""Test doubles: an in-process capture backend and the fake capture command.""" from __future__ import annotations import pathlib import socket import struct import sys import threading import time from fake_capture import png_bytes # noqa: F401 (re-exported for the tests) from hhstream.capture import CaptureError #: argv prefix for the fake `grim`; append its flags. FAKE_CAPTURE = [sys.executable, str(pathlib.Path(__file__).with_name("fake_capture.py"))] class FakeCapture: """A `CaptureBackend` with no subprocess: deterministic, fast, scriptable.""" def __init__(self, frames=None, size=(1280, 720), fail_until=0, delay=0.0): self.frames = list(frames) if frames else [png_bytes(4, 2)] self._size = size self.fail_until = fail_until 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_until: raise CaptureError(f"simulated capture failure {call}") return self.frames[(call - 1 - self.fail_until) % len(self.frames)] def size(self) -> tuple[int, int]: if self.calls <= self.fail_until: raise CaptureError("size is not known yet") return self._size def distinct_frames(count: int) -> list[bytes]: """`count` unique, decodable PNGs, in order.""" return [png_bytes(4, 2, (i % 251, (i * 7) % 251, (i * 13) % 251)) for i in range(1, count + 1)] def connect(path: str, timeout: float = 5.0, rcvbuf: int | None = None) -> socket.socket: conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if rcvbuf is not None: conn.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf) conn.settimeout(timeout) conn.connect(path) return conn def abort(conn: socket.socket) -> None: """Close with SO_LINGER 0: the peer sees the connection torn down, not EOF.""" conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) conn.close()