"""Lambda test module.""" from unittest.mock import patch import boto3 import moto import lambda_retention def _create_fake_volume_with_snapshots(tag): """Create fake volume with provided tag for snapshot creation testing. Args: tag (str): tag value. Returns: str, list: volume id, list of snapshot ids. """ 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': '1' }, ] ) snapshot_ids = [] for i in range(3): snapshot = ec2_client.create_snapshot(VolumeId=response['VolumeId']) snapshot_ids.append(snapshot['SnapshotId']) return response['VolumeId'], snapshot_ids @moto.mock_ec2 @patch('os.environ', {'VOLUME_TAG': 'mock_tag'}) def test_handler_via_moto_mock(): """Test handler function.""" # preparation mock_tag = 'mock_tag' volume_id, snapshot_ids = _create_fake_volume_with_snapshots(mock_tag) fake_event_string = 'event-data/{0}'.format(snapshot_ids[0]) ec2_client = boto3.client('ec2', region_name='us-east-1') result_snapshot = ec2_client.describe_snapshots( Filters=[ { 'Name': 'volume-id', 'Values': [ volume_id ] } ] ) assert len(result_snapshot['Snapshots']) == 3 # test functional call lambda_retention.handler(fake_event_string, None) # checking result_snapshot = ec2_client.describe_snapshots( Filters=[ { 'Name': 'volume-id', 'Values': [ volume_id ] } ] ) assert len(result_snapshot['Snapshots']) == 1