File: test_lambda_eventsourcemapping.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (703 lines) | stat: -rw-r--r-- 25,124 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import json
import sys
import time
import uuid
from unittest import SkipTest

import boto3
import pytest
from botocore.exceptions import ClientError

from moto import mock_aws
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.utilities.distutils_version import LooseVersion

from ..markers import requires_docker
from .utilities import (
    get_role_name,
    get_test_zip_file3,
    get_test_zip_file_error,
    wait_for_log_msg,
)

PYTHON_VERSION = "python3.11"
_lambda_region = "us-west-2"
botocore_version = sys.modules["botocore"].__version__


@mock_aws
def test_create_event_source_mapping():
    if LooseVersion(botocore_version) < LooseVersion("1.23.12"):
        raise SkipTest("Parameter FilterCriteria is not available in older versions")

    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )

    destination_config = {
        "OnSuccess": {"Destination": "s3"},
        "OnFailure": {"Destination": "s4"},
    }
    doc_db_config = {
        "DatabaseName": "db",
        "CollectionName": "cn",
        "FullDocument": "UpdateLookup",
    }
    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"],
        FunctionName=func["FunctionArn"],
        BatchSize=1,
        FilterCriteria={
            "Filters": [{"Pattern": r"asdf"}],
        },
        MaximumBatchingWindowInSeconds=5,
        ParallelizationFactor=4,
        StartingPosition="AT_TIMESTAMP",
        DestinationConfig=destination_config,
        MaximumRecordAgeInSeconds=59,
        BisectBatchOnFunctionError=True,
        MaximumRetryAttempts=9000,
        Tags={"k1": "v1"},
        TumblingWindowInSeconds=100,
        Topics=["t1", "T2"],
        Queues=["q1", "q2"],
        SourceAccessConfigurations=[
            {"Type": "BASIC_AUTH", "URI": "http://auth.endpoint"},
        ],
        SelfManagedEventSource={
            "Endpoints": {
                "key": ["v1"],
            },
        },
        FunctionResponseTypes=["ReportBatchItemFailures"],
        AmazonManagedKafkaEventSourceConfig={"ConsumerGroupId": "cgid"},
        SelfManagedKafkaEventSourceConfig={"ConsumerGroupId": "cgid2"},
        ScalingConfig={"MaximumConcurrency": 100},
        DocumentDBEventSourceConfig=doc_db_config,
        KMSKeyArn="arn:kms:key",
        MetricsConfig={"Metrics": ["EventCount"]},
        ProvisionedPollerConfig={"MinimumPollers": 12, "MaximumPollers": 13},
    )

    assert response["EventSourceArn"] == queue.attributes["QueueArn"]
    assert response["FunctionArn"] == func["FunctionArn"]
    assert response["State"] == "Enabled"
    assert response["BatchSize"] == 1
    assert response["StartingPosition"] == "AT_TIMESTAMP"
    assert response["MaximumBatchingWindowInSeconds"] == 5
    assert response["ParallelizationFactor"] == 4
    assert response["FilterCriteria"] == {"Filters": [{"Pattern": "asdf"}]}
    assert response["DestinationConfig"] == destination_config
    assert response["Topics"] == ["t1", "T2"]
    assert response["Queues"] == ["q1", "q2"]
    assert response["SourceAccessConfigurations"] == [
        {"Type": "BASIC_AUTH", "URI": "http://auth.endpoint"}
    ]
    assert response["SelfManagedEventSource"] == {"Endpoints": {"key": ["v1"]}}
    assert response["MaximumRecordAgeInSeconds"] == 59
    assert response["BisectBatchOnFunctionError"] is True
    assert response["MaximumRetryAttempts"] == 9000
    assert response["TumblingWindowInSeconds"] == 100
    assert response["FunctionResponseTypes"] == ["ReportBatchItemFailures"]
    assert response["AmazonManagedKafkaEventSourceConfig"] == {
        "ConsumerGroupId": "cgid"
    }
    assert response["SelfManagedKafkaEventSourceConfig"] == {"ConsumerGroupId": "cgid2"}
    assert response["ScalingConfig"] == {"MaximumConcurrency": 100}
    assert response["DocumentDBEventSourceConfig"] == doc_db_config
    assert response["KMSKeyArn"] == "arn:kms:key"
    assert response["MetricsConfig"] == {"Metrics": ["EventCount"]}
    assert response["ProvisionedPollerConfig"] == {
        "MinimumPollers": 12,
        "MaximumPollers": 13,
    }
    expected_esm_arn = (
        f"arn:aws:lambda:us-east-1:{ACCOUNT_ID}:event-source-mapping:{response['UUID']}"
    )
    assert response["EventSourceMappingArn"] == expected_esm_arn


