56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
"""FluentGerman.ai — Auth tests."""
|
|
|
|
import pytest
|
|
from httpx import AsyncClient
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_login_success(client: AsyncClient, admin_token: str):
|
|
"""Admin can log in and receives a token."""
|
|
assert admin_token is not None
|
|
assert len(admin_token) > 20
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_login_wrong_password(client: AsyncClient):
|
|
"""Wrong password returns 401."""
|
|
from app.auth import hash_password
|
|
from app.models import User
|
|
from tests.conftest import test_session
|
|
|
|
async with test_session() as db:
|
|
user = User(
|
|
username="logintest",
|
|
email="logintest@test.com",
|
|
hashed_password=hash_password("correct"),
|
|
)
|
|
db.add(user)
|
|
await db.commit()
|
|
|
|
resp = await client.post("/api/auth/login", json={"username": "logintest", "password": "wrong"})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_login_nonexistent_user(client: AsyncClient):
|
|
"""Nonexistent user returns 401."""
|
|
resp = await client.post("/api/auth/login", json={"username": "nobody", "password": "pass"})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_me_endpoint(client: AsyncClient, admin_token: str):
|
|
"""Authenticated user can access /me."""
|
|
resp = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {admin_token}"})
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["username"] == "admin"
|
|
assert data["is_admin"] is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_me_unauthenticated(client: AsyncClient):
|
|
"""Unauthenticated request to /me returns 401."""
|
|
resp = await client.get("/api/auth/me")
|
|
assert resp.status_code == 401
|