from unittest import mock import freezegun import redis from anydi import Container from fansifter_common.utils import timezone from app.handler import SendEmailsHandler, SendEmailsRequest from app.main import handle def test_handle(container: Container) -> None: handler_mock = mock.MagicMock(spec=SendEmailsHandler) handler_mock.handle.return_value = [] batch_id = 100 campaign_id = "campaign_123" current_hourly_quota = 500.0 emails_to_send = 1000 with container.override(SendEmailsHandler, instance=handler_mock): response = handle( { "batch_id": batch_id, "campaign_id": campaign_id, "current_hourly_quota": current_hourly_quota, "emails_to_send": emails_to_send, }, None, ) assert response == {"status": "OK"} handler_mock.handle.assert_called_once_with( SendEmailsRequest( batch_id=100, campaign_id="campaign_123", current_hourly_quota=500.0, emails_to_send=1000, dispatch_time=None, ) ) def test_handle_dispatch_time(container: Container) -> None: handler_mock = mock.MagicMock(spec=SendEmailsHandler) handler_mock.handle.return_value = [] batch_id = 100 campaign_id = "campaign_123" current_hourly_quota = 500.0 emails_to_send = 1000 dispatch_time = timezone.now() with container.override(SendEmailsHandler, instance=handler_mock): response = handle( { "batch_id": batch_id, "campaign_id": campaign_id, "current_hourly_quota": current_hourly_quota, "emails_to_send": emails_to_send, "dispatch_time": dispatch_time.isoformat(), }, None, ) assert response == {"status": "OK"} def test_handle_skipped(container: Container, redis_client: redis.Redis) -> None: handler_mock = mock.MagicMock(spec=SendEmailsHandler) handler_mock.handle.return_value = [] batch_id = 100 with ( container.override(SendEmailsHandler, instance=handler_mock), redis_client.lock(f"sender:batch:{batch_id}"), ): response = handle( { "batch_id": batch_id, "campaign_id": "campaign_123", "provider": "google", "current_hourly_quota": 500.0, "emails_to_send": 1000, }, None, ) handler_mock.handle.assert_not_called() assert response == {"status": "SKIPPED"} @freezegun.freeze_time("2021-04-01") def test_handle_lock_ignored(container: Container, redis_client: redis.Redis) -> None: handler_mock = mock.MagicMock(spec=SendEmailsHandler) handler_mock.handle.return_value = [] batch_id = 100 with ( container.override(SendEmailsHandler, instance=handler_mock), redis_client.lock(f"sender:batch:{batch_id + 1}"), ): response = handle( { "batch_id": batch_id, "campaign_id": "campaign_123", "provider": "google", "current_hourly_quota": 500.0, "emails_to_send": 1000, }, None, ) handler_mock.handle.assert_called_once() assert response == {"status": "OK"} handler_mock.handle.assert_called_once_with( SendEmailsRequest( batch_id=100, campaign_id="campaign_123", current_hourly_quota=500.0, emails_to_send=1000, dispatch_time=None, ) )