Add global domain exception handlers in main.py
Register consistent HTTP error mappings for common domain exceptions and add regression tests for 404/400/500 handler behavior.
This commit is contained in:
@@ -10,6 +10,7 @@ from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import init_db
|
||||
from app.exceptions import ConfigValidationError, ConfigWriteError, JailNotFoundError
|
||||
from app.main import CORSMiddleware, _lifespan, create_app
|
||||
from app.services import setup_service
|
||||
|
||||
@@ -82,6 +83,46 @@ def test_create_app_initialises_runtime_state_manager() -> None:
|
||||
assert app.state.server_status.online is False
|
||||
|
||||
|
||||
async def test_create_app_global_domain_exception_handlers() -> None:
|
||||
"""Global exception handlers map domain exceptions to consistent HTTP responses."""
|
||||
settings = Settings(
|
||||
database_path="/tmp/test.db",
|
||||
fail2ban_socket="/tmp/fake_fail2ban.sock",
|
||||
fail2ban_config_dir="/tmp/fail2ban",
|
||||
session_secret="test-secret-key-do-not-use-in-production",
|
||||
session_duration_minutes=60,
|
||||
timezone="UTC",
|
||||
log_level="debug",
|
||||
)
|
||||
app = create_app(settings=settings)
|
||||
|
||||
@app.get("/not-found")
|
||||
async def raise_not_found() -> None:
|
||||
raise JailNotFoundError("ssh")
|
||||
|
||||
@app.get("/bad-request")
|
||||
async def raise_bad_request() -> None:
|
||||
raise ConfigValidationError("invalid payload")
|
||||
|
||||
@app.get("/server-error")
|
||||
async def raise_server_error() -> None:
|
||||
raise ConfigWriteError("write failed")
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/not-found")
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Jail not found: 'ssh'"}
|
||||
|
||||
response = await client.get("/bad-request")
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "invalid payload"}
|
||||
|
||||
response = await client.get("/server-error")
|
||||
assert response.status_code == 500
|
||||
assert response.json() == {"detail": "write failed"}
|
||||
|
||||
|
||||
def test_create_app_disables_cors_by_default() -> None:
|
||||
"""The FastAPI app does not add CORS middleware when no origins are configured by environment."""
|
||||
settings = Settings(
|
||||
|
||||
Reference in New Issue
Block a user