"""Lambda test module.""" import pytest from unittest.mock import call from unittest.mock import MagicMock from unittest.mock import patch import uuid from boto3.dynamodb.types import TypeDeserializer from boto3.dynamodb.types import TypeSerializer from src import app as index from config import BATCH_SIZE @pytest.mark.parametrize( 'items, batch_size, output', [ ([], 10, []), # empty list ([1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]), # list gt batch ([1, 2, 3, 4, 5], 5, [[1, 2, 3, 4, 5]]), # list eq batch ([1, 2, 3, 4, 5], 10, [[1, 2, 3, 4, 5]]), # list lt batch ] ) @patch.object(index, 'dynamo_client') @patch.object(index, 'sqs_client') def test_batching(sqs_client, dynamo_client, items, batch_size, output): """Test splitting list into batches.""" result = index.batch_items(items, batch_size) assert result == output @patch.object(index, 'dynamo_client') @patch.object(index, 'sqs_client') def test_handler( sqs_client, dynamo_client, monkeypatch): """Test handler function.""" S = TypeSerializer() D = TypeDeserializer() mock_id = 'f691014c-bf83-4357-961e-5b0f1122a1ce' monkeypatch.setattr( uuid, 'uuid4', MagicMock(return_value=uuid.UUID(mock_id))) result_count = int(BATCH_SIZE * 1.5) scan_result = { 'Items': [ {'buffer_id': S.serialize(str(i))} for i in range(result_count) ] } dynamo_client.scan.return_value = scan_result index.handler(None, None) assert sqs_client.send_message_batch.call_args_list == [ call( Entries=[ { 'Id': mock_id, 'MessageBody': D.deserialize(r['buffer_id']) } for r in scan_result['Items'][0:BATCH_SIZE] ], QueueUrl=None ), call( Entries=[ { 'Id': mock_id, 'MessageBody': D.deserialize(r['buffer_id']) } for r in scan_result['Items'][BATCH_SIZE:result_count] ], QueueUrl=None ) ] @patch.object(index, 'dynamo_client') @patch.object(index, 'sqs_client') def test_handler_fifo(sqs_client, dynamo_client, monkeypatch): """Test message formatting for fifo queue.""" S = TypeSerializer() mock_id = 'f691014c-bf83-4357-961e-5b0f1122a1ce' monkeypatch.setattr( uuid, 'uuid4', MagicMock(return_value=uuid.UUID(mock_id))) scan_result = { 'Items': [ {'buffer_id': S.serialize(str('buffer-id'))} ] } dynamo_client.scan.return_value = scan_result index.handler(None, None) assert sqs_client.send_message_batch.call_args_list == [ call( Entries=[ { 'Id': mock_id, 'MessageBody': 'buffer-id', } ], QueueUrl=None ) ]