import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
import jwt
from app.core.config import settings
from app.core.auth.dependencies import get_auth_context
def test_missing_authorization_header_returns_401() -> None:
app = FastAPI()
@app.get("/protected")
async def protected(ctx=Depends(get_auth_context)):
return {"user_id": ctx.user_id}
client = TestClient(app)
resp = client.get("/protected")
assert resp.status_code == 401
def test_valid_jwt_returns_user_id(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(settings, "auth_mode", "local_jwt")
monkeypatch.setattr(settings, "secret_key", "test_secret")
token = jwt.encode({"sub": "123"}, "test_secret", algorithm="HS256")
app = FastAPI()
@app.get("/protected")
async def protected(ctx=Depends(get_auth_context)):
return {"user_id": ctx.user_id}
client = TestClient(app)
resp = client.get("/protected", headers={"Authorization": f"Bearer {token}"})
assert resp.status_code == 200
assert resp.json()["user_id"] == "123"