From 666a37c1365a41b8fbf0a9210e39bedd5c204dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=85=D0=B2=D0=B0=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=A0=D0=B5?= =?UTF-8?q?=D0=BC=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 1 Oct 2026 21:17:35 +0300 Subject: [PATCH] feat: establish lab1 HTTP contract skeleton --- requirements.txt | 3 ++ src/api.py | 22 ++++++++++ src/main.py | 64 ++++++++++++++++++++++++++++ src/models.py | 53 +++++++++++++++++++++++ student-tests/test_api.py | 89 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 231 insertions(+) create mode 100644 requirements.txt create mode 100644 src/api.py create mode 100644 src/main.py create mode 100644 src/models.py create mode 100644 student-tests/test_api.py diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a56d2b3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +fastapi==0.118.3 +pydantic==2.12.4 +uvicorn==0.38.0 diff --git a/src/api.py b/src/api.py new file mode 100644 index 0000000..9cfe73f --- /dev/null +++ b/src/api.py @@ -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") diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..a9e9537 --- /dev/null +++ b/src/main.py @@ -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) diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..7937880 --- /dev/null +++ b/src/models.py @@ -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 diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 0000000..80b668f --- /dev/null +++ b/student-tests/test_api.py @@ -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()