-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
test_s3.py
3548 lines (2868 loc) · 123 KB
/
test_s3.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 datetime
import json
import os
import pickle
import uuid
import zlib
from gzip import GzipFile
from io import BytesIO
from time import sleep
from unittest import SkipTest
from urllib.parse import parse_qs, urlparse
import boto3
import botocore.exceptions
import pytest
import requests
from botocore.client import ClientError
from botocore.handlers import disable_signing
from freezegun import freeze_time
import moto.s3.models as s3model
from moto import mock_aws, moto_proxy, settings
from moto.core.utils import utcnow
from moto.moto_api import state_manager
from moto.s3.models import s3_backends
from moto.s3.responses import DEFAULT_REGION_NAME
from tests import DEFAULT_ACCOUNT_ID, aws_verified
from . import s3_aws_verified
class MyModel:
def __init__(self, name, value, metadata=None):
self.name = name
self.value = value
self.metadata = metadata or {}
def save(self, region=None):
s3_client = boto3.client("s3", region_name=region or DEFAULT_REGION_NAME)
s3_client.put_object(
Bucket="mybucket", Key=self.name, Body=self.value, Metadata=self.metadata
)
@mock_aws
def test_keys_are_pickleable():
"""Keys must be pickleable due to boto3 implementation details."""
key = s3model.FakeKey(
"name", b"data!", account_id=DEFAULT_ACCOUNT_ID, region_name="us-east-1"
)
assert key.value == b"data!"
pickled = pickle.dumps(key)
loaded = pickle.loads(pickled)
assert loaded.value == key.value
assert loaded.account_id == key.account_id
@mock_aws
@pytest.mark.parametrize(
"region,partition",
[("us-west-2", "aws"), ("cn-north-1", "aws-cn"), ("us-isob-east-1", "aws-iso-b")],
)
def test_my_model_save(region, partition):
# Create Bucket so that test can run
conn = boto3.resource("s3", region_name=region)
conn.create_bucket(
Bucket="mybucket", CreateBucketConfiguration={"LocationConstraint": region}
)
####################################
model_instance = MyModel("steve", "is awesome")
model_instance.save(region)
body = conn.Object("mybucket", "steve").get()["Body"].read().decode()
assert body == "is awesome"
@mock_aws
def test_object_metadata():
"""Metadata keys can contain certain special characters like dash and dot"""
# Create Bucket so that test can run
conn = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
conn.create_bucket(Bucket="mybucket")
####################################
metadata = {"meta": "simple", "my-meta": "dash", "meta.data": "namespaced"}
model_instance = MyModel("steve", "is awesome", metadata=metadata)
model_instance.save()
meta = conn.Object("mybucket", "steve").get()["Metadata"]
assert meta == metadata
@mock_aws
def test_resource_get_object_returns_etag():
conn = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
conn.create_bucket(Bucket="mybucket")
model_instance = MyModel("steve", "is awesome")
model_instance.save()
assert conn.Bucket("mybucket").Object("steve").e_tag == (
'"d32bda93738f7e03adb22e66c90fbc04"'
)
@mock_aws
def test_key_save_to_missing_bucket():
s3_resource = boto3.resource("s3")
key = s3_resource.Object("mybucket", "the-key")
with pytest.raises(ClientError) as ex:
key.put(Body=b"foobar")
assert ex.value.response["Error"]["Code"] == "NoSuchBucket"
assert ex.value.response["Error"]["Message"] == (
"The specified bucket does not exist"
)
@mock_aws
def test_missing_key_request():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Only test status code in DecoratorMode")
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_client.create_bucket(Bucket="foobar")
response = requests.get("http://foobar.s3.amazonaws.com/the-key")
assert response.status_code == 404
@mock_aws
def test_empty_key():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"")
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["ContentLength"] == 0
assert resp["Body"].read() == b""
@mock_aws
def test_key_name_encoding_in_listing():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
name = "6T7\x159\x12\r\x08.txt"
key = s3_resource.Object("foobar", name)
key.put(Body=b"")
key_received = client.list_objects(Bucket="foobar")["Contents"][0]["Key"]
assert key_received == name
key_received = client.list_objects_v2(Bucket="foobar")["Contents"][0]["Key"]
assert key_received == name
name = "example/file.text"
client.put_object(Bucket="foobar", Key=name, Body=b"")
key_received = client.list_objects(
Bucket="foobar", Prefix="example/", Delimiter="/", MaxKeys=1, EncodingType="url"
)["Contents"][0]["Key"]
assert key_received == name
@mock_aws
def test_empty_key_set_on_existing_key():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"some content")
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["ContentLength"] == 12
assert resp["Body"].read() == b"some content"
key.put(Body=b"")
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["ContentLength"] == 0
assert resp["Body"].read() == b""
@mock_aws
def test_large_key_save():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"foobar" * 100000)
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["Body"].read() == b"foobar" * 100000
@mock_aws
def test_set_metadata():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"some value", Metadata={"md": "Metadatastring"})
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["Metadata"] == {"md": "Metadatastring"}
@freeze_time("2012-01-01 12:00:00")
@mock_aws
def test_last_modified():
# See https://github.com/boto/boto/issues/466
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_resource.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"some value", Metadata={"md": "Metadatastring"})
resp = client.list_objects_v2(Bucket="foobar")["Contents"]
assert isinstance(resp[0]["LastModified"], datetime.datetime)
resp = client.get_object(Bucket="foobar", Key="the-key")
assert isinstance(resp["LastModified"], datetime.datetime)
as_header = resp["ResponseMetadata"]["HTTPHeaders"]["last-modified"]
assert isinstance(as_header, str)
if settings.TEST_DECORATOR_MODE:
assert as_header == "Sun, 01 Jan 2012 12:00:00 GMT"
@mock_aws
def test_missing_bucket():
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
with pytest.raises(ClientError) as ex:
client.head_bucket(Bucket="mybucket")
assert ex.value.response["Error"]["Code"] == "404"
assert ex.value.response["Error"]["Message"] == "Not Found"
with pytest.raises(ClientError) as ex:
client.head_bucket(Bucket="dash-in-name")
assert ex.value.response["Error"]["Code"] == "404"
assert ex.value.response["Error"]["Message"] == "Not Found"
@mock_aws
def test_create_existing_bucket():
"""Creating a bucket that already exists should raise an Error."""
client = boto3.client("s3", region_name="us-west-2")
kwargs = {
"Bucket": "foobar",
"CreateBucketConfiguration": {"LocationConstraint": "us-west-2"},
}
client.create_bucket(**kwargs)
with pytest.raises(ClientError) as ex:
client.create_bucket(**kwargs)
assert ex.value.response["Error"]["Code"] == "BucketAlreadyOwnedByYou"
assert ex.value.response["Error"]["Message"] == (
"Your previous request to create the named bucket succeeded and you already own it."
)
@aws_verified
@pytest.mark.aws_verified
@pytest.mark.parametrize(
"constraint", ["us-east-1", "us-east-2", "eu-central-1", "us-gov-east-2"]
)
def test_create_bucket_with_wrong_location_constraint(constraint):
client = boto3.client("s3", region_name="us-west-2")
kwargs = {
"Bucket": str(uuid.uuid4()),
"CreateBucketConfiguration": {"LocationConstraint": constraint},
}
with pytest.raises(ClientError) as ex:
client.create_bucket(**kwargs)
err = ex.value.response["Error"]
assert err["Code"] == "IllegalLocationConstraintException"
assert (
err["Message"]
== f"The {constraint} location constraint is incompatible for the region specific endpoint this request was sent to."
)
@aws_verified
@pytest.mark.aws_verified
@pytest.mark.parametrize("constraint", ["us-east-2", "eu-central-1"])
def test_create_bucket_in_regions_from_us_east_1(constraint):
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket_name = str(uuid.uuid4())
client.create_bucket(
Bucket=bucket_name, CreateBucketConfiguration={"LocationConstraint": constraint}
)
assert (
client.get_bucket_location(Bucket=bucket_name)["LocationConstraint"]
== constraint
)
client.delete_bucket(Bucket=bucket_name)
@mock_aws
def test_create_existing_bucket_in_us_east_1():
"""Creating a bucket that already exists in us-east-1 returns the bucket.
http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
Your previous request to create the named bucket succeeded and you already
own it. You get this error in all AWS regions except US Standard,
us-east-1. In us-east-1 region, you will get 200 OK, but it is no-op (if
bucket exists it Amazon S3 will not do anything).
"""
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="foobar")
client.create_bucket(Bucket="foobar")
@mock_aws
def test_bucket_deletion():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="foobar")
key = s3_resource.Object("foobar", "the-key")
key.put(Body=b"some value")
# Try to delete a bucket that still has keys
with pytest.raises(ClientError) as ex:
client.delete_bucket(Bucket="foobar")
assert ex.value.response["Error"]["Code"] == "BucketNotEmpty"
assert ex.value.response["Error"]["Message"] == (
"The bucket you tried to delete is not empty"
)
client.delete_object(Bucket="foobar", Key="the-key")
client.delete_bucket(Bucket="foobar")
# Delete non-existent bucket
with pytest.raises(ClientError) as ex:
client.delete_bucket(Bucket="foobar")
assert ex.value.response["Error"]["Code"] == "NoSuchBucket"
assert ex.value.response["Error"]["Message"] == (
"The specified bucket does not exist"
)
@mock_aws
def test_get_all_buckets():
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="foobar")
client.create_bucket(Bucket="foobar2")
assert len(client.list_buckets()["Buckets"]) == 2
@mock_aws
def test_post_to_bucket():
if not settings.TEST_DECORATOR_MODE:
# ServerMode does not allow unauthorized requests
raise SkipTest()
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="foobar")
requests.post(
"https://foobar.s3.amazonaws.com/", {"key": "the-key", "file": "nothing"}
)
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["Body"].read() == b"nothing"
@mock_aws
def test_post_with_metadata_to_bucket():
if not settings.TEST_DECORATOR_MODE:
# ServerMode does not allow unauthorized requests
raise SkipTest()
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="foobar")
requests.post(
"https://foobar.s3.amazonaws.com/",
{"key": "the-key", "file": "nothing", "x-amz-meta-test": "metadata"},
)
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["Metadata"] == {"test": "metadata"}
@mock_aws
def test_delete_versioned_objects():
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = "test"
key = "test"
s3_client.create_bucket(Bucket=bucket)
s3_client.put_object(Bucket=bucket, Key=key, Body=b"")
s3_client.put_bucket_versioning(
Bucket=bucket, VersioningConfiguration={"Status": "Enabled"}
)
objects = s3_client.list_objects_v2(Bucket=bucket).get("Contents")
versions = s3_client.list_object_versions(Bucket=bucket).get("Versions")
delete_markers = s3_client.list_object_versions(Bucket=bucket).get("DeleteMarkers")
assert len(objects) == 1
assert len(versions) == 1
assert delete_markers is None
s3_client.delete_object(Bucket=bucket, Key=key)
objects = s3_client.list_objects_v2(Bucket=bucket).get("Contents")
versions = s3_client.list_object_versions(Bucket=bucket).get("Versions")
delete_markers = s3_client.list_object_versions(Bucket=bucket).get("DeleteMarkers")
assert objects is None
assert len(versions) == 1
assert len(delete_markers) == 1
s3_client.delete_object(
Bucket=bucket, Key=key, VersionId=versions[0].get("VersionId")
)
objects = s3_client.list_objects_v2(Bucket=bucket).get("Contents")
versions = s3_client.list_object_versions(Bucket=bucket).get("Versions")
delete_markers = s3_client.list_object_versions(Bucket=bucket).get("DeleteMarkers")
assert objects is None
assert versions is None
assert len(delete_markers) == 1
s3_client.delete_object(
Bucket=bucket, Key=key, VersionId=delete_markers[0].get("VersionId")
)
objects = s3_client.list_objects_v2(Bucket=bucket).get("Contents")
versions = s3_client.list_object_versions(Bucket=bucket).get("Versions")
delete_markers = s3_client.list_object_versions(Bucket=bucket).get("DeleteMarkers")
assert objects is None
assert versions is None
assert delete_markers is None
@s3_aws_verified
@pytest.mark.aws_verified
def test_delete_missing_key(bucket_name=None):
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket(bucket_name)
s3_resource.Object(bucket_name, "key1").put(Body=b"some value")
s3_resource.Object(bucket_name, "key2").put(Body=b"some value")
s3_resource.Object(bucket_name, "key3").put(Body=b"some value")
s3_resource.Object(bucket_name, "key4").put(Body=b"some value")
result = bucket.delete_objects(
Delete={
"Objects": [
{"Key": "unknown"},
{"Key": "key1"},
{"Key": "key3"},
{"Key": "typo"},
]
}
)
assert len(result["Deleted"]) == 4
assert {"Key": "unknown"} in result["Deleted"]
assert {"Key": "key1"} in result["Deleted"]
assert {"Key": "key3"} in result["Deleted"]
assert {"Key": "typo"} in result["Deleted"]
assert "Errors" not in result
objects = list(bucket.objects.all())
assert {o.key for o in objects} == set(["key2", "key4"])
@mock_aws
def test_delete_empty_keys_list():
with pytest.raises(ClientError) as err:
boto3.client("s3").delete_objects(Bucket="foobar", Delete={"Objects": []})
assert err.value.response["Error"]["Code"] == "MalformedXML"
@pytest.mark.parametrize("name", ["firstname.lastname", "with-dash"])
@mock_aws
def test_bucket_name_with_special_chars(name):
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket(name)
bucket.create()
s3_resource.Object(name, "the-key").put(Body=b"some value")
resp = client.get_object(Bucket=name, Key="the-key")
assert resp["Body"].read() == b"some value"
@pytest.mark.parametrize(
"key", ["normal", "test_list_keys_2/x?y", "/the-key-unîcode/test"]
)
@mock_aws
def test_key_with_special_characters(key):
if settings.is_test_proxy_mode():
raise SkipTest("Keys starting with a / don't work well in ProxyMode")
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("testname")
bucket.create()
s3_resource.Object("testname", key).put(Body=b"value")
objects = list(bucket.objects.all())
assert [o.key for o in objects] == [key]
resp = client.get_object(Bucket="testname", Key=key)
assert resp["Body"].read() == b"value"
@s3_aws_verified
@pytest.mark.aws_verified
@pytest.mark.parametrize("versioned", [True, False], ids=["versioned", "not versioned"])
def test_conditional_write(versioned, bucket_name=None):
s3 = boto3.client("s3", region_name="us-east-1")
if versioned:
enable_versioning(bucket_name, s3)
s3.put_object(
Key="test_object",
Body="test",
Bucket=bucket_name,
IfNoneMatch="*",
)
with pytest.raises(ClientError) as exc:
s3.put_object(
Key="test_object",
Body="another_test",
Bucket=bucket_name,
IfNoneMatch="*",
)
err = exc.value.response["Error"]
assert err["Code"] == "PreconditionFailed"
assert (
err["Message"]
== "At least one of the pre-conditions you specified did not hold"
)
assert err["Condition"] == "If-None-Match"
@mock_aws
def test_bucket_key_listing_order():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket_name = "test_bucket"
bucket = s3_resource.Bucket(bucket_name)
bucket.create()
prefix = "toplevel/"
names = ["x/key", "y.key1", "y.key2", "y.key3", "x/y/key", "x/y/z/key"]
for name in names:
s3_resource.Object(bucket_name, prefix + name).put(Body=b"somedata")
delimiter = ""
keys = [x.key for x in bucket.objects.filter(Prefix=prefix, Delimiter=delimiter)]
assert keys == [
"toplevel/x/key",
"toplevel/x/y/key",
"toplevel/x/y/z/key",
"toplevel/y.key1",
"toplevel/y.key2",
"toplevel/y.key3",
]
delimiter = "/"
keys = [x.key for x in bucket.objects.filter(Prefix=prefix, Delimiter=delimiter)]
assert keys == ["toplevel/y.key1", "toplevel/y.key2", "toplevel/y.key3"]
# Test delimiter with no prefix
keys = [x.key for x in bucket.objects.filter(Delimiter=delimiter)]
assert keys == []
prefix = "toplevel/x"
keys = [x.key for x in bucket.objects.filter(Prefix=prefix)]
assert keys == ["toplevel/x/key", "toplevel/x/y/key", "toplevel/x/y/z/key"]
keys = [x.key for x in bucket.objects.filter(Prefix=prefix, Delimiter=delimiter)]
assert keys == []
@mock_aws
@pytest.mark.parametrize(
"region,partition",
[("us-west-2", "aws"), ("cn-north-1", "aws-cn"), ("us-isob-east-1", "aws-iso-b")],
)
def test_key_with_reduced_redundancy(region, partition):
s3_resource = boto3.resource("s3", region_name=region)
bucket_name = "test_bucket"
s3_resource.create_bucket(
Bucket=bucket_name, CreateBucketConfiguration={"LocationConstraint": region}
)
bucket = s3_resource.Bucket(bucket_name)
bucket.put_object(
Key="test_rr_key", Body=b"somedata", StorageClass="REDUCED_REDUNDANCY"
)
# we use the bucket iterator because of:
# https:/github.com/boto/boto/issues/1173
assert [x.storage_class for x in bucket.objects.all()] == ["REDUCED_REDUNDANCY"]
@freeze_time("2012-01-01 12:00:00")
@mock_aws
def test_restore_key():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
key = bucket.put_object(Key="the-key", Body=b"somedata", StorageClass="GLACIER")
assert key.restore is None
resp = key.restore_object(RestoreRequest={"Days": 1})
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 202
if settings.TEST_SERVER_MODE:
assert 'ongoing-request="false"' in key.restore
elif settings.TEST_DECORATOR_MODE:
assert key.restore == (
'ongoing-request="false", expiry-date="Mon, 02 Jan 2012 12:00:00 GMT"'
)
resp = key.restore_object(RestoreRequest={"Days": 2})
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
if settings.TEST_SERVER_MODE:
assert 'ongoing-request="false"' in key.restore
elif settings.TEST_DECORATOR_MODE:
assert key.restore == (
'ongoing-request="false", expiry-date="Tue, 03 Jan 2012 12:00:00 GMT"'
)
@freeze_time("2012-01-01 12:00:00")
@mock_aws
def test_restore_key_transition():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Can't set transition directly in ServerMode")
state_manager.set_transition(
model_name="s3::keyrestore", transition={"progression": "manual", "times": 1}
)
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
key = bucket.put_object(Key="the-key", Body=b"somedata", StorageClass="GLACIER")
assert key.restore is None
key.restore_object(RestoreRequest={"Days": 1})
# first call: there should be an ongoing request
assert 'ongoing-request="true"' in key.restore
# second call: request should be done
key.load()
assert 'ongoing-request="false"' in key.restore
# third call: request should still be done
key.load()
assert 'ongoing-request="false"' in key.restore
state_manager.unset_transition(model_name="s3::keyrestore")
@mock_aws
def test_restore_unknown_key():
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
client.create_bucket(Bucket="mybucket")
with pytest.raises(ClientError) as exc:
client.restore_object(
Bucket="mybucket", Key="unknown", RestoreRequest={"Days": 1}
)
err = exc.value.response["Error"]
assert err["Code"] == "NoSuchKey"
@mock_aws
def test_cannot_restore_standard_class_object():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
key = bucket.put_object(Key="the-key", Body=b"somedata")
with pytest.raises(ClientError) as exc:
key.restore_object(RestoreRequest={"Days": 1})
err = exc.value.response["Error"]
assert err["Code"] == "InvalidObjectState"
assert err["StorageClass"] == "STANDARD"
assert err["Message"] == (
"The operation is not valid for the object's storage class"
)
@mock_aws
def test_restore_object_invalid_request_params():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Can't set transition directly in ServerMode")
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
key = bucket.put_object(Key="the-key", Body=b"somedata", StorageClass="GLACIER")
# `Days` must be provided except for select requests
with pytest.raises(ClientError) as exc:
key.restore_object(RestoreRequest={})
err = exc.value.response["Error"]
assert err["Code"] == "DaysMustProvidedExceptForSelectRequest"
assert err["Message"] == "`Days` must be provided except for select requests"
# `Days` must not be provided for select requests
with pytest.raises(ClientError) as exc:
key.restore_object(RestoreRequest={"Days": 1, "Type": "SELECT"})
err = exc.value.response["Error"]
assert err["Code"] == "DaysMustNotProvidedForSelectRequest"
assert err["Message"] == "`Days` must not be provided for select requests"
@mock_aws
def test_get_versioning_status():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
version_info = s3_resource.BucketVersioning("foobar")
assert version_info.status is None
version_info.enable()
assert version_info.status == "Enabled"
version_info.suspend()
assert version_info.status == "Suspended"
@mock_aws
def test_key_version():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
bucket.Versioning().enable()
versions = []
key = bucket.put_object(Key="the-key", Body=b"somedata")
versions.append(key.version_id)
key.put(Body=b"some string")
versions.append(key.version_id)
assert len(set(versions)) == 2
key = client.get_object(Bucket="foobar", Key="the-key")
assert key["VersionId"] == versions[-1]
@mock_aws
def test_list_versions():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
bucket.Versioning().enable()
key_versions = []
key = bucket.put_object(Key="the-key", Body=b"Version 1")
key_versions.append(key.version_id)
key = bucket.put_object(Key="the-key", Body=b"Version 2")
key_versions.append(key.version_id)
assert len(key_versions) == 2
versions = client.list_object_versions(Bucket="foobar")["Versions"]
assert len(versions) == 2
assert versions[0]["Key"] == "the-key"
assert versions[0]["VersionId"] == key_versions[1]
resp = client.get_object(Bucket="foobar", Key="the-key")
assert resp["Body"].read() == b"Version 2"
resp = client.get_object(
Bucket="foobar", Key="the-key", VersionId=versions[0]["VersionId"]
)
assert resp["Body"].read() == b"Version 2"
assert versions[1]["Key"] == "the-key"
assert versions[1]["VersionId"] == key_versions[0]
resp = client.get_object(
Bucket="foobar", Key="the-key", VersionId=versions[1]["VersionId"]
)
assert resp["Body"].read() == b"Version 1"
bucket.put_object(Key="the2-key", Body=b"Version 1")
assert len(list(bucket.objects.all())) == 2
versions = client.list_object_versions(Bucket="foobar", Prefix="the2")["Versions"]
assert len(versions) == 1
@mock_aws
def test_acl_setting():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
content = b"imafile"
keyname = "test.txt"
bucket.put_object(
Key=keyname, Body=content, ContentType="text/plain", ACL="public-read"
)
grants = client.get_object_acl(Bucket="foobar", Key=keyname)["Grants"]
assert {
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AllUsers",
},
"Permission": "READ",
} in grants
@mock_aws
def test_acl_setting_via_headers():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
keyname = "test.txt"
bucket.put_object(Key=keyname, Body=b"imafile")
client.put_object_acl(ACL="public-read", Bucket="foobar", Key=keyname)
grants = client.get_object_acl(Bucket="foobar", Key=keyname)["Grants"]
assert {
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AllUsers",
},
"Permission": "READ",
} in grants
@mock_aws
def test_acl_switching():
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = s3_resource.Bucket("foobar")
bucket.create()
keyname = "test.txt"
bucket.put_object(Key=keyname, Body=b"asdf", ACL="public-read")
client.put_object_acl(ACL="private", Bucket="foobar", Key=keyname)
grants = client.get_object_acl(Bucket="foobar", Key=keyname)["Grants"]
assert {
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AllUsers",
},
"Permission": "READ",
} not in grants
@mock_aws
def test_acl_switching_nonexistent_key():
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_client.create_bucket(Bucket="mybucket")
with pytest.raises(ClientError) as exc:
s3_client.put_object_acl(Bucket="mybucket", Key="nonexistent", ACL="private")
assert exc.value.response["Error"]["Code"] == "NoSuchKey"
@mock_aws
def test_streaming_upload_from_file_to_presigned_url():
s3_resource = boto3.resource("s3", region_name="us-east-1")
bucket = s3_resource.Bucket("test-bucket")
bucket.create()
bucket.put_object(Body=b"ABCD", Key="file.txt")
params = {"Bucket": "test-bucket", "Key": "file.txt"}
presigned_url = boto3.client("s3").generate_presigned_url(
"put_object", params, ExpiresIn=900
)
with open(__file__, "rb") as fhandle:
get_kwargs = {"data": fhandle}
if settings.is_test_proxy_mode():
add_proxy_details(get_kwargs)
response = requests.get(presigned_url, **get_kwargs)
assert response.status_code == 200
@mock_aws
def test_upload_from_file_to_presigned_url():
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_client.create_bucket(Bucket="mybucket")
params = {"Bucket": "mybucket", "Key": "file_upload"}
presigned_url = boto3.client("s3").generate_presigned_url(
"put_object", params, ExpiresIn=900
)
file = open("text.txt", "w", encoding="utf-8")
file.write("test")
file.close()
files = {"upload_file": open("text.txt", "rb")}
put_kwargs = {"files": files}
if settings.is_test_proxy_mode():
add_proxy_details(put_kwargs)
requests.put(presigned_url, **put_kwargs)
resp = s3_client.get_object(Bucket="mybucket", Key="file_upload")
data = resp["Body"].read()
assert data == b"test"
# cleanup
os.remove("text.txt")
@mock_aws
def test_upload_file_with_checksum_algorithm():
random_bytes = (
b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00"
b"\x00\xff\n\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\n"
)
with open("rb.tmp", mode="wb") as fhandle:
fhandle.write(random_bytes)
s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = "mybucket"
s3_client.create_bucket(Bucket=bucket)
s3_client.upload_file(
"rb.tmp", bucket, "my_key.csv", ExtraArgs={"ChecksumAlgorithm": "SHA256"}
)
os.remove("rb.tmp")
actual_content = s3_resource.Object(bucket, "my_key.csv").get()["Body"].read()
assert random_bytes == actual_content
@mock_aws
def test_put_large_with_checksum_algorithm():
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
bucket = "mybucket"
s3_client.create_bucket(Bucket=bucket)
s3_client.put_object(
Bucket=bucket,
Key="the-key",
Body=b"test" * 1000000,
ChecksumAlgorithm="SHA256",
)
resp = s3_client.get_object(Bucket="mybucket", Key="the-key")
assert resp["Body"].read() == b"test" * 1000000
@mock_aws
def test_put_chunked_with_v4_signature_in_body():
bucket_name = "mybucket"
file_name = "file"
content = "CONTENT"
content_bytes = bytes(content, encoding="utf8")
# 'CONTENT' as received in moto, when PutObject is called in java AWS SDK v2
chunked_body = (
b"7;chunk-signature=bd479c607ec05dd9d570893f74eed76a4b333dfa37ad"
b"6446f631ec47dc52e756\r\nCONTENT\r\n"
b"0;chunk-signature=d192ec4075ddfc18d2ef4da4f55a87dc762ba4417b3b"
b"d41e70c282f8bec2ece0\r\n\r\n"
)
s3_client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
s3_client.create_bucket(Bucket=bucket_name)
model = MyModel(file_name, content)
model.save()
boto_etag = s3_client.get_object(Bucket=bucket_name, Key=file_name)["ETag"]
params = {"Bucket": bucket_name, "Key": file_name}
# We'll use manipulated presigned PUT, to mimick PUT from SDK