|
| 1 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 2 | + |
| 3 | +import httpx |
| 4 | +import pytest |
| 5 | +from fastapi.testclient import TestClient |
| 6 | +from pydantic import ValidationError |
| 7 | +from tenacity import RetryError |
| 8 | + |
| 9 | +from app.api.v1.endpoints.leads import send_telegram_notification |
| 10 | +from app.main import app |
| 11 | +from app.schemas.lead import ContactFormLead |
| 12 | +from app.services.telegram_service import TelegramService |
| 13 | + |
| 14 | + |
| 15 | +# 1. Pydantic schema tests |
| 16 | +def test_clean_and_validate_phone_success() -> None: |
| 17 | + lead = ContactFormLead( |
| 18 | + name="Test", phone_number="+38 (093) 123-45-67", contact_method="telegram" |
| 19 | + ) |
| 20 | + assert lead.phone_number == "+380931234567" |
| 21 | + |
| 22 | + |
| 23 | +def test_clean_and_validate_phone_no_country_code() -> None: |
| 24 | + lead = ContactFormLead(name="Test", phone_number="093 123 45 67", contact_method="telegram") |
| 25 | + assert lead.phone_number == "0931234567" |
| 26 | + |
| 27 | + |
| 28 | +def test_clean_and_validate_phone_too_short() -> None: |
| 29 | + with pytest.raises(ValidationError) as exc: |
| 30 | + ContactFormLead(name="Test", phone_number="093 123", contact_method="telegram") |
| 31 | + assert "Некоректний формат телефону" in str(exc.value) |
| 32 | + |
| 33 | + |
| 34 | +def test_clean_and_validate_phone_integer() -> None: |
| 35 | + lead = ContactFormLead( |
| 36 | + name="Test", |
| 37 | + phone_number=380931234567, # type: ignore |
| 38 | + contact_method="telegram", |
| 39 | + ) |
| 40 | + assert lead.phone_number == "380931234567" |
| 41 | + |
| 42 | + |
| 43 | +# 2. TelegramService tests |
| 44 | +@pytest.mark.asyncio |
| 45 | +async def test_telegram_service_success() -> None: |
| 46 | + service = TelegramService( |
| 47 | + MagicMock(telegram_bot_token="test", telegram_chat_id="test", tg_leads_chat_id="test") |
| 48 | + ) |
| 49 | + |
| 50 | + with patch("httpx.AsyncClient.post", new_callable=AsyncMock) as mock_post: |
| 51 | + mock_response = MagicMock() |
| 52 | + mock_response.raise_for_status = MagicMock() |
| 53 | + mock_post.return_value = mock_response |
| 54 | + |
| 55 | + await service.send_alert("Test message") |
| 56 | + mock_post.assert_called_once() |
| 57 | + mock_response.raise_for_status.assert_called_once() |
| 58 | + |
| 59 | + |
| 60 | +@pytest.mark.asyncio |
| 61 | +async def test_telegram_service_http_error() -> None: |
| 62 | + service = TelegramService( |
| 63 | + MagicMock(telegram_bot_token="test", telegram_chat_id="test", tg_leads_chat_id="test") |
| 64 | + ) |
| 65 | + |
| 66 | + with patch("httpx.AsyncClient.post", new_callable=AsyncMock) as mock_post: |
| 67 | + mock_response = MagicMock() |
| 68 | + mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( |
| 69 | + "HTTP Error", request=MagicMock(), response=MagicMock() |
| 70 | + ) |
| 71 | + mock_post.return_value = mock_response |
| 72 | + |
| 73 | + with pytest.raises(httpx.HTTPStatusError): |
| 74 | + await service.send_alert("Test message") |
| 75 | + |
| 76 | + |
| 77 | +@pytest.mark.asyncio |
| 78 | +async def test_telegram_service_network_error() -> None: |
| 79 | + service = TelegramService( |
| 80 | + MagicMock(telegram_bot_token="test", telegram_chat_id="test", tg_leads_chat_id="test") |
| 81 | + ) |
| 82 | + |
| 83 | + with patch("httpx.AsyncClient.post", new_callable=AsyncMock) as mock_post: |
| 84 | + mock_post.side_effect = httpx.ConnectError("Network Error") |
| 85 | + |
| 86 | + with pytest.raises(httpx.ConnectError): |
| 87 | + await service.send_alert("Test message") |
| 88 | + |
| 89 | + |
| 90 | +# 3. Tenacity tests |
| 91 | +@pytest.mark.asyncio |
| 92 | +async def test_send_telegram_notification_retry_limit() -> None: |
| 93 | + with patch( |
| 94 | + "app.api.v1.endpoints.leads.telegram_service.send_alert", new_callable=AsyncMock |
| 95 | + ) as mock_send_alert: |
| 96 | + # Mock telegram service to always raise ConnectError |
| 97 | + mock_send_alert.side_effect = httpx.ConnectError("Network Error") |
| 98 | + |
| 99 | + with pytest.raises(RetryError): |
| 100 | + # This should retry exactly 3 times as configured |
| 101 | + await send_telegram_notification(lead_id=1, message="Test retry") |
| 102 | + |
| 103 | + assert mock_send_alert.call_count == 3 |
| 104 | + |
| 105 | + |
| 106 | +# 4. API Endpoint tests |
| 107 | +client = TestClient(app) |
| 108 | + |
| 109 | + |
| 110 | +def test_api_create_lead_honeypot() -> None: |
| 111 | + response = client.post( |
| 112 | + "/api/v1/leads", |
| 113 | + json={ |
| 114 | + "name": "Spam Bot", |
| 115 | + "phone_number": "0931234567", |
| 116 | + "contact_method": "telegram", |
| 117 | + "honeypot": "spammed_data", |
| 118 | + }, |
| 119 | + ) |
| 120 | + |
| 121 | + # Should return 200 OK to trick the bot, but not actually process it |
| 122 | + assert response.status_code == 200 |
| 123 | + assert response.json() == {"status": "success"} |
| 124 | + |
| 125 | + |
| 126 | +@patch("app.api.v1.endpoints.leads.AsyncSessionLocal") |
| 127 | +@patch("app.api.v1.endpoints.leads.BackgroundTasks.add_task") |
| 128 | +def test_api_create_lead_success(mock_add_task: MagicMock, mock_session_local: MagicMock) -> None: |
| 129 | + # Set up the async context manager mock |
| 130 | + mock_session = AsyncMock() |
| 131 | + mock_session_local.return_value.__aenter__.return_value = mock_session |
| 132 | + |
| 133 | + response = client.post( |
| 134 | + "/api/v1/leads", |
| 135 | + json={"name": "Real User", "phone_number": "+380931234567", "contact_method": "telegram"}, |
| 136 | + ) |
| 137 | + |
| 138 | + assert response.status_code == 200 |
| 139 | + assert response.json() == {"status": "success"} |
| 140 | + |
| 141 | + # Verify DB insertion |
| 142 | + mock_session.add.assert_called_once() |
| 143 | + mock_session.commit.assert_called_once() |
| 144 | + mock_session.refresh.assert_called_once() |
| 145 | + |
| 146 | + # Verify background task was queued |
| 147 | + mock_add_task.assert_called_once() |
0 commit comments