/
fixtures.py
2223 lines (1751 loc) 路 72.9 KB
/
fixtures.py
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import dataclasses
import json
import logging
import os
import re
import textwrap
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import botocore.auth
import botocore.config
import botocore.credentials
import botocore.session
import pytest
from _pytest.config import Config
from _pytest.nodes import Item
from botocore.exceptions import ClientError
from botocore.regions import EndpointResolver
from pytest_httpserver import HTTPServer
from werkzeug import Request, Response
from localstack import config
from localstack.constants import (
AWS_REGION_US_EAST_1,
SECONDARY_TEST_AWS_ACCOUNT_ID,
SECONDARY_TEST_AWS_REGION_NAME,
TEST_AWS_ACCOUNT_ID,
TEST_AWS_REGION_NAME,
)
from localstack.services.stores import (
AccountRegionBundle,
BaseStore,
CrossAccountAttribute,
CrossRegionAttribute,
LocalAttribute,
)
from localstack.testing.aws.cloudformation_utils import load_template_file, render_template
from localstack.testing.aws.util import get_lambda_logs, is_aws_cloud
from localstack.utils import testutil
from localstack.utils.aws.client import SigningHttpClient
from localstack.utils.aws.resources import create_dynamodb_table
from localstack.utils.bootstrap import is_api_enabled
from localstack.utils.collections import ensure_list
from localstack.utils.functions import run_safe
from localstack.utils.http import safe_requests as requests
from localstack.utils.json import CustomEncoder, json_safe
from localstack.utils.net import wait_for_port_open
from localstack.utils.strings import short_uid, to_str
from localstack.utils.sync import ShortCircuitWaitException, poll_condition, retry, wait_until
LOG = logging.getLogger(__name__)
# URL of public HTTP echo server, used primarily for AWS parity/snapshot testing
PUBLIC_HTTP_ECHO_SERVER_URL = "http://httpbin.org"
WAITER_CHANGE_SET_CREATE_COMPLETE = "change_set_create_complete"
WAITER_STACK_CREATE_COMPLETE = "stack_create_complete"
WAITER_STACK_UPDATE_COMPLETE = "stack_update_complete"
WAITER_STACK_DELETE_COMPLETE = "stack_delete_complete"
@pytest.fixture(scope="class")
def aws_http_client_factory(aws_session):
"""
Returns a factory for creating new ``SigningHttpClient`` instances using a configurable botocore request signer.
The default signer is a SigV4QueryAuth. The credentials are extracted from the ``boto3_sessions`` fixture that
transparently uses your global profile when TEST_TARGET=AWS_CLOUD, or test credentials when running against
LocalStack.
Example invocations
client = aws_signing_http_client_factory("sqs")
client.get("http://localhost:4566/000000000000/my-queue")
or
client = aws_signing_http_client_factory("dynamodb", signer_factory=SigV4Auth)
client.post("...")
"""
def factory(
service: str,
region: str = None,
signer_factory: Callable[
[botocore.credentials.Credentials, str, str], botocore.auth.BaseSigner
] = botocore.auth.SigV4QueryAuth,
endpoint_url: str = None,
aws_access_key_id: str = None,
aws_secret_access_key: str = None,
):
region = region or aws_session.region_name or AWS_REGION_US_EAST_1
if aws_access_key_id or aws_secret_access_key:
credentials = botocore.credentials.Credentials(
access_key=aws_access_key_id, secret_key=aws_secret_access_key
)
else:
credentials = aws_session.get_credentials()
creds = credentials.get_frozen_credentials()
if not endpoint_url:
if is_aws_cloud():
# FIXME: this is a bit raw. we should probably re-use boto in a better way
resolver: EndpointResolver = aws_session._session.get_component("endpoint_resolver")
endpoint_url = "https://" + resolver.construct_endpoint(service, region)["hostname"]
else:
endpoint_url = config.internal_service_url()
return SigningHttpClient(signer_factory(creds, service, region), endpoint_url=endpoint_url)
return factory
@pytest.fixture(scope="class")
def s3_vhost_client(aws_client_factory):
return aws_client_factory(config=botocore.config.Config(s3={"addressing_style": "virtual"})).s3
@pytest.fixture
def dynamodb_wait_for_table_active(aws_client):
def wait_for_table_active(table_name: str, client=None):
def wait():
return (client or aws_client.dynamodb).describe_table(TableName=table_name)["Table"][
"TableStatus"
] == "ACTIVE"
poll_condition(wait, timeout=30)
return wait_for_table_active
@pytest.fixture
def dynamodb_create_table_with_parameters(dynamodb_wait_for_table_active, aws_client):
tables = []
def factory(**kwargs):
if "TableName" not in kwargs:
kwargs["TableName"] = f"test-table-{short_uid()}"
tables.append(kwargs["TableName"])
response = aws_client.dynamodb.create_table(**kwargs)
dynamodb_wait_for_table_active(kwargs["TableName"])
return response
yield factory
# cleanup
for table in tables:
try:
# table has to be in ACTIVE state before deletion
dynamodb_wait_for_table_active(table)
aws_client.dynamodb.delete_table(TableName=table)
except Exception as e:
LOG.debug("error cleaning up table %s: %s", table, e)
@pytest.fixture
def dynamodb_create_table(dynamodb_wait_for_table_active, aws_client):
# beware, this swallows exception in create_dynamodb_table utility function
tables = []
def factory(**kwargs):
kwargs["client"] = aws_client.dynamodb
if "table_name" not in kwargs:
kwargs["table_name"] = f"test-table-{short_uid()}"
if "partition_key" not in kwargs:
kwargs["partition_key"] = "id"
tables.append(kwargs["table_name"])
return create_dynamodb_table(**kwargs)
yield factory
# cleanup
for table in tables:
try:
# table has to be in ACTIVE state before deletion
dynamodb_wait_for_table_active(table)
aws_client.dynamodb.delete_table(TableName=table)
except Exception as e:
LOG.debug("error cleaning up table %s: %s", table, e)
@pytest.fixture
def s3_create_bucket(s3_empty_bucket, aws_client):
buckets = []
def factory(**kwargs) -> str:
if "Bucket" not in kwargs:
kwargs["Bucket"] = "test-bucket-%s" % short_uid()
if (
"CreateBucketConfiguration" not in kwargs
and aws_client.s3.meta.region_name != "us-east-1"
):
kwargs["CreateBucketConfiguration"] = {
"LocationConstraint": aws_client.s3.meta.region_name
}
aws_client.s3.create_bucket(**kwargs)
buckets.append(kwargs["Bucket"])
return kwargs["Bucket"]
yield factory
# cleanup
for bucket in buckets:
try:
s3_empty_bucket(bucket)
aws_client.s3.delete_bucket(Bucket=bucket)
except Exception as e:
LOG.debug("error cleaning up bucket %s: %s", bucket, e)
@pytest.fixture
def s3_bucket(s3_create_bucket, aws_client) -> str:
region = aws_client.s3.meta.region_name
kwargs = {}
if region != "us-east-1":
kwargs["CreateBucketConfiguration"] = {"LocationConstraint": region}
return s3_create_bucket(**kwargs)
@pytest.fixture
def s3_empty_bucket(aws_client):
"""
Returns a factory that given a bucket name, deletes all objects and deletes all object versions
"""
# Boto resource would make this a straightforward task, but our internal client does not support Boto resource
# FIXME: this won't work when bucket has more than 1000 objects
def factory(bucket_name: str):
kwargs = {}
try:
aws_client.s3.get_object_lock_configuration(Bucket=bucket_name)
kwargs["BypassGovernanceRetention"] = True
except ClientError:
pass
response = aws_client.s3.list_objects_v2(Bucket=bucket_name)
objects = [{"Key": obj["Key"]} for obj in response.get("Contents", [])]
if objects:
aws_client.s3.delete_objects(
Bucket=bucket_name,
Delete={"Objects": objects},
**kwargs,
)
response = aws_client.s3.list_object_versions(Bucket=bucket_name)
versions = response.get("Versions", [])
versions.extend(response.get("DeleteMarkers", []))
object_versions = [{"Key": obj["Key"], "VersionId": obj["VersionId"]} for obj in versions]
if object_versions:
aws_client.s3.delete_objects(
Bucket=bucket_name,
Delete={"Objects": object_versions},
**kwargs,
)
yield factory
@pytest.fixture
def sqs_create_queue(aws_client):
queue_urls = []
def factory(**kwargs):
if "QueueName" not in kwargs:
kwargs["QueueName"] = "test-queue-%s" % short_uid()
response = aws_client.sqs.create_queue(**kwargs)
url = response["QueueUrl"]
queue_urls.append(url)
return url
yield factory
# cleanup
for queue_url in queue_urls:
try:
aws_client.sqs.delete_queue(QueueUrl=queue_url)
except Exception as e:
LOG.debug("error cleaning up queue %s: %s", queue_url, e)
@pytest.fixture
def sqs_receive_messages_delete(aws_client):
def factory(
queue_url: str,
expected_messages: Optional[int] = None,
wait_time: Optional[int] = 5,
):
response = aws_client.sqs.receive_message(
QueueUrl=queue_url,
MessageAttributeNames=["All"],
VisibilityTimeout=0,
WaitTimeSeconds=wait_time,
)
messages = []
for m in response["Messages"]:
message = json.loads(to_str(m["Body"]))
messages.append(message)
if expected_messages is not None:
assert len(messages) == expected_messages
for message in response["Messages"]:
aws_client.sqs.delete_message(
QueueUrl=queue_url, ReceiptHandle=message["ReceiptHandle"]
)
return messages
return factory
@pytest.fixture
def sqs_receive_num_messages(sqs_receive_messages_delete):
def factory(queue_url: str, expected_messages: int, max_iterations: int = 3):
all_messages = []
for _ in range(max_iterations):
try:
messages = sqs_receive_messages_delete(queue_url, wait_time=5)
except KeyError:
# there were no messages
continue
all_messages.extend(messages)
if len(all_messages) >= expected_messages:
return all_messages[:expected_messages]
raise AssertionError(f"max iterations reached with {len(all_messages)} messages received")
return factory
@pytest.fixture
def sqs_queue(sqs_create_queue):
return sqs_create_queue()
@pytest.fixture
def sqs_get_queue_arn(aws_client) -> Callable:
def _get_queue_arn(queue_url: str) -> str:
return aws_client.sqs.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["QueueArn"])[
"Attributes"
]["QueueArn"]
return _get_queue_arn
@pytest.fixture
def sqs_queue_exists(aws_client):
def _queue_exists(queue_url: str) -> bool:
"""
Checks whether a queue with the given queue URL exists.
:param queue_url: the queue URL
:return: true if the queue exists, false otherwise
"""
try:
result = aws_client.sqs.get_queue_url(QueueName=queue_url.split("/")[-1])
return result.get("QueueUrl") == queue_url
except ClientError as e:
if "NonExistentQueue" in e.response["Error"]["Code"]:
return False
raise
yield _queue_exists
@pytest.fixture
def sns_create_topic(aws_client):
topic_arns = []
def _create_topic(**kwargs):
if "Name" not in kwargs:
kwargs["Name"] = "test-topic-%s" % short_uid()
response = aws_client.sns.create_topic(**kwargs)
topic_arns.append(response["TopicArn"])
return response
yield _create_topic
for topic_arn in topic_arns:
try:
aws_client.sns.delete_topic(TopicArn=topic_arn)
except Exception as e:
LOG.debug("error cleaning up topic %s: %s", topic_arn, e)
@pytest.fixture
def sns_wait_for_topic_delete(aws_client):
def wait_for_topic_delete(topic_arn: str) -> None:
def wait():
try:
aws_client.sns.get_topic_attributes(TopicArn=topic_arn)
return False
except Exception as e:
if "NotFound" in e.response["Error"]["Code"]:
return True
raise
poll_condition(wait, timeout=30)
return wait_for_topic_delete
@pytest.fixture
def sns_subscription(aws_client):
sub_arns = []
def _create_sub(**kwargs):
if kwargs.get("ReturnSubscriptionArn") is None:
kwargs["ReturnSubscriptionArn"] = True
# requires 'TopicArn', 'Protocol', and 'Endpoint'
response = aws_client.sns.subscribe(**kwargs)
sub_arn = response["SubscriptionArn"]
sub_arns.append(sub_arn)
return response
yield _create_sub
for sub_arn in sub_arns:
try:
aws_client.sns.unsubscribe(SubscriptionArn=sub_arn)
except Exception as e:
LOG.debug(f"error cleaning up subscription {sub_arn}: {e}")
@pytest.fixture
def sns_topic(sns_create_topic, aws_client):
topic_arn = sns_create_topic()["TopicArn"]
return aws_client.sns.get_topic_attributes(TopicArn=topic_arn)
@pytest.fixture
def sns_allow_topic_sqs_queue(aws_client):
def _allow_sns_topic(sqs_queue_url, sqs_queue_arn, sns_topic_arn) -> None:
# allow topic to write to sqs queue
aws_client.sqs.set_queue_attributes(
QueueUrl=sqs_queue_url,
Attributes={
"Policy": json.dumps(
{
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": "sqs:SendMessage",
"Resource": sqs_queue_arn,
"Condition": {"ArnEquals": {"aws:SourceArn": sns_topic_arn}},
}
]
}
)
},
)
return _allow_sns_topic
@pytest.fixture
def sns_create_sqs_subscription(sns_allow_topic_sqs_queue, sqs_get_queue_arn, aws_client):
subscriptions = []
def _factory(topic_arn: str, queue_url: str, **kwargs) -> Dict[str, str]:
queue_arn = sqs_get_queue_arn(queue_url)
# connect sns topic to sqs
subscription = aws_client.sns.subscribe(
TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn, **kwargs
)
subscription_arn = subscription["SubscriptionArn"]
# allow topic to write to sqs queue
sns_allow_topic_sqs_queue(
sqs_queue_url=queue_url, sqs_queue_arn=queue_arn, sns_topic_arn=topic_arn
)
subscriptions.append(subscription_arn)
return aws_client.sns.get_subscription_attributes(SubscriptionArn=subscription_arn)[
"Attributes"
]
yield _factory
for arn in subscriptions:
try:
aws_client.sns.unsubscribe(SubscriptionArn=arn)
except Exception as e:
LOG.error("error cleaning up subscription %s: %s", arn, e)
@pytest.fixture
def sns_create_http_endpoint(sns_create_topic, sns_subscription, aws_client):
# This fixture can be used with manual setup to expose the HTTPServer fixture to AWS. One example is to use a
# a service like localhost.run, and set up a specific port to start the `HTTPServer(port=40000)` for example,
# and tunnel `localhost:40000` to a specific domain that you can manually return from this fixture.
http_servers = []
def _create_http_endpoint(
raw_message_delivery: bool = False,
) -> Tuple[str, str, str, HTTPServer]:
server = HTTPServer()
server.start()
http_servers.append(server)
server.expect_request("/sns-endpoint").respond_with_data(status=200)
endpoint_url = server.url_for("/sns-endpoint")
wait_for_port_open(endpoint_url)
topic_arn = sns_create_topic()["TopicArn"]
subscription = sns_subscription(TopicArn=topic_arn, Protocol="http", Endpoint=endpoint_url)
subscription_arn = subscription["SubscriptionArn"]
delivery_policy = {
"healthyRetryPolicy": {
"minDelayTarget": 1,
"maxDelayTarget": 1,
"numRetries": 0,
"numNoDelayRetries": 0,
"numMinDelayRetries": 0,
"numMaxDelayRetries": 0,
"backoffFunction": "linear",
},
"sicklyRetryPolicy": None,
"throttlePolicy": {"maxReceivesPerSecond": 1000},
"guaranteed": False,
}
aws_client.sns.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName="DeliveryPolicy",
AttributeValue=json.dumps(delivery_policy),
)
if raw_message_delivery:
aws_client.sns.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName="RawMessageDelivery",
AttributeValue="true",
)
return topic_arn, subscription_arn, endpoint_url, server
yield _create_http_endpoint
for http_server in http_servers:
if http_server.is_running():
http_server.stop()
@pytest.fixture
def route53_hosted_zone(aws_client):
hosted_zones = []
def factory(**kwargs):
if "Name" not in kwargs:
kwargs["Name"] = f"www.{short_uid()}.com."
if "CallerReference" not in kwargs:
kwargs["CallerReference"] = f"caller-ref-{short_uid()}"
response = aws_client.route53.create_hosted_zone(
Name=kwargs["Name"], CallerReference=kwargs["CallerReference"]
)
hosted_zones.append(response["HostedZone"]["Id"])
return response
yield factory
for zone in hosted_zones:
try:
aws_client.route53.delete_hosted_zone(Id=zone)
except Exception as e:
LOG.debug(f"error cleaning up route53 HostedZone {zone}: {e}")
@pytest.fixture
def transcribe_create_job(s3_bucket, aws_client):
job_names = []
def _create_job(audio_file: str, params: Optional[dict[str, Any]] = None) -> str:
s3_key = "test-clip.wav"
if not params:
params = {}
if "TranscriptionJobName" not in params:
params["TranscriptionJobName"] = f"test-transcribe-{short_uid()}"
if "LanguageCode" not in params:
params["LanguageCode"] = "en-GB"
if "Media" not in params:
params["Media"] = {"MediaFileUri": f"s3://{s3_bucket}/{s3_key}"}
# upload test wav to a s3 bucket
with open(audio_file, "rb") as f:
aws_client.s3.upload_fileobj(f, s3_bucket, s3_key)
response = aws_client.transcribe.start_transcription_job(**params)
job_name = response["TranscriptionJob"]["TranscriptionJobName"]
job_names.append(job_name)
return job_name
yield _create_job
for job_name in job_names:
with contextlib.suppress(ClientError):
aws_client.transcribe.delete_transcription_job(TranscriptionJobName=job_name)
@pytest.fixture
def kinesis_create_stream(aws_client):
stream_names = []
def _create_stream(**kwargs):
if "StreamName" not in kwargs:
kwargs["StreamName"] = f"test-stream-{short_uid()}"
aws_client.kinesis.create_stream(**kwargs)
stream_names.append(kwargs["StreamName"])
return kwargs["StreamName"]
yield _create_stream
for stream_name in stream_names:
try:
aws_client.kinesis.delete_stream(StreamName=stream_name, EnforceConsumerDeletion=True)
except Exception as e:
LOG.debug("error cleaning up kinesis stream %s: %s", stream_name, e)
@pytest.fixture
def wait_for_stream_ready(aws_client):
def _wait_for_stream_ready(stream_name: str):
def is_stream_ready():
describe_stream_response = aws_client.kinesis.describe_stream(StreamName=stream_name)
return describe_stream_response["StreamDescription"]["StreamStatus"] in [
"ACTIVE",
"UPDATING",
]
return poll_condition(is_stream_ready)
return _wait_for_stream_ready
@pytest.fixture
def wait_for_delivery_stream_ready(aws_client):
def _wait_for_stream_ready(delivery_stream_name: str):
def is_stream_ready():
describe_stream_response = aws_client.firehose.describe_delivery_stream(
DeliveryStreamName=delivery_stream_name
)
return (
describe_stream_response["DeliveryStreamDescription"]["DeliveryStreamStatus"]
== "ACTIVE"
)
poll_condition(is_stream_ready)
return _wait_for_stream_ready
@pytest.fixture
def wait_for_dynamodb_stream_ready(aws_client):
def _wait_for_stream_ready(stream_arn: str):
def is_stream_ready():
describe_stream_response = aws_client.dynamodbstreams.describe_stream(
StreamArn=stream_arn
)
return describe_stream_response["StreamDescription"]["StreamStatus"] == "ENABLED"
return poll_condition(is_stream_ready)
return _wait_for_stream_ready
@pytest.fixture()
def kms_create_key(aws_client_factory):
key_ids = []
def _create_key(region_name: str = None, **kwargs):
if "Description" not in kwargs:
kwargs["Description"] = f"test description - {short_uid()}"
key_metadata = aws_client_factory(region_name=region_name).kms.create_key(**kwargs)[
"KeyMetadata"
]
key_ids.append((region_name, key_metadata["KeyId"]))
return key_metadata
yield _create_key
for region_name, key_id in key_ids:
try:
# shortest amount of time you can schedule the deletion
aws_client_factory(region_name=region_name).kms.schedule_key_deletion(
KeyId=key_id, PendingWindowInDays=7
)
except Exception as e:
exception_message = str(e)
# Some tests schedule their keys for deletion themselves.
if (
"KMSInvalidStateException" not in exception_message
or "is pending deletion" not in exception_message
):
LOG.debug("error cleaning up KMS key %s: %s", key_id, e)
@pytest.fixture()
def kms_replicate_key(aws_client_factory):
key_ids = []
def _replicate_key(region_from=None, **kwargs):
region_to = kwargs.get("ReplicaRegion")
key_ids.append((region_to, kwargs.get("KeyId")))
return aws_client_factory(region_name=region_from).kms.replicate_key(**kwargs)
yield _replicate_key
for region_to, key_id in key_ids:
try:
# shortest amount of time you can schedule the deletion
aws_client_factory(region_name=region_to).kms.schedule_key_deletion(
KeyId=key_id, PendingWindowInDays=7
)
except Exception as e:
LOG.debug("error cleaning up KMS key %s: %s", key_id, e)
# kms_create_key fixture is used here not just to be able to create aliases without a key specified,
# but also to make sure that kms_create_key gets executed before and teared down after kms_create_alias -
# to make sure that we clean up aliases before keys get cleaned up.
@pytest.fixture()
def kms_create_alias(kms_create_key, aws_client):
aliases = []
def _create_alias(**kwargs):
if "AliasName" not in kwargs:
kwargs["AliasName"] = f"alias/{short_uid()}"
if "TargetKeyId" not in kwargs:
kwargs["TargetKeyId"] = kms_create_key()["KeyId"]
aws_client.kms.create_alias(**kwargs)
aliases.append(kwargs["AliasName"])
return kwargs["AliasName"]
yield _create_alias
for alias in aliases:
try:
aws_client.kms.delete_alias(AliasName=alias)
except Exception as e:
LOG.debug("error cleaning up KMS alias %s: %s", alias, e)
@pytest.fixture()
def kms_create_grant(kms_create_key, aws_client):
grants = []
def _create_grant(**kwargs):
# Just a random ARN, since KMS in LocalStack currently doesn't validate GranteePrincipal,
# but some GranteePrincipal is required to create a grant.
GRANTEE_PRINCIPAL_ARN = (
"arn:aws:kms:eu-central-1:123456789876:key/198a5a78-52c3-489f-ac70-b06a4d11027a"
)
if "Operations" not in kwargs:
kwargs["Operations"] = ["Decrypt", "Encrypt"]
if "GranteePrincipal" not in kwargs:
kwargs["GranteePrincipal"] = GRANTEE_PRINCIPAL_ARN
if "KeyId" not in kwargs:
kwargs["KeyId"] = kms_create_key()["KeyId"]
grant_id = aws_client.kms.create_grant(**kwargs)["GrantId"]
grants.append((grant_id, kwargs["KeyId"]))
return grant_id, kwargs["KeyId"]
yield _create_grant
for grant_id, key_id in grants:
try:
aws_client.kms.retire_grant(GrantId=grant_id, KeyId=key_id)
except Exception as e:
LOG.debug("error cleaning up KMS grant %s: %s", grant_id, e)
@pytest.fixture
def kms_key(kms_create_key):
return kms_create_key()
@pytest.fixture
def kms_grant_and_key(kms_key, aws_client):
user_arn = aws_client.sts.get_caller_identity()["Arn"]
return [
aws_client.kms.create_grant(
KeyId=kms_key["KeyId"],
GranteePrincipal=user_arn,
Operations=["Decrypt", "Encrypt"],
),
kms_key,
]
@pytest.fixture
def opensearch_wait_for_cluster(aws_client):
def _wait_for_cluster(domain_name: str):
def finished_processing():
status = aws_client.opensearch.describe_domain(DomainName=domain_name)["DomainStatus"]
return status["Processing"] is False
assert poll_condition(
finished_processing, timeout=5 * 60
), f"could not start domain: {domain_name}"
return _wait_for_cluster
@pytest.fixture
def opensearch_create_domain(opensearch_wait_for_cluster, aws_client):
domains = []
def factory(**kwargs) -> str:
if "DomainName" not in kwargs:
kwargs["DomainName"] = f"test-domain-{short_uid()}"
aws_client.opensearch.create_domain(**kwargs)
opensearch_wait_for_cluster(domain_name=kwargs["DomainName"])
domains.append(kwargs["DomainName"])
return kwargs["DomainName"]
yield factory
# cleanup
for domain in domains:
try:
aws_client.opensearch.delete_domain(DomainName=domain)
except Exception as e:
LOG.debug("error cleaning up domain %s: %s", domain, e)
@pytest.fixture
def opensearch_domain(opensearch_create_domain) -> str:
return opensearch_create_domain()
@pytest.fixture
def opensearch_endpoint(opensearch_domain, aws_client) -> str:
status = aws_client.opensearch.describe_domain(DomainName=opensearch_domain)["DomainStatus"]
assert "Endpoint" in status
return f"https://{status['Endpoint']}"
@pytest.fixture
def opensearch_document_path(opensearch_endpoint, aws_client):
document = {
"first_name": "Boba",
"last_name": "Fett",
"age": 41,
"about": "I'm just a simple man, trying to make my way in the universe.",
"interests": ["mandalorian armor", "tusken culture"],
}
document_path = f"{opensearch_endpoint}/bountyhunters/_doc/1"
response = requests.put(
document_path,
data=json.dumps(document),
headers={"content-type": "application/json", "Accept-encoding": "identity"},
)
assert response.status_code == 201, f"could not create document at: {document_path}"
return document_path
# Cleanup fixtures
@pytest.fixture
def cleanup_stacks(aws_client):
def _cleanup_stacks(stacks: List[str]) -> None:
stacks = ensure_list(stacks)
for stack in stacks:
try:
aws_client.cloudformation.delete_stack(StackName=stack)
aws_client.cloudformation.get_waiter("stack_delete_complete").wait(StackName=stack)
except Exception:
LOG.debug(f"Failed to cleanup stack '{stack}'")
return _cleanup_stacks
@pytest.fixture
def cleanup_changesets(aws_client):
def _cleanup_changesets(changesets: List[str]) -> None:
changesets = ensure_list(changesets)
for cs in changesets:
try:
aws_client.cloudformation.delete_change_set(ChangeSetName=cs)
except Exception:
LOG.debug(f"Failed to cleanup changeset '{cs}'")
return _cleanup_changesets
# Helpers for Cfn
# TODO: exports(!)
@dataclasses.dataclass(frozen=True)
class DeployResult:
change_set_id: str
stack_id: str
stack_name: str
change_set_name: str
outputs: Dict[str, str]
destroy: Callable[[], None]
class StackDeployError(Exception):
def __init__(self, describe_res: dict, events: list[dict]):
self.describe_result = describe_res
self.events = events
encoded_describe_output = json.dumps(self.describe_result, cls=CustomEncoder)
if config.CFN_VERBOSE_ERRORS:
msg = f"Describe output:\n{encoded_describe_output}\nEvents:\n{self.format_events(events)}"
else:
msg = f"Describe output:\n{encoded_describe_output}\nFailing resources:\n{self.format_events(events)}"
super().__init__(msg)
def format_events(self, events: list[dict]) -> str:
formatted_events = []
chronological_events = sorted(events, key=lambda event: event["Timestamp"])
for event in chronological_events:
if event["ResourceStatus"].endswith("FAILED") or config.CFN_VERBOSE_ERRORS:
formatted_events.append(self.format_event(event))
return "\n".join(formatted_events)
@staticmethod
def format_event(event: dict) -> str:
if reason := event.get("ResourceStatusReason"):
reason = reason.replace("\n", "; ")
return f"- {event['LogicalResourceId']} ({event['ResourceType']}) -> {event['ResourceStatus']} ({reason})"
else:
return f"- {event['LogicalResourceId']} ({event['ResourceType']}) -> {event['ResourceStatus']}"
@pytest.fixture
def deploy_cfn_template(
cleanup_stacks,
cleanup_changesets,
is_change_set_created_and_available,
is_change_set_finished,
aws_client,
):
state = []
def _deploy(
*,
is_update: Optional[bool] = False,
stack_name: Optional[str] = None,
change_set_name: Optional[str] = None,
template: Optional[str] = None,
template_path: Optional[str | os.PathLike] = None,
template_mapping: Optional[Dict[str, any]] = None,
parameters: Optional[Dict[str, str]] = None,
role_arn: Optional[str] = None,
max_wait: Optional[int] = None,
delay_between_polls: Optional[int] = 2,
) -> DeployResult:
if is_update:
assert stack_name
stack_name = stack_name or f"stack-{short_uid()}"
change_set_name = change_set_name or f"change-set-{short_uid()}"
if max_wait is None:
max_wait = 1800 if is_aws_cloud() else 180
if template_path is not None:
template = load_template_file(template_path)
template_rendered = render_template(template, **(template_mapping or {}))
kwargs = dict(
StackName=stack_name,
ChangeSetName=change_set_name,
TemplateBody=template_rendered,
Capabilities=["CAPABILITY_AUTO_EXPAND", "CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
ChangeSetType=("UPDATE" if is_update else "CREATE"),
Parameters=[
{
"ParameterKey": k,
"ParameterValue": v,