"""Shared fixtures. Two things are worth knowing: * **Nothing here sleeps for real time** except where the brief requires it: the one integration test that proves a real three-second idle reap. Everything else either injects a clock or polls with a deadline. * **Unix socket paths are short by force.** ``AF_UNIX`` caps a path at 108 bytes and ``pytest``'s ``tmp_path`` can exceed that on a deep ``TMPDIR``, so sockets live in a shallow ``mkdtemp`` of their own rather than under ``tmp_path``. """ from __future__ import annotations import os import shutil import socket import sys import tempfile import time from pathlib import Path import pytest # `tests/` for the shared helpers, and this directory for `fakes`, which the # unit tests and the integration tests both import. sys.path.insert(0, str(Path(__file__).resolve().parents[1])) sys.path.insert(0, str(Path(__file__).resolve().parent)) #: Linux's sun_path is 108 bytes including the NUL. SUN_PATH_MAX = 107 @pytest.fixture def short_tmpdir() -> Path: """A temp directory shallow enough to hold a unix socket path.""" path = Path(tempfile.mkdtemp(prefix="hh")) try: yield path finally: shutil.rmtree(path, ignore_errors=True) def socket_path(directory: Path, name: str = "c.sock") -> str: path = str(directory / name) if len(path.encode()) > SUN_PATH_MAX: pytest.skip(f"socket path too long for AF_UNIX ({len(path)} bytes): {path}") return path def wait_until(predicate, timeout: float, interval: float = 0.02, what: str = "condition"): """Poll ``predicate`` until it is truthy. Returns its value, or fails. This is how the integration tests wait: a deadline and a tight poll, never a fixed sleep sized by guesswork. """ deadline = time.monotonic() + timeout while True: value = predicate() if value: return value if time.monotonic() > deadline: pytest.fail(f"timed out after {timeout}s waiting for {what}") time.sleep(interval) def pid_alive(pid: int) -> bool: return os.path.isdir(f"/proc/{pid}") def socket_is_live(path: str) -> bool: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: sock.settimeout(0.5) sock.connect(path) return True except OSError: return False finally: sock.close()