feat: establish lab1 HTTP contract skeleton
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""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"):
|
||||
headers = {"Content-Type": content_type} if body is not None else {}
|
||||
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))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user