import pytest from ...src import app from ...src.constants import Response SAMPLE_VALID_PAYLOAD: dict = dict( subject="Test Subject", body="Test Body", to=["john.doe@theorchard.com"], cc=["jane.doe@theorchard.com"], bcc=["jane.doe@theorchard.com"], reply_to=["john.doe@theorchard.com"], text="Test Text", html="Test HTML", ) class TestHandler: @property def sample_valid_payload(self): return SAMPLE_VALID_PAYLOAD.copy() @pytest.fixture def patcher_send_raw_email(self, mocker): return mocker.patch.object(app, "send_raw_email") @pytest.mark.parametrize( "event", [ { k: v for k, v in SAMPLE_VALID_PAYLOAD.items() if k in ["subject", "body"] }, # Incomplete {}, # Empty ], ) def test_handler_event_payload_invalid(self, event, patcher_send_raw_email): """Test handler with invalid event payload, missing mandatory keys.""" response = app.handler(event) assert ( response[Response.STATUS_CODE] == 422 ), "Expected 422 Unprocessable Entity" assert not patcher_send_raw_email.called, "Expected send_email to not be called" def test_handler_event_payload_valid(self, patcher_send_raw_email): """Test handler with valid event payload and sending success.""" app.handler(self.sample_valid_payload) assert patcher_send_raw_email.called, "Expected send_email to be called" def test_handler_event_payload_ses_exception(self, patcher_send_raw_email): """Test handler with valid event payload but exception raised by SES, resulting in failed sending. """ patcher_send_raw_email.side_effect = Exception("SES exception") response = app.handler(self.sample_valid_payload) assert patcher_send_raw_email.called, "Expected send_email to be called" assert ( response[Response.STATUS_CODE] == 500 ), "Expected 500 Internal Server Error" assert response[ Response.BODY ], "Expected non-empty response body with error message" @pytest.mark.parametrize("key", ["subject", "text", "to"]) def test_handler_event_payload_value_is_mandatory( self, key, patcher_send_raw_email ): payload = self.sample_valid_payload payload[key] = None response = app.handler(payload) assert ( response[Response.STATUS_CODE] == 422 ), "Expected 422 Unprocessable Entity" assert not patcher_send_raw_email.called, "Expected send_email to not be called" @pytest.mark.parametrize("key", ["to", "cc", "bcc", "reply_to"]) def test_handler_event_payload_value_should_be_email_list( self, key, patcher_send_raw_email ): payload = self.sample_valid_payload payload[key] = "john.doe@theorchard.com" response = app.handler(payload) assert ( response[Response.STATUS_CODE] == 422 ), "Expected 422 Unprocessable Entity" assert not patcher_send_raw_email.called, "Expected send_email to not be called"