"""Focused HTTP checks for the contract transport layer.""" import json import socket import threading import time import unittest from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen import uvicorn from src.main import app class APIContractTests(unittest.TestCase): @classmethod def setUpClass(cls): def unexpected_error(): raise RuntimeError("private exception detail") app.add_api_route("/_test_error", unexpected_error) with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] cls.url = f"http://127.0.0.1:{port}" cls.server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="critical")) cls.thread = threading.Thread(target=cls.server.run, daemon=True) cls.thread.start() for _ in range(100): try: cls.call("GET", "/health/live") break except URLError: time.sleep(0.05) else: raise RuntimeError("test server did not start") @classmethod def tearDownClass(cls): cls.server.should_exit = True cls.thread.join(timeout=5) @classmethod def call(cls, method, path, body=None, content_type="application/json", actor=None): headers = {"Content-Type": content_type} if body is not None else {} if actor is not None: headers["X-User-Id"] = actor request = Request(cls.url + path, data=body, headers=headers, method=method) try: response = urlopen(request, timeout=3) except HTTPError as error: response = error with response: return response.status, response.headers, json.loads(response.read()) def assert_error(self, status, headers, payload, expected_status): self.assertEqual(status, expected_status) self.assertEqual(headers.get_content_type(), "application/json") self.assertTrue(headers.get("X-Request-Id")) self.assertEqual(payload["error"]["request_id"], headers["X-Request-Id"]) def test_health(self): status, headers, payload = self.call("GET", "/health/live") self.assertEqual((status, payload), (200, {"status": "ok"})) self.assertTrue(headers.get("X-Request-Id")) def test_bad_json_and_fields(self): bodies = ( b"{", b'{"username":"alice","display_name":"Alice","extra":1}', b'{"username":123,"display_name":"Alice"}', b'{"username":"alice","display_name":" "}', b'{"username":"alice","display_name":"\xff"}', ) for body in bodies: with self.subTest(body=body): self.assert_error(*self.call("POST", "/api/v1/users", body), 400) def test_unsupported_media_type(self): self.assert_error(*self.call("POST", "/api/v1/users", b"{}", "text/plain"), 415) def test_unexpected_error_is_private(self): status, headers, payload = self.call("GET", "/_test_error") self.assert_error(status, headers, payload, 500) self.assertEqual(payload["error"]["code"], "internal_error") self.assertNotIn("private exception detail", json.dumps(payload)) def test_users_chats_and_cursor(self): def user(name): status, _, value = self.call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": name}).encode()) self.assertEqual(status, 201) return value alice, bob, eve = (user(name) for name in ("u2_alice", "u2_bob", "u2_eve")) self.assert_error(*self.call("POST", "/api/v1/users", b'{"username":"u2_alice","display_name":"Other"}'), 409) self.assert_error(*self.call("GET", "/api/v1/users/me"), 401) self.assert_error(*self.call("GET", "/api/v1/users/me", actor="00000000-0000-4000-8000-000000000000"), 401) self.assertEqual(self.call("GET", "/api/v1/users/me", actor=alice["id"])[2], alice) def chat(member_ids): body = json.dumps({"title": "Чат 👋", "member_ids": member_ids}).encode() return self.call("POST", "/api/v1/chats", body, actor=alice["id"]) for members in ([alice["id"], alice["id"]], [bob["id"]], [alice["id"], "00000000-0000-4000-8000-000000000000"]): self.assert_error(*chat(members), 400) self.assertEqual(self.call("GET", "/api/v1/chats", actor=alice["id"])[2]["items"], []) first = chat([alice["id"], bob["id"]])[2] second = chat([alice["id"], bob["id"]])[2] self.assertEqual(self.call("GET", f'/api/v1/chats/{first["id"]}', actor=bob["id"])[2], first) self.assert_error(*self.call("GET", f'/api/v1/chats/{first["id"]}', actor=eve["id"]), 404) self.assertEqual(self.call("GET", "/api/v1/chats", actor=eve["id"])[2]["items"], []) page = self.call("GET", "/api/v1/chats?limit=1", actor=alice["id"])[2] self.assertEqual(page["items"], [first]) self.assertTrue(page["next_cursor"]) from urllib.parse import quote next_path = "/api/v1/chats?limit=1&cursor=" + quote(page["next_cursor"], safe="") self.assertEqual(self.call("GET", next_path, actor=alice["id"])[2], {"items": [second], "next_cursor": None}) self.assert_error(*self.call("GET", next_path, actor=bob["id"]), 400) self.assert_error(*self.call("GET", "/api/v1/chats?limit=0", actor=alice["id"]), 400) def test_messages_access_validation_and_pages(self): from urllib.parse import quote def user(name): status, _, value = self.call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": name}).encode()) self.assertEqual(status, 201) return value alice, bob, eve = (user(name) for name in ("u3_alice", "u3_bob", "u3_eve")) def chat(): body = json.dumps({"title": "U3 👋", "member_ids": [alice["id"], bob["id"]]}).encode() status, _, value = self.call("POST", "/api/v1/chats", body, actor=alice["id"]) self.assertEqual(status, 201) return value first_chat, second_chat = chat(), chat() path = f'/api/v1/chats/{first_chat["id"]}/messages' other_path = f'/api/v1/chats/{second_chat["id"]}/messages' def send(actor, body, target=path): return self.call("POST", target, json.dumps(body, ensure_ascii=False).encode(), actor=actor) for actor, text in ((alice, "Привет 👋"), (bob, "Ответ Боба"), (alice, "Третье сообщение")): status, _, value = send(actor["id"], {"text": text}) self.assertEqual(status, 201) self.assertEqual((value["chat_id"], value["sender_id"], value["text"]), (first_chat["id"], actor["id"], text)) seen = [] cursor = None while True: suffix = "?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else "") status, _, page = self.call("GET", path + suffix, actor=bob["id"]) self.assertEqual(status, 200) self.assertEqual(len(page["items"]), 1) seen.extend(page["items"]) cursor = page["next_cursor"] if cursor is None: break self.assertEqual([item["text"] for item in seen], ["Привет 👋", "Ответ Боба", "Третье сообщение"]) self.assertEqual(len({item["id"] for item in seen}), 3) self.assertEqual(seen, sorted(seen, key=lambda item: (item["created_at"], item["id"]))) for body in ({"text": ""}, {"text": " "}, {"text": "a" * 4001}, {"text": "x", "sender_id": eve["id"]}): self.assert_error(*send(alice["id"], body), 400) self.assertEqual(send(alice["id"], {"text": "🌟" * 4000})[0], 201) self.assert_error(*send(eve["id"], {"text": "чужое"}), 404) self.assert_error(*self.call("GET", path, actor=eve["id"]), 404) self.assert_error(*self.call("GET", path + "?limit=0", actor=alice["id"]), 400) self.assert_error(*self.call("GET", path + "?cursor=broken", actor=alice["id"]), 400) self.assert_error(*self.call("GET", other_path + "?cursor=" + quote(self.call("GET", path + "?limit=1", actor=alice["id"])[2]["next_cursor"], safe=""), actor=alice["id"]), 400) if __name__ == "__main__": unittest.main()