from unittest.mock import AsyncMock, patch import httpx import pytest from backend.src.models.central_db_models import User # noqa: F401 from backend.src.services.central_db_service import CentralDBService @pytest.fixture def central_db_service(): return CentralDBService(base_url="http://test-central-db") @pytest.mark.asyncio async def test_get_user_by_email_success(central_db_service): mock_response = AsyncMock() mock_response.status_code = 200 mock_response.json.return_value = [ {"id": "1", "username": "testuser", "email": "test@example.com"} ] with patch("httpx.AsyncClient.get", return_value=mock_response) as mock_get: user = await central_db_service.get_user_by_email("test@example.com") mock_get.assert_called_once_with( "http://test-central-db/users?email=test@example.com" ) assert user is not None assert user.email == "test@example.com" @pytest.mark.asyncio async def test_get_user_by_email_not_found(central_db_service): mock_response = AsyncMock() mock_response.status_code = 200 mock_response.json.return_value = [] with patch("httpx.AsyncClient.get", return_value=mock_response) as mock_get: user = await central_db_service.get_user_by_email("nonexistent@example.com") mock_get.assert_called_once_with( "http://test-central-db/users?email=nonexistent@example.com" ) assert user is None @pytest.mark.asyncio async def test_get_user_by_email_api_error(central_db_service): mock_response = AsyncMock() mock_response.status_code = 500 mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( "Server Error", request=httpx.Request( "GET", "http://test-central-db/users?email=error@example.com" ), response=mock_response, ) with patch("httpx.AsyncClient.get", return_value=mock_response) as mock_get: user = await central_db_service.get_user_by_email("error@example.com") mock_get.assert_called_once_with( "http://test-central-db/users?email=error@example.com" ) assert user is None