acupedia-api/tests/api/test_auth_api.py

190 lines
6.9 KiB
Python

from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.auth.deps import get_auth_service
from app.features.auth.errors import InvalidCredentialsError, SamePasswordError, UserAlreadyExistsError
from app.features.auth.schema import (
AuthTokenResponse,
AuthTokenUserResponse,
ForgotPasswordResponse,
UserIdentityResponse,
)
@pytest.fixture
def mock_auth_service() -> MagicMock:
service = MagicMock()
service.session = AsyncMock()
service.session.commit = AsyncMock()
service.session.rollback = AsyncMock()
return service
@pytest.mark.asyncio
async def test_register_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.register = AsyncMock(return_value=AuthTokenResponse(
access_token="mock_access_token_123",
token_type="bearer",
user=AuthTokenUserResponse(
id=user_id,
email="dr.smith@acupedia.test",
display_name="Dr. Smith",
country="India",
roles=["practitioner"],
)
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "dr.smith@acupedia.test",
"password": "SecurePassword123!",
"full_name": "Dr. Smith",
"country": "India",
}
response = await async_client.post("/api/auth/register", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["access_token"] == "mock_access_token_123"
assert data["user"]["email"] == "dr.smith@acupedia.test"
assert "practitioner" in data["user"]["roles"]
@pytest.mark.asyncio
async def test_register_duplicate_email_fails(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.register = AsyncMock(side_effect=UserAlreadyExistsError("An account already exists."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "existing@acupedia.test",
"password": "SecurePassword123!",
}
response = await async_client.post("/api/auth/register", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "already exists" in response.json()["detail"]
@pytest.mark.asyncio
async def test_register_invalid_payload_fails_validation(async_client: AsyncClient) -> None:
# Missing required password field
response = await async_client.post("/api/auth/register", json={"email": "bad@test.com"})
assert response.status_code == 422
@pytest.mark.asyncio
async def test_login_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.login = AsyncMock(return_value=AuthTokenResponse(
access_token="valid_login_token_abc",
token_type="bearer",
user=AuthTokenUserResponse(
id=user_id,
email="dr.login@acupedia.test",
display_name="Dr. Login",
country="India",
roles=["practitioner"],
)
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "dr.login@acupedia.test",
"password": "CorrectPassword123!",
}
response = await async_client.post("/api/auth/login", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["access_token"] == "valid_login_token_abc"
@pytest.mark.asyncio
async def test_login_invalid_credentials_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.login = AsyncMock(side_effect=InvalidCredentialsError("Invalid email/phone or password."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "wrong@acupedia.test",
"password": "WrongPassword123!",
}
response = await async_client.post("/api/auth/login", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "Invalid email/phone or password" in response.json()["detail"]
@pytest.mark.asyncio
async def test_get_identity_unauthorized_when_no_token(async_client: AsyncClient) -> None:
response = await async_client.get("/api/auth/me")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_success_with_token(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.get_identity = AsyncMock(return_value=UserIdentityResponse(
id=user_id,
email="doctor@acupedia.test",
display_name="Doctor A",
country="India",
roles=["practitioner"],
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
headers = {"Authorization": "Bearer sample_valid_token"}
response = await async_client.get("/api/auth/me", headers=headers)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["email"] == "doctor@acupedia.test"
@pytest.mark.asyncio
async def test_forgot_password_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.forgot_password = AsyncMock(return_value=(
ForgotPasswordResponse(
status="success",
message="If an account exists, a reset code was sent.",
),
"123456",
))
mock_auth_service.send_password_reset_email = AsyncMock(return_value=True)
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
response = await async_client.post("/api/auth/forgot-password", json={"email": "dr.smith@acupedia.test"})
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
assert response.json()["status"] == "success"
assert mock_auth_service.send_password_reset_email.await_count == 1
@pytest.mark.asyncio
async def test_change_password_same_password_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.change_password = AsyncMock(side_effect=SamePasswordError("New password cannot be the same as current password."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"old_password": "OldPassword123!",
"new_password": "OldPassword123!",
}
headers = {"Authorization": "Bearer sample_valid_token"}
response = await async_client.post("/api/auth/change-password", json=payload, headers=headers)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "New password cannot be the same as current password" in response.json()["detail"]