"""Test create_ingestion_lock handler.""" from unittest.mock import MagicMock, patch from botocore.errorfactory import ClientError from index import handler, LockfileExistsException import pytest @patch('index.logger') @patch('index.StateMachineSchema') @patch('index.s3_client') @patch('index.config') def test_handler_lockfile_exists( mock_config, mock_s3_client, mock_state_machine_schema, mock_current_logger, context, deserialized_context ): """Test the main handler when lockfile exists.""" mock_state_machine_schema.return_value.load = ( lambda _: deserialized_context) mock_head_object = MagicMock() mock_s3_client.head_object = mock_head_object expected_bucket = 'bucket' expected_s3_path = 'path/' expected_lockfile = f'{deserialized_context.product.upc}.lock' mock_config.INGESTION_LOCK_S3_BUCKET = expected_bucket mock_config.INGESTION_LOCK_S3_PATH = expected_s3_path with pytest.raises(LockfileExistsException): handler(context, None) mock_head_object.assert_called_once_with( Bucket=expected_bucket, Key=f'{expected_s3_path}{expected_lockfile}') @patch('index.logger') @patch('index.StateMachineSchema') @patch('index.s3_client') @patch('index.config') def test_handler_creates_lockfile( mock_config, mock_s3_client, mock_state_machine_schema, mock_current_logger, context, deserialized_context ): """Test the main handler creates lockfile.""" mock_state_machine_schema.return_value.load = ( lambda _: deserialized_context) mock_state_machine_schema.return_value.dump = ( lambda _: context) mock_head_object = MagicMock( side_effect=ClientError( error_response={}, operation_name='') ) mock_s3_client.head_object.side_effect = mock_head_object mock_put_object = MagicMock() mock_s3_client.put_object = mock_put_object expected_bucket = 'bucket' expected_s3_path = 'path/' expected_lockfile = f'{deserialized_context.product.upc}.lock' mock_config.INGESTION_LOCK_S3_BUCKET = expected_bucket mock_config.INGESTION_LOCK_S3_PATH = expected_s3_path output = handler(context, None) mock_head_object.assert_called_once_with( Bucket=expected_bucket, Key=f'{expected_s3_path}{expected_lockfile}') mock_put_object.assert_called_once_with( Bucket=expected_bucket, Key=f'{expected_s3_path}{expected_lockfile}') assert output == context