Files
CitrusMusic/backend/tests/test_admin.py

58 lines
2.2 KiB
Python

import pytest
import httpx
from app.core.security import create_access_token
BASE_URL = "http://localhost:8000"
async def get_token(username, password):
async with httpx.AsyncClient() as client:
response = await client.post(f"{BASE_URL}/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
@pytest.mark.asyncio
async def test_admin_list_users():
token = await get_token("admin", "password123")
headers = {"Authorization": f"Bearer {token}"}
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/admin/users", headers=headers)
assert response.status_code == 200
users = response.json()
assert len(users) > 0
@pytest.mark.asyncio
async def test_admin_toggle_user_status():
token = await get_token("admin", "password123")
headers = {"Authorization": f"Bearer {token}"}
# Create a temporary user to toggle
async with httpx.AsyncClient() as client:
reg_res = await client.post(f"{BASE_URL}/auth/register", json={
"username": "totoggle",
"email": "toggle@example.com",
"password": "password123",
"role": "listener"
})
user_id = reg_res.json().get("id")
if not user_id:
users_res = await client.get(f"{BASE_URL}/admin/users", headers=headers)
user = next((u for u in users_res.json() if u["username"] == "totoggle"), None)
user_id = user["id"] if user else None
assert user_id is not None
# Toggle the status
toggle_res = await client.post(f"{BASE_URL}/admin/users/{user_id}/toggle-status", headers=headers)
assert toggle_res.status_code == 200
assert "active status set to" in toggle_res.json()["message"]
@pytest.mark.asyncio
async def test_admin_access_forbidden_for_author():
token = await get_token("author", "password123")
headers = {"Authorization": f"Bearer {token}"}
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/admin/users", headers=headers)
assert response.status_code == 403 # Forbidden