-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
test_plugin.py
2271 lines (1941 loc) · 92.2 KB
/
test_plugin.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 -*-
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
# The following tests are performed to ensure that the commands work.
# It does not check every possible parameter that can be thrown as
# those are checked by tests in other classes
import os
import platform
import contextlib
import time
import stat
import signal
import string
import socket
import tempfile
import shutil
import copy
import logging
import pytest
from awscli.compat import BytesIO, urlopen
import botocore.session
from awscli.testutils import unittest, get_stdout_encoding
from awscli.testutils import skip_if_windows
from awscli.testutils import aws as _aws
from awscli.testutils import BaseS3CLICommand
from awscli.testutils import random_chars, random_bucket_name
from awscli.customizations.s3.transferconfig import DEFAULTS
from awscli.customizations.scalarparse import add_scalar_parsers, identity
# Using the same log name as testutils.py
LOG = logging.getLogger('awscli.tests.integration')
_SHARED_BUCKET = random_bucket_name()
_NON_EXISTENT_BUCKET = random_bucket_name()
_DEFAULT_REGION = 'us-west-2'
_DEFAULT_AZ = 'usw2-az1'
_SHARED_DIR_BUCKET = f'{random_bucket_name()}--{_DEFAULT_AZ}--x-s3'
def setup_module():
s3 = botocore.session.get_session().create_client('s3')
waiter = s3.get_waiter('bucket_exists')
params = {
'Bucket': _SHARED_BUCKET,
'CreateBucketConfiguration': {
'LocationConstraint': _DEFAULT_REGION,
},
'ObjectOwnership': 'ObjectWriter'
}
dir_bucket_params = {
'Bucket': _SHARED_DIR_BUCKET,
'CreateBucketConfiguration': {
'Location': {
'Type': 'AvailabilityZone',
'Name': _DEFAULT_AZ
},
'Bucket': {
'Type': 'Directory',
'DataRedundancy': 'SingleAvailabilityZone'
}
}
}
try:
s3.create_bucket(**params)
s3.create_bucket(**dir_bucket_params)
except Exception as e:
# A create_bucket can fail for a number of reasons.
# We're going to defer to the waiter below to make the
# final call as to whether or not the bucket exists.
LOG.debug("create_bucket() raised an exception: %s", e, exc_info=True)
waiter.wait(Bucket=_SHARED_BUCKET)
waiter.wait(Bucket=_SHARED_DIR_BUCKET)
s3.delete_public_access_block(
Bucket=_SHARED_BUCKET
)
# Validate that "_NON_EXISTENT_BUCKET" doesn't exist.
waiter = s3.get_waiter('bucket_not_exists')
try:
waiter.wait(Bucket=_NON_EXISTENT_BUCKET)
except Exception as e:
LOG.debug(
f"The following bucket was unexpectedly discovered: {_NON_EXISTENT_BUCKET}",
e,
exc_info=True,
)
def clear_out_bucket(bucket, delete_bucket=False):
s3 = botocore.session.get_session().create_client(
's3', region_name=_DEFAULT_REGION)
page = s3.get_paginator('list_objects_v2')
# Use pages paired with batch delete_objects().
for page in page.paginate(Bucket=bucket):
keys = [{'Key': obj['Key']} for obj in page.get('Contents', [])]
if keys:
s3.delete_objects(Bucket=bucket, Delete={'Objects': keys})
if delete_bucket:
try:
s3.delete_bucket(Bucket=bucket)
except Exception as e:
# We can sometimes get exceptions when trying to
# delete a bucket. We'll let the waiter make
# the final call as to whether the bucket was able
# to be deleted.
LOG.debug("delete_bucket() raised an exception: %s",
e, exc_info=True)
waiter = s3.get_waiter('bucket_not_exists')
waiter.wait(Bucket=bucket)
def teardown_module():
clear_out_bucket(_SHARED_BUCKET, delete_bucket=True)
clear_out_bucket(_SHARED_DIR_BUCKET, delete_bucket=True)
@contextlib.contextmanager
def cd(directory):
original = os.getcwd()
try:
os.chdir(directory)
yield
finally:
os.chdir(original)
def aws(command, collect_memory=False, env_vars=None, wait_for_finish=True,
input_data=None, input_file=None):
if not env_vars:
env_vars = os.environ.copy()
env_vars['AWS_DEFAULT_REGION'] = "us-west-2"
return _aws(command, collect_memory=collect_memory, env_vars=env_vars,
wait_for_finish=wait_for_finish, input_data=input_data,
input_file=input_file)
def wait_for_process_exit(process, timeout=60):
deadline = time.time() + timeout
while time.time() < deadline:
rc = process.poll()
if rc is not None:
break
time.sleep(1)
else:
process.kill()
raise AssertionError("CLI did not exist within %s seconds of "
"receiving a Ctrl+C" % timeout)
def _running_on_rhel():
return (
hasattr(platform, 'linux_distribution') and
platform.linux_distribution()[0] == 'Red Hat Enterprise Linux Server')
class BaseS3IntegrationTest(BaseS3CLICommand):
def setUp(self):
clear_out_bucket(_SHARED_BUCKET)
clear_out_bucket(_SHARED_DIR_BUCKET)
super(BaseS3IntegrationTest, self).setUp()
class TestMoveCommand(BaseS3IntegrationTest):
def assert_mv_local_to_s3(self, bucket_name):
full_path = self.files.create_file('foo.txt', 'this is foo.txt')
p = aws('s3 mv %s s3://%s/foo.txt' % (full_path,
bucket_name))
self.assert_no_errors(p)
# When we move an object, the local file is gone:
self.assertTrue(not os.path.exists(full_path))
# And now resides in s3.
self.assert_key_contents_equal(bucket_name, 'foo.txt',
'this is foo.txt')
def assert_mv_s3_to_local(self, bucket_name):
self.put_object(bucket_name, 'foo.txt', 'this is foo.txt')
full_path = self.files.full_path('foo.txt')
self.assertTrue(self.key_exists(bucket_name, key_name='foo.txt'))
p = aws('s3 mv s3://%s/foo.txt %s' % (bucket_name, full_path))
self.assert_no_errors(p)
self.assertTrue(os.path.exists(full_path))
with open(full_path, 'r') as f:
self.assertEqual(f.read(), 'this is foo.txt')
# The s3 file should not be there anymore.
self.assertTrue(self.key_not_exists(bucket_name, key_name='foo.txt'))
def assert_mv_s3_to_s3(self, from_bucket, create_bucket_call):
to_bucket = create_bucket_call()
self.put_object(from_bucket, 'foo.txt', 'this is foo.txt')
p = aws('s3 mv s3://%s/foo.txt s3://%s/foo.txt' % (from_bucket,
to_bucket))
self.assert_no_errors(p)
contents = self.get_key_contents(to_bucket, 'foo.txt')
self.assertEqual(contents, 'this is foo.txt')
# And verify that the object no longer exists in the from_bucket.
self.assertTrue(self.key_not_exists(from_bucket, key_name='foo.txt'))
def test_mv_local_to_s3(self):
self.assert_mv_local_to_s3(_SHARED_BUCKET)
def test_mv_local_to_s3_express(self):
self.assert_mv_local_to_s3(_SHARED_DIR_BUCKET)
def test_mv_s3_to_local(self):
self.assert_mv_s3_to_local(_SHARED_BUCKET)
def test_mv_s3_express_to_local(self):
self.assert_mv_s3_to_local(_SHARED_DIR_BUCKET)
def test_mv_s3_to_s3(self):
self.assert_mv_s3_to_s3(_SHARED_BUCKET, self.create_bucket)
def test_mv_s3_to_s3_express(self):
self.assert_mv_s3_to_s3(_SHARED_BUCKET, self.create_dir_bucket)
def test_mv_s3_express_to_s3_express(self):
self.assert_mv_s3_to_s3(_SHARED_DIR_BUCKET, self.create_dir_bucket)
def test_mv_s3_express_to_s3(self):
self.assert_mv_s3_to_s3(_SHARED_DIR_BUCKET, self.create_bucket)
@pytest.mark.slow
def test_mv_s3_to_s3_multipart(self):
from_bucket = _SHARED_BUCKET
to_bucket = self.create_bucket()
file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
self.put_object(from_bucket, 'foo.txt', file_contents)
p = aws('s3 mv s3://%s/foo.txt s3://%s/foo.txt' % (from_bucket,
to_bucket))
self.assert_no_errors(p)
self.assert_key_contents_equal(to_bucket, 'foo.txt', file_contents)
# And verify that the object no longer exists in the from_bucket.
self.assertTrue(self.key_not_exists(from_bucket, key_name='foo.txt'))
def test_mv_s3_to_s3_multipart_recursive(self):
from_bucket = _SHARED_BUCKET
to_bucket = self.create_bucket()
large_file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
small_file_contents = 'small file contents'
self.put_object(from_bucket, 'largefile', large_file_contents)
self.put_object(from_bucket, 'smallfile', small_file_contents)
p = aws('s3 mv s3://%s/ s3://%s/ --recursive' % (from_bucket,
to_bucket))
self.assert_no_errors(p)
# Nothing's in the from_bucket.
self.assertTrue(self.key_not_exists(from_bucket,
key_name='largefile'))
self.assertTrue(self.key_not_exists(from_bucket,
key_name='smallfile'))
# And both files are in the to_bucket.
self.assertTrue(self.key_exists(to_bucket, key_name='largefile'))
self.assertTrue(self.key_exists(to_bucket, key_name='smallfile'))
# And the contents are what we expect.
self.assert_key_contents_equal(to_bucket, 'smallfile',
small_file_contents)
self.assert_key_contents_equal(to_bucket, 'largefile',
large_file_contents)
def test_mv_s3_to_s3_with_sig4(self):
to_region = 'eu-central-1'
from_region = 'us-west-2'
from_bucket = self.create_bucket(region=from_region)
to_bucket = self.create_bucket(region=to_region)
file_name = 'hello.txt'
file_contents = 'hello'
self.put_object(from_bucket, file_name, file_contents)
p = aws('s3 mv s3://{0}/{4} s3://{1}/{4} '
'--source-region {2} --region {3}'
.format(from_bucket, to_bucket, from_region, to_region,
file_name))
self.assert_no_errors(p)
self.assertTrue(self.key_not_exists(from_bucket, file_name))
self.assertTrue(self.key_exists(to_bucket, file_name))
@pytest.mark.slow
def test_mv_with_large_file(self):
bucket_name = _SHARED_BUCKET
# 40MB will force a multipart upload.
file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
foo_txt = self.files.create_file(
'foo.txt', file_contents.getvalue().decode('utf-8'))
p = aws('s3 mv %s s3://%s/foo.txt' % (foo_txt, bucket_name))
self.assert_no_errors(p)
# When we move an object, the local file is gone:
self.assertTrue(not os.path.exists(foo_txt))
# And now resides in s3.
self.assert_key_contents_equal(bucket_name, 'foo.txt', file_contents)
# Now verify we can download this file.
p = aws('s3 mv s3://%s/foo.txt %s' % (bucket_name, foo_txt))
self.assert_no_errors(p)
self.assertTrue(os.path.exists(foo_txt))
self.assertEqual(os.path.getsize(foo_txt),
len(file_contents.getvalue()))
def test_mv_to_nonexistent_bucket(self):
full_path = self.files.create_file('foo.txt', 'this is foo.txt')
p = aws(f's3 mv {full_path} s3://{_NON_EXISTENT_BUCKET}/foo.txt')
self.assertEqual(p.rc, 1)
def test_cant_move_file_onto_itself_small_file(self):
# We don't even need a remote file in this case. We can
# immediately validate that we can't move a file onto itself.
bucket_name = _SHARED_BUCKET
self.put_object(bucket_name, key_name='key.txt', contents='foo')
p = aws('s3 mv s3://%s/key.txt s3://%s/key.txt' %
(bucket_name, bucket_name))
self.assertEqual(p.rc, 255)
self.assertIn('Cannot mv a file onto itself', p.stderr)
def test_cant_move_large_file_onto_itself(self):
# At the API level, you can multipart copy an object onto itself,
# but a mv command doesn't make sense because a mv is just a
# cp + an rm of the src file. We should be consistent and
# not allow large files to be mv'd onto themselves.
file_contents = BytesIO(b'a' * (1024 * 1024 * 10))
bucket_name = _SHARED_BUCKET
self.put_object(bucket_name, key_name='key.txt',
contents=file_contents)
p = aws('s3 mv s3://%s/key.txt s3://%s/key.txt' %
(bucket_name, bucket_name))
self.assertEqual(p.rc, 255)
self.assertIn('Cannot mv a file onto itself', p.stderr)
class TestRm(BaseS3IntegrationTest):
def assert_rm_with_page_size(self, bucket_name):
self.put_object(bucket_name, 'foo.txt', contents='hello world')
self.put_object(bucket_name, 'bar.txt', contents='hello world2')
p = aws('s3 rm s3://%s/ --recursive --page-size 1' % bucket_name)
self.assert_no_errors(p)
self.assertTrue(self.key_not_exists(bucket_name, key_name='foo.txt'))
self.assertTrue(self.key_not_exists(bucket_name, key_name='bar.txt'))
@skip_if_windows('Newline in filename test not valid on windows.')
# Windows won't let you do this. You'll get:
# [Errno 22] invalid mode ('w') or filename:
# 'c:\\windows\\temp\\tmp0fv8uu\\foo\r.txt'
def test_rm_with_newlines(self):
bucket_name = _SHARED_BUCKET
# Note the carriage return in the key name.
foo_txt = self.files.create_file('foo\r.txt', 'this is foo.txt')
p = aws('s3 cp %s s3://%s/foo\r.txt' % (foo_txt, bucket_name))
self.assert_no_errors(p)
# Make sure object is in bucket.
self.assertTrue(self.key_exists(bucket_name, key_name='foo\r.txt'))
# Then delete the file.
p = aws('s3 rm s3://%s/ --recursive' % (bucket_name,))
# And verify it's gone.
self.assertTrue(self.key_not_exists(bucket_name, key_name='foo\r.txt'))
def test_rm_with_page_size(self):
self.assert_rm_with_page_size(_SHARED_BUCKET)
def test_s3_express_rm_with_page_size(self):
self.assert_rm_with_page_size(_SHARED_DIR_BUCKET)
class TestCp(BaseS3IntegrationTest):
def assert_cp_to_and_from_s3(self, bucket_name):
# This tests the ability to put a single file in s3
# move it to a different bucket.
# and download the file locally
# copy file into bucket.
foo_txt = self.files.create_file('foo.txt', 'this is foo.txt')
p = aws('s3 cp %s s3://%s/foo.txt' % (foo_txt, bucket_name))
self.assert_no_errors(p)
# Make sure object is in bucket.
self.assertTrue(self.key_exists(bucket_name, key_name='foo.txt'))
self.assertEqual(
self.get_key_contents(bucket_name, key_name='foo.txt'),
'this is foo.txt')
self.assertEqual(
self.content_type_for_key(bucket_name, key_name='foo.txt'),
'text/plain')
# Make a new name for the file and copy it locally.
full_path = self.files.full_path('bar.txt')
p = aws('s3 cp s3://%s/foo.txt %s' % (bucket_name, full_path))
self.assert_no_errors(p)
with open(full_path, 'r') as f:
self.assertEqual(f.read(), 'this is foo.txt')
def test_cp_to_and_from_s3(self):
self.assert_cp_to_and_from_s3(_SHARED_BUCKET)
def test_cp_to_and_from_s3_express(self):
self.assert_cp_to_and_from_s3(_SHARED_DIR_BUCKET)
def test_cp_without_trailing_slash(self):
# There's a unit test for this, but we still want to verify this
# with an integration test.
bucket_name = _SHARED_BUCKET
# copy file into bucket.
foo_txt = self.files.create_file('foo.txt', 'this is foo.txt')
# Note that the destination has no trailing slash.
p = aws('s3 cp %s s3://%s' % (foo_txt, bucket_name))
self.assert_no_errors(p)
# Make sure object is in bucket.
self.assertTrue(self.key_exists(bucket_name, key_name='foo.txt'))
self.assertEqual(
self.get_key_contents(bucket_name, key_name='foo.txt'),
'this is foo.txt')
@pytest.mark.slow
def test_cp_s3_s3_multipart(self):
from_bucket = _SHARED_BUCKET
to_bucket = self.create_bucket()
file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
self.put_object(from_bucket, 'foo.txt', file_contents)
p = aws('s3 cp s3://%s/foo.txt s3://%s/foo.txt' %
(from_bucket, to_bucket))
self.assert_no_errors(p)
self.assert_key_contents_equal(to_bucket, 'foo.txt', file_contents)
self.assertTrue(self.key_exists(from_bucket, key_name='foo.txt'))
def test_guess_mime_type(self):
bucket_name = _SHARED_BUCKET
bar_png = self.files.create_file('bar.jpeg', 'fake png image')
p = aws('s3 cp %s s3://%s/bar.jpeg' % (bar_png, bucket_name))
self.assert_no_errors(p)
# We should have correctly guessed the content type based on the
# filename extension.
self.assertEqual(
self.content_type_for_key(bucket_name, key_name='bar.jpeg'),
'image/jpeg')
@pytest.mark.slow
def test_download_large_file(self):
# This will force a multipart download.
bucket_name = _SHARED_BUCKET
foo_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
self.put_object(bucket_name, key_name='foo.txt',
contents=foo_contents)
local_foo_txt = self.files.full_path('foo.txt')
p = aws('s3 cp s3://%s/foo.txt %s' % (bucket_name, local_foo_txt))
self.assert_no_errors(p)
self.assertEqual(os.path.getsize(local_foo_txt),
len(foo_contents.getvalue()))
@pytest.mark.slow
@skip_if_windows('SIGINT not supported on Windows.')
def test_download_ctrl_c_does_not_hang(self):
bucket_name = _SHARED_BUCKET
foo_contents = BytesIO(b'abcd' * (1024 * 1024 * 40))
self.put_object(bucket_name, key_name='foo.txt',
contents=foo_contents)
local_foo_txt = self.files.full_path('foo.txt')
# --quiet is added to make sure too much output is not communicated
# to the PIPE, causing a deadlock when not consumed.
process = aws('s3 cp s3://%s/foo.txt %s --quiet' %
(bucket_name, local_foo_txt), wait_for_finish=False)
# Give it some time to start up and enter it's main task loop.
time.sleep(3)
# The process has 60 seconds to finish after being sent a Ctrl+C,
# otherwise the test fails.
process.send_signal(signal.SIGINT)
wait_for_process_exit(process, timeout=60)
# A Ctrl+C should have a non-zero RC.
# We either caught the process in
# its main polling loop (rc=1), or it was successfully terminated by
# the SIGINT (rc=-2).
#
# There is also the chance the interrupt happened before the transfer
# process started or even after transfer process finished. So the
# signal may have never been encountered, resulting in an rc of 0.
# Therefore, it is acceptable to have an rc of 0 as the important part
# about this test is that it does not hang.
self.assertIn(process.returncode, [0, 1, -2])
@pytest.mark.slow
@skip_if_windows('SIGINT not supported on Windows.')
def test_cleans_up_aborted_uploads(self):
bucket_name = _SHARED_BUCKET
foo_txt = self.files.create_file('foo.txt', '')
with open(foo_txt, 'wb') as f:
for i in range(20):
f.write(b'a' * 1024 * 1024)
# --quiet is added to make sure too much output is not communicated
# to the PIPE, causing a deadlock when not consumed.
process = aws('s3 cp %s s3://%s/ --quiet' % (foo_txt, bucket_name),
wait_for_finish=False)
time.sleep(3)
# The process has 60 seconds to finish after being sent a Ctrl+C,
# otherwise the test fails.
process.send_signal(signal.SIGINT)
wait_for_process_exit(process, timeout=60)
uploads_after = self.client.list_multipart_uploads(
Bucket=bucket_name).get('Uploads', [])
self.assertEqual(uploads_after, [],
"Not all multipart uploads were properly "
"aborted after receiving Ctrl-C: %s" % uploads_after)
def test_cp_to_nonexistent_bucket(self):
foo_txt = self.files.create_file('foo.txt', 'this is foo.txt')
p = aws(f's3 cp {foo_txt} s3://{_NON_EXISTENT_BUCKET}/foo.txt')
self.assertEqual(p.rc, 1)
def test_cp_empty_file(self):
bucket_name = _SHARED_BUCKET
foo_txt = self.files.create_file('foo.txt', contents='')
p = aws('s3 cp %s s3://%s/' % (foo_txt, bucket_name))
self.assertEqual(p.rc, 0)
self.assertNotIn('failed', p.stderr)
self.assertTrue(self.key_exists(bucket_name, 'foo.txt'))
def test_download_non_existent_key(self):
p = aws(f's3 cp s3://{_NON_EXISTENT_BUCKET}/foo.txt foo.txt')
self.assertEqual(p.rc, 1)
expected_err_msg = (
'An error occurred (404) when calling the '
'HeadObject operation: Key "foo.txt" does not exist')
self.assertIn(expected_err_msg, p.stderr)
def test_download_encrypted_kms_object(self):
bucket_name = self.create_bucket(region='eu-central-1')
extra_args = {
'ServerSideEncryption': 'aws:kms',
'SSEKMSKeyId': 'alias/aws/s3'
}
object_name = 'foo.txt'
contents = 'this is foo.txt'
self.put_object(bucket_name, object_name, contents,
extra_args=extra_args)
local_filename = self.files.full_path('foo.txt')
p = aws('s3 cp s3://%s/%s %s --region eu-central-1' %
(bucket_name, object_name, local_filename))
self.assertEqual(p.rc, 0)
# Assert that the file was downloaded properly.
with open(local_filename, 'r') as f:
self.assertEqual(f.read(), contents)
def test_download_empty_object(self):
bucket_name = _SHARED_BUCKET
object_name = 'empty-object'
self.put_object(bucket_name, object_name, '')
local_filename = self.files.full_path('empty.txt')
p = aws('s3 cp s3://%s/%s %s' % (
bucket_name, object_name, local_filename))
self.assertEqual(p.rc, 0)
# Assert that the file was downloaded and has no content.
with open(local_filename, 'r') as f:
self.assertEqual(f.read(), '')
def test_website_redirect_ignore_paramfile(self):
bucket_name = _SHARED_BUCKET
foo_txt = self.files.create_file('foo.txt', 'bar')
website_redirect = 'http://someserver'
p = aws('s3 cp %s s3://%s/foo.txt --website-redirect %s' %
(foo_txt, bucket_name, website_redirect))
self.assert_no_errors(p)
# Ensure that the web address is used as opposed to the contents
# of the web address. We can check via a head object.
response = self.head_object(bucket_name, 'foo.txt')
self.assertEqual(response['WebsiteRedirectLocation'], website_redirect)
@pytest.mark.slow
def test_copy_large_file_signature_v4(self):
# Just verify that we can upload a large file to a region
# that uses signature version 4.
bucket_name = self.create_bucket(region='eu-central-1')
num_mb = 200
foo_txt = self.files.create_file('foo.txt', '')
with open(foo_txt, 'wb') as f:
for i in range(num_mb):
f.write(b'a' * 1024 * 1024)
p = aws('s3 cp %s s3://%s/ --region eu-central-1' % (
foo_txt, bucket_name))
self.assert_no_errors(p)
self.assertTrue(self.key_exists(bucket_name, key_name='foo.txt'))
def test_copy_metadata(self):
# Copy the same style of parsing as the CLI session. This is needed
# For comparing expires timestamp.
add_scalar_parsers(self.session)
bucket_name = _SHARED_BUCKET
key = random_chars(6)
filename = self.files.create_file(key, contents='')
p = aws('s3 cp %s s3://%s/%s --metadata keyname=value' %
(filename, bucket_name, key))
self.assert_no_errors(p)
response = self.head_object(bucket_name, key)
# These values should have the metadata of the source object
self.assertEqual(response['Metadata'].get('keyname'), 'value')
def test_copy_metadata_directive(self):
# Copy the same style of parsing as the CLI session. This is needed
# For comparing expires timestamp.
self.override_parser(timestamp_parser=identity)
bucket_name = _SHARED_BUCKET
original_key = '%s-a' % random_chars(6)
new_key = '%s-b' % random_chars(6)
metadata = {
'ContentType': 'foo',
'ContentDisposition': 'foo',
'ContentEncoding': 'foo',
'ContentLanguage': 'foo',
'CacheControl': '90',
'Expires': '0'
}
self.put_object(bucket_name, original_key, contents='foo',
extra_args=metadata)
p = aws('s3 cp s3://%s/%s s3://%s/%s' %
(bucket_name, original_key, bucket_name, new_key))
self.assert_no_errors(p)
response = self.head_object(bucket_name, new_key)
# These values should have the metadata of the source object
metadata_ref = copy.copy(metadata)
metadata_ref['Expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
for name, value in metadata_ref.items():
self.assertEqual(response[name], value)
# Use REPLACE to wipe out all of the metadata when copying to a new
# key.
new_key = '%s-c' % random_chars(6)
p = aws('s3 cp s3://%s/%s s3://%s/%s --metadata-directive REPLACE' %
(bucket_name, original_key, bucket_name, new_key))
self.assert_no_errors(p)
response = self.head_object(bucket_name, new_key)
# Make sure all of the original metadata is gone.
for name, value in metadata_ref.items():
self.assertNotEqual(response.get(name), value)
# Use REPLACE to wipe out all of the metadata but include a new
# metadata value.
new_key = '%s-d' % random_chars(6)
p = aws('s3 cp s3://%s/%s s3://%s/%s --metadata-directive REPLACE '
'--content-type bar' %
(bucket_name, original_key, bucket_name, new_key))
self.assert_no_errors(p)
response = self.head_object(bucket_name, new_key)
# Make sure the content type metadata is included
self.assertEqual(response['ContentType'], 'bar')
# Make sure all of the original metadata is gone.
for name, value in metadata_ref.items():
self.assertNotEqual(response.get(name), value)
def test_cp_with_request_payer(self):
bucket_name = _SHARED_BUCKET
foo_txt = self.files.create_file('foo.txt', 'this is foo.txt')
p = aws('s3 cp %s s3://%s/mykey --request-payer' % (
foo_txt, bucket_name))
# From the S3 API, the only way to for sure know that request payer is
# working is to set up a bucket with request payer and have another
# account with permissions make a request to that bucket. If they
# do not include request payer, they will get an access denied error.
# Setting this up for an integration test would be tricky as it
# requires having/creating another account outside of the one running
# the integration tests. So instead at the very least we want to
# make sure we can use the parameter, have the command run
# successfully, and correctly upload the key to S3.
self.assert_no_errors(p)
self.assertTrue(self.key_exists(bucket_name, key_name='mykey'))
self.assertEqual(
self.get_key_contents(bucket_name, key_name='mykey'),
'this is foo.txt')
class TestSync(BaseS3IntegrationTest):
def test_sync_with_plus_chars_paginate(self):
# This test ensures pagination tokens are url decoded.
# 1. Create > 2 files with '+' in the filename.
# 2. Sync up to s3 while the page size is 2.
# 3. Sync up to s3 while the page size is 2.
# 4. Verify nothing was synced up down from s3 in step 3.
bucket_name = _SHARED_BUCKET
filenames = []
for i in range(4):
# Create a file with a space char and a '+' char in the filename.
# We're interested in testing the filename comparisons, not the
# mtime comparisons so we're setting the mtime to some time
# in the past to avoid mtime comparisons interfering with
# test results.
mtime = time.time() - 300
filenames.append(
self.files.create_file('foo +%06d' % i,
contents='',
mtime=mtime))
p = aws('s3 sync %s s3://%s/ --page-size 2' %
(self.files.rootdir, bucket_name))
self.assert_no_errors(p)
time.sleep(1)
p2 = aws('s3 sync %s s3://%s/ --page-size 2'
% (self.files.rootdir, bucket_name))
self.assertNotIn('upload:', p2.stdout)
self.assertEqual('', p2.stdout)
def test_s3_to_s3_sync_with_plus_char_paginate(self):
keynames = []
for i in range(4):
keyname = 'foo+%d' % i
keynames.append(keyname)
self.files.create_file(keyname, contents='')
bucket_name = _SHARED_BUCKET
bucket_name_2 = self.create_bucket()
p = aws('s3 sync %s s3://%s' % (self.files.rootdir, bucket_name))
self.assert_no_errors(p)
for key in keynames:
self.assertTrue(self.key_exists(bucket_name, key))
p = aws('s3 sync s3://%s/ s3://%s/ --page-size 2' %
(bucket_name, bucket_name_2))
self.assert_no_errors(p)
for key in keynames:
self.assertTrue(self.key_exists(bucket_name_2, key))
p2 = aws('s3 sync s3://%s/ s3://%s/ --page-size 2' %
(bucket_name, bucket_name_2))
self.assertNotIn('copy:', p2.stdout)
self.assertEqual('', p2.stdout)
def test_sync_no_resync(self):
self.files.create_file('xyz123456789', contents='test1')
self.files.create_file(os.path.join('xyz1', 'test'), contents='test2')
self.files.create_file(os.path.join('xyz', 'test'), contents='test3')
bucket_name = _SHARED_BUCKET
p = aws('s3 sync %s s3://%s' % (self.files.rootdir, bucket_name))
self.assert_no_errors(p)
time.sleep(2)
self.assertTrue(self.key_exists(bucket_name, 'xyz123456789'))
self.assertTrue(self.key_exists(bucket_name, 'xyz1/test'))
self.assertTrue(self.key_exists(bucket_name, 'xyz/test'))
p2 = aws('s3 sync %s s3://%s/' % (self.files.rootdir, bucket_name))
self.assertNotIn('upload:', p2.stdout)
self.assertEqual('', p2.stdout)
def test_sync_to_from_s3(self):
bucket_name = _SHARED_BUCKET
foo_txt = self.files.create_file('foo.txt', 'foo contents')
bar_txt = self.files.create_file('bar.txt', 'bar contents')
# Sync the directory and the bucket.
p = aws('s3 sync %s s3://%s' % (self.files.rootdir, bucket_name))
self.assert_no_errors(p)
# Ensure both files are in the bucket.
self.assertTrue(self.key_exists(bucket_name, 'foo.txt'))
self.assertTrue(self.key_exists(bucket_name, 'bar.txt'))
# Sync back down. First remote the local files.
os.remove(foo_txt)
os.remove(bar_txt)
p = aws('s3 sync s3://%s %s' % (bucket_name, self.files.rootdir))
# The files should be back now.
self.assertTrue(os.path.isfile(foo_txt))
self.assertTrue(os.path.isfile(bar_txt))
with open(foo_txt, 'r') as f:
self.assertEqual(f.read(), 'foo contents')
with open(bar_txt, 'r') as f:
self.assertEqual(f.read(), 'bar contents')
def test_sync_to_nonexistent_bucket(self):
self.files.create_file('foo.txt', 'foo contents')
self.files.create_file('bar.txt', 'bar contents')
# Sync the directory and the bucket.
p = aws('s3 sync %s s3://noexist-bkt-nme-1412' % (self.files.rootdir,))
self.assertEqual(p.rc, 1)
def test_sync_with_empty_files(self):
self.files.create_file('foo.txt', 'foo contents')
self.files.create_file('bar.txt', contents='')
bucket_name = _SHARED_BUCKET
p = aws('s3 sync %s s3://%s/' % (self.files.rootdir, bucket_name))
self.assertEqual(p.rc, 0)
self.assertNotIn('failed', p.stderr)
self.assertTrue(
self.key_exists(bucket_name=bucket_name, key_name='bar.txt'))
def test_sync_with_delete_option_with_same_prefix(self):
# Test for issue 440 (https://github.com/aws/aws-cli/issues/440)
# First, we need to create a directory structure that has a dir with
# the same prefix as some of the files:
#
# test/foo.txt
# test-123.txt
# test-321.txt
# test.txt
bucket_name = _SHARED_BUCKET
# create test/foo.txt
nested_dir = os.path.join(self.files.rootdir, 'test')
os.mkdir(nested_dir)
self.files.create_file(os.path.join(nested_dir, 'foo.txt'),
contents='foo.txt contents')
# Then create test-123.txt, test-321.txt, test.txt.
self.files.create_file('test-123.txt', 'test-123.txt contents')
self.files.create_file('test-321.txt', 'test-321.txt contents')
self.files.create_file('test.txt', 'test.txt contents')
# Now sync this content up to s3.
# Allow settling time so that we have a different time between
# source and destination.
time.sleep(2)
p = aws('s3 sync %s s3://%s/' % (self.files.rootdir, bucket_name))
self.assert_no_errors(p)
# Now here's the issue. If we try to sync the contents down
# with the --delete flag we should *not* see any output, the
# sync operation should determine that nothing is different and
# therefore do nothing. We can just use --dryrun to show the issue.
p = aws('s3 sync s3://%s/ %s --dryrun --delete' % (
bucket_name, self.files.rootdir))
self.assert_no_errors(p)
# These assertion methods will give better error messages than just
# checking if the output is empty.
self.assertNotIn('download:', p.stdout)
self.assertNotIn('delete:', p.stdout)
self.assertEqual('', p.stdout)
def test_sync_with_delete_across_sig4_regions(self):
src_region = 'us-west-2'
dst_region = 'eu-central-1'
src_bucket = self.create_bucket(region=src_region)
dst_bucket = self.create_bucket(region=dst_region)
src_key_name = 'hello.txt'
self.files.create_file(src_key_name, contents='hello')
p = aws('s3 sync %s s3://%s --region %s' %
(self.files.rootdir, src_bucket, src_region))
self.assert_no_errors(p)
self.assertTrue(self.key_exists(src_bucket, src_key_name))
self.files.remove_all()
dst_key_name = 'goodbye.txt'
self.files.create_file(dst_key_name, contents='goodbye')
p = aws('s3 sync %s s3://%s --region %s' %
(self.files.rootdir, dst_bucket, dst_region))
self.assert_no_errors(p)
self.assertTrue(self.key_exists(dst_bucket, dst_key_name))
self.assertTrue(self.key_not_exists(dst_bucket, src_key_name))
p = aws('s3 sync --delete s3://%s s3://%s '
'--source-region %s --region %s' %
(src_bucket, dst_bucket, src_region, dst_region))
self.assert_no_errors(p)
self.assertTrue(self.key_exists(src_bucket, src_key_name))
self.assertTrue(self.key_exists(dst_bucket, src_key_name))
self.assertTrue(self.key_not_exists(src_bucket, dst_key_name))
self.assertTrue(self.key_not_exists(dst_bucket, dst_key_name))
def test_sync_delete_locally(self):
bucket_name = _SHARED_BUCKET
file_to_delete = self.files.create_file(
'foo.txt', contents='foo contents')
self.put_object(bucket_name, 'bar.txt', contents='bar contents')
p = aws('s3 sync s3://%s/ %s --delete' % (
bucket_name, self.files.rootdir))
self.assert_no_errors(p)
# Make sure the uploaded file got downloaded and the previously
# existing local file got deleted
self.assertTrue(os.path.exists(
os.path.join(self.files.rootdir, 'bar.txt')))
self.assertFalse(os.path.exists(file_to_delete))
class TestSourceRegion(BaseS3IntegrationTest):
def extra_setup(self):
name_comp = []
# This creates a non DNS compatible bucket name by making two random
# sequences of characters and joining them with a period and
# adding a .com at the end.
for i in range(2):
name_comp.append(random_chars(10))
self.src_name = '.'.join(name_comp + ['com'])
name_comp = []
for i in range(2):
name_comp.append(random_chars(10))
self.dest_name = '.'.join(name_comp + ['com'])
self.src_region = 'us-west-1'
self.dest_region = 'us-east-1'
self.src_bucket = self.create_bucket(self.src_name, self.src_region)
self.dest_bucket = self.create_bucket(self.dest_name, self.dest_region)
def test_cp_region(self):
self.files.create_file('foo.txt', 'foo')
p = aws('s3 sync %s s3://%s/ --region %s' %
(self.files.rootdir, self.src_bucket, self.src_region))
self.assert_no_errors(p)
p2 = aws('s3 cp s3://%s/ s3://%s/ --region %s --source-region %s '
'--recursive' %
(self.src_bucket, self.dest_bucket, self.dest_region,
self.src_region))
self.assertEqual(p2.rc, 0, p2.stdout)
self.assertTrue(
self.key_exists(bucket_name=self.dest_bucket, key_name='foo.txt'))
def test_sync_region(self):
self.files.create_file('foo.txt', 'foo')
p = aws('s3 sync %s s3://%s/ --region %s' %
(self.files.rootdir, self.src_bucket, self.src_region))
self.assert_no_errors(p)
p2 = aws('s3 sync s3://%s/ s3://%s/ --region %s --source-region %s ' %
(self.src_bucket, self.dest_bucket, self.dest_region,
self.src_region))
self.assertEqual(p2.rc, 0, p2.stdout)
self.assertTrue(
self.key_exists(bucket_name=self.dest_bucket, key_name='foo.txt'))
def test_mv_region(self):
self.files.create_file('foo.txt', 'foo')
p = aws('s3 sync %s s3://%s/ --region %s' %
(self.files.rootdir, self.src_bucket, self.src_region))
self.assert_no_errors(p)
p2 = aws('s3 mv s3://%s/ s3://%s/ --region %s --source-region %s '
'--recursive' %
(self.src_bucket, self.dest_bucket, self.dest_region,
self.src_region))
self.assertEqual(p2.rc, 0, p2.stdout)
self.assertTrue(
self.key_exists(bucket_name=self.dest_bucket, key_name='foo.txt'))
self.assertTrue(
self.key_not_exists(
bucket_name=self.src_bucket, key_name='foo.txt'))
@pytest.mark.slow
def test_mv_large_file_region(self):
foo_txt = self.files.create_file('foo.txt', 'a' * 1024 * 1024 * 10)
p = aws('s3 cp %s s3://%s/foo.txt --region %s' %
(foo_txt, self.src_bucket, self.src_region))
self.assert_no_errors(p)
p2 = aws(
's3 mv s3://%s/foo.txt s3://%s/ --region %s --source-region %s ' %
(self.src_bucket, self.dest_bucket, self.dest_region,
self.src_region)
)
self.assert_no_errors(p2)
self.assertTrue(
self.key_exists(bucket_name=self.dest_bucket, key_name='foo.txt'))
self.assertTrue(
self.key_not_exists(
bucket_name=self.src_bucket, key_name='foo.txt'))
class TestWarnings(BaseS3IntegrationTest):
def test_no_exist(self):
bucket_name = _SHARED_BUCKET
filename = os.path.join(self.files.rootdir, "no-exists-file")
p = aws('s3 cp %s s3://%s/' % (filename, bucket_name))
# If the local path provided by the user is nonexistent for an
# upload, this should error out.
self.assertEqual(p.rc, 255, p.stderr)
self.assertIn('The user-provided path %s does not exist.' %
filename, p.stderr)
@skip_if_windows('Read permissions tests only supported on mac/linux')
def test_no_read_access(self):