import pytest from fastapi.testclient import TestClient def test_create_user(client: TestClient, admin_token: str): """Test user creation with admin authentication.""" user_data = { "username": "testuser", "password": "testpassword", "role": "read_only" } response = client.post("/api/v1/users/", json=user_data, headers={"Authorization": f"Bearer {admin_token}"}) assert response.status_code == 201 data = response.json() assert data["username"] == "testuser" assert data["role"] == "read_only" assert "id" in data def test_create_user_unauthorized(client: TestClient): """Test user creation without authentication should fail.""" user_data = { "username": "testuser2", "password": "testpassword", "role": "read_only" } response = client.post("/api/v1/users/", json=user_data) # HTTPBearer returns 403 when no Authorization header is provided assert response.status_code == 403 def test_create_user_invalid_token(client: TestClient): """Test user creation with invalid token should fail.""" user_data = { "username": "testuser3", "password": "testpassword", "role": "read_only" } response = client.post("/api/v1/users/", json=user_data, headers={"Authorization": "Bearer invalid_token"}) # Invalid token should return 401 assert response.status_code == 401 def test_login_user(client: TestClient, admin_token: str): """Test user login.""" # First create a user using admin token user_data = { "username": "logintest", "password": "testpassword", "role": "read_only" } client.post("/api/v1/users/", json=user_data, headers={"Authorization": f"Bearer {admin_token}"}) # Then try to login login_data = { "username": "logintest", "password": "testpassword" } response = client.post("/api/v1/users/login", json=login_data) assert response.status_code == 200 data = response.json() assert "access_token" in data assert data["token_type"] == "bearer" assert "expires_in" in data def test_get_current_user(client: TestClient, admin_token: str): """Test getting current user info.""" # Create and login user user_data = { "username": "currenttest", "password": "testpassword", "role": "admin" } client.post("/api/v1/users/", json=user_data, headers={"Authorization": f"Bearer {admin_token}"}) login_response = client.post("/api/v1/users/login", json={ "username": "currenttest", "password": "testpassword" }) token = login_response.json()["access_token"] # Get current user response = client.get("/api/v1/users/me", headers={ "Authorization": f"Bearer {token}" }) assert response.status_code == 200 data = response.json() assert data["username"] == "currenttest" assert data["role"] == "admin"