@pytest.mark.network
@pytest.mark.parametrize("key", ["FunctionName", "FunctionArn"])
@mock_aws
@requires_docker
def test_invoke_function_from_sqs(key):
    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    name_or_arn = func[key]

    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=name_or_arn
    )

    assert response["EventSourceArn"] == queue.attributes["QueueArn"]
    assert response["State"] == "Enabled"

    sqs_client = boto3.client("sqs", region_name="us-east-1")
    sqs_client.send_message(QueueUrl=queue.url, MessageBody="test")

    expected_msg = "get_test_zip_file3 success"
    log_group = f"/aws/lambda/{function_name}"
    msg_showed_up, all_logs = wait_for_log_msg(expected_msg, log_group)

    assert msg_showed_up, (
        expected_msg
        + " was not found after sending an SQS message. All logs: "
        + str(all_logs)
    )


@pytest.mark.network
@mock_aws
@requires_docker
def test_invoke_function_from_dynamodb_put():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = str(uuid.uuid4())[0:6] + "_table"
    table = dynamodb.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
        StreamSpecification={
            "StreamEnabled": True,
            "StreamViewType": "NEW_AND_OLD_IMAGES",
        },
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 5},
    )

    conn = boto3.client("lambda", region_name="us-east-1")
    function_name = str(uuid.uuid4())[0:6]
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function executed after a DynamoDB table is updated",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )

    response = conn.create_event_source_mapping(
        EventSourceArn=table["TableDescription"]["LatestStreamArn"],
        FunctionName=func["FunctionArn"],
    )

    assert response["EventSourceArn"] == table["TableDescription"]["LatestStreamArn"]
    assert response["State"] == "Enabled"

    item_to_create = {"id": {"S": "item 1"}, "data": {"M": {"nested": {"S": "stuff"}}}}
    dynamodb.put_item(TableName=table_name, Item=item_to_create)

    expected_msg = "get_test_zip_file3 success"
    log_group = f"/aws/lambda/{function_name}"
    msg_showed_up, all_logs = wait_for_log_msg(expected_msg, log_group)

    assert msg_showed_up, (
        expected_msg + " was not found after a DDB insert. All logs: " + str(all_logs)
    )
    assert any(
        json.dumps(item_to_create, separators=(",", ":")) in msg for msg in all_logs
    )


@pytest.mark.network
@mock_aws
@requires_docker
def test_invoke_function_from_dynamodb_update():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = str(uuid.uuid4())[0:6] + "_table"
    table = dynamodb.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
        StreamSpecification={
            "StreamEnabled": True,
            "StreamViewType": "NEW_AND_OLD_IMAGES",
        },
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 5},
    )

    conn = boto3.client("lambda", region_name="us-east-1")
    function_name = str(uuid.uuid4())[0:6]
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function executed after a DynamoDB table is updated",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )

    conn.create_event_source_mapping(
        EventSourceArn=table["TableDescription"]["LatestStreamArn"],
        FunctionName=func["FunctionArn"],
    )

    dynamodb.put_item(TableName=table_name, Item={"id": {"S": "item 1"}})
    log_group = f"/aws/lambda/{function_name}"
    expected_msg = "get_test_zip_file3 success"
    msg_showed_up, all_logs = wait_for_log_msg(expected_msg, log_group)
    assert "Nr_of_records(1)" in all_logs, "Only one item should be inserted"

    dynamodb.update_item(
        TableName=table_name,
        Key={"id": {"S": "item 1"}},
        UpdateExpression="set #attr = :val",
        ExpressionAttributeNames={"#attr": "new_attr"},
        ExpressionAttributeValues={":val": {"S": "new_val"}},
    )
    msg_showed_up, all_logs = wait_for_log_msg(expected_msg, log_group)

    assert msg_showed_up, (
        expected_msg + " was not found after updating DDB. All logs: " + str(all_logs)
    )
    assert "Nr_of_records(1)" in all_logs, "Only one item should be updated"
    assert "Nr_of_records(2)" not in all_logs, (
        "The inserted item should not show up again"
    )


