feat: establish lab1 HTTP contract skeleton
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
fastapi==0.118.3
|
||||
pydantic==2.12.4
|
||||
uvicorn==0.38.0
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"""HTTP routes; domain operations are added in subsequent units."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .models import CreateUser
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def ready():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser):
|
||||
raise NotImplementedError("User registration is implemented in U2")
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"""FastAPI entry point and contract-wide response handling."""
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .api import router
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
|
||||
ERRORS = {
|
||||
400: ("invalid_request", "Неверный запрос"),
|
||||
401: ("unauthorized", "Требуется действительный пользователь"),
|
||||
404: ("not_found", "Объект не найден"),
|
||||
409: ("conflict", "Конфликт данных"),
|
||||
413: ("payload_too_large", "Слишком большой запрос"),
|
||||
415: ("unsupported_media_type", "Неподдерживаемый тип данных"),
|
||||
429: ("rate_limited", "Слишком много запросов"),
|
||||
503: ("unavailable", "Сервис недоступен"),
|
||||
}
|
||||
|
||||
|
||||
def error_response(request: Request, status: int) -> JSONResponse:
|
||||
code, message = ERRORS.get(status, ("internal_error", "Внутренняя ошибка"))
|
||||
request_id = request.state.request_id
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_contract(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
if request.method == "POST" and request.url.path.startswith("/api/v1/"):
|
||||
media_type, _, charset = request.headers.get("content-type", "").lower().partition(";")
|
||||
if media_type.strip() != "application/json" or (charset and charset.strip() != "charset=utf-8"):
|
||||
return error_response(request, 415)
|
||||
try:
|
||||
(await request.body()).decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return error_response(request, 400)
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request: Request, exc: HTTPException):
|
||||
return error_response(request, exc.status_code)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error(request: Request, exc: Exception):
|
||||
return error_response(request, 500)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Request bodies from the lab 1 contract."""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class StrictBody(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
class CreateUser(StrictBody):
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def nonblank_name(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("blank display name")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(StrictBody):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def nonblank_title(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("blank title")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def valid_members(cls, value: list[str]) -> list[str]:
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError("duplicate member")
|
||||
for member_id in value:
|
||||
UUID(member_id)
|
||||
return value
|
||||
|
||||
|
||||
class CreateMessage(StrictBody):
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def nonblank_text(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("blank text")
|
||||
return value
|
||||
@@ -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