-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathtest_s3fs.py
2441 lines (1921 loc) · 72.7 KB
/
test_s3fs.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
# -*- coding: utf-8 -*-
import asyncio
import errno
import datetime
from contextlib import contextmanager
import json
from concurrent.futures import ProcessPoolExecutor
import io
import os
import random
import requests
import time
import sys
import pytest
import moto
from itertools import chain
import fsspec.core
from dateutil.tz import tzutc
import s3fs.core
from s3fs.core import S3FileSystem
from s3fs.utils import ignoring, SSEParams
from botocore.exceptions import NoCredentialsError
from fsspec.asyn import sync
from fsspec.callbacks import Callback
from packaging import version
test_bucket_name = "test"
secure_bucket_name = "test-secure"
versioned_bucket_name = "test-versioned"
files = {
"test/accounts.1.json": (
b'{"amount": 100, "name": "Alice"}\n'
b'{"amount": 200, "name": "Bob"}\n'
b'{"amount": 300, "name": "Charlie"}\n'
b'{"amount": 400, "name": "Dennis"}\n'
),
"test/accounts.2.json": (
b'{"amount": 500, "name": "Alice"}\n'
b'{"amount": 600, "name": "Bob"}\n'
b'{"amount": 700, "name": "Charlie"}\n'
b'{"amount": 800, "name": "Dennis"}\n'
),
}
csv_files = {
"2014-01-01.csv": (
b"name,amount,id\n" b"Alice,100,1\n" b"Bob,200,2\n" b"Charlie,300,3\n"
),
"2014-01-02.csv": (b"name,amount,id\n"),
"2014-01-03.csv": (
b"name,amount,id\n" b"Dennis,400,4\n" b"Edith,500,5\n" b"Frank,600,6\n"
),
}
text_files = {
"nested/file1": b"hello\n",
"nested/file2": b"world",
"nested/nested2/file1": b"hello\n",
"nested/nested2/file2": b"world",
}
glob_files = {"file.dat": b"", "filexdat": b""}
a = test_bucket_name + "/tmp/test/a"
b = test_bucket_name + "/tmp/test/b"
c = test_bucket_name + "/tmp/test/c"
d = test_bucket_name + "/tmp/test/d"
port = 5555
endpoint_uri = "http://127.0.0.1:%s/" % port
@pytest.fixture()
def s3_base():
# writable local S3 system
import shlex
import subprocess
try:
# should fail since we didn't start server yet
r = requests.get(endpoint_uri)
except:
pass
else:
if r.ok:
raise RuntimeError("moto server already up")
if "AWS_SECRET_ACCESS_KEY" not in os.environ:
os.environ["AWS_SECRET_ACCESS_KEY"] = "foo"
if "AWS_ACCESS_KEY_ID" not in os.environ:
os.environ["AWS_ACCESS_KEY_ID"] = "foo"
proc = subprocess.Popen(
shlex.split("moto_server s3 -p %s" % port),
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stdin=subprocess.DEVNULL,
)
timeout = 5
while timeout > 0:
try:
print("polling for moto server")
r = requests.get(endpoint_uri)
if r.ok:
break
except:
pass
timeout -= 0.1
time.sleep(0.1)
print("server up")
yield
print("moto done")
proc.terminate()
proc.wait()
def get_boto3_client():
from botocore.session import Session
# NB: we use the sync botocore client for setup
session = Session()
return session.create_client("s3", endpoint_url=endpoint_uri)
@pytest.fixture()
def s3(s3_base):
client = get_boto3_client()
client.create_bucket(Bucket=test_bucket_name, ACL="public-read")
client.create_bucket(Bucket=versioned_bucket_name, ACL="public-read")
client.put_bucket_versioning(
Bucket=versioned_bucket_name, VersioningConfiguration={"Status": "Enabled"}
)
# initialize secure bucket
client.create_bucket(Bucket=secure_bucket_name, ACL="public-read")
policy = json.dumps(
{
"Version": "2012-10-17",
"Id": "PutObjPolicy",
"Statement": [
{
"Sid": "DenyUnEncryptedObjectUploads",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::{bucket_name}/*".format(
bucket_name=secure_bucket_name
),
"Condition": {
"StringNotEquals": {
"s3:x-amz-server-side-encryption": "aws:kms"
}
},
}
],
}
)
client.put_bucket_policy(Bucket=secure_bucket_name, Policy=policy)
for flist in [files, csv_files, text_files, glob_files]:
for f, data in flist.items():
client.put_object(Bucket=test_bucket_name, Key=f, Body=data)
S3FileSystem.clear_instance_cache()
s3 = S3FileSystem(anon=False, client_kwargs={"endpoint_url": endpoint_uri})
s3.invalidate_cache()
yield s3
@contextmanager
def expect_errno(expected_errno):
"""Expect an OSError and validate its errno code."""
with pytest.raises(OSError) as error:
yield
assert error.value.errno == expected_errno, "OSError has wrong error code."
def test_simple(s3):
data = b"a" * (10 * 2**20)
with s3.open(a, "wb") as f:
f.write(data)
with s3.open(a, "rb") as f:
out = f.read(len(data))
assert len(data) == len(out)
assert out == data
@pytest.mark.parametrize("default_cache_type", ["none", "bytes", "mmap"])
def test_default_cache_type(s3, default_cache_type):
data = b"a" * (10 * 2**20)
s3 = S3FileSystem(
anon=False,
default_cache_type=default_cache_type,
client_kwargs={"endpoint_url": endpoint_uri},
)
with s3.open(a, "wb") as f:
f.write(data)
with s3.open(a, "rb") as f:
assert isinstance(f.cache, fsspec.core.caches[default_cache_type])
out = f.read(len(data))
assert len(data) == len(out)
assert out == data
def test_ssl_off():
s3 = S3FileSystem(use_ssl=False, client_kwargs={"endpoint_url": endpoint_uri})
assert s3.s3.meta.endpoint_url.startswith("http://")
def test_client_kwargs():
s3 = S3FileSystem(client_kwargs={"endpoint_url": "http://foo"})
assert s3.s3.meta.endpoint_url.startswith("http://foo")
def test_config_kwargs():
s3 = S3FileSystem(
config_kwargs={"signature_version": "s3v4"},
client_kwargs={"endpoint_url": endpoint_uri},
)
assert s3.connect().meta.config.signature_version == "s3v4"
def test_config_kwargs_class_attributes_default():
s3 = S3FileSystem(client_kwargs={"endpoint_url": endpoint_uri})
assert s3.connect().meta.config.connect_timeout == 5
assert s3.connect().meta.config.read_timeout == 15
def test_config_kwargs_class_attributes_override():
s3 = S3FileSystem(
config_kwargs={
"connect_timeout": 60,
"read_timeout": 120,
},
client_kwargs={"endpoint_url": endpoint_uri},
)
assert s3.connect().meta.config.connect_timeout == 60
assert s3.connect().meta.config.read_timeout == 120
def test_user_session_is_preserved():
from aiobotocore.session import get_session
session = get_session()
s3 = S3FileSystem(session=session)
s3.connect()
assert s3.session == session
def test_idempotent_connect(s3):
first = s3.s3
assert s3.connect(refresh=True) is not first
def test_multiple_objects(s3):
s3.connect()
s3.ls("test")
s32 = S3FileSystem(anon=False, client_kwargs={"endpoint_url": endpoint_uri})
assert s32.session
assert s3.ls("test") == s32.ls("test")
def test_info(s3):
s3.touch(a)
s3.touch(b)
info = s3.info(a)
linfo = s3.ls(a, detail=True)[0]
assert abs(info.pop("LastModified") - linfo.pop("LastModified")).seconds < 1
info.pop("VersionId")
info.pop("ContentType")
linfo.pop("Key")
linfo.pop("Size")
assert info == linfo
parent = a.rsplit("/", 1)[0]
s3.invalidate_cache() # remove full path from the cache
s3.ls(parent) # fill the cache with parent dir
assert s3.info(a) == s3.dircache[parent][0] # correct value
assert id(s3.info(a)) == id(s3.dircache[parent][0]) # is object from cache
new_parent = test_bucket_name + "/foo"
s3.mkdir(new_parent)
with pytest.raises(FileNotFoundError):
s3.info(new_parent)
s3.ls(new_parent)
with pytest.raises(FileNotFoundError):
s3.info(new_parent)
def test_info_cached(s3):
path = test_bucket_name + "/tmp/"
fqpath = "s3://" + path
s3.touch(path + "test")
info = s3.info(fqpath)
assert info == s3.info(fqpath)
assert info == s3.info(path)
def test_checksum(s3):
bucket = test_bucket_name
d = "checksum"
prefix = d + "/e"
o1 = prefix + "1"
o2 = prefix + "2"
path1 = bucket + "/" + o1
path2 = bucket + "/" + o2
client = s3.s3
# init client and files
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="")
sync(s3.loop, client.put_object, Bucket=bucket, Key=o2, Body="")
# change one file, using cache
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="foo")
checksum = s3.checksum(path1)
s3.ls(path1) # force caching
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="bar")
# refresh == False => checksum doesn't change
assert checksum == s3.checksum(path1)
# change one file, without cache
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="foo")
checksum = s3.checksum(path1, refresh=True)
s3.ls(path1) # force caching
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="bar")
# refresh == True => checksum changes
assert checksum != s3.checksum(path1, refresh=True)
# Test for nonexistent file
sync(s3.loop, client.put_object, Bucket=bucket, Key=o1, Body="bar")
s3.ls(path1) # force caching
sync(s3.loop, client.delete_object, Bucket=bucket, Key=o1)
with pytest.raises(FileNotFoundError):
s3.checksum(o1, refresh=True)
# Test multipart upload
upload_id = sync(
s3.loop,
client.create_multipart_upload,
Bucket=bucket,
Key=o1,
)["UploadId"]
etag1 = sync(
s3.loop,
client.upload_part,
Bucket=bucket,
Key=o1,
UploadId=upload_id,
PartNumber=1,
Body="0" * (5 * 1024 * 1024),
)["ETag"]
etag2 = sync(
s3.loop,
client.upload_part,
Bucket=bucket,
Key=o1,
UploadId=upload_id,
PartNumber=2,
Body="0",
)["ETag"]
sync(
s3.loop,
client.complete_multipart_upload,
Bucket=bucket,
Key=o1,
UploadId=upload_id,
MultipartUpload={
"Parts": [
{"PartNumber": 1, "ETag": etag1},
{"PartNumber": 2, "ETag": etag2},
]
},
)
s3.checksum(path1, refresh=True)
test_xattr_sample_metadata = {"test_xattr": "1"}
def test_xattr(s3):
bucket, key = (test_bucket_name, "tmp/test/xattr")
filename = bucket + "/" + key
body = b"aaaa"
public_read_acl = {
"Permission": "READ",
"Grantee": {
"URI": "http://acs.amazonaws.com/groups/global/AllUsers",
"Type": "Group",
},
}
sync(
s3.loop,
s3.s3.put_object,
Bucket=bucket,
Key=key,
ACL="public-read",
Metadata=test_xattr_sample_metadata,
Body=body,
)
# save etag for later
etag = s3.info(filename)["ETag"]
assert (
public_read_acl
in sync(s3.loop, s3.s3.get_object_acl, Bucket=bucket, Key=key)["Grants"]
)
assert (
s3.getxattr(filename, "test_xattr") == test_xattr_sample_metadata["test_xattr"]
)
assert s3.metadata(filename) == {"test-xattr": "1"} # note _ became -
s3file = s3.open(filename)
assert s3file.getxattr("test_xattr") == test_xattr_sample_metadata["test_xattr"]
assert s3file.metadata() == {"test-xattr": "1"} # note _ became -
s3file.setxattr(test_xattr="2")
assert s3file.getxattr("test_xattr") == "2"
s3file.setxattr(**{"test_xattr": None})
assert s3file.metadata() == {}
assert s3.cat(filename) == body
# check that ACL and ETag are preserved after updating metadata
assert (
public_read_acl
in sync(s3.loop, s3.s3.get_object_acl, Bucket=bucket, Key=key)["Grants"]
)
assert s3.info(filename)["ETag"] == etag
def test_xattr_setxattr_in_write_mode(s3):
s3file = s3.open(a, "wb")
with pytest.raises(NotImplementedError):
s3file.setxattr(test_xattr="1")
@pytest.mark.xfail()
def test_delegate(s3):
out = s3.get_delegated_s3pars()
assert out
assert out["token"]
s32 = S3FileSystem(client_kwargs={"endpoint_url": endpoint_uri}, **out)
assert not s32.anon
assert out == s32.get_delegated_s3pars()
def test_not_delegate():
s3 = S3FileSystem(anon=True, client_kwargs={"endpoint_url": endpoint_uri})
out = s3.get_delegated_s3pars()
assert out == {"anon": True}
s3 = S3FileSystem(
anon=False, client_kwargs={"endpoint_url": endpoint_uri}
) # auto credentials
out = s3.get_delegated_s3pars()
assert out == {"anon": False}
def test_ls(s3):
assert set(s3.ls("", detail=False)) == {
test_bucket_name,
secure_bucket_name,
versioned_bucket_name,
}
with pytest.raises(FileNotFoundError):
s3.ls("nonexistent")
fn = test_bucket_name + "/test/accounts.1.json"
assert fn in s3.ls(test_bucket_name + "/test", detail=False)
def test_pickle(s3):
import pickle
s32 = pickle.loads(pickle.dumps(s3))
assert s3.ls("test") == s32.ls("test")
s33 = pickle.loads(pickle.dumps(s32))
assert s3.ls("test") == s33.ls("test")
def test_ls_touch(s3):
assert not s3.exists(test_bucket_name + "/tmp/test")
s3.touch(a)
s3.touch(b)
L = s3.ls(test_bucket_name + "/tmp/test", True)
assert {d["Key"] for d in L} == {a, b}
L = s3.ls(test_bucket_name + "/tmp/test", False)
assert set(L) == {a, b}
@pytest.mark.parametrize("version_aware", [True, False])
def test_exists_versioned(s3, version_aware):
"""Test to ensure that a prefix exists when using a versioned bucket"""
import uuid
n = 3
s3 = S3FileSystem(
anon=False,
version_aware=version_aware,
client_kwargs={"endpoint_url": endpoint_uri},
)
segments = [versioned_bucket_name] + [str(uuid.uuid4()) for _ in range(n)]
path = "/".join(segments)
for i in range(2, n + 1):
assert not s3.exists("/".join(segments[:i]))
s3.touch(path)
for i in range(2, n + 1):
assert s3.exists("/".join(segments[:i]))
def test_isfile(s3):
assert not s3.isfile("")
assert not s3.isfile("/")
assert not s3.isfile(test_bucket_name)
assert not s3.isfile(test_bucket_name + "/test")
assert not s3.isfile(test_bucket_name + "/test/foo")
assert s3.isfile(test_bucket_name + "/test/accounts.1.json")
assert s3.isfile(test_bucket_name + "/test/accounts.2.json")
assert not s3.isfile(a)
s3.touch(a)
assert s3.isfile(a)
assert not s3.isfile(b)
assert not s3.isfile(b + "/")
s3.mkdir(b)
assert not s3.isfile(b)
assert not s3.isfile(b + "/")
assert not s3.isfile(c)
assert not s3.isfile(c + "/")
s3.mkdir(c + "/")
assert not s3.isfile(c)
assert not s3.isfile(c + "/")
def test_isdir(s3):
assert s3.isdir("")
assert s3.isdir("/")
assert s3.isdir(test_bucket_name)
assert s3.isdir(test_bucket_name + "/test")
assert not s3.isdir(test_bucket_name + "/test/foo")
assert not s3.isdir(test_bucket_name + "/test/accounts.1.json")
assert not s3.isdir(test_bucket_name + "/test/accounts.2.json")
assert not s3.isdir(a)
s3.touch(a)
assert not s3.isdir(a)
assert not s3.isdir(b)
assert not s3.isdir(b + "/")
assert not s3.isdir(c)
assert not s3.isdir(c + "/")
# test cache
s3.invalidate_cache()
assert not s3.dircache
s3.ls(test_bucket_name + "/nested")
assert test_bucket_name + "/nested" in s3.dircache
assert not s3.isdir(test_bucket_name + "/nested/file1")
assert not s3.isdir(test_bucket_name + "/nested/file2")
assert s3.isdir(test_bucket_name + "/nested/nested2")
assert s3.isdir(test_bucket_name + "/nested/nested2/")
def test_rm(s3):
assert not s3.exists(a)
s3.touch(a)
assert s3.exists(a)
s3.rm(a)
assert not s3.exists(a)
# the API is OK with deleting non-files; maybe this is an effect of using bulk
# with pytest.raises(FileNotFoundError):
# s3.rm(test_bucket_name + '/nonexistent')
with pytest.raises(FileNotFoundError):
s3.rm("nonexistent")
s3.rm(test_bucket_name + "/nested", recursive=True)
assert not s3.exists(test_bucket_name + "/nested/nested2/file1")
# whole bucket
s3.rm(test_bucket_name, recursive=True)
assert not s3.exists(test_bucket_name + "/2014-01-01.csv")
assert not s3.exists(test_bucket_name)
def test_rmdir(s3):
bucket = "test1_bucket"
s3.mkdir(bucket)
s3.rmdir(bucket)
assert bucket not in s3.ls("/")
def test_mkdir(s3):
bucket = "test1_bucket"
s3.mkdir(bucket)
assert bucket in s3.ls("/")
def test_mkdir_existing_bucket(s3):
# mkdir called on existing bucket should be no-op and not calling create_bucket
# creating a s3 bucket
bucket = "test1_bucket"
s3.mkdir(bucket)
assert bucket in s3.ls("/")
# a second call.
with pytest.raises(FileExistsError):
s3.mkdir(bucket)
def test_mkdir_bucket_and_key_1(s3):
bucket = "test1_bucket"
file = bucket + "/a/b/c"
s3.mkdir(file, create_parents=True)
assert bucket in s3.ls("/")
def test_mkdir_bucket_and_key_2(s3):
bucket = "test1_bucket"
file = bucket + "/a/b/c"
with pytest.raises(FileNotFoundError):
s3.mkdir(file, create_parents=False)
assert bucket not in s3.ls("/")
def test_mkdir_region_name(s3):
bucket = "test2_bucket"
s3.mkdir(bucket, region_name="eu-central-1")
assert bucket in s3.ls("/")
def test_mkdir_client_region_name(s3):
bucket = "test3_bucket"
s3 = S3FileSystem(
anon=False,
client_kwargs={"region_name": "eu-central-1", "endpoint_url": endpoint_uri},
)
s3.mkdir(bucket)
assert bucket in s3.ls("/")
def test_makedirs(s3):
bucket = "test_makedirs_bucket"
test_file = bucket + "/a/b/c/file"
s3.makedirs(test_file)
assert bucket in s3.ls("/")
def test_makedirs_existing_bucket(s3):
bucket = "test_makedirs_bucket"
s3.mkdir(bucket)
assert bucket in s3.ls("/")
test_file = bucket + "/a/b/c/file"
# no-op, and no error.
s3.makedirs(test_file)
def test_makedirs_pure_bucket_exist_ok(s3):
bucket = "test1_bucket"
s3.mkdir(bucket)
s3.makedirs(bucket, exist_ok=True)
def test_makedirs_pure_bucket_error_on_exist(s3):
bucket = "test1_bucket"
s3.mkdir(bucket)
with pytest.raises(FileExistsError):
s3.makedirs(bucket, exist_ok=False)
def test_bulk_delete(s3):
with pytest.raises(FileNotFoundError):
s3.rm(["nonexistent/file"])
filelist = s3.find(test_bucket_name + "/nested")
s3.rm(filelist)
assert not s3.exists(test_bucket_name + "/nested/nested2/file1")
@pytest.mark.xfail(reason="anon user is still privileged on moto")
def test_anonymous_access(s3):
with ignoring(NoCredentialsError):
s3 = S3FileSystem(anon=True, client_kwargs={"endpoint_url": endpoint_uri})
assert s3.ls("") == []
# TODO: public bucket doesn't work through moto
with pytest.raises(PermissionError):
s3.mkdir("newbucket")
def test_s3_file_access(s3):
fn = test_bucket_name + "/nested/file1"
data = b"hello\n"
assert s3.cat(fn) == data
assert s3.head(fn, 3) == data[:3]
assert s3.tail(fn, 3) == data[-3:]
assert s3.tail(fn, 10000) == data
def test_s3_file_info(s3):
fn = test_bucket_name + "/nested/file1"
data = b"hello\n"
assert fn in s3.find(test_bucket_name)
assert s3.exists(fn)
assert not s3.exists(fn + "another")
assert s3.info(fn)["Size"] == len(data)
with pytest.raises(FileNotFoundError):
s3.info(fn + "another")
def test_content_type_is_set(s3, tmpdir):
test_file = str(tmpdir) + "/test.json"
destination = test_bucket_name + "/test.json"
open(test_file, "w").write("text")
s3.put(test_file, destination)
assert s3.info(destination)["ContentType"] == "application/json"
def test_content_type_is_not_overrided(s3, tmpdir):
test_file = os.path.join(str(tmpdir), "test.json")
destination = os.path.join(test_bucket_name, "test.json")
open(test_file, "w").write("text")
s3.put(test_file, destination, ContentType="text/css")
assert s3.info(destination)["ContentType"] == "text/css"
def test_bucket_exists(s3):
assert s3.exists(test_bucket_name)
assert not s3.exists(test_bucket_name + "x")
s3 = S3FileSystem(anon=True, client_kwargs={"endpoint_url": endpoint_uri})
assert s3.exists(test_bucket_name)
assert not s3.exists(test_bucket_name + "x")
def test_du(s3):
d = s3.du(test_bucket_name, total=False)
assert all(isinstance(v, int) and v >= 0 for v in d.values())
assert test_bucket_name + "/nested/file1" in d
assert s3.du(test_bucket_name + "/test/", total=True) == sum(
map(len, files.values())
)
assert s3.du(test_bucket_name) == s3.du("s3://" + test_bucket_name)
def test_s3_ls(s3):
fn = test_bucket_name + "/nested/file1"
assert fn not in s3.ls(test_bucket_name + "/")
assert fn in s3.ls(test_bucket_name + "/nested/")
assert fn in s3.ls(test_bucket_name + "/nested")
assert s3.ls("s3://" + test_bucket_name + "/nested/") == s3.ls(
test_bucket_name + "/nested"
)
def test_s3_big_ls(s3):
for x in range(1200):
s3.touch(test_bucket_name + "/thousand/%i.part" % x)
assert len(s3.find(test_bucket_name)) > 1200
s3.rm(test_bucket_name + "/thousand/", recursive=True)
assert len(s3.find(test_bucket_name + "/thousand/")) == 0
def test_s3_ls_detail(s3):
L = s3.ls(test_bucket_name + "/nested", detail=True)
assert all(isinstance(item, dict) for item in L)
def test_s3_glob(s3):
fn = test_bucket_name + "/nested/file1"
assert fn not in s3.glob(test_bucket_name + "/")
assert fn not in s3.glob(test_bucket_name + "/*")
assert fn not in s3.glob(test_bucket_name + "/nested")
assert fn in s3.glob(test_bucket_name + "/nested/*")
assert fn in s3.glob(test_bucket_name + "/nested/file*")
assert fn in s3.glob(test_bucket_name + "/*/*")
assert all(
any(p.startswith(f + "/") or p == f for p in s3.find(test_bucket_name))
for f in s3.glob(test_bucket_name + "/nested/*")
)
assert [test_bucket_name + "/nested/nested2"] == s3.glob(
test_bucket_name + "/nested/nested2"
)
out = s3.glob(test_bucket_name + "/nested/nested2/*")
assert {"test/nested/nested2/file1", "test/nested/nested2/file2"} == set(out)
with pytest.raises(ValueError):
s3.glob("*")
# Make sure glob() deals with the dot character (.) correctly.
assert test_bucket_name + "/file.dat" in s3.glob(test_bucket_name + "/file.*")
assert test_bucket_name + "/filexdat" not in s3.glob(test_bucket_name + "/file.*")
def test_get_list_of_summary_objects(s3):
L = s3.ls(test_bucket_name + "/test")
assert len(L) == 2
assert [l.lstrip(test_bucket_name).lstrip("/") for l in sorted(L)] == sorted(
list(files)
)
L2 = s3.ls("s3://" + test_bucket_name + "/test")
assert L == L2
def test_read_keys_from_bucket(s3):
for k, data in files.items():
file_contents = s3.cat("/".join([test_bucket_name, k]))
assert file_contents == data
assert s3.cat("/".join([test_bucket_name, k])) == s3.cat(
"s3://" + "/".join([test_bucket_name, k])
)
def test_url(s3):
fn = test_bucket_name + "/nested/file1"
url = s3.url(fn, expires=100)
assert "http" in url
import urllib.parse
components = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(components.query)
exp = int(query["Expires"][0])
delta = abs(exp - time.time() - 100)
assert delta < 5
with s3.open(fn) as f:
assert "http" in f.url()
def test_seek(s3):
with s3.open(a, "wb") as f:
f.write(b"123")
with s3.open(a) as f:
f.seek(1000)
with pytest.raises(ValueError):
f.seek(-1)
with pytest.raises(ValueError):
f.seek(-5, 2)
with pytest.raises(ValueError):
f.seek(0, 10)
f.seek(0)
assert f.read(1) == b"1"
f.seek(0)
assert f.read(1) == b"1"
f.seek(3)
assert f.read(1) == b""
f.seek(-1, 2)
assert f.read(1) == b"3"
f.seek(-1, 1)
f.seek(-1, 1)
assert f.read(1) == b"2"
for i in range(4):
assert f.seek(i) == i
def test_bad_open(s3):
with pytest.raises(ValueError):
s3.open("")
def test_copy(s3):
fn = test_bucket_name + "/test/accounts.1.json"
s3.copy(fn, fn + "2")
assert s3.cat(fn) == s3.cat(fn + "2")
def test_copy_managed(s3):
data = b"abc" * 12 * 2**20
fn = test_bucket_name + "/test/biggerfile"
with s3.open(fn, "wb") as f:
f.write(data)
sync(s3.loop, s3._copy_managed, fn, fn + "2", size=len(data), block=5 * 2**20)
assert s3.cat(fn) == s3.cat(fn + "2")
with pytest.raises(ValueError):
sync(s3.loop, s3._copy_managed, fn, fn + "3", size=len(data), block=4 * 2**20)
with pytest.raises(ValueError):
sync(s3.loop, s3._copy_managed, fn, fn + "3", size=len(data), block=6 * 2**30)
@pytest.mark.parametrize("recursive", [True, False])
def test_move(s3, recursive):
fn = test_bucket_name + "/test/accounts.1.json"
data = s3.cat(fn)
s3.mv(fn, fn + "2", recursive=recursive)
assert s3.cat(fn + "2") == data
assert not s3.exists(fn)
def test_get_put(s3, tmpdir):
test_file = str(tmpdir.join("test.json"))
s3.get(test_bucket_name + "/test/accounts.1.json", test_file)
data = files["test/accounts.1.json"]
assert open(test_file, "rb").read() == data
s3.put(test_file, test_bucket_name + "/temp")
assert s3.du(test_bucket_name + "/temp", total=False)[
test_bucket_name + "/temp"
] == len(data)
assert s3.cat(test_bucket_name + "/temp") == data
def test_get_put_big(s3, tmpdir):
test_file = str(tmpdir.join("test"))
data = b"1234567890A" * 2**20
open(test_file, "wb").write(data)
s3.put(test_file, test_bucket_name + "/bigfile")
test_file = str(tmpdir.join("test2"))
s3.get(test_bucket_name + "/bigfile", test_file)
assert open(test_file, "rb").read() == data
def test_get_put_with_callback(s3, tmpdir):
test_file = str(tmpdir.join("test.json"))
class BranchingCallback(Callback):
def branch(self, path_1, path_2, kwargs):
kwargs["callback"] = BranchingCallback()
cb = BranchingCallback()
s3.get(test_bucket_name + "/test/accounts.1.json", test_file, callback=cb)
assert cb.size == 1
assert cb.value == 1
cb = BranchingCallback()
s3.put(test_file, test_bucket_name + "/temp", callback=cb)
assert cb.size == 1
assert cb.value == 1
def test_get_file_with_callback(s3, tmpdir):
test_file = str(tmpdir.join("test.json"))
cb = Callback()
s3.get_file(test_bucket_name + "/test/accounts.1.json", test_file, callback=cb)
assert cb.size == os.stat(test_file).st_size
assert cb.value == cb.size
@pytest.mark.parametrize("size", [2**10, 10 * 2**20])
def test_put_file_with_callback(s3, tmpdir, size):
test_file = str(tmpdir.join("test.json"))
with open(test_file, "wb") as f:
f.write(b"1234567890A" * size)
cb = Callback()
s3.put_file(test_file, test_bucket_name + "/temp", callback=cb)
assert cb.size == os.stat(test_file).st_size
assert cb.value == cb.size
@pytest.mark.parametrize("size", [2**10, 2**20, 10 * 2**20])
def test_pipe_cat_big(s3, size):
data = b"1234567890A" * size
s3.pipe(test_bucket_name + "/bigfile", data)
assert s3.cat(test_bucket_name + "/bigfile") == data
def test_errors(s3):
with pytest.raises(FileNotFoundError):
s3.open(test_bucket_name + "/tmp/test/shfoshf", "rb")
# This is fine, no need for interleaving directories on S3
# with pytest.raises((IOError, OSError)):
# s3.touch('tmp/test/shfoshf/x')
# Deleting nonexistent or zero paths is allowed for now
# with pytest.raises(FileNotFoundError):
# s3.rm(test_bucket_name + '/tmp/test/shfoshf/x')
with pytest.raises(FileNotFoundError):
s3.mv(test_bucket_name + "/tmp/test/shfoshf/x", "tmp/test/shfoshf/y")
with pytest.raises(ValueError):
s3.open("x", "rb")
with pytest.raises(FileNotFoundError):
s3.rm("unknown")
with pytest.raises(ValueError):
with s3.open(test_bucket_name + "/temp", "wb") as f:
f.read()
with pytest.raises(ValueError):
f = s3.open(test_bucket_name + "/temp", "rb")
f.close()
f.read()
with pytest.raises(ValueError):
s3.mkdir("/")
with pytest.raises(ValueError):
s3.find("")