@pytest.mark.network
@mock_aws
@requires_docker
def test_invoke_function_from_sqs_exception():
    function_name = str(uuid.uuid4())[0:6]
    logs_conn = boto3.client("logs", region_name="us-east-1")
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file_error()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )

    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=func["FunctionArn"]
    )

    assert response["EventSourceArn"] == queue.attributes["QueueArn"]
    assert response["State"] == "Enabled"

    entries = []
    for i in range(2):
        body = {"uuid": str(uuid.uuid4()), "test": f"test_{i}"}
        entry = {"Id": str(i), "MessageBody": json.dumps(body)}
        entries.append(entry)

    queue.send_messages(Entries=entries)

    start = time.time()
    while (time.time() - start) < 30:
        result = logs_conn.describe_log_streams(
            logGroupName=f"/aws/lambda/{function_name}"
        )
        log_streams = result.get("logStreams")
        if not log_streams:
            time.sleep(1)
            continue
        assert len(log_streams) >= 1

        result = logs_conn.get_log_events(
            logGroupName=f"/aws/lambda/{function_name}",
            logStreamName=log_streams[0]["logStreamName"],
        )
        for event in result.get("events"):
            if "I failed!" in event["message"]:
                messages = queue.receive_messages(MaxNumberOfMessages=10)
                # Verify messages are still visible and unprocessed
                assert len(messages) == 2
                return
        time.sleep(1)

    raise AssertionError("Test Failed")


@pytest.mark.network
@mock_aws
@requires_docker
def test_invoke_function_from_sns():
    logs_conn = boto3.client("logs", region_name=_lambda_region)
    sns_conn = boto3.client("sns", region_name=_lambda_region)
    sns_conn.create_topic(Name="some-topic")
    topics_json = sns_conn.list_topics()
    topics = topics_json["Topics"]
    topic_arn = topics[0]["TopicArn"]

    conn = boto3.client("lambda", _lambda_region)
    function_name = str(uuid.uuid4())[0:6]
    result = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )

    sns_conn.subscribe(
        TopicArn=topic_arn, Protocol="lambda", Endpoint=result["FunctionArn"]
    )

    sns_conn.publish(TopicArn=topic_arn, Message=json.dumps({}))

    start = time.time()
    events = []
    while (time.time() - start) < 10:
        result = logs_conn.describe_log_streams(
            logGroupName=f"/aws/lambda/{function_name}"
        )
        log_streams = result.get("logStreams")
        if not log_streams:
            time.sleep(1)
            continue

        assert len(log_streams) == 1
        result = logs_conn.get_log_events(
            logGroupName=f"/aws/lambda/{function_name}",
            logStreamName=log_streams[0]["logStreamName"],
        )
        events = result.get("events")
        for event in events:
            if event["message"] == "get_test_zip_file3 success":
                return

        time.sleep(1)

    raise AssertionError("Expected message not found in logs:" + str(events))


