feat(live): one port, a router, and a phrase per session (stage 1)
The session-stream web app: a single HTTP listener (9988) that serves a page
per enabled session, keyed by a spoken phrase.
src/hhstream_live/phrase.py four EFF-large words + a 5-char base-36 tail
(~77.5 bits); the phrase is the password
src/hhstream_live/publisher.py one capture thread + one frame slot per
output, one slot/no queue, capture paused at
zero viewers
src/hhstream_live/server.py the router: /, /<phrase>/, /stream.mjpg,
/frame.jpg, /status.json; unknown phrase is
an empty 404, rate-limited
src/hhstream_live/pages.py the built-in dark pages (no CDN, no build)
src/hhstream_live/__main__.py hhstream-live serve|phrase, standalone
The root page is a form, never a list: the phrase is known only by whoever
enabled the stream. Tests: tests/live (51), all green with the full suite
(958). Not yet wired to the broker -- that is stage 2.
This commit is contained in:
1 parent
edbf15f259
commit
d770bcd298
17 files changed
+9330
-18
No files matched your search
@@ -0,0 +1,86 @@
|
||||
"""Fixtures for the session-stream web app suite.
|
||||
|
||||
Everything is standard library and everything is in-process: a real
|
||||
`LiveServer` on a loopback ephemeral port, fed by a stub capture, with plain
|
||||
`http.client` for the requests. No compositor, no `grim`, no broker.
|
||||
|
||||
The doubles (`StubCapture`, `read_parts`, `PHRASE`) live in `live_helpers.py`, not
|
||||
here, so the tests import them by a plain module name -- the same shape as
|
||||
`tests/unit`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import http.client
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
_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
|
||||
from live_helpers import PHRASE, StubCapture # noqa: E402
|
||||
from hhstream_live.publisher import StreamRegistry, StreamSpec # noqa: E402
|
||||
from hhstream_live.server import LiveServer, RateLimiter # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jpg():
|
||||
return jpeg_bytes
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry():
|
||||
reg = StreamRegistry()
|
||||
yield reg
|
||||
reg.stop_all()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def serve(registry):
|
||||
"""`with serve(phrase=..., capture=..., fps=...) as (server, capture)`."""
|
||||
servers: list[LiveServer] = []
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _serve(*, phrase: str = PHRASE, capture: StubCapture | None = None,
|
||||
fps: int = 5, label: str = "demo", limit: int = 30):
|
||||
capture = capture or StubCapture()
|
||||
spec = StreamSpec(phrase=phrase, output="hh-demo", fps=fps, session="demo",
|
||||
label=label)
|
||||
registry.add(spec, capture)
|
||||
server = LiveServer(registry, host="127.0.0.1", port=0,
|
||||
limiter=RateLimiter(limit=limit))
|
||||
servers.append(server)
|
||||
server.start()
|
||||
assert server.ready.wait(5)
|
||||
try:
|
||||
yield server, capture
|
||||
finally:
|
||||
server.stop()
|
||||
|
||||
yield _serve
|
||||
for server in servers:
|
||||
with contextlib.suppress(Exception):
|
||||
server.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def http_conn():
|
||||
"""Open an HTTP connection to a running server; closed at teardown."""
|
||||
connections: list[http.client.HTTPConnection] = []
|
||||
|
||||
def _connect(server: LiveServer, timeout: float = 10.0) -> http.client.HTTPConnection:
|
||||
conn = http.client.HTTPConnection("127.0.0.1", server.port, timeout=timeout)
|
||||
connections.append(conn)
|
||||
return conn
|
||||
|
||||
yield _connect
|
||||
for conn in connections:
|
||||
with contextlib.suppress(Exception):
|
||||
conn.close()
|
||||
@@ -0,0 +1,31 @@
|
||||
"""A tiny real JPEG, for tests that need decodable image bytes.
|
||||
|
||||
The frame server's tests use a fake that writes a PNG (zlib is in the standard
|
||||
library). MJPEG needs *JPEG* parts, and there is no JPEG encoder in the stdlib,
|
||||
so the smallest honest thing is one real 1x1 JPEG embedded as base64 and reused.
|
||||
|
||||
`jpeg_bytes(marker)` rewrites one *quantisation-table* byte, so two frames differ
|
||||
byte-for-byte (a test can prove "a new frame arrived") while the image stays
|
||||
valid: the EOI marker, the headers and the scan data are untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
#: A 1x1 JPEG. Real enough that `hhstream.capture.image_size` reports (1, 1).
|
||||
_ONE_PIXEL = (
|
||||
"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRof"
|
||||
"Hh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCAABAAEBAREA/8QAFAAB"
|
||||
"AAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AVN//2Q=="
|
||||
)
|
||||
#: The start of the quantisation table: `FFDB`, length `0043`, precision/id `00`.
|
||||
_DQT = b"\xff\xdb\x00C\x00"
|
||||
|
||||
|
||||
def jpeg_bytes(marker: int = 0) -> bytes:
|
||||
"""The 1x1 JPEG with one table byte varied by `marker` (0..249)."""
|
||||
data = bytearray(base64.b64decode(_ONE_PIXEL))
|
||||
start = data.index(_DQT) + len(_DQT)
|
||||
data[start + 63] = (marker % 250) + 1 # a nonzero quantiser keeps it decodable
|
||||
return bytes(data)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The command line: it aims a capture at an output, and it can mint a phrase."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from contextlib import redirect_stdout
|
||||
|
||||
import pytest
|
||||
from hhstream_live.__main__ import DEFAULT_CAPTURE, capture_argv, main, parse_stream
|
||||
|
||||
|
||||
def test_capture_command_is_aimed_by_inserting_the_output_before_stdout():
|
||||
assert capture_argv(DEFAULT_CAPTURE, "hh-demo") == [
|
||||
"grim", "-c", "-t", "jpeg", "-q", "80", "-o", "hh-demo", "-",
|
||||
]
|
||||
|
||||
|
||||
def test_capture_command_without_a_trailing_dash_gets_the_output_appended():
|
||||
assert capture_argv(["grim", "-t", "jpeg"], "hh-x") == [
|
||||
"grim", "-t", "jpeg", "-o", "hh-x",
|
||||
]
|
||||
|
||||
|
||||
def test_parse_stream_reads_a_pair_and_normalizes_the_phrase():
|
||||
assert parse_stream("Amber-Otter-Lantern-Harbor-7K2QP=hh-demo") == (
|
||||
"amber-otter-lantern-harbor-7k2qp", "hh-demo",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["no-equals-sign", "=hh-demo", "phrase=", "ab=hh"])
|
||||
def test_parse_stream_rejects_a_bad_pair(bad):
|
||||
import argparse
|
||||
|
||||
with pytest.raises(argparse.ArgumentTypeError):
|
||||
parse_stream(bad)
|
||||
|
||||
|
||||
def test_the_phrase_subcommand_prints_a_phrase():
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
assert main(["phrase"]) == 0
|
||||
printed = out.getvalue().strip()
|
||||
assert printed.count("-") == 4 # four words + tail
|
||||
|
||||
|
||||
def test_the_phrase_subcommand_can_print_several():
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
main(["phrase", "--count", "3"])
|
||||
assert len(out.getvalue().split()) == 3
|
||||
@@ -0,0 +1,63 @@
|
||||
"""The phrase: shape, entropy, and the rejection of anything unusable."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from hhstream_live import phrase
|
||||
|
||||
SHAPE = re.compile(r"^[a-z]+(-[a-z]+){3}-[a-z0-9]{5}$")
|
||||
|
||||
|
||||
def test_generated_phrase_has_the_agreed_shape():
|
||||
for _ in range(50):
|
||||
generated = phrase.generate()
|
||||
assert SHAPE.match(generated), generated
|
||||
head, _, tail = generated.rpartition("-")
|
||||
assert len(tail) == 5
|
||||
assert all(word in phrase.words() for word in head.split("-"))
|
||||
|
||||
|
||||
def test_entropy_is_what_the_plan_claims():
|
||||
# Four EFF-large words plus a five-character base-36 tail, ~77.5 bits.
|
||||
assert phrase.entropy_bits() > 75
|
||||
|
||||
|
||||
def test_wordlist_is_the_eff_large_list():
|
||||
words = phrase.words()
|
||||
assert len(words) == 7776
|
||||
assert len(set(words)) == 7776
|
||||
assert "abacus" in words
|
||||
|
||||
|
||||
def test_generate_is_not_reproducible_from_a_seed():
|
||||
# SystemRandom/secrets: seeding the module RNG must not pin the output.
|
||||
import random
|
||||
|
||||
random.seed(1234)
|
||||
first = phrase.generate()
|
||||
random.seed(1234)
|
||||
second = phrase.generate()
|
||||
assert first != second
|
||||
|
||||
|
||||
def test_normalize_lowercases_and_trims():
|
||||
assert phrase.normalize(" Amber-Otter-7K2 ") == "amber-otter-7k2"
|
||||
|
||||
|
||||
def test_validate_accepts_a_good_phrase_and_returns_the_normalized_form():
|
||||
assert phrase.validate("Amber-Otter-Lantern-7K2QP") == "amber-otter-lantern-7k2qp"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "single", "two-tokens", "has space-phrase-x",
|
||||
"dash--double-phrase", "-leading-hyphen",
|
||||
"trailing-hyphen-", "under_score-in-phrase"])
|
||||
def test_validate_rejects_a_phrase_that_is_not_the_shape(bad):
|
||||
with pytest.raises(ValueError):
|
||||
phrase.validate(bad)
|
||||
|
||||
|
||||
def test_validate_rejects_an_overlong_phrase():
|
||||
with pytest.raises(ValueError):
|
||||
phrase.validate("-".join(["averyverylongword"] * 8))
|
||||
@@ -0,0 +1,125 @@
|
||||
"""The publisher: no capture while unwatched, one slot, and giving up when dead."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from live_helpers import PHRASE, StubCapture
|
||||
from hhstream_live.publisher import (FPS_CAP, FAILURE_LIMIT, Stream, StreamRegistry,
|
||||
StreamSpec)
|
||||
|
||||
|
||||
def make_stream(capture, *, fps=10, phrase=PHRASE):
|
||||
return Stream(StreamSpec(phrase=phrase, output="hh-demo", fps=fps), capture)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [0, -1, True, 1.5, FPS_CAP + 1])
|
||||
def test_fps_must_be_a_positive_int_within_the_cap(bad):
|
||||
with pytest.raises(ValueError):
|
||||
make_stream(StubCapture(), fps=bad)
|
||||
|
||||
|
||||
def test_no_capture_while_nobody_is_watching():
|
||||
"""An enabled stream costs nothing until a request arrives."""
|
||||
capture = StubCapture()
|
||||
stream = make_stream(capture)
|
||||
stream.start()
|
||||
try:
|
||||
time.sleep(0.4)
|
||||
assert capture.calls == 0
|
||||
finally:
|
||||
stream.stop()
|
||||
|
||||
|
||||
def test_capture_starts_when_a_viewer_arrives_and_stops_when_it_leaves():
|
||||
capture = StubCapture()
|
||||
stream = make_stream(capture)
|
||||
stream.start()
|
||||
try:
|
||||
stream.add_viewer()
|
||||
frame, seq = stream.wait_frame(0, timeout=5)
|
||||
assert frame and seq >= 1
|
||||
stream.remove_viewer()
|
||||
time.sleep(0.3)
|
||||
settled = capture.calls
|
||||
time.sleep(0.4)
|
||||
assert capture.calls == settled # idle again
|
||||
finally:
|
||||
stream.stop()
|
||||
|
||||
|
||||
def test_snapshot_is_none_before_anyone_watches_and_bytes_after():
|
||||
stream = make_stream(StubCapture())
|
||||
stream.start()
|
||||
try:
|
||||
assert stream.snapshot() is None
|
||||
stream.add_viewer()
|
||||
frame, _ = stream.wait_frame(0, timeout=5)
|
||||
stream.remove_viewer()
|
||||
assert frame is not None
|
||||
assert stream.snapshot() == frame
|
||||
finally:
|
||||
stream.stop()
|
||||
|
||||
|
||||
def test_a_slow_viewer_does_not_queue_frames():
|
||||
"""One slot: a viewer that sleeps sees the latest frame, never a backlog."""
|
||||
stream = make_stream(StubCapture(delay=0.01), fps=10)
|
||||
stream.start()
|
||||
try:
|
||||
stream.add_viewer()
|
||||
first, seq = stream.wait_frame(0, timeout=5)
|
||||
time.sleep(0.3) # let many frames go by unsent
|
||||
later, seq2 = stream.wait_frame(seq, timeout=5)
|
||||
assert later is not None
|
||||
# seq jumped by more than one: the frames in between were dropped, not
|
||||
# buffered for us.
|
||||
assert seq2 > seq + 1
|
||||
finally:
|
||||
stream.stop()
|
||||
|
||||
|
||||
def test_a_dead_capture_gives_up_and_closes_viewers():
|
||||
capture = StubCapture(fail_first=10_000) # never succeeds
|
||||
stream = make_stream(capture, fps=10)
|
||||
stream.start()
|
||||
try:
|
||||
stream.add_viewer()
|
||||
frame, _ = stream.wait_frame(0, timeout=10)
|
||||
assert frame is None
|
||||
assert stream.stopped
|
||||
assert capture.calls >= FAILURE_LIMIT
|
||||
finally:
|
||||
stream.stop()
|
||||
|
||||
|
||||
# ---- registry --------------------------------------------------------------
|
||||
|
||||
def test_registry_adds_and_finds_a_phrase_case_insensitively():
|
||||
registry = StreamRegistry()
|
||||
try:
|
||||
registry.add(StreamSpec(phrase=PHRASE, output="hh-demo"), StubCapture())
|
||||
assert registry.get("Amber-Otter-Lantern-Harbor-7K2QP") is not None
|
||||
assert registry.get("nope-not-here-at-all") is None
|
||||
finally:
|
||||
registry.stop_all()
|
||||
|
||||
|
||||
def test_registry_refuses_a_duplicate_phrase():
|
||||
registry = StreamRegistry()
|
||||
try:
|
||||
registry.add(StreamSpec(phrase=PHRASE, output="hh-demo"), StubCapture())
|
||||
with pytest.raises(ValueError):
|
||||
registry.add(StreamSpec(phrase=PHRASE, output="hh-other"), StubCapture())
|
||||
finally:
|
||||
registry.stop_all()
|
||||
|
||||
|
||||
def test_registry_remove_stops_the_stream():
|
||||
registry = StreamRegistry()
|
||||
stream = registry.add(StreamSpec(phrase=PHRASE, output="hh-demo"), StubCapture())
|
||||
assert registry.remove(PHRASE) is stream
|
||||
assert registry.get(PHRASE) is None
|
||||
assert stream.stopped
|
||||
assert registry.remove(PHRASE) is None
|
||||
@@ -0,0 +1,165 @@
|
||||
"""The web app's obligations: the router, the pages, and MJPEG over one port."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from live_helpers import PHRASE, StubCapture, read_parts
|
||||
from hhstream_live.server import BOUNDARY
|
||||
|
||||
WRONG = "no-such-phrase-here-00000"
|
||||
|
||||
|
||||
def get(conn, path):
|
||||
conn.request("GET", path)
|
||||
resp = conn.getresponse()
|
||||
body = resp.read()
|
||||
return resp.status, resp, body
|
||||
|
||||
|
||||
def test_landing_page_is_a_form_and_names_no_phrase(serve, http_conn):
|
||||
with serve() as (server, _capture):
|
||||
conn = http_conn(server)
|
||||
status, resp, body = get(conn, "/")
|
||||
assert status == 200
|
||||
assert resp.getheader("Content-Type").startswith("text/html")
|
||||
assert PHRASE not in body.decode()
|
||||
assert "hh-demo" not in body.decode()
|
||||
assert b"phrase" in body.lower()
|
||||
|
||||
|
||||
def test_healthz(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, _, body = get(http_conn(server), "/healthz")
|
||||
assert status == 200 and body.strip() == b"ok"
|
||||
|
||||
|
||||
def test_unknown_phrase_is_404_with_an_empty_body(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, resp, body = get(http_conn(server), f"/{WRONG}/")
|
||||
assert status == 404
|
||||
assert body == b""
|
||||
assert WRONG not in resp.getheader("Content-Type", "")
|
||||
|
||||
|
||||
def test_a_wrong_subpath_under_a_valid_phrase_is_404(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, _, body = get(http_conn(server), f"/{PHRASE}/secrets.txt")
|
||||
assert status == 404 and body == b""
|
||||
|
||||
|
||||
def test_viewer_page_names_the_output_and_points_at_the_stream(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, _, body = get(http_conn(server), f"/{PHRASE}/")
|
||||
assert status == 200
|
||||
page = body.decode()
|
||||
assert f"/{PHRASE}/stream.mjpg" in page
|
||||
assert "hh-demo" in page
|
||||
|
||||
|
||||
def test_phrase_is_case_insensitive(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, _, _ = get(http_conn(server), f"/{PHRASE.upper()}/")
|
||||
assert status == 200
|
||||
|
||||
|
||||
def test_status_json_shape(serve, http_conn):
|
||||
import json
|
||||
|
||||
with serve() as (server, _):
|
||||
status, resp, body = get(http_conn(server), f"/{PHRASE}/status.json")
|
||||
assert status == 200
|
||||
assert resp.getheader("Content-Type").startswith("application/json")
|
||||
doc = json.loads(body)
|
||||
assert doc["session"] == "demo"
|
||||
assert doc["output"] == "hh-demo"
|
||||
assert doc["fps"] == 5
|
||||
assert doc["viewers"] == 0
|
||||
assert doc["stopped"] is False
|
||||
|
||||
|
||||
def test_snapshot_is_503_until_someone_has_watched(serve, http_conn):
|
||||
with serve() as (server, _):
|
||||
status, _, body = get(http_conn(server), f"/{PHRASE}/frame.jpg")
|
||||
assert status == 503 and body == b""
|
||||
|
||||
|
||||
def test_stream_is_mjpeg_and_delivers_valid_jpeg_parts(serve, http_conn):
|
||||
with serve(fps=10) as (server, capture):
|
||||
conn = http_conn(server)
|
||||
conn.request("GET", f"/{PHRASE}/stream.mjpg")
|
||||
resp = conn.getresponse()
|
||||
assert resp.status == 200
|
||||
assert resp.getheader("Content-Type") == (
|
||||
f"multipart/x-mixed-replace; boundary={BOUNDARY}"
|
||||
)
|
||||
parts = read_parts(resp, 2)
|
||||
assert len(parts) == 2
|
||||
for part in parts:
|
||||
assert part.startswith(b"\xff\xd8") # JPEG SOI
|
||||
assert part.endswith(b"\xff\xd9") # JPEG EOI
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_snapshot_works_after_a_viewer_has_pulled_a_frame(serve, http_conn):
|
||||
with serve(fps=10) as (server, _):
|
||||
stream_conn = http_conn(server)
|
||||
stream_conn.request("GET", f"/{PHRASE}/stream.mjpg")
|
||||
resp = stream_conn.getresponse()
|
||||
assert read_parts(resp, 1)
|
||||
stream_conn.close()
|
||||
time.sleep(0.05)
|
||||
|
||||
status, ctype, body = get(http_conn(server), f"/{PHRASE}/frame.jpg")
|
||||
assert status == 200
|
||||
assert ctype.getheader("Content-Type") == "image/jpeg"
|
||||
assert body.startswith(b"\xff\xd8")
|
||||
|
||||
|
||||
def test_two_viewers_both_receive_frames(serve, http_conn):
|
||||
with serve(fps=10) as (server, _):
|
||||
results: dict[str, object] = {}
|
||||
|
||||
def watch(name: str) -> None:
|
||||
conn = http_conn(server)
|
||||
conn.request("GET", f"/{PHRASE}/stream.mjpg")
|
||||
resp = conn.getresponse()
|
||||
results[name] = read_parts(resp, 1)
|
||||
conn.close()
|
||||
|
||||
threads = [threading.Thread(target=watch, args=(n,)) for n in ("a", "b")]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join(timeout=10)
|
||||
assert results["a"] and results["b"]
|
||||
|
||||
|
||||
def test_no_capture_until_a_request_arrives(serve):
|
||||
with serve() as (server, capture):
|
||||
time.sleep(0.4)
|
||||
assert capture.calls == 0
|
||||
import http.client
|
||||
|
||||
conn = http.client.HTTPConnection("127.0.0.1", server.port, timeout=10)
|
||||
conn.request("GET", f"/{PHRASE}/stream.mjpg")
|
||||
resp = conn.getresponse()
|
||||
assert read_parts(resp, 1)
|
||||
conn.close()
|
||||
assert capture.calls >= 1
|
||||
|
||||
|
||||
def test_repeated_wrong_phrases_are_rate_limited(serve, http_conn):
|
||||
with serve(limit=3) as (server, _):
|
||||
conn = http_conn(server)
|
||||
seen = [get(conn, f"/{WRONG}-{i}/")[0] for i in range(3)]
|
||||
assert seen == [404, 404, 404]
|
||||
assert get(conn, f"/{WRONG}-9/")[0] == 429
|
||||
|
||||
|
||||
def test_the_server_binds_and_reports_its_port(serve):
|
||||
with serve() as (server, _):
|
||||
assert server.ready.is_set()
|
||||
assert server.port > 0
|
||||
assert server.url_for(PHRASE) == f"http://127.0.0.1:{server.port}/{PHRASE}/"
|
||||
Reference in new issue
Block a user