forked from getmoto/moto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_sqs.py
3112 lines (2527 loc) · 103 KB
/
test_sqs.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 json
import time
import uuid
import hashlib
import boto3
import botocore.exceptions
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from freezegun import freeze_time
from moto import mock_sqs, settings
from unittest import SkipTest, mock
import pytest
from moto.core import ACCOUNT_ID
from moto.sqs.models import (
Queue,
MAXIMUM_MESSAGE_SIZE_ATTR_LOWER_BOUND,
MAXIMUM_MESSAGE_SIZE_ATTR_UPPER_BOUND,
MAXIMUM_MESSAGE_LENGTH,
)
from uuid import uuid4
TEST_POLICY = """
{
"Version":"2012-10-17",
"Statement":[
{
"Effect": "Allow",
"Principal": { "AWS": "*" },
"Action": "sqs:SendMessage",
"Resource": "'$sqs_queue_arn'",
"Condition":{
"ArnEquals":{
"aws:SourceArn":"'$sns_topic_arn'"
}
}
}
]
}
"""
MOCK_DEDUPLICATION_TIME_IN_SECONDS = 5
@mock_sqs
def test_create_fifo_queue_fail():
sqs = boto3.client("sqs", region_name="us-east-1")
try:
sqs.create_queue(QueueName=str(uuid4())[0:6], Attributes={"FifoQueue": "true"})
except botocore.exceptions.ClientError as err:
err.response["Error"]["Code"].should.equal("InvalidParameterValue")
else:
raise RuntimeError("Should of raised InvalidParameterValue Exception")
@mock_sqs
def test_create_queue_with_same_attributes():
sqs = boto3.client("sqs", region_name="us-east-1")
dlq_url = sqs.create_queue(QueueName=str(uuid4()))["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(QueueUrl=dlq_url, AttributeNames=["All"])[
"Attributes"
]["QueueArn"]
attributes = {
"DelaySeconds": "900",
"MaximumMessageSize": "262144",
"MessageRetentionPeriod": "1209600",
"ReceiveMessageWaitTimeSeconds": "20",
"RedrivePolicy": '{"deadLetterTargetArn": "%s", "maxReceiveCount": 100}'
% (dlq_arn),
"VisibilityTimeout": "43200",
}
q_name = str(uuid4())[0:6]
sqs.create_queue(QueueName=q_name, Attributes=attributes)
sqs.create_queue(QueueName=q_name, Attributes=attributes)
@mock_sqs
def test_create_queue_with_different_attributes_fail():
sqs = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
sqs.create_queue(QueueName=q_name, Attributes={"VisibilityTimeout": "10"})
try:
sqs.create_queue(QueueName=q_name, Attributes={"VisibilityTimeout": "60"})
except botocore.exceptions.ClientError as err:
err.response["Error"]["Code"].should.equal("QueueAlreadyExists")
else:
raise RuntimeError("Should of raised QueueAlreadyExists Exception")
q_name2 = str(uuid4())[0:6]
response = sqs.create_queue(QueueName=q_name2, Attributes={"FifoQueue": "tru"})
attributes = {"VisibilityTimeout": "60"}
sqs.set_queue_attributes(QueueUrl=response.get("QueueUrl"), Attributes=attributes)
new_response = sqs.create_queue(QueueName=q_name2, Attributes={"FifoQueue": "tru"})
new_response["QueueUrl"].should.equal(response.get("QueueUrl"))
@mock_sqs
def test_create_fifo_queue():
# given
region_name = "us-east-1"
sqs = boto3.client("sqs", region_name=region_name)
queue_name = f"{str(uuid4())[0:6]}.fifo"
# when
queue_url = sqs.create_queue(
QueueName=queue_name, Attributes={"FifoQueue": "true"}
)["QueueUrl"]
# then
queue_url.should.contain(queue_name)
attributes = sqs.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"])[
"Attributes"
]
attributes["ApproximateNumberOfMessages"].should.equal("0")
attributes["ApproximateNumberOfMessagesNotVisible"].should.equal("0")
attributes["ApproximateNumberOfMessagesDelayed"].should.equal("0")
attributes["CreatedTimestamp"].should.be.a(str)
attributes["ContentBasedDeduplication"].should.equal("false")
attributes["DeduplicationScope"].should.equal("queue")
attributes["DelaySeconds"].should.equal("0")
attributes["LastModifiedTimestamp"].should.be.a(str)
attributes["FifoQueue"].should.equal("true")
attributes["FifoThroughputLimit"].should.equal("perQueue")
attributes["MaximumMessageSize"].should.equal("262144")
attributes["MessageRetentionPeriod"].should.equal("345600")
attributes["QueueArn"].should.equal(
f"arn:aws:sqs:{region_name}:{ACCOUNT_ID}:{queue_name}"
)
attributes["ReceiveMessageWaitTimeSeconds"].should.equal("0")
attributes["VisibilityTimeout"].should.equal("30")
@mock_sqs
def test_create_fifo_queue_with_high_throughput():
# given
sqs = boto3.client("sqs", region_name="us-east-1")
queue_name = f"{str(uuid4())[0:6]}.fifo"
# when
queue_url = sqs.create_queue(
QueueName=queue_name,
Attributes={
"FifoQueue": "true",
"DeduplicationScope": "messageGroup",
"FifoThroughputLimit": "perMessageGroupId",
},
)["QueueUrl"]
# then
queue_url.should.contain(queue_name)
attributes = sqs.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"])[
"Attributes"
]
attributes["DeduplicationScope"].should.equal("messageGroup")
attributes["FifoQueue"].should.equal("true")
attributes["FifoThroughputLimit"].should.equal("perMessageGroupId")
@mock_sqs
def test_create_queue():
sqs = boto3.resource("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
new_queue = sqs.create_queue(QueueName=q_name)
new_queue.should.have.property("url").should.contain(q_name)
queue = sqs.get_queue_by_name(QueueName=q_name)
queue.attributes.get("QueueArn").split(":")[-1].should.equal(q_name)
queue.attributes.get("QueueArn").split(":")[3].should.equal("us-east-1")
queue.attributes.get("VisibilityTimeout").should.equal("30")
@mock_sqs
def test_create_queue_kms():
sqs = boto3.resource("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
sqs.create_queue(
QueueName=q_name,
Attributes={
"KmsMasterKeyId": "master-key-id",
"KmsDataKeyReusePeriodSeconds": "600",
},
)
queue = sqs.get_queue_by_name(QueueName=q_name)
queue.attributes.get("KmsMasterKeyId").should.equal("master-key-id")
queue.attributes.get("KmsDataKeyReusePeriodSeconds").should.equal("600")
@mock_sqs
def test_create_queue_with_tags():
client = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
response = client.create_queue(
QueueName=q_name, tags={"tag_key_1": "tag_value_1", "tag_key_2": ""}
)
queue_url = response["QueueUrl"]
client.list_queue_tags(QueueUrl=queue_url)["Tags"].should.equal(
{"tag_key_1": "tag_value_1", "tag_key_2": ""}
)
@mock_sqs
def test_create_queue_with_policy():
client = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
response = client.create_queue(
QueueName=q_name,
Attributes={
"Policy": json.dumps(
{
"Version": "2012-10-17",
"Id": "test",
"Statement": [{"Effect": "Allow", "Principal": "*", "Action": "*"}],
}
)
},
)
queue_url = response["QueueUrl"]
response = client.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["Policy"]
)
json.loads(response["Attributes"]["Policy"]).should.equal(
{
"Version": "2012-10-17",
"Id": "test",
"Statement": [{"Effect": "Allow", "Principal": "*", "Action": "*"}],
}
)
@mock_sqs
def test_set_queue_attribute_empty_policy_removes_attr():
client = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
response = client.create_queue(
QueueName=q_name,
Attributes={
"Policy": json.dumps(
{
"Version": "2012-10-17",
"Id": "test",
"Statement": [{"Effect": "Allow", "Principal": "*", "Action": "*"}],
}
)
},
)
queue_url = response["QueueUrl"]
empty_policy = {"Policy": ""}
client.set_queue_attributes(QueueUrl=queue_url, Attributes=empty_policy)
response = client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"])[
"Attributes"
]
response.shouldnt.have.key("Policy")
def test_is_empty_redrive_policy_returns_true_for_empty_and_falsy_values():
assert Queue._is_empty_redrive_policy("")
assert Queue._is_empty_redrive_policy("{}")
def test_is_empty_redrive_policy_returns_false_for_valid_policy_format():
test_dlq_arn = "arn:aws:sqs:us-east-1:123456789012:test-dlr-queue"
assert not Queue._is_empty_redrive_policy(
json.dumps({"deadLetterTargetArn": test_dlq_arn, "maxReceiveCount": 5})
)
assert not Queue._is_empty_redrive_policy(json.dumps({"maxReceiveCount": 5}))
@mock_sqs
def test_set_queue_attribute_empty_redrive_removes_attr():
client = boto3.client("sqs", region_name="us-east-1")
dlq_resp = client.create_queue(QueueName="test-dlr-queue")
dlq_arn1 = client.get_queue_attributes(
QueueUrl=dlq_resp["QueueUrl"], AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
q_name = str(uuid4())[0:6]
response = client.create_queue(
QueueName=q_name,
Attributes={
"RedrivePolicy": json.dumps(
{"deadLetterTargetArn": dlq_arn1, "maxReceiveCount": 5}
),
},
)
queue_url = response["QueueUrl"]
no_redrive = {"RedrivePolicy": ""}
client.set_queue_attributes(QueueUrl=queue_url, Attributes=no_redrive)
response = client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"])[
"Attributes"
]
response.shouldnt.have.key("RedrivePolicy")
@mock_sqs
def test_get_queue_url():
client = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
client.create_queue(QueueName=q_name)
response = client.get_queue_url(QueueName=q_name)
response.should.have.key("QueueUrl").which.should.contain(q_name)
@mock_sqs
def test_get_queue_url_error_not_exists():
# given
client = boto3.client("sqs", region_name="us-east-1")
# when
with pytest.raises(ClientError) as e:
client.get_queue_url(QueueName="not-exists")
# then
ex = e.value
ex.operation_name.should.equal("GetQueueUrl")
ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.response["Error"]["Code"].should.contain(
"AWS.SimpleQueueService.NonExistentQueue"
)
ex.response["Error"]["Message"].should.equal(
"The specified queue does not exist for this wsdl version."
)
@mock_sqs
def test_get_nonexistent_queue():
sqs = boto3.resource("sqs", region_name="us-east-1")
with pytest.raises(ClientError) as err:
sqs.Queue("http://whatever-incorrect-queue-address").load()
ex = err.value
ex.operation_name.should.equal("GetQueueAttributes")
ex.response["Error"]["Code"].should.equal("AWS.SimpleQueueService.NonExistentQueue")
ex.response["Error"]["Message"].should.equal(
"The specified queue does not exist for this wsdl version."
)
@mock_sqs
def test_message_send_without_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
msg = queue.send_message(MessageBody="derp")
msg.get("MD5OfMessageBody").should.equal("58fd9edd83341c29f1aebba81c31e257")
msg.shouldnt.have.key("MD5OfMessageAttributes")
msg.get("MessageId").should_not.contain(" \n")
messages = queue.receive_messages()
messages.should.have.length_of(1)
@mock_sqs
def test_message_send_with_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
msg = queue.send_message(
MessageBody="derp",
MessageAttributes={
"SOME_Valid.attribute-Name": {
"StringValue": "1493147359900",
"DataType": "Number",
}
},
)
msg.get("MD5OfMessageBody").should.equal("58fd9edd83341c29f1aebba81c31e257")
msg.get("MD5OfMessageAttributes").should.equal("36655e7e9d7c0e8479fa3f3f42247ae7")
msg.get("MessageId").should_not.contain(" \n")
messages = queue.receive_messages()
messages.should.have.length_of(1)
@mock_sqs
def test_message_retention_period():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(
QueueName=str(uuid4())[0:6], Attributes={"MessageRetentionPeriod": "3"}
)
queue.send_message(
MessageBody="derp",
MessageAttributes={
"SOME_Valid.attribute-Name": {
"StringValue": "1493147359900",
"DataType": "Number",
}
},
)
messages = queue.receive_messages()
assert len(messages) == 1
queue.send_message(
MessageBody="derp",
MessageAttributes={
"SOME_Valid.attribute-Name": {
"StringValue": "1493147359900",
"DataType": "Number",
}
},
)
time.sleep(5)
messages = queue.receive_messages()
assert len(messages) == 0
@mock_sqs
def test_queue_retention_period():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(
QueueName=str(uuid4())[0:6], Attributes={"MessageRetentionPeriod": "3"}
)
time.sleep(5)
queue.send_message(
MessageBody="derp",
MessageAttributes={
"SOME_Valid.attribute-Name": {
"StringValue": "1493147359900",
"DataType": "Number",
}
},
)
messages = queue.receive_messages()
assert len(messages) == 1
@mock_sqs
def test_message_with_invalid_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
with pytest.raises(ClientError) as e:
queue.send_message(
MessageBody="derp",
MessageAttributes={
"öther_encodings": {"DataType": "String", "StringValue": "str"},
},
)
ex = e.value
ex.response["Error"]["Code"].should.equal("MessageAttributesInvalid")
ex.response["Error"]["Message"].should.equal(
"The message attribute name 'öther_encodings' is invalid. "
"Attribute name can contain A-Z, a-z, 0-9, underscore (_), hyphen (-), and period (.) characters."
)
@mock_sqs
def test_message_with_string_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
msg = queue.send_message(
MessageBody="derp",
MessageAttributes={
"id": {
"StringValue": "2018fc74-4f77-1a5a-1be0-c2d037d5052b",
"DataType": "String",
},
"contentType": {"StringValue": "application/json", "DataType": "String"},
"timestamp": {
"StringValue": "1602845432024",
"DataType": "Number.java.lang.Long",
},
},
)
msg.get("MD5OfMessageBody").should.equal("58fd9edd83341c29f1aebba81c31e257")
msg.get("MD5OfMessageAttributes").should.equal("b12289320bb6e494b18b645ef562b4a9")
msg.get("MessageId").should_not.contain(" \n")
messages = queue.receive_messages()
messages.should.have.length_of(1)
@mock_sqs
def test_message_with_binary_attribute():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
msg = queue.send_message(
MessageBody="derp",
MessageAttributes={
"id": {
"StringValue": "453ae55e-f03b-21a6-a4b1-70c2e2e8fe71",
"DataType": "String",
},
"mybin": {"BinaryValue": "kekchebukek", "DataType": "Binary"},
"timestamp": {
"StringValue": "1603134247654",
"DataType": "Number.java.lang.Long",
},
"contentType": {"StringValue": "application/json", "DataType": "String"},
},
)
msg.get("MD5OfMessageBody").should.equal("58fd9edd83341c29f1aebba81c31e257")
msg.get("MD5OfMessageAttributes").should.equal("049075255ebc53fb95f7f9f3cedf3c50")
msg.get("MessageId").should_not.contain(" \n")
messages = queue.receive_messages()
messages.should.have.length_of(1)
@mock_sqs
def test_message_with_attributes_have_labels():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
msg = queue.send_message(
MessageBody="derp",
MessageAttributes={
"timestamp": {
"DataType": "Number.java.lang.Long",
"StringValue": "1493147359900",
}
},
)
msg.get("MD5OfMessageBody").should.equal("58fd9edd83341c29f1aebba81c31e257")
msg.get("MD5OfMessageAttributes").should.equal("2e2e4876d8e0bd6b8c2c8f556831c349")
msg.get("MessageId").should_not.contain(" \n")
messages = queue.receive_messages()
messages.should.have.length_of(1)
@mock_sqs
def test_message_with_attributes_invalid_datatype():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
with pytest.raises(ClientError) as e:
queue.send_message(
MessageBody="derp",
MessageAttributes={
"timestamp": {
"DataType": "InvalidNumber",
"StringValue": "149314735990a",
}
},
)
ex = e.value
ex.response["Error"]["Code"].should.equal("MessageAttributesInvalid")
ex.response["Error"]["Message"].should.equal(
"The message attribute 'timestamp' has an invalid message attribute type, the set of supported type "
"prefixes is Binary, Number, and String."
)
@mock_sqs
def test_send_message_with_message_group_id():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(
QueueName=f"{str(uuid4())[0:6]}.fifo", Attributes={"FifoQueue": "true"}
)
queue.send_message(
MessageBody="mydata",
MessageDeduplicationId="dedupe_id_1",
MessageGroupId="group_id_1",
)
messages = queue.receive_messages(
AttributeNames=["MessageDeduplicationId", "MessageGroupId"]
)
messages.should.have.length_of(1)
message_attributes = messages[0].attributes
message_attributes.should.contain("MessageGroupId")
message_attributes["MessageGroupId"].should.equal("group_id_1")
message_attributes.should.contain("MessageDeduplicationId")
message_attributes["MessageDeduplicationId"].should.equal("dedupe_id_1")
@mock_sqs
def test_send_message_with_message_group_id_standard_queue():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
with pytest.raises(ClientError) as ex:
queue.send_message(MessageBody="mydata", MessageGroupId="group_id_1")
err = ex.value.response["Error"]
err["Code"].should.equal("InvalidParameterValue")
err["Message"].should.equal(
"Value group_id_1 for parameter MessageGroupId is invalid. "
"Reason: The request include parameter that is not valid for this queue type."
)
@mock_sqs
def test_send_message_with_unicode_characters():
body_one = "Héllo!😀"
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
queue.send_message(MessageBody=body_one)
messages = queue.receive_messages()
message_body = messages[0].body
message_body.should.equal(body_one)
@mock_sqs
def test_set_queue_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
queue = sqs.create_queue(QueueName=str(uuid4())[0:6])
queue.attributes["VisibilityTimeout"].should.equal("30")
queue.set_attributes(Attributes={"VisibilityTimeout": "45"})
queue.attributes["VisibilityTimeout"].should.equal("45")
@mock_sqs
def test_create_queues_in_multiple_region():
w1 = boto3.client("sqs", region_name="us-west-1")
w1_name = str(uuid4())[0:6]
w1.create_queue(QueueName=w1_name)
w2 = boto3.client("sqs", region_name="us-west-2")
w2_name = str(uuid4())[0:6]
w2.create_queue(QueueName=w2_name)
base_url = (
"http://localhost:5000"
if settings.TEST_SERVER_MODE
else "https://us-west-1.queue.amazonaws.com"
)
w1.list_queues()["QueueUrls"].should.contain(f"{base_url}/{ACCOUNT_ID}/{w1_name}")
w1.list_queues()["QueueUrls"].shouldnt.contain(f"{base_url}/{ACCOUNT_ID}/{w2_name}")
base_url = (
"http://localhost:5000"
if settings.TEST_SERVER_MODE
else "https://us-west-2.queue.amazonaws.com"
)
w2.list_queues()["QueueUrls"].shouldnt.contain(f"{base_url}/{ACCOUNT_ID}/{w1_name}")
w2.list_queues()["QueueUrls"].should.contain(f"{base_url}/{ACCOUNT_ID}/{w2_name}")
@mock_sqs
def test_get_queue_with_prefix():
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName=str(uuid4())[0:6])
q_name1 = str(uuid4())[0:6]
conn.create_queue(QueueName=q_name1)
prefix = str(uuid4())[0:6]
q_name2 = f"{prefix}-test"
conn.create_queue(QueueName=q_name2)
base_url = (
"http://localhost:5000"
if settings.TEST_SERVER_MODE
else "https://us-west-1.queue.amazonaws.com"
)
expected_url1 = f"{base_url}/{ACCOUNT_ID}/{q_name1}"
expected_url2 = f"{base_url}/{ACCOUNT_ID}/{q_name2}"
all_urls = conn.list_queues()["QueueUrls"]
all_urls.should.contain(expected_url1)
all_urls.should.contain(expected_url2)
queue = conn.list_queues(QueueNamePrefix=prefix)["QueueUrls"]
queue.should.have.length_of(1)
queue[0].should.equal(expected_url2)
@mock_sqs
def test_delete_queue():
sqs = boto3.resource("sqs", region_name="us-east-1")
conn = boto3.client("sqs", region_name="us-east-1")
q_name = str(uuid4())[0:6]
q_resp = conn.create_queue(QueueName=q_name, Attributes={"VisibilityTimeout": "3"})
queue = sqs.Queue(q_resp["QueueUrl"])
all_urls = conn.list_queues()["QueueUrls"]
[u[u.rfind("/") + 1 :] for u in all_urls].should.contain(q_name)
queue.delete()
all_urls = conn.list_queues().get("QueueUrls", [])
[u[u.rfind("/") + 1 :] for u in all_urls].shouldnt.contain(q_name)
@mock_sqs
def test_delete_queue_error_not_exists():
client = boto3.client("sqs", region_name="us-east-1")
with pytest.raises(ClientError) as e:
client.delete_queue(
QueueUrl=f"https://queue.amazonaws.com/{ACCOUNT_ID}/not-exists"
)
ex = e.value
ex.operation_name.should.equal("DeleteQueue")
ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.response["Error"]["Code"].should.contain(
"AWS.SimpleQueueService.NonExistentQueue"
)
ex.response["Error"]["Message"].should.equal(
"The specified queue does not exist for this wsdl version."
)
@mock_sqs
def test_get_queue_attributes():
client = boto3.client("sqs", region_name="us-east-1")
dlq_resp = client.create_queue(QueueName="test-dlr-queue")
dlq_arn1 = client.get_queue_attributes(
QueueUrl=dlq_resp["QueueUrl"], AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
q_name = str(uuid4())[0:6]
response = client.create_queue(
QueueName=q_name,
Attributes={
"RedrivePolicy": json.dumps(
{"deadLetterTargetArn": dlq_arn1, "maxReceiveCount": 2}
),
},
)
queue_url = response["QueueUrl"]
response = client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"])
response["Attributes"]["ApproximateNumberOfMessages"].should.equal("0")
response["Attributes"]["ApproximateNumberOfMessagesDelayed"].should.equal("0")
response["Attributes"]["ApproximateNumberOfMessagesNotVisible"].should.equal("0")
response["Attributes"]["CreatedTimestamp"].should.be.a(str)
response["Attributes"]["DelaySeconds"].should.equal("0")
response["Attributes"]["LastModifiedTimestamp"].should.be.a(str)
response["Attributes"]["MaximumMessageSize"].should.equal("262144")
response["Attributes"]["MessageRetentionPeriod"].should.equal("345600")
response["Attributes"]["QueueArn"].should.equal(
"arn:aws:sqs:us-east-1:{}:{}".format(ACCOUNT_ID, q_name)
)
response["Attributes"]["ReceiveMessageWaitTimeSeconds"].should.equal("0")
response["Attributes"]["VisibilityTimeout"].should.equal("30")
response = client.get_queue_attributes(
QueueUrl=queue_url,
AttributeNames=[
"ApproximateNumberOfMessages",
"MaximumMessageSize",
"QueueArn",
"RedrivePolicy",
"VisibilityTimeout",
],
)
response["Attributes"].should.equal(
{
"ApproximateNumberOfMessages": "0",
"MaximumMessageSize": "262144",
"QueueArn": "arn:aws:sqs:us-east-1:{}:{}".format(ACCOUNT_ID, q_name),
"VisibilityTimeout": "30",
"RedrivePolicy": json.dumps(
{"deadLetterTargetArn": dlq_arn1, "maxReceiveCount": 2}
),
}
)
# should not return any attributes, if it was not set before
response = client.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["KmsMasterKeyId"]
)
response.should_not.have.key("Attributes")
@mock_sqs
def test_get_queue_attributes_errors():
client = boto3.client("sqs", region_name="us-east-1")
response = client.create_queue(QueueName=str(uuid4())[0:6])
queue_url = response["QueueUrl"]
client.get_queue_attributes.when.called_with(
QueueUrl=queue_url,
AttributeNames=["QueueArn", "not-existing", "VisibilityTimeout"],
).should.throw(ClientError, "Unknown Attribute not-existing.")
client.get_queue_attributes.when.called_with(
QueueUrl=queue_url, AttributeNames=[""]
).should.throw(ClientError, "Unknown Attribute .")
client.get_queue_attributes.when.called_with(
QueueUrl=queue_url, AttributeNames=[]
).should.throw(ClientError, "Unknown Attribute .")
@mock_sqs
def test_get_queue_attributes_error_not_exists():
# given
client = boto3.client("sqs", region_name="us-east-1")
# when
with pytest.raises(ClientError) as e:
client.get_queue_attributes(
QueueUrl=f"https://queue.amazonaws.com/{ACCOUNT_ID}/not-exists"
)
# then
ex = e.value
ex.operation_name.should.equal("GetQueueAttributes")
ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
ex.response["Error"]["Code"].should.contain(
"AWS.SimpleQueueService.NonExistentQueue"
)
ex.response["Error"]["Message"].should.equal(
"The specified queue does not exist for this wsdl version."
)
@mock_sqs
def test_set_queue_attribute():
sqs = boto3.resource("sqs", region_name="us-east-1")
conn = boto3.client("sqs", region_name="us-east-1")
q_resp = conn.create_queue(
QueueName=str(uuid4())[0:6], Attributes={"VisibilityTimeout": "3"}
)
queue = sqs.Queue(q_resp["QueueUrl"])
queue.attributes["VisibilityTimeout"].should.equal("3")
queue.set_attributes(Attributes={"VisibilityTimeout": "45"})
queue = sqs.Queue(q_resp["QueueUrl"])
queue.attributes["VisibilityTimeout"].should.equal("45")
@mock_sqs
def test_send_receive_message_without_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
conn = boto3.client("sqs", region_name="us-east-1")
q_resp = conn.create_queue(QueueName=str(uuid4())[0:6])
queue = sqs.Queue(q_resp["QueueUrl"])
body_one = "this is a test message"
body_two = "this is another test message"
queue.send_message(MessageBody=body_one)
queue.send_message(MessageBody=body_two)
messages = conn.receive_message(QueueUrl=queue.url, MaxNumberOfMessages=2)[
"Messages"
]
message1 = messages[0]
message2 = messages[1]
message1["Body"].should.equal(body_one)
message2["Body"].should.equal(body_two)
message1.shouldnt.have.key("MD5OfMessageAttributes")
message2.shouldnt.have.key("MD5OfMessageAttributes")
message1.should_not.have.key("Attributes")
message2.should_not.have.key("Attributes")
@mock_sqs
def test_send_receive_message_with_attributes():
sqs = boto3.resource("sqs", region_name="us-east-1")
conn = boto3.client("sqs", region_name="us-east-1")
q_resp = conn.create_queue(QueueName=str(uuid4())[0:6])
queue = sqs.Queue(q_resp["QueueUrl"])
body_one = "this is a test message"
body_two = "this is another test message"
queue.send_message(
MessageBody=body_one,
MessageAttributes={
"timestamp": {"StringValue": "1493147359900", "DataType": "Number"}
},
)
queue.send_message(
MessageBody=body_two,
MessageAttributes={
"timestamp": {"StringValue": "1493147359901", "DataType": "Number"}
},
)
messages = conn.receive_message(
QueueUrl=queue.url, MaxNumberOfMessages=2, MessageAttributeNames=["timestamp"]
)["Messages"]
message1 = messages[0]
message2 = messages[1]
message1.get("Body").should.equal(body_one)
message2.get("Body").should.equal(body_two)
message1.get("MD5OfMessageAttributes").should.equal(
"235c5c510d26fb653d073faed50ae77c"
)
message2.get("MD5OfMessageAttributes").should.equal(
"994258b45346a2cc3f9cbb611aa7af30"
)
@mock_sqs
def test_send_receive_message_with_attributes_with_labels():
sqs = boto3.resource("sqs", region_name="us-east-1")
conn = boto3.client("sqs", region_name="us-east-1")
q_resp = conn.create_queue(QueueName=str(uuid4())[0:6])
queue = sqs.Queue(q_resp["QueueUrl"])
body_one = "this is a test message"
body_two = "this is another test message"
queue.send_message(
MessageBody=body_one,
MessageAttributes={
"timestamp": {
"StringValue": "1493147359900",
"DataType": "Number.java.lang.Long",
}
},
)
queue.send_message(
MessageBody=body_two,
MessageAttributes={
"timestamp": {
"StringValue": "1493147359901",
"DataType": "Number.java.lang.Long",
}
},
)
messages = conn.receive_message(
QueueUrl=queue.url, MaxNumberOfMessages=2, MessageAttributeNames=["timestamp"]
)["Messages"]
message1 = messages[0]
message2 = messages[1]
message1.get("Body").should.equal(body_one)
message2.get("Body").should.equal(body_two)
message1.get("MD5OfMessageAttributes").should.equal(
"2e2e4876d8e0bd6b8c2c8f556831c349"
)
message2.get("MD5OfMessageAttributes").should.equal(
"cfa7c73063c6e2dbf9be34232a1978cf"
)
response = queue.send_message(
MessageBody="test message",
MessageAttributes={
"somevalue": {"StringValue": "somevalue", "DataType": "String.custom"}
},
)
response.get("MD5OfMessageAttributes").should.equal(
"9e05cca738e70ff6c6041e82d5e77ef1"
)
@mock_sqs
def test_receive_message_with_xml_content():
sqs = boto3.client("sqs", region_name="eu-west-2")
queue_url = sqs.create_queue(QueueName=str(uuid4())[0:6])["QueueUrl"]
original_payload = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom"/>'
data = {"Payload": {"DataType": "String", "StringValue": original_payload}}
sqs.send_message(
QueueUrl=queue_url, MessageBody="NSWSS Atom Feed", MessageAttributes=data
)
messages = sqs.receive_message(
QueueUrl=queue_url,
MessageAttributeNames=("Payload",),
MaxNumberOfMessages=1,
VisibilityTimeout=0,
)["Messages"]
attr = messages[0]["MessageAttributes"]["Payload"]["StringValue"]