73 lines
2.6 KiB
Python
73 lines
2.6 KiB
Python
from datetime import UTC, datetime
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from pydantic import ValidationError
|
|
|
|
from app.api.v1.auth import router
|
|
from app.core import security
|
|
from app.db.session import DEFAULT_LOGIN_USERS, get_db
|
|
from app.models.user import User
|
|
from app.schemas.user import UserRegister
|
|
|
|
|
|
async def identity_request(monkeypatch, user, token=None):
|
|
result = MagicMock()
|
|
result.scalar_one_or_none.return_value = user
|
|
db = AsyncMock()
|
|
db.execute.return_value = result
|
|
monkeypatch.setattr(security.redis_client, "sismember", lambda *_: False)
|
|
app = FastAPI()
|
|
app.include_router(router, prefix="/auth")
|
|
|
|
async def override_db():
|
|
yield db
|
|
|
|
app.dependency_overrides[get_db] = override_db
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
|
) as client:
|
|
return await client.get(
|
|
"/auth/me",
|
|
headers={"Authorization": "Bearer " + (token or security.create_access_token({"sub": 1}))},
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("default", DEFAULT_LOGIN_USERS)
|
|
async def test_default_identity_preserves_profile_fields(monkeypatch, default):
|
|
created = datetime(2026, 9, 21, tzinfo=UTC)
|
|
user = User(
|
|
id=1, username=default["username"], email=default["email"],
|
|
role=default["role"], password_hash="not-exposed", is_active=True,
|
|
email_verified=True, gatekeeper_groups=["ops"], created_at=created,
|
|
)
|
|
response = await identity_request(monkeypatch, user)
|
|
assert response.status_code == 200
|
|
payload = response.json()
|
|
assert payload["email"] == default["email"]
|
|
assert payload["email_verified"] is True
|
|
assert datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")) == created
|
|
assert payload["gatekeeper_groups"] == ["ops"]
|
|
assert "password_hash" not in payload
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("user", [None, User(id=1, is_active=False)])
|
|
async def test_missing_or_inactive_identity_is_rejected(monkeypatch, user):
|
|
response = await identity_request(monkeypatch, user)
|
|
assert response.status_code == 401
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_refresh_token_is_not_an_access_identity(monkeypatch):
|
|
response = await identity_request(monkeypatch, None, security.create_refresh_token({"sub": 1}))
|
|
assert response.status_code == 401
|
|
|
|
|
|
def test_registration_still_validates_email():
|
|
with pytest.raises(ValidationError):
|
|
UserRegister(username="newuser", email="newuser@planet.local", password="example-password")
|