"""Lambda test module.""" from unittest.mock import patch import boto3 import moto import pytest import lambda_backup @pytest.mark.parametrize( 'describe_volumes_mock, create_snapshot_mock', [ ( { 'Volumes': [ {'VolumeId': 10}, {'VolumeId': 11} ] }, [ {'SnapshotId': 1}, {'SnapshotId': 2} ] ), ( {'Volumes': []}, [] ) ]) @patch('os.environ', {'VOLUME_TAG': 'mock_tag'}) @patch('lambda_backup.client') def test_handler( ec2_client, describe_volumes_mock, create_snapshot_mock): """Test handler function.""" # mocking ec2_client.describe_volumes.return_value = describe_volumes_mock ec2_client.create_snapshot.side_effect = create_snapshot_mock # test functional call lambda_backup.handler(None, None) # checking ec2_client.describe_volumes.assert_called_once_with( Filters=[ { 'Name': 'tag-key', 'Values': [ 'mock_tag' ] } ]) for i in range(len(describe_volumes_mock['Volumes'])): description = 'Snapshot for volume {}'.format( describe_volumes_mock['Volumes'][i]['VolumeId']) ec2_client.create_snapshot.assert_any_call( VolumeId=describe_volumes_mock['Volumes'][i]['VolumeId'], Description=description ) ec2_client.create_tags.assert_any_call( Resources=[ create_snapshot_mock[i]['SnapshotId'], ], Tags=[ { 'Key': 'mock_tag', 'Value': 'true' }, ] ) def _create_fake_volume(tag): """Create fake volume with provided tag for snapshot creation testing. Args: tag (str): tag value. Returns: str: volume id. """ ec2_client = boto3.client('ec2', region_name='us-east-1') response = ec2_client.create_volume( AvailabilityZone='us-east-1a', Size=80, VolumeType='gp2', ) ec2_client.create_tags( Resources=[ response['VolumeId'], ], Tags=[ { 'Key': tag, 'Value': 'true' }, ] ) return response['VolumeId'] @moto.mock_ec2 @patch('os.environ', {'VOLUME_TAG': 'mock_tag'}) def test_handler_via_moto_mock(): """Test handler function.""" mock_tag = 'mock_tag' volume_id = _create_fake_volume(mock_tag) # test functional call lambda_backup.handler(None, None) # checking ec2_client = boto3.client('ec2', region_name='us-east-1') result_snapshot = ec2_client.describe_snapshots( Filters=[ { 'Name': 'volume-id', 'Values': [ volume_id ] } ] ) assert result_snapshot['Snapshots'][0]['Tags'][0]['Key'] == mock_tag