@pytest.mark.network
@mock_aws
@requires_docker
def test_invoke_function_from_kinesis():
    logs_conn = boto3.client("logs", region_name=_lambda_region)
    kinesis = boto3.client("kinesis", region_name=_lambda_region)
    stream_name = "my_stream"

    kinesis.create_stream(StreamName=stream_name, ShardCount=2)
    resp = kinesis.describe_stream(StreamName=stream_name)
    kinesis_arn = resp["StreamDescription"]["StreamARN"]

    conn = boto3.client("lambda", _lambda_region)
    function_name = str(uuid.uuid4())[0:6]
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
    )

    conn.create_event_source_mapping(
        EventSourceArn=kinesis_arn,
        FunctionName=func["FunctionArn"],
    )

    # Send Data
    kinesis.put_record(StreamName=stream_name, Data="data", PartitionKey="1")

    start = time.time()
    events = []
    while (time.time() - start) < 10:
        result = logs_conn.describe_log_streams(
            logGroupName=f"/aws/lambda/{function_name}"
        )
        log_streams = result.get("logStreams")
        if not log_streams:
            time.sleep(1)
            continue

        assert len(log_streams) == 1
        result = logs_conn.get_log_events(
            logGroupName=f"/aws/lambda/{function_name}",
            logStreamName=log_streams[0]["logStreamName"],
        )
        events = result.get("events")
        for event in events:
            if event["message"] == "get_test_zip_file3 success":
                return

        time.sleep(0.5)

    raise AssertionError("Expected message not found in logs:" + str(events))


@mock_aws
def test_list_event_source_mappings():
    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=func["FunctionArn"]
    )
    mappings = conn.list_event_source_mappings(EventSourceArn="123")
    assert len(mappings["EventSourceMappings"]) == 0

    mappings = conn.list_event_source_mappings(
        EventSourceArn=queue.attributes["QueueArn"]
    )
    assert len(mappings["EventSourceMappings"]) >= 1
    assert mappings["EventSourceMappings"][0]["UUID"] == response["UUID"]
    assert mappings["EventSourceMappings"][0]["FunctionArn"] == func["FunctionArn"]


@mock_aws
def test_get_event_source_mapping():
    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=func["FunctionArn"]
    )
    mapping = conn.get_event_source_mapping(UUID=response["UUID"])
    assert mapping["UUID"] == response["UUID"]
    assert mapping["FunctionArn"] == func["FunctionArn"]

    with pytest.raises(ClientError) as exc:
        conn.get_event_source_mapping(UUID="1")
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "The resource you requested does not exist."


@mock_aws
def test_update_event_source_mapping():
    if LooseVersion(botocore_version) < LooseVersion("1.23.12"):
        raise SkipTest("Parameter FilterCriteria is not available in older versions")

    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func1 = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    func2 = conn.create_function(
        FunctionName="testFunction2",
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=func1["FunctionArn"]
    )
    assert response["FunctionArn"] == func1["FunctionArn"]
    assert response["BatchSize"] == 10
    assert response["State"] == "Enabled"

    destination_config = {
        "OnSuccess": {"Destination": "s3"},
        "OnFailure": {"Destination": "s4"},
    }
    doc_db_config = {
        "DatabaseName": "db",
        "CollectionName": "cn",
        "FullDocument": "UpdateLookup",
    }

    mapping = conn.update_event_source_mapping(
        UUID=response["UUID"],
        Enabled=False,
        BatchSize=2,
        FunctionName="testFunction2",
        FilterCriteria={
            "Filters": [{"Pattern": r"asdf"}],
        },
        MaximumBatchingWindowInSeconds=5,
        ParallelizationFactor=4,
        DestinationConfig=destination_config,
        MaximumRecordAgeInSeconds=59,
        BisectBatchOnFunctionError=True,
        MaximumRetryAttempts=9000,
        TumblingWindowInSeconds=100,
        SourceAccessConfigurations=[
            {"Type": "BASIC_AUTH", "URI": "http://auth.endpoint"},
        ],
        FunctionResponseTypes=["ReportBatchItemFailures"],
        ScalingConfig={"MaximumConcurrency": 100},
        DocumentDBEventSourceConfig=doc_db_config,
        KMSKeyArn="arn:kms:key",
        MetricsConfig={"Metrics": ["EventCount"]},
        ProvisionedPollerConfig={"MinimumPollers": 12, "MaximumPollers": 13},
    )
    assert mapping["UUID"] == response["UUID"]
    assert mapping["FunctionArn"] == func2["FunctionArn"]
    assert mapping["State"] == "Disabled"
    assert mapping["BatchSize"] == 2

    assert mapping["MaximumBatchingWindowInSeconds"] == 5
    assert mapping["ParallelizationFactor"] == 4
    assert mapping["FilterCriteria"] == {"Filters": [{"Pattern": "asdf"}]}
    assert mapping["DestinationConfig"] == destination_config
    assert mapping["SourceAccessConfigurations"] == [
        {"Type": "BASIC_AUTH", "URI": "http://auth.endpoint"}
    ]
    assert mapping["MaximumRecordAgeInSeconds"] == 59
    assert mapping["BisectBatchOnFunctionError"] is True
    assert mapping["MaximumRetryAttempts"] == 9000
    assert mapping["TumblingWindowInSeconds"] == 100
    assert mapping["FunctionResponseTypes"] == ["ReportBatchItemFailures"]
    assert mapping["ScalingConfig"] == {"MaximumConcurrency": 100}
    assert mapping["DocumentDBEventSourceConfig"] == doc_db_config
    assert mapping["KMSKeyArn"] == "arn:kms:key"
    assert mapping["MetricsConfig"] == {"Metrics": ["EventCount"]}
    assert mapping["ProvisionedPollerConfig"] == {
        "MinimumPollers": 12,
        "MaximumPollers": 13,
    }


