import json import unittest from kurgan.hw import protocol from kurgan.hw.protocol import ( BAD_REQUEST, HELLO_FIRST, INTERNAL, INVALID, MAX_MESSAGE, PROTOCOL_VERSION, TOO_LARGE, UNAVAILABLE, UNKNOWN_OP, VERSION, LineBuffer, ProtocolError, RemoteError, Session, Unavailable, decode_reply, decode_request, encode_request, ) def line(obj) -> bytes: return json.dumps(obj).encode() class DecodeRequestTest(unittest.TestCase): def assertRejected(self, raw: bytes, code: str): with self.assertRaises(ProtocolError) as caught: decode_request(raw) self.assertEqual(caught.exception.code, code, str(caught.exception)) return caught.exception def test_well_formed_requests(self): request = decode_request(line({"op": "set_profile", "args": {"profile": "quiet"}, "id": 3})) self.assertEqual((request.op, request.args, request.id), ("set_profile", {"profile": "quiet"}, 3)) self.assertEqual(decode_request(line({"op": "state", "id": "a"})).args, {}) # args may be left out chase = decode_request(line({"op": "ram_chase", "id": 1, "args": {"phase": 6, "rate": 6.7, "power": None}})) self.assertEqual(chase.args, {"phase": 6.0, "rate": 6.7, "power": None}) def test_malformed_input_is_rejected(self): for raw in (b"", b"not json", b"[1, 2]", b'"state"', b"\xff\xfe{}", b'{"op": "state"', b'{"op": "state", "id": 1, "id": 2}', # duplicate key b'{"op": "ram_chase", "id": 1, "args": {"phase": NaN, "rate": 1, "power": null}}', b'{"op": "ram_chase", "id": 1, "args": {"phase": Infinity, "rate": 1, "power": null}}', b"[" * 30_000 + b"]" * 30_000, # deep nesting line({"op": "state"}), # no id line({"op": "state", "id": True}), # bool is not an id line({"op": "state", "id": 1.5}), line({"op": "state", "id": "x" * 65}), line({"op": 7, "id": 1}), line({"id": 1})): with self.subTest(raw=raw[:60]): self.assertRejected(raw, BAD_REQUEST) def test_errors_echo_the_id_when_it_was_readable(self): self.assertEqual(self.assertRejected(line({"op": "reboot", "id": 9}), UNKNOWN_OP).request_id, 9) self.assertIsNone(self.assertRejected(line({"op": "state", "id": [1]}), BAD_REQUEST).request_id) def test_unknown_ops_and_fields_are_rejected(self): self.assertRejected(line({"op": "reboot", "id": 1}), UNKNOWN_OP) self.assertRejected(line({"op": "__class__", "id": 1}), UNKNOWN_OP) self.assertRejected(line({"op": "state", "id": 1, "extra": 1}), BAD_REQUEST) self.assertRejected(line({"op": "state", "id": 1, "args": {"verbose": True}}), INVALID) self.assertRejected(line({"op": "set_profile", "id": 1, "args": {"profile": "quiet", "x": 1}}), INVALID) def test_arguments_are_checked_like_the_api_checks_them(self): for args in ({}, {"profile": "turbo"}, {"profile": 1}, {"profile": ["quiet"]}): with self.subTest(args=args): self.assertRejected(line({"op": "set_profile", "id": 1, "args": args}), INVALID) for mode in ("rainbow", "", None, True): with self.subTest(mode=mode): self.assertRejected(line({"op": "set_ram_lighting", "id": 1, "args": {"mode": mode}}), INVALID) for args in ({"phase": 1, "rate": -1, "power": None}, {"phase": "1", "rate": 1, "power": None}, {"phase": 1, "rate": True, "power": None}, {"phase": 1, "rate": 1}, {"phase": 1, "rate": 1, "power": 1e9}): with self.subTest(args=args): self.assertRejected(line({"op": "ram_chase", "id": 1, "args": args}), INVALID) self.assertRejected(line({"op": "state", "id": 1, "args": []}), INVALID) self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": "1"}}), INVALID) self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": 1, "client": "x" * 65}}), INVALID) def test_oversized_messages_are_rejected(self): padding = "x" * MAX_MESSAGE self.assertRejected(line({"op": "state", "id": padding}), TOO_LARGE) with self.assertRaises(ValueError): protocol.encode({"padding": padding}) def test_client_side_encoding_uses_the_same_checks(self): self.assertEqual(json.loads(encode_request("set_profile", {"profile": "full"}, 2)), {"op": "set_profile", "args": {"profile": "full"}, "id": 2}) for op, args in (("set_profile", {"profile": "turbo"}), ("reboot", {}), ("state", {"x": 1})): with self.subTest(op=op): with self.assertRaises(ValueError): encode_request(op, args, 1) class DecodeReplyTest(unittest.TestCase): def test_results_errors_and_mismatches(self): self.assertEqual(decode_reply(line({"id": 4, "ok": True, "result": {"a": 1}}), 4), {"a": 1}) with self.assertRaises(RemoteError) as caught: decode_reply(line({"id": 4, "ok": False, "error": {"code": INVALID, "message": "bad"}}), 4) self.assertEqual((caught.exception.code, str(caught.exception)), (INVALID, "bad")) for reply in ({"id": 5, "ok": True, "result": 1}, # someone else's reply {"id": 4, "ok": 1, "result": 1}, {"id": 4, "ok": True}, {"id": 4, "ok": True, "result": 1, "extra": 2}, {"id": 4, "ok": False, "error": "bad"}, {"id": 4, "ok": False, "error": {"code": "x"}}, [4, True]): with self.subTest(reply=reply): with self.assertRaises(ProtocolError): decode_reply(line(reply), 4) class LineBufferTest(unittest.TestCase): def test_lines_split_across_reads_and_crlf(self): buffer = LineBuffer() self.assertEqual(buffer.feed(b'{"a"'), []) self.assertTrue(buffer.partial) self.assertEqual(buffer.feed(b':1}\r\n{"b":2}\n{"c"'), [b'{"a":1}', b'{"b":2}']) self.assertEqual(buffer.feed(b":3}\n"), [b'{"c":3}']) self.assertFalse(buffer.partial) def test_a_line_over_the_limit_is_refused_before_it_ends(self): buffer = LineBuffer(limit=10) self.assertEqual(buffer.feed(b"x" * 10 + b"\n"), [b"x" * 10]) with self.assertRaises(ProtocolError) as caught: buffer.feed(b"y" * 11) # no newline yet: refused without waiting for the rest self.assertEqual(caught.exception.code, TOO_LARGE) with self.assertRaises(ProtocolError): LineBuffer(limit=10).feed(b"z" * 11 + b"\n") class SessionTest(unittest.TestCase): def setUp(self): self.calls = [] def dispatch(op, args): self.calls.append((op, args)) if args.get("profile") == "quiet": raise ValueError("can't today") if args.get("profile") == "full": raise Unavailable("settings are invalid") if args.get("profile") == "performance": raise RuntimeError("bug") if op == "state": return {"temp": float("nan")} return {"done": op} self.session = Session(dispatch, "9.9.9") def send(self, obj): reply, close = self.session.handle(line(obj) if not isinstance(obj, bytes) else obj) return json.loads(reply), close def hello(self, version=PROTOCOL_VERSION): return self.send({"op": "hello", "id": 0, "args": {"protocol": version, "client": "test"}}) def test_hello_first_then_operations(self): reply, close = self.send({"op": "set_profile", "id": 1, "args": {"profile": "balanced"}}) self.assertEqual((reply["error"]["code"], close), (HELLO_FIRST, False)) self.assertEqual(self.calls, []) reply, close = self.hello() self.assertEqual((reply["result"], close), ({"protocol": PROTOCOL_VERSION, "service": "9.9.9"}, False)) reply, _ = self.send({"op": "set_profile", "id": 2, "args": {"profile": "balanced"}}) self.assertEqual(reply, {"id": 2, "ok": True, "result": {"done": "set_profile"}}) def test_version_mismatch_is_answered_then_the_connection_closes(self): reply, close = self.hello(PROTOCOL_VERSION + 1) self.assertEqual((reply["error"]["code"], close), (VERSION, True)) self.assertIn(str(PROTOCOL_VERSION), reply["error"]["message"]) self.assertFalse(self.session.greeted) def test_operation_failures_map_to_error_codes(self): self.hello() for profile, code in (("quiet", INVALID), ("full", UNAVAILABLE), ("performance", INTERNAL)): with self.subTest(profile=profile): if code == INTERNAL: with self.assertLogs("kurgan.hw.protocol", level="ERROR"): reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}}) else: reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}}) self.assertEqual((reply["id"], reply["error"]["code"], close), (3, code, False)) def test_a_reply_that_cannot_be_encoded_is_an_internal_error(self): self.hello() with self.assertLogs("kurgan.hw.protocol", level="ERROR"): reply, close = self.send({"op": "state", "id": 4}) self.assertEqual((reply["error"]["code"], close), (INTERNAL, False)) def test_bad_lines_keep_the_connection_but_oversized_ones_close_it(self): reply, close = self.send(b"garbage") self.assertEqual((reply["error"]["code"], close), (BAD_REQUEST, False)) reply, close = self.send(b"x" * (MAX_MESSAGE + 1)) self.assertEqual((reply["error"]["code"], close), (TOO_LARGE, True)) if __name__ == "__main__": unittest.main()