59 lines
2.3 KiB
Python
59 lines
2.3 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_delete_user():
|
|
token = await get_token("admin", "password123")
|
|
headers = {"Authorization": f"Bearer {token}"}
|
|
|
|
# Create a temporary user to delete
|
|
async with httpx.AsyncClient() as client:
|
|
reg_res = await client.post(f"{BASE_URL}/auth/register", json={
|
|
"username": "todelete",
|
|
"email": "delete@example.com",
|
|
"password": "password123",
|
|
"role": "listener"
|
|
})
|
|
user_id = reg_res.json().get("id") # Need to check if register returns id, otherwise we list users first
|
|
|
|
# If registration doesn't return ID, get it from the list
|
|
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"] == "todelete"), None)
|
|
user_id = user["id"] if user else None
|
|
|
|
assert user_id is not None
|
|
|
|
# Delete the user
|
|
del_res = await client.delete(f"{BASE_URL}/admin/users/{user_id}", headers=headers)
|
|
assert del_res.status_code == 200
|
|
assert del_res.json()["message"] == "User deleted successfully"
|
|
|
|
@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
|