"""Unit tests for app handler.""" from unittest.mock import MagicMock, patch import pytest from src.app import handler from src.errors import TransientError from src.schemas import OutboxProcessResponse @pytest.fixture def mock_mysql_connection(): """Mock MySQL connection context manager.""" with patch('src.app.mysql_connection') as mock: mock_conn = MagicMock() mock.return_value.__enter__.return_value = mock_conn yield mock @pytest.fixture def mock_repository(): """Mock Repository.""" with patch('src.app.Repository') as mock: yield mock @pytest.fixture def mock_eb_connector(): """Mock EventBridgeConnector.""" with patch('src.app.EventBridgeConnector') as mock: yield mock @pytest.fixture def mock_get_events_client(): """Mock get_events_client.""" with patch('src.app.get_events_client') as mock: yield mock @pytest.fixture def mock_process(): """Mock OutboxProcessor.""" with patch('src.app.OutboxProcessor') as mock: yield mock @pytest.fixture def lambda_context(): """Mock Lambda context.""" context = MagicMock() context.invoked_function_arn = ( 'arn:aws:lambda:us-east-1:123456789012:function:test-function' ) return context class TestHandler: """Test Lambda handler.""" def test_handler_success( self, mock_mysql_connection, mock_repository, mock_eb_connector, mock_get_events_client, mock_process, lambda_context, ): """Test successful execution.""" # Setup processor response mock_instance = mock_process.return_value mock_instance.process.return_value = OutboxProcessResponse( total=10, processed=10, failed=0, skipped=0 ) response = handler({}, lambda_context) assert response == { 'total': 10, 'processed': 10, 'failed': 0, 'skipped': 0, } mock_mysql_connection.assert_called_once() mock_repository.assert_called_once() mock_get_events_client.assert_called_once() mock_eb_connector.assert_called_once() mock_process.assert_called_once() mock_instance.process.assert_called_once() def test_handler_transient_error( self, mock_mysql_connection, mock_repository, mock_eb_connector, mock_get_events_client, mock_process, lambda_context, ): """Test handling of TransientError.""" mock_instance = mock_process.return_value mock_instance.process.side_effect = TransientError('Connection failed') with pytest.raises(TransientError, match='Connection failed'): handler({}, lambda_context) def test_handler_generic_exception( self, mock_mysql_connection, mock_repository, mock_eb_connector, mock_get_events_client, mock_process, lambda_context, ): """Test handling of unexpected exceptions.""" mock_instance = mock_process.return_value mock_instance.process.side_effect = Exception('Unexpected crash') with pytest.raises(Exception, match='Unexpected crash'): handler({}, lambda_context)