import json from datetime import UTC, datetime from time import time from typing import Any from unittest import mock import pytest from dirty_equals import IsUUID from freezegun import freeze_time from app.adapters.db.twilio.models import TwilioAccount from app.config import Settings from app.exceptions import RequestValidationError from app.handler import TwilioWebhooksOutboundHandler from tests.unit.types import CreateModel @pytest.mark.db def test_handle_success( handler: TwilioWebhooksOutboundHandler, producer_mock: mock.MagicMock, settings: Settings, test_event: dict[str, Any], create_model: CreateModel, kms_client_mock: mock.MagicMock, ) -> None: kms_client_mock.decrypt.return_value = {"Plaintext": b"test"} create_model(TwilioAccount, account_sid="test") handler.request_validator.accounts_repository = mock.MagicMock() now = round(time()) with freeze_time(datetime.fromtimestamp(now, tz=UTC)): response = handler.handle(test_event) producer_mock.produce.assert_called_with( settings.kafka_event_topic, key=IsUUID(), value=json.dumps( { "body": { "MessagingServiceSid": "test", "MessageStatus": "sent", "To": "+1111", "From": "+1111", "MessageSid": "test", "AccountSid": "test", }, "params": test_event.get("queryStringParameters"), "timestamp": now, } ), callback=handler.kafka_producer_callback, ) producer_mock.flush.assert_called_with() assert response == {"statusCode": 200, "body": "OK"} @pytest.mark.db def test_handle_validation_fail( handler: TwilioWebhooksOutboundHandler, producer_mock: mock.MagicMock, test_event: dict[str, Any], create_model: CreateModel, kms_client_mock: mock.MagicMock, request_validator_mock: mock.MagicMock, ) -> None: kms_client_mock.decrypt.return_value = {"Plaintext": b"test"} request_validator_mock.validate.side_effect = RequestValidationError create_model(TwilioAccount, account_sid="test") handler.request_validator.accounts_repository = mock.MagicMock() response = handler.handle(test_event) producer_mock.produce.assert_not_called() producer_mock.flush.assert_not_called() assert response == {"statusCode": 403, "body": "Forbidden"}