"""Lambda test module.""" import base64 import json from unittest.mock import call from unittest.mock import patch import pytest from pydantic import ValidationError from src import app from src import utils from tests.unit.conftest import get_sample_event @patch.object(app, 'logic') def test_handler_single(logic_mock): """Test handler function.""" sample_event = get_sample_event() asset_event = utils.FinalAsset(**sample_event) app.handler_single(sample_event) assert logic_mock.download_and_process.call_args_list == [ call( bucket='prod-orcd-mezzanine-assets', key='6afc7e28_d140_4c29_abd8_9c8d06c8fe61.wav' ) ] assert logic_mock.produce_kafka_event.call_args_list == [call( asset_event, logic_mock.download_and_process.return_value )] def test_handler_single_wrong_file_format(): """Negative test handler function.""" sample_event = get_sample_event() sample_event['FILENAME'] = 'not_a_audio.txt' with pytest.raises(ValueError): app.handler_single(event=sample_event) def test_handler_wrong_event(): """Negative test handler function.""" sample_event = get_sample_event() del sample_event['BUCKET'] with pytest.raises(ValidationError): app.handler_single(event=sample_event) @patch.object(app, 'handler_single') def test_handler(handler_single_mock): """Test handler.""" sample_event = get_sample_event() batched_event = { 'records': { 'mytopic-0': [ { 'topic': 'mytopic', 'partition': 0, 'offset': 15, 'key': 'abcDEFghiJKLmnoPQRstuVWXyz1234==', 'value': base64.b64encode(json.dumps( sample_event).encode('ascii')), } ], 'mytopic-1': [ { 'topic': 'mytopic', 'partition': 0, 'offset': 16, 'key': 'abcDEFghiJKLmnoPQRstuVWXyz1234==', 'value': base64.b64encode(json.dumps( sample_event).encode('ascii')), } ], } } result = app.handler(event=batched_event, context=None) assert result == {'status': 'OK'} assert handler_single_mock.call_count == 2 assert handler_single_mock.call_args_list == [ call(sample_event), call(sample_event), ] @patch.object(app, 'logic') def test_handler_one_broken_event(logic_mock): """Test handler.""" sample_event = get_sample_event() sample_event_broken = sample_event.copy() del sample_event_broken['FILENAME'] # first broken event should let second one to run batched_event = { 'records': { 'mytopic-0': [ { 'topic': 'mytopic', 'partition': 0, 'offset': 15, 'key': 'abcDEFghiJKLmnoPQRstuVWXyz1234==', 'value': base64.b64encode(json.dumps( sample_event_broken).encode('ascii')), } ], 'mytopic-1': [ { 'topic': 'mytopic', 'partition': 0, 'offset': 16, 'key': 'abcDEFghiJKLmnoPQRstuVWXyz1234==', 'value': base64.b64encode(json.dumps( sample_event).encode('ascii')), } ], } } result = app.handler(event=batched_event, context=None) assert result == {'status': 'OK'}