Aniworld/tests/api/test_auth_endpoints.py

57 lines
1.9 KiB
Python

"""Tests for authentication API endpoints."""
import pytest
from httpx import ASGITransport, AsyncClient
from src.server.fastapi_app import app
from src.server.services.auth_service import auth_service
@pytest.fixture(autouse=True)
def reset_auth_state():
"""Reset auth service state before each test."""
# Clear any rate limiting state and password hash
if hasattr(auth_service, '_failed'):
auth_service._failed.clear()
auth_service._hash = None
yield
# Cleanup after test
if hasattr(auth_service, '_failed'):
auth_service._failed.clear()
@pytest.mark.anyio
async def test_auth_flow_setup_login_status_logout():
"""Test complete authentication flow."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# Setup
r = await client.post("/api/auth/setup", json={"master_password": "Aa!strong1"})
assert r.status_code == 201
# Bad login
r = await client.post("/api/auth/login", json={"password": "wrong"})
assert r.status_code == 401
# Good login
r = await client.post("/api/auth/login", json={"password": "Aa!strong1"})
assert r.status_code == 200
data = r.json()
assert "access_token" in data
token = data["access_token"]
# Status unauthenticated when no auth header
r = await client.get("/api/auth/status")
assert r.status_code == 200
assert r.json()["configured"] is True
# Status authenticated with header
r = await client.get("/api/auth/status", headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200
assert r.json()["authenticated"] is True
# Logout
r = await client.post("/api/auth/logout", headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200