The union of main and the four slices cannot be collected by pytest: an import-file-mismatch on test_protocol.py (the frame wire's, the broker's) and test_server.py (the frame server's, the pointer driver's). Per-directory runs never hit it, so this is what the union run is for. The tempting fix is --import-mode=importlib, and it is wrong: importlib does not put a test file's directory on sys.path, which the slices' tests rely on for sibling imports (from conftest import HANG, from test_ops import RecordingSink). That trades a collection error for an ImportError. Renaming the two colliding modules keeps the import behaviour and fixes the actual problem: tests/pointer/test_server.py -> test_pointer_server.py tests/sessions/unit/test_protocol.py -> test_broker_protocol.py tests: 551 passed.
137 lines
4.5 KiB
Python
137 lines
4.5 KiB
Python
"""The driver's socket: framing, not logic.
|
|
|
|
The dispatcher is tested next door; what is proved here is that a real
|
|
``AF_UNIX`` connection carrying newline-delimited JSON gets one response object
|
|
per request line, that a garbled line is answered rather than fatal, and that
|
|
the connection stays open for the next request — which matters because the
|
|
broker holds one connection for the life of a lease.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import shutil
|
|
import socket
|
|
import tempfile
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from hhstream_pointer.ops import Dispatcher
|
|
from hhstream_pointer.server import PointerServer
|
|
|
|
from test_ops import RecordingSink
|
|
|
|
#: Linux's sun_path is 108 bytes including the NUL, and pytest's tmp_path can
|
|
#: exceed it, so the socket lives in a shallow directory of its own.
|
|
SUN_PATH_MAX = 107
|
|
|
|
|
|
@pytest.fixture
|
|
def connection():
|
|
"""A listening driver and a connected client, torn down together."""
|
|
|
|
directory = Path(tempfile.mkdtemp(prefix="hhp"))
|
|
path = directory / "p.sock"
|
|
if len(str(path).encode()) > SUN_PATH_MAX:
|
|
pytest.skip(f"socket path too long for AF_UNIX: {path}")
|
|
|
|
sink = RecordingSink()
|
|
server = PointerServer(path, Dispatcher(sink).handle)
|
|
server.listen()
|
|
thread = threading.Thread(target=_serve_once, args=(server,), daemon=True)
|
|
thread.start()
|
|
|
|
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
client.settimeout(5.0)
|
|
client.connect(str(path))
|
|
try:
|
|
yield _Client(client), sink
|
|
finally:
|
|
client.close()
|
|
thread.join(timeout=5.0)
|
|
server.close()
|
|
shutil.rmtree(directory, ignore_errors=True)
|
|
|
|
|
|
def _serve_once(server: PointerServer) -> None:
|
|
conn, _ = server._sock.accept()
|
|
with conn:
|
|
server._serve_connection(conn)
|
|
|
|
|
|
class _Client:
|
|
def __init__(self, sock: socket.socket) -> None:
|
|
self._stream = sock.makefile("rwb")
|
|
|
|
def call(self, request: dict) -> dict:
|
|
self._stream.write(json.dumps(request).encode() + b"\n")
|
|
self._stream.flush()
|
|
return json.loads(self._stream.readline())
|
|
|
|
def send_raw(self, line: bytes) -> dict:
|
|
self._stream.write(line)
|
|
self._stream.flush()
|
|
return json.loads(self._stream.readline())
|
|
|
|
|
|
def test_one_request_gets_one_response(connection):
|
|
client, _ = connection
|
|
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": []}
|
|
|
|
|
|
def test_many_requests_share_one_connection(connection):
|
|
client, sink = connection
|
|
assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True}
|
|
assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True}
|
|
assert client.call({"op": "frame"}) == {"ok": True}
|
|
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": ["left"]}
|
|
assert client.call({"op": "release_all"}) == {"ok": True, "lifted": ["left"]}
|
|
assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"]
|
|
|
|
|
|
def test_a_rejected_request_leaves_the_connection_usable(connection):
|
|
client, _ = connection
|
|
assert client.call({"op": "nonsense"})["ok"] is False
|
|
assert client.call({"op": "pressed"})["ok"] is True
|
|
|
|
|
|
def test_malformed_json_is_answered_not_fatal(connection):
|
|
client, _ = connection
|
|
response = client.send_raw(b"{not json\n")
|
|
assert response["ok"] is False
|
|
assert "malformed JSON" in response["error"]
|
|
# Still talking.
|
|
assert client.call({"op": "pressed"})["ok"] is True
|
|
|
|
|
|
def test_an_oversized_line_is_refused(connection):
|
|
from hhstream_pointer.server import MAX_LINE_BYTES
|
|
|
|
client, _ = connection
|
|
response = client.send_raw(b'{"op":"' + b"x" * MAX_LINE_BYTES + b'"}\n')
|
|
assert response == {"ok": False, "error": "request line too long"}
|
|
|
|
|
|
def test_listen_replaces_a_stale_socket_file():
|
|
"""A crashed driver leaves the file behind; the unit must still start."""
|
|
|
|
directory = Path(tempfile.mkdtemp(prefix="hhp"))
|
|
path = directory / "p.sock"
|
|
if len(str(path).encode()) > SUN_PATH_MAX:
|
|
pytest.skip("socket path too long for AF_UNIX")
|
|
try:
|
|
first = PointerServer(path, Dispatcher(RecordingSink()).handle)
|
|
first.listen()
|
|
first._sock.close() # the file survives; the listener does not
|
|
|
|
second = PointerServer(path, Dispatcher(RecordingSink()).handle)
|
|
second.listen()
|
|
assert path.is_socket()
|
|
assert path.stat().st_mode & 0o777 == 0o660
|
|
second.close()
|
|
assert not path.exists()
|
|
finally:
|
|
shutil.rmtree(directory, ignore_errors=True)
|