"""The framing. Other people's clients depend on these bytes being exact.""" from __future__ import annotations import io import json import pytest from hhstream import MAGIC, protocol # -- Hello --------------------------------------------------------------- def test_hello_matches_the_contract_byte_for_byte(): assert protocol.hello(1280, 720, "image/png", 30) == ( b'{"magic":"HHS1","width":1280,"height":720,"format":"image/png","fps":30}\n' ) def test_hello_round_trip(): line = protocol.hello(640, 480, "image/jpeg", 15) assert line.endswith(b"\n") and line.count(b"\n") == 1 assert protocol.parse_hello(line) == { "magic": MAGIC, "width": 640, "height": 480, "format": "image/jpeg", "fps": 15, } def test_parse_hello_tolerates_a_missing_trailing_newline(): line = protocol.hello(8, 8, "image/png", 1) assert protocol.parse_hello(line.rstrip(b"\n")) == protocol.parse_hello(line) @pytest.mark.parametrize("width,height,fps", [(0, 720, 30), (1280, 0, 30), (1280, 720, 0), (-1, 720, 30)]) def test_hello_refuses_a_zero_or_negative_size(width, height, fps): with pytest.raises(ValueError): protocol.hello(width, height, "image/png", fps) @pytest.mark.parametrize("payload", [ b"", b"not json at all", b"[1,2,3]", b'"a string"', b'{"magic":"HHS0","width":1,"height":1,"format":"image/png","fps":1}', b'{"width":1,"height":1,"format":"image/png","fps":1}', b'{"magic":"HHS1","height":1,"format":"image/png","fps":1}', b'{"magic":"HHS1","width":1,"height":1,"fps":1}', b'{"magic":"HHS1","width":1,"height":1,"format":"image/png"}', b'{"magic":"HHS1","width":0,"height":1,"format":"image/png","fps":1}', b'{"magic":"HHS1","width":"1","height":1,"format":"image/png","fps":1}', b'{"magic":"HHS1","width":true,"height":1,"format":"image/png","fps":1}', b'{"magic":"HHS1","width":1,"height":1,"format":"","fps":1}', b'{"magic":"HHS1","width":1,"height":1,"format":"image/png","fps":1}\xff', ]) def test_parse_hello_rejects_bad_input(payload): with pytest.raises(ValueError): protocol.parse_hello(payload) def test_read_hello_then_frames_from_one_stream(): stream = io.BytesIO( protocol.hello(2, 2, "image/png", 5) + protocol.frame(b"one") + protocol.frame(b"two") ) assert protocol.read_hello(stream)["width"] == 2 assert protocol.read_frame(stream) == b"one" assert protocol.read_frame(stream) == b"two" assert protocol.read_frame(stream) is None def test_read_hello_on_a_truncated_line(): with pytest.raises(EOFError): protocol.read_hello(io.BytesIO(b'{"magic":"HHS1"')) def test_read_hello_gives_up_on_an_endless_line(): with pytest.raises(ValueError): protocol.read_hello(_Endless(b"x")) # -- frames -------------------------------------------------------------- @pytest.mark.parametrize("payload", [ b"", b"\n", b"a\nb", b"\n\n\n", b"12\n34", # payload that looks like a frame itself b"\x89PNG\r\n\x1a\n", bytes(range(256)), b"x" * (1 << 20), ]) def test_frame_round_trip(payload): wire = protocol.frame(payload) assert wire.startswith(str(len(payload)).encode("ascii") + b"\n") assert len(wire) == len(payload) + len(str(len(payload))) + 1 assert protocol.read_frame(io.BytesIO(wire)) == payload def test_zero_length_frame_is_a_frame_not_an_eof(): stream = io.BytesIO(protocol.frame(b"") + protocol.frame(b"after")) assert protocol.frame(b"") == b"0\n" assert protocol.read_frame(stream) == b"" assert protocol.read_frame(stream) == b"after" def test_payload_containing_newlines_is_not_resplit(): payload = b"row1\nrow2\n" * 500 stream = io.BytesIO(protocol.frame(payload) + protocol.frame(b"next")) assert protocol.read_frame(stream) == payload assert protocol.read_frame(stream) == b"next" def test_length_prefix_has_no_leading_zeros_and_no_sign(): assert protocol.frame(b"abc") == b"3\nabc" assert not protocol.frame(b"x" * 10).startswith(b"+") def test_read_frame_stops_exactly_at_the_end_of_the_payload(): stream = io.BytesIO(protocol.frame(b"abc") + b"LEFTOVER") assert protocol.read_frame(stream) == b"abc" assert stream.read() == b"LEFTOVER" def test_clean_eof_between_frames_is_none(): assert protocol.read_frame(io.BytesIO(b"")) is None @pytest.mark.parametrize("wire", [ b"\nabc", # empty length prefix b"007\nabcdefg", # leading zero b"0012\n", # leading zeros b"12x\nabc", # not a digit b" 3\nabc", # leading space b"+3\nabc", # sign b"-3\nabc", # negative b"3.0\nabc", # not an integer b"1" * 21 + b"\n", # absurdly long prefix ]) def test_garbage_length_prefix_raises_value_error(wire): with pytest.raises(ValueError): protocol.read_frame(io.BytesIO(wire)) @pytest.mark.parametrize("wire", [ b"5\nabc", # payload short b"5\n", # payload absent b"1048576\n" + b"x" * 1000, b"12", # EOF inside the length prefix ]) def test_truncated_payload_raises_eof_error(wire): with pytest.raises(EOFError): protocol.read_frame(io.BytesIO(wire)) def test_read_frame_gives_up_on_endless_digits_instead_of_hanging(): with pytest.raises(ValueError): protocol.read_frame(_Endless(b"1")) def test_a_huge_length_prefix_does_not_preallocate(): # 10**19 bytes is not going to arrive; we must notice the EOF, not the RAM. with pytest.raises(EOFError): protocol.read_frame(io.BytesIO(b"9999999999999999999\nshort")) def test_frame_rejects_non_bytes(): with pytest.raises(ValueError): protocol.frame("a str is not bytes") # type: ignore[arg-type] def test_hello_is_valid_json_with_the_documented_field_order(): line = protocol.hello(1280, 720, "image/png", 30).decode("utf-8") assert list(json.loads(line)) == ["magic", "width", "height", "format", "fps"] class _Endless: """A stream that never ends and never blocks -- proves we bail out.""" def __init__(self, byte: bytes): self.byte = byte def read(self, size: int = -1) -> bytes: return self.byte * (1 if size in (-1, None) else size)