@mock_aws
def test_delete_event_source_mapping():
    function_name = str(uuid.uuid4())[0:6]
    sqs = boto3.resource("sqs", region_name="us-east-1")
    queue = sqs.create_queue(QueueName=f"{function_name}_queue")

    conn = boto3.client("lambda", region_name="us-east-1")
    func1 = conn.create_function(
        FunctionName=function_name,
        Runtime=PYTHON_VERSION,
        Role=get_role_name(),
        Handler="lambda_function.lambda_handler",
        Code={"ZipFile": get_test_zip_file3()},
        Description="test lambda function",
        Timeout=3,
        MemorySize=128,
        Publish=True,
    )
    response = conn.create_event_source_mapping(
        EventSourceArn=queue.attributes["QueueArn"], FunctionName=func1["FunctionArn"]
    )
    assert response["FunctionArn"] == func1["FunctionArn"]
    assert response["BatchSize"] == 10
    assert response["State"] == "Enabled"

    response = conn.delete_event_source_mapping(UUID=response["UUID"])

    assert response["State"] == "Deleting"
    with pytest.raises(ClientError) as exc:
        conn.get_event_source_mapping(UUID=response["UUID"])
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "The resource you requested does not exist."


@mock_aws
def test_event_source_mapping_tagging_lifecycle():
    if LooseVersion(botocore_version) < LooseVersion("1.35.23"):
        raise SkipTest(
            "Tagging support for Lambda event source mapping is not available in older Botocore versions"
        )

    iam = boto3.client("iam", region_name="us-east-1")
    iam_role = iam.create_role(RoleName="role", AssumeRolePolicyDocument="{}")
    client = boto3.client("lambda", region_name="us-east-1")
    client.create_function(
        FunctionName="any-function-name",
        Runtime="python3.6",
        Role=iam_role["Role"]["Arn"],
        Handler="any-handler",
        Code={
            "ZipFile": b"any zip file",
        },
    )
    sqs = boto3.client("sqs", region_name="us-east-1")
    queue_url = sqs.create_queue(QueueName="any-queue-name")
    queue_arn = sqs.get_queue_attributes(
        QueueUrl=queue_url["QueueUrl"], AttributeNames=["QueueArn"]
    )["Attributes"]["QueueArn"]
    event_source_mapping = client.create_event_source_mapping(
        FunctionName="any-function-name",
        EventSourceArn=queue_arn,
    )
    esm_arn = event_source_mapping["EventSourceMappingArn"]
    tags = {"foo": "bar", "baz": "qux"}
    client.tag_resource(Resource=esm_arn, Tags=tags)
    resp = client.list_tags(Resource=esm_arn)
    for key, value in tags.items():
        assert resp["Tags"][key] == value
    client.untag_resource(Resource=esm_arn, TagKeys=["foo"])
    resp = client.list_tags(Resource=esm_arn)
    assert resp["Tags"] == {"baz": "qux"}