"""Test Auth API endpoints.""" import pytest REGISTER_URL = "/api/v1/auth/register" LOGIN_URL = "/api/v1/auth/login" ME_URL = "/api/v1/auth/me" @pytest.mark.asyncio async def test_register_new_user(client): """Should register a new user and return 201 with a JWT token.""" response = await client.post( REGISTER_URL, json={"email": "newuser@example.com", "password": "securepassword123"}, ) assert response.status_code == 201 data = response.json() assert "access_token" in data assert data["token_type"] == "bearer" assert len(data["access_token"]) > 0 @pytest.mark.asyncio async def test_register_duplicate_email(client): """Should return 409 when registering with an email that already exists.""" # Register first user await client.post( REGISTER_URL, json={"email": "duplicate@example.com", "password": "password123"}, ) # Try to register again with same email response = await client.post( REGISTER_URL, json={"email": "duplicate@example.com", "password": "differentpassword"}, ) assert response.status_code == 409 assert "already exists" in response.json()["detail"].lower() @pytest.mark.asyncio async def test_login_correct_password(client): """Should return 200 with a JWT token on successful login.""" # Register a user first await client.post( REGISTER_URL, json={"email": "loginuser@example.com", "password": "mypassword"}, ) # Login with correct password response = await client.post( LOGIN_URL, json={"email": "loginuser@example.com", "password": "mypassword"}, ) assert response.status_code == 200 data = response.json() assert "access_token" in data assert data["token_type"] == "bearer" @pytest.mark.asyncio async def test_login_wrong_password(client): """Should return 401 when logging in with wrong password.""" # Register a user first await client.post( REGISTER_URL, json={"email": "wrongpw@example.com", "password": "correctpassword"}, ) # Login with wrong password response = await client.post( LOGIN_URL, json={"email": "wrongpw@example.com", "password": "wrongpassword"}, ) assert response.status_code == 401 @pytest.mark.asyncio async def test_me_with_valid_token(client): """Should return 200 with user profile when using a valid JWT token.""" # Register a user and get token reg_response = await client.post( REGISTER_URL, json={"email": "meuser@example.com", "password": "password123"}, ) token = reg_response.json()["access_token"] # Get profile with valid token response = await client.get( ME_URL, headers={"Authorization": f"Bearer {token}"}, ) assert response.status_code == 200 data = response.json() assert data["email"] == "meuser@example.com" assert "id" in data assert data["is_email_verified"] is False @pytest.mark.asyncio async def test_me_without_token(client): """Should return 401 when accessing /me without a token.""" response = await client.get(ME_URL) assert response.status_code in (401, 403)