Add environment-driven CORS settings and backend regression tests
This commit is contained in:
50
backend/tests/test_main.py
Normal file
50
backend/tests/test_main.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""Unit tests for backend application startup and middleware configuration."""
|
||||
|
||||
from app.config import Settings
|
||||
from app.main import CORSMiddleware, create_app
|
||||
|
||||
|
||||
def test_create_app_configures_cors_from_settings() -> None:
|
||||
"""The FastAPI app registers CORS middleware with the configured origins."""
|
||||
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",
|
||||
cors_allowed_origins=["https://frontend.example.com"],
|
||||
)
|
||||
|
||||
app = create_app(settings=settings)
|
||||
cors_middleware = [
|
||||
middleware for middleware in app.user_middleware if middleware.cls is CORSMiddleware
|
||||
]
|
||||
|
||||
assert len(cors_middleware) == 1
|
||||
assert cors_middleware[0].kwargs["allow_origins"] == ["https://frontend.example.com"]
|
||||
assert cors_middleware[0].kwargs["allow_credentials"] is True
|
||||
assert cors_middleware[0].kwargs["allow_methods"] == ["*"]
|
||||
assert cors_middleware[0].kwargs["allow_headers"] == ["*"]
|
||||
|
||||
|
||||
def test_create_app_skips_cors_when_no_origins_are_configured() -> None:
|
||||
"""The FastAPI app does not add CORS middleware when no origins are configured."""
|
||||
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",
|
||||
cors_allowed_origins=[],
|
||||
)
|
||||
|
||||
app = create_app(settings=settings)
|
||||
cors_middleware = [
|
||||
middleware for middleware in app.user_middleware if middleware.cls is CORSMiddleware
|
||||
]
|
||||
|
||||
assert cors_middleware == []
|
||||
Reference in New Issue
Block a user