test_middleware.py (1999B)
1 """Tests for auth middleware and app routing.""" 2 3 import pytest 4 from httpx import ASGITransport, AsyncClient 5 6 from app.main import app 7 8 9 @pytest.fixture 10 async def client() -> AsyncClient: 11 """Async client for testing.""" 12 async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: 13 yield c 14 15 16 class TestHealthEndpoint: 17 """GET /api/health — no auth required.""" 18 19 async def test_health_returns_ok(self, client: AsyncClient) -> None: 20 resp = await client.get("/api/health") 21 assert resp.status_code == 200 22 assert resp.json() == {"status": "ok"} 23 24 25 class TestAuthMiddleware: 26 """Middleware enforces JWT on /api/* routes.""" 27 28 async def test_unauthenticated_api_returns_401(self, client: AsyncClient) -> None: 29 """API route without JWT returns 401.""" 30 resp = await client.get("/api/nonexistent") 31 assert resp.status_code == 401 32 33 async def test_auth_routes_bypass_middleware(self, client: AsyncClient) -> None: 34 """Auth routes are exempt from JWT check.""" 35 resp = await client.get("/api/auth/status") 36 assert resp.status_code == 200 37 38 async def test_non_api_routes_bypass_middleware(self, client: AsyncClient) -> None: 39 """Non-API routes are not affected by middleware.""" 40 resp = await client.get("/docs") 41 assert resp.status_code == 200 42 43 44 class TestRegisterRoutes: 45 """register_routes includes all routers.""" 46 47 def test_includes_all_routers(self) -> None: 48 from fastapi import FastAPI 49 from app.routes import register_routes 50 app = FastAPI() 51 register_routes(app) 52 # Verify routers were added by checking route count increased 53 assert len(app.routes) > 0 54 55 def test_adds_auth_middleware(self) -> None: 56 from fastapi import FastAPI 57 from app.routes import register_routes 58 app = FastAPI() 59 register_routes(app) 60 assert len(app.middleware_stack.__class__.__mro__) > 1 61