"""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) if __name__ == "__main__": unittest.main()