"""Проверка проводки FastAPI-адаптера на подставном модуле `fastapi`. Настоящего FastAPI в окружении нет, поэтому здесь проверяется только то, что роуты вызывают обработчики с правильными аргументами и переносят статус, заголовки и cookie в ответ. Поведение самого FastAPI (разбор форм, пул потоков) этим тестом не проверяется. """ import sys import types import unittest from unittest import mock from helpers import SiteTestCase from test_auth import PASSWORD, Clock, make_cfg from site_engine.services.auth import COOKIE_NAME, AuthService from site_engine.web.admin.editor import EditorHandlers from site_engine.web.admin.handlers import AdminHandlers ORIGIN = {"host": "admin.example", "origin": "https://admin.example"} class FakeHeaders(dict): def __init__(self): super().__init__() self.appended = [] def append(self, key, value): self.appended.append((key, value)) class FakeResponse: def __init__(self, content="", status_code=200, media_type=None): self.content, self.status_code, self.media_type = content, status_code, media_type self.headers = FakeHeaders() class FakeRouter: def __init__(self, prefix=""): self.prefix, self.routes = prefix, {} def _register(self, method, path): def deco(fn): self.routes[(method, self.prefix + path)] = fn return fn return deco def get(self, path): return self._register("GET", path) def post(self, path): return self._register("POST", path) def api_route(self, path, methods): def deco(fn): for method in methods: self.routes[(method, self.prefix + path)] = fn return fn return deco class FakeRequest: def __init__(self, cookies=None, headers=None, ip="1.2.3.4", method="GET", query=None, form=None): self.cookies, self.headers = cookies or {}, headers or {} self.client = types.SimpleNamespace(host=ip) self.method, self.query_params, self._form = method, query or {}, form or [] async def form(self): return types.SimpleNamespace(multi_items=lambda: list(self._form)) def fake_fastapi(): mod = types.ModuleType("fastapi") mod.APIRouter, mod.Response, mod.Request = FakeRouter, FakeResponse, FakeRequest mod.Form = lambda default="": default return mod def fake_starlette(): pkg, conc = types.ModuleType("starlette"), types.ModuleType("starlette.concurrency") async def run_in_threadpool(fn, *args): return fn(*args) conc.run_in_threadpool = run_in_threadpool return {"starlette": pkg, "starlette.concurrency": conc} class RoutesWiringTest(SiteTestCase): def setUp(self): super().setUp() self.auth = AuthService(make_cfg(), self.tmp / "state", clock=Clock()) handlers = AdminHandlers(self.auth, self.site) self.editor = EditorHandlers(self.auth, self.site, self.tmp / "dist") with mock.patch.dict(sys.modules, {"fastapi": fake_fastapi(), **fake_starlette()}): from site_engine.web.admin.routes import create_admin_router self.router = create_admin_router(handlers, self.editor) def route(self, method, path): return self.router.routes[(method, path)] def test_all_expected_routes_exist(self): self.assertEqual( sorted(self.router.routes), [("GET", "/admin/"), ("GET", "/admin/login"), ("GET", "/admin/static/{name}"), ("GET", "/admin/{rest:path}"), ("POST", "/admin/login"), ("POST", "/admin/logout"), ("POST", "/admin/{rest:path}")], ) def test_login_flow_through_routes(self): request = FakeRequest(headers=ORIGIN) response = self.route("POST", "/admin/login")(request, login="admin", password=PASSWORD) self.assertEqual((response.status_code, response.headers["Location"]), (303, "/admin/")) key, cookie = response.headers.appended[0] self.assertEqual(key, "set-cookie") value = cookie.split(";")[0].split("=", 1)[1] dash = self.route("GET", "/admin/")(FakeRequest(cookies={COOKIE_NAME: value})) self.assertEqual(dash.status_code, 200) self.assertIn("Главная", dash.content) self.assertEqual(dash.headers["X-Frame-Options"], "DENY") anonymous = self.route("GET", "/admin/")(FakeRequest()) self.assertEqual((anonymous.status_code, anonymous.headers["Location"]), (303, "/admin/login")) def test_bad_login_and_logout_wiring(self): bad = self.route("POST", "/admin/login")(FakeRequest(headers=ORIGIN), login="admin", password="wrong password!!") self.assertEqual((bad.status_code, bad.headers.appended), (401, [])) good = self.route("POST", "/admin/login")(FakeRequest(headers=ORIGIN), login="admin", password=PASSWORD) value = good.headers.appended[0][1].split(";")[0].split("=", 1)[1] csrf = self.auth.csrf_token(self.auth.authenticate(value)) out = self.route("POST", "/admin/logout")(FakeRequest(cookies={COOKIE_NAME: value}, headers=ORIGIN), csrf=csrf) self.assertEqual((out.status_code, out.headers["Location"]), (303, "/admin/login")) self.assertIn("Max-Age=0", out.headers.appended[0][1]) def test_annotations_are_real_types(self): """Регрессия: с `from __future__ import annotations` и локальным импортом Request FastAPI не разрешает аннотацию, считает `request` query-параметром и отвечает 422 {"loc": ["query", "request"]}.""" import typing from pathlib import Path source = (Path(__file__).resolve().parent.parent / "src/site_engine/web/admin/routes.py").read_text(encoding="utf-8") import re self.assertIsNone(re.search(r"^from __future__ import annotations", source, re.M)) for key, fn in self.router.routes.items(): hints = typing.get_type_hints(fn) # как это делает FastAPI: имена берутся из globals модуля if "request" in hints: self.assertIs(hints["request"], FakeRequest, key) self.assertFalse(any(isinstance(v, str) for v in fn.__annotations__.values()), key) def test_static_and_login_page_routes(self): css = self.route("GET", "/admin/static/{name}")("admin.css") self.assertTrue(css.media_type.startswith("text/css")) self.assertEqual(self.route("GET", "/admin/static/{name}")("secret.txt").status_code, 404) page = self.route("GET", "/admin/login")(FakeRequest()) self.assertEqual(page.status_code, 200) def test_editor_catch_all_passes_method_path_query_form_and_cookie(self): import asyncio good = self.route("POST", "/admin/login")(FakeRequest(headers=ORIGIN), login="admin", password=PASSWORD) value = good.headers.appended[0][1].split(";")[0].split("=", 1)[1] cookies = {COOKIE_NAME: value} get = self.route("GET", "/admin/{rest:path}") response = asyncio.run(get(FakeRequest(cookies=cookies, query={"msg": "saved"}), rest="pages")) self.assertEqual(response.status_code, 200) self.assertIn("Новая страница", response.content) self.assertIn("Сохранено", response.content) # query дошёл до обработчика csrf = self.auth.csrf_token(self.auth.authenticate(value)) post = self.route("POST", "/admin/{rest:path}") request = FakeRequest(cookies=cookies, headers=ORIGIN, method="POST", form=[("csrf", csrf), ("page_id", "wired-page"), ("title", "Через адаптер")]) response = asyncio.run(post(request, rest="pages/new")) self.assertEqual((response.status_code, response.headers["Location"]), (303, "/admin/pages/wired-page?msg=created")) self.assertTrue((self.site / "pages" / "wired-page.md").is_file()) nobody = asyncio.run(get(FakeRequest(), rest="pages")) self.assertEqual((nobody.status_code, nobody.headers["Location"]), (303, "/admin/login")) if __name__ == "__main__": unittest.main()