File: test_plugin.py

package info (click to toggle)
awscli 2.31.35-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 156,692 kB
  • sloc: python: 213,816; xml: 14,082; makefile: 189; sh: 178; javascript: 8
file content (2432 lines) | stat: -rw-r--r-- 92,270 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
# 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 contextlib
import copy
import datetime
import os
import platform
import re
import signal
import socket
import stat
import tempfile
import time

import pytest
from dateutil.tz import tzutc

from awscli.compat import BytesIO, urlopen
from awscli.customizations.s3.transferconfig import DEFAULTS
from awscli.testutils import aws as _aws
from awscli.testutils import (
    get_stdout_encoding,
    random_bucket_name,
    random_chars,
    skip_if_windows,
    unittest,
)
from tests.integration.customizations.s3 import BaseS3IntegrationTest

_NON_EXISTENT_BUCKET = random_bucket_name()


@pytest.fixture
def symlink_files(files):
    nested_dir = os.path.join(files.rootdir, 'realfiles')
    os.mkdir(nested_dir)
    sample_file = files.create_file(
        os.path.join(nested_dir, 'foo.txt'), contents='foo.txt contents'
    )
    # Create a symlink to foo.txt.
    os.symlink(sample_file, os.path.join(files.rootdir, 'a-goodsymlink'))
    # Create a bad symlink.
    os.symlink(
        'non-existent-file', os.path.join(files.rootdir, 'b-badsymlink')
    )
    # Create a symlink to directory where foo.txt is.
    os.symlink(nested_dir, os.path.join(files.rootdir, 'c-goodsymlink'))


@pytest.fixture
def config_with_profile(session, files):
    config_file = os.path.join(files.rootdir, 'tmpconfig')
    with open(config_file, 'w') as f:
        creds = session.get_credentials()
        f.write(
            "[profile testprofile]\n"
            "aws_access_key_id=%s\n"
            "aws_secret_access_key=%s\n" % (creds.access_key, creds.secret_key)
        )
        if creds.token is not None:
            f.write("aws_session_token=%s\n" % creds.token)
        f.flush()
    yield config_file


@pytest.fixture
def aws_config_copy(monkeypatch, tmpdir, session):
    config_contents = _get_config_contents(session)
    tmp_config_file = os.path.join(tmpdir, 'config')
    with open(tmp_config_file, 'w') as f:
        f.write(config_contents)
        f.flush()
    monkeypatch.setenv('AWS_CONFIG_FILE', tmp_config_file)
    yield tmp_config_file


def _get_config_contents(session):
    config_file = session.get_config_variable('config_file')
    if config_file:
        config_path = os.path.expanduser(os.path.expandvars(config_file))
        if os.path.exists(config_path):
            with open(config_path) as f:
                return f.read()
    return ''


@pytest.fixture
def preferred_transfer_client(request, aws_config_copy):
    configure_preferred_transfer_client(request.param)


@pytest.fixture
def encrypt_key():
    return 'a' * 32


@pytest.fixture
def other_encrypt_key():
    return 'b' * 32


@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 configure_preferred_transfer_client(value):
    aws(f'configure set s3.preferred_transfer_client {value}')


def _running_on_rhel():
    return (
        hasattr(platform, 'linux_distribution')
        and platform.linux_distribution()[0]
        == 'Red Hat Enterprise Linux Server'
    )


@pytest.mark.parametrize(
    'preferred_transfer_client', ['classic', 'crt'], indirect=True
)
@pytest.mark.usefixtures('preferred_transfer_client')
class BaseParameterizedS3ClientTest(BaseS3IntegrationTest):
    # Use this base class if you want to run tests once for
    # when the preferred_transfer_client is set to default and
    # once when the preferred_transfer_client is set to crt.
    pass


class TestMoveCommand(BaseParameterizedS3ClientTest):
    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_mv_local_to_s3(self, s3_bucket, files, s3_utils, request):
        shared_bucket = request.getfixturevalue(s3_bucket)
        full_path = files.create_file('foo.txt', 'this is foo.txt')
        p = aws('s3 mv %s s3://%s/foo.txt' % (full_path, shared_bucket))
        self.assert_no_errors(p)
        # When we move an object, the local file is gone:
        assert not os.path.exists(full_path)
        # And now resides in s3.
        s3_utils.assert_key_contents_equal(
            shared_bucket, 'foo.txt', 'this is foo.txt'
        )

    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_mv_s3_to_local(self, s3_bucket, files, s3_utils, request):
        shared_bucket = request.getfixturevalue(s3_bucket)
        s3_utils.put_object(shared_bucket, 'foo.txt', 'this is foo.txt')
        full_path = files.full_path(f'{s3_bucket}_foo.txt')
        assert s3_utils.key_exists(shared_bucket, key_name='foo.txt')
        p = aws('s3 mv s3://%s/foo.txt %s' % (shared_bucket, full_path))
        self.assert_no_errors(p)
        assert os.path.exists(full_path)
        with open(full_path) as f:
            assert f.read() == 'this is foo.txt'
        # The s3 file should not be there anymore.
        assert s3_utils.key_not_exists(shared_bucket, key_name='foo.txt')

    @pytest.mark.parametrize(
        's3_bucket, copy_s3_bucket',
        [
            ('shared_bucket', 'shared_copy_bucket'),
            ('shared_bucket', 'shared_copy_dir_bucket'),
            ('shared_dir_bucket', 'shared_copy_dir_bucket'),
            ('shared_dir_bucket', 'shared_copy_bucket'),
        ],
    )
    def test_mv_s3_to_s3(self, s3_bucket, copy_s3_bucket, s3_utils, request):
        from_bucket = request.getfixturevalue(s3_bucket)
        to_bucket = request.getfixturevalue(copy_s3_bucket)
        from_key = f'{s3_bucket}_foo.txt'
        to_key = f'{copy_s3_bucket}_foo.txt'
        s3_utils.put_object(from_bucket, from_key, 'this is foo.txt')

        p = aws(
            f"s3 mv s3://{from_bucket}/{from_key} s3://{to_bucket}/{to_key}"
        )

        self.assert_no_errors(p)
        contents = s3_utils.get_key_contents(to_bucket, to_key)
        assert contents == 'this is foo.txt'
        # And verify that the object no longer exists in the from_bucket.
        assert s3_utils.key_not_exists(from_bucket, key_name=from_key)

    @pytest.mark.slow
    def test_mv_s3_to_s3_multipart(
        self, s3_utils, shared_bucket, shared_copy_bucket
    ):
        from_bucket = shared_bucket
        to_bucket = shared_copy_bucket
        file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
        s3_utils.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)
        s3_utils.assert_key_contents_equal(to_bucket, 'foo.txt', file_contents)
        # And verify that the object no longer exists in the from_bucket.
        assert s3_utils.key_not_exists(from_bucket, key_name='foo.txt')

    def test_mv_s3_to_s3_multipart_recursive(
        self, s3_utils, shared_bucket, shared_copy_bucket
    ):
        from_bucket = shared_bucket
        to_bucket = shared_copy_bucket

        large_file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
        small_file_contents = 'small file contents'
        s3_utils.put_object(from_bucket, 'largefile', large_file_contents)
        s3_utils.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.
        assert s3_utils.key_not_exists(from_bucket, key_name='largefile')
        assert s3_utils.key_not_exists(from_bucket, key_name='smallfile')

        # And both files are in the to_bucket.
        assert s3_utils.key_exists(to_bucket, key_name='largefile')
        assert s3_utils.key_exists(to_bucket, key_name='smallfile')

        # And the contents are what we expect.
        s3_utils.assert_key_contents_equal(
            to_bucket, 'smallfile', small_file_contents
        )
        s3_utils.assert_key_contents_equal(
            to_bucket, 'largefile', large_file_contents
        )

    def test_mv_s3_to_s3_with_sig4(
        self, s3_utils, shared_bucket, shared_cross_region_bucket
    ):
        to_region = 'eu-central-1'
        from_region = 'us-west-2'

        from_bucket = shared_bucket
        to_bucket = shared_cross_region_bucket

        file_name = 'hello.txt'
        file_contents = 'hello'
        s3_utils.put_object(from_bucket, file_name, file_contents)

        p = aws(
            f's3 mv s3://{from_bucket}/{file_name} s3://{to_bucket}/{file_name} '
            f'--source-region {from_region} --region {to_region}'
        )
        self.assert_no_errors(p)

        assert s3_utils.key_not_exists(from_bucket, file_name)
        assert s3_utils.key_exists(to_bucket, file_name)

    def test_mv_with_large_file(self, files, s3_utils, shared_bucket):
        # 40MB will force a multipart upload.
        file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
        foo_txt = files.create_file(
            'foo.txt', file_contents.getvalue().decode('utf-8')
        )
        p = aws('s3 mv %s s3://%s/foo.txt' % (foo_txt, shared_bucket))
        self.assert_no_errors(p)
        # When we move an object, the local file is gone:
        assert not os.path.exists(foo_txt)
        # And now resides in s3.
        s3_utils.assert_key_contents_equal(
            shared_bucket, 'foo.txt', file_contents
        )

        # Now verify we can download this file.
        p = aws('s3 mv s3://%s/foo.txt %s' % (shared_bucket, foo_txt))
        self.assert_no_errors(p)
        assert os.path.exists(foo_txt)
        assert os.path.getsize(foo_txt) == len(file_contents.getvalue())

    def test_mv_to_nonexistent_bucket(self, files):
        full_path = files.create_file('foo.txt', 'this is foo.txt')
        p = aws(f's3 mv {full_path} s3://{_NON_EXISTENT_BUCKET}/foo.txt')
        assert p.rc == 1

    def test_cant_move_file_onto_itself_small_file(
        self, s3_utils, shared_bucket
    ):
        # We don't even need a remote file in this case.  We can
        # immediately validate that we can't move a file onto itself.
        s3_utils.put_object(shared_bucket, key_name='key.txt', contents='foo')
        p = aws(
            's3 mv s3://%s/key.txt s3://%s/key.txt'
            % (shared_bucket, shared_bucket)
        )
        assert p.rc == 252
        assert 'Cannot mv a file onto itself' in p.stderr

    def test_cant_move_large_file_onto_itself(self, s3_utils, shared_bucket):
        # 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))
        s3_utils.put_object(
            shared_bucket, key_name='key.txt', contents=file_contents
        )
        p = aws(
            's3 mv s3://%s/key.txt s3://%s/key.txt'
            % (shared_bucket, shared_bucket)
        )
        assert p.rc == 252
        assert 'Cannot mv a file onto itself' in p.stderr


class TestRm(BaseParameterizedS3ClientTest):
    @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, files, s3_utils, shared_bucket):
        # Note the carriage return in the key name.
        foo_txt = files.create_file('foo\r.txt', 'this is foo.txt')
        p = aws('s3 cp %s s3://%s/foo\r.txt' % (foo_txt, shared_bucket))
        self.assert_no_errors(p)

        # Make sure object is in bucket.
        assert s3_utils.key_exists(shared_bucket, key_name='foo\r.txt')

        # Then delete the file.
        aws('s3 rm s3://%s/ --recursive' % (shared_bucket,))

        # And verify it's gone.
        assert s3_utils.key_not_exists(shared_bucket, key_name='foo\r.txt')

    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_rm_with_page_size(self, s3_bucket, s3_utils, request):
        shared_bucket = request.getfixturevalue(s3_bucket)
        s3_utils.put_object(shared_bucket, 'foo.txt', contents='hello world')
        s3_utils.put_object(shared_bucket, 'bar.txt', contents='hello world2')
        p = aws('s3 rm s3://%s/ --recursive --page-size 1' % shared_bucket)
        self.assert_no_errors(p)

        assert s3_utils.key_not_exists(shared_bucket, key_name='foo.txt')
        assert s3_utils.key_not_exists(shared_bucket, key_name='bar.txt')


class TestCp(BaseParameterizedS3ClientTest):
    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_cp_to_and_from_s3(self, s3_bucket, files, s3_utils, request):
        # This tests the ability to put a single file in s3
        # move it to a different bucket.
        # and download the file locally
        shared_bucket = request.getfixturevalue(s3_bucket)

        # copy file into bucket.
        foo_txt = files.create_file(f'{s3_bucket}_foo.txt', 'this is foo.txt')
        p = aws('s3 cp %s s3://%s/foo.txt' % (foo_txt, shared_bucket))
        self.assert_no_errors(p)

        # Make sure object is in bucket.
        assert s3_utils.key_exists(shared_bucket, key_name='foo.txt')
        contents = s3_utils.get_key_contents(shared_bucket, key_name='foo.txt')
        assert contents == 'this is foo.txt'
        content_type = s3_utils.content_type_for_key(
            shared_bucket, key_name='foo.txt'
        )
        assert content_type == 'text/plain'

        # Make a new name for the file and copy it locally.
        full_path = files.full_path(f'{s3_bucket}_bar.txt')
        p = aws('s3 cp s3://%s/foo.txt %s' % (shared_bucket, full_path))
        self.assert_no_errors(p)

        with open(full_path) as f:
            assert f.read() == 'this is foo.txt'

    def test_cp_without_trailing_slash(self, files, s3_utils, shared_bucket):
        # There's a unit test for this, but we still want to verify this
        # with an integration test.

        # copy file into bucket.
        foo_txt = 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, shared_bucket))
        self.assert_no_errors(p)

        # Make sure object is in bucket.
        assert s3_utils.key_exists(shared_bucket, key_name='foo.txt')
        contents = s3_utils.get_key_contents(shared_bucket, key_name='foo.txt')
        assert contents == 'this is foo.txt'

    @pytest.mark.slow
    def test_cp_s3_s3_multipart(
        self, s3_utils, shared_bucket, shared_copy_bucket
    ):
        from_bucket = shared_bucket
        to_bucket = shared_copy_bucket
        file_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
        s3_utils.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)
        s3_utils.assert_key_contents_equal(to_bucket, 'foo.txt', file_contents)
        assert s3_utils.key_exists(from_bucket, key_name='foo.txt')

    def test_guess_mime_type(self, files, s3_utils, shared_bucket):
        bar_png = files.create_file('bar.jpeg', 'fake png image')
        p = aws('s3 cp %s s3://%s/bar.jpeg' % (bar_png, shared_bucket))
        self.assert_no_errors(p)

        # We should have correctly guessed the content type based on the
        # filename extension.
        content_type = s3_utils.content_type_for_key(
            shared_bucket, key_name='bar.jpeg'
        )
        assert content_type == 'image/jpeg'

    def test_download_large_file(self, files, s3_utils, shared_bucket):
        # This will force a multipart download.
        foo_contents = BytesIO(b'abcd' * (1024 * 1024 * 10))
        s3_utils.put_object(
            shared_bucket, key_name='foo.txt', contents=foo_contents
        )
        local_foo_txt = files.full_path('foo.txt')
        p = aws('s3 cp s3://%s/foo.txt %s' % (shared_bucket, local_foo_txt))
        self.assert_no_errors(p)
        assert os.path.getsize(local_foo_txt) == len(foo_contents.getvalue())

    @skip_if_windows('SIGINT not supported on Windows.')
    def test_download_ctrl_c_does_not_hang(
        self, files, s3_utils, shared_bucket
    ):
        foo_contents = BytesIO(b'abcd' * (1024 * 1024 * 40))
        s3_utils.put_object(
            shared_bucket, key_name='foo.txt', contents=foo_contents
        )
        local_foo_txt = 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'
            % (shared_bucket, 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.
        assert process.returncode in [0, 1, -2]

    @skip_if_windows('SIGINT not supported on Windows.')
    def test_cleans_up_aborted_uploads(self, files, s3_utils, shared_bucket):
        foo_txt = 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, shared_bucket),
            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 = s3_utils.list_multipart_uploads(shared_bucket)
        assert uploads_after == [], (
            f"Not all multipart uploads were properly "
            f"aborted after receiving Ctrl-C: {uploads_after}"
        )

    def test_cp_to_nonexistent_bucket(self, files):
        foo_txt = files.create_file('foo.txt', 'this is foo.txt')
        p = aws(f's3 cp {foo_txt} s3://{_NON_EXISTENT_BUCKET}/foo.txt')
        assert p.rc == 1

    def test_cp_empty_file(self, files, s3_utils, shared_bucket):
        foo_txt = files.create_file('foo.txt', contents='')
        p = aws('s3 cp %s s3://%s/' % (foo_txt, shared_bucket))
        assert p.rc == 0
        assert 'failed' not in p.stderr
        assert s3_utils.key_exists(shared_bucket, 'foo.txt')

    def test_download_non_existent_key(self):
        p = aws(f's3 cp s3://{_NON_EXISTENT_BUCKET}/foo.txt foo.txt')
        assert p.rc == 1
        expected_err_msg = (
            'An error occurred (404) when calling the '
            'HeadObject operation: Key "foo.txt" does not exist'
        )
        assert expected_err_msg in p.stderr

    def test_download_encrypted_kms_object(
        self, s3_utils, files, shared_cross_region_bucket
    ):
        bucket_name = shared_cross_region_bucket
        extra_args = {
            'ServerSideEncryption': 'aws:kms',
            'SSEKMSKeyId': 'alias/aws/s3',
        }
        object_name = 'foo.txt'
        contents = 'this is foo.txt'
        s3_utils.put_object(
            bucket_name, object_name, contents, extra_args=extra_args
        )
        local_filename = files.full_path('foo.txt')
        p = aws(
            's3 cp s3://%s/%s %s --region eu-central-1'
            % (bucket_name, object_name, local_filename)
        )
        assert p.rc == 0
        # Assert that the file was downloaded properly.
        with open(local_filename) as f:
            assert f.read() == contents

    def test_download_empty_object(self, files, s3_utils, shared_bucket):
        object_name = 'empty-object'
        s3_utils.put_object(shared_bucket, object_name, '')
        local_filename = files.full_path('empty.txt')
        p = aws(
            's3 cp s3://%s/%s %s'
            % (shared_bucket, object_name, local_filename)
        )
        assert p.rc == 0
        # Assert that the file was downloaded and has no content.
        with open(local_filename) as f:
            assert f.read() == ''

    def test_website_redirect_ignore_paramfile(
        self, files, s3_utils, shared_bucket
    ):
        foo_txt = files.create_file('foo.txt', 'bar')
        website_redirect = 'http://someserver'
        p = aws(
            's3 cp %s s3://%s/foo.txt --website-redirect %s'
            % (foo_txt, shared_bucket, 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 = s3_utils.head_object(shared_bucket, 'foo.txt')
        assert response['WebsiteRedirectLocation'] == website_redirect

    def test_copy_large_file_signature_v4(
        self, s3_utils, files, shared_cross_region_bucket
    ):
        # Just verify that we can upload a large file to a region
        # that uses signature version 4.
        bucket_name = shared_cross_region_bucket
        num_mb = 200
        foo_txt = 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)
        assert s3_utils.key_exists(bucket_name, key_name='foo.txt')

    def test_copy_metadata(self, s3_utils, files, shared_bucket):
        # Copy the same style of parsing as the CLI session. This is needed
        # For comparing expires timestamp.
        key = random_chars(6)
        filename = files.create_file(key, contents='')
        p = aws(
            's3 cp %s s3://%s/%s --metadata keyname=value'
            % (filename, shared_bucket, key)
        )
        self.assert_no_errors(p)
        response = s3_utils.head_object(shared_bucket, key)
        # These values should have the metadata of the source object
        assert response['Metadata'].get('keyname') == 'value'

    def test_copy_metadata_directive(self, s3_utils, shared_bucket):
        # Copy the same style of parsing as the CLI session. This is needed
        # For comparing expires timestamp.
        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',
        }
        s3_utils.put_object(
            shared_bucket, original_key, contents='foo', extra_args=metadata
        )
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s'
            % (shared_bucket, original_key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)
        response = s3_utils.head_object(shared_bucket, new_key)
        # These values should have the metadata of the source object
        metadata_ref = copy.copy(metadata)
        expires_datetime = datetime.datetime.utcfromtimestamp(0)
        expires_datetime = expires_datetime.replace(tzinfo=tzutc())
        metadata_ref['Expires'] = expires_datetime
        for name, value in metadata_ref.items():
            assert 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'
            % (shared_bucket, original_key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)
        response = s3_utils.head_object(shared_bucket, new_key)
        # Make sure all of the original metadata is gone.
        for name, value in metadata_ref.items():
            assert 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'
            % (shared_bucket, original_key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)
        response = s3_utils.head_object(shared_bucket, new_key)
        # Make sure the content type metadata is included
        assert response['ContentType'] == 'bar'
        # Make sure all of the original metadata is gone.
        for name, value in metadata_ref.items():
            assert response.get(name) != value

    def test_cp_with_request_payer(self, files, s3_utils, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'this is foo.txt')
        p = aws(
            's3 cp %s s3://%s/mykey --request-payer' % (foo_txt, shared_bucket)
        )

        # 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)
        assert s3_utils.key_exists(shared_bucket, key_name='mykey')
        contents = s3_utils.get_key_contents(shared_bucket, key_name='mykey')
        assert contents == 'this is foo.txt'


class TestSync(BaseParameterizedS3ClientTest):
    def test_sync_with_plus_chars_paginate(self, files, shared_bucket):
        # 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.
        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(
                files.create_file('foo +%06d' % i, contents='', mtime=mtime)
            )
        p = aws(
            's3 sync %s s3://%s/ --page-size 2'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        time.sleep(1)
        p2 = aws(
            's3 sync %s s3://%s/ --page-size 2'
            % (files.rootdir, shared_bucket)
        )
        assert 'upload:' not in p2.stdout
        assert '' == p2.stdout

    def test_s3_to_s3_sync_with_plus_char_paginate(
        self, files, s3_utils, shared_bucket, shared_copy_bucket
    ):
        keynames = []
        for i in range(4):
            keyname = 'foo+%d' % i
            keynames.append(keyname)
            files.create_file(keyname, contents='')

        bucket_name = shared_bucket
        bucket_name_2 = shared_copy_bucket

        p = aws('s3 sync %s s3://%s' % (files.rootdir, bucket_name))
        self.assert_no_errors(p)
        for key in keynames:
            assert s3_utils.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:
            assert s3_utils.key_exists(bucket_name_2, key)

        p2 = aws(
            's3 sync s3://%s/ s3://%s/ --page-size 2'
            % (bucket_name, bucket_name_2)
        )
        assert 'copy:' not in p2.stdout
        assert '' == p2.stdout

    def test_sync_no_resync(self, files, s3_utils, shared_bucket):
        files.create_file('xyz123456789', contents='test1')
        files.create_file(os.path.join('xyz1', 'test'), contents='test2')
        files.create_file(os.path.join('xyz', 'test'), contents='test3')

        p = aws('s3 sync %s s3://%s' % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)
        time.sleep(2)
        assert s3_utils.key_exists(shared_bucket, 'xyz123456789')
        assert s3_utils.key_exists(shared_bucket, 'xyz1/test')
        assert s3_utils.key_exists(shared_bucket, 'xyz/test')

        p2 = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        assert 'upload:' not in p2.stdout
        assert '' == p2.stdout

    def test_sync_to_from_s3(self, files, s3_utils, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')
        bar_txt = files.create_file('bar.txt', 'bar contents')

        # Sync the directory and the bucket.
        p = aws('s3 sync %s s3://%s' % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)

        # Ensure both files are in the bucket.
        assert s3_utils.key_exists(shared_bucket, 'foo.txt')
        assert s3_utils.key_exists(shared_bucket, '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' % (shared_bucket, files.rootdir))
        # The files should be back now.
        assert os.path.isfile(foo_txt)
        assert os.path.isfile(bar_txt)
        with open(foo_txt) as f:
            assert f.read() == 'foo contents'
        with open(bar_txt) as f:
            assert f.read() == 'bar contents'

    def test_sync_to_nonexistent_bucket(self, files):
        files.create_file('foo.txt', 'foo contents')
        files.create_file('bar.txt', 'bar contents')

        # Sync the directory and the bucket.
        p = aws(f's3 sync {files.rootdir} s3://{_NON_EXISTENT_BUCKET}')
        assert p.rc == 1

    def test_sync_with_empty_files(self, files, s3_utils, shared_bucket):
        files.create_file('foo.txt', 'foo contents')
        files.create_file('bar.txt', contents='')
        p = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        assert p.rc == 0
        assert 'failed' not in p.stderr
        assert s3_utils.key_exists(shared_bucket, 'bar.txt')

    def test_sync_with_delete_option_with_same_prefix(
        self, files, shared_bucket
    ):
        # 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
        # create test/foo.txt
        nested_dir = os.path.join(files.rootdir, 'test')
        os.mkdir(nested_dir)
        files.create_file(
            os.path.join(nested_dir, 'foo.txt'), contents='foo.txt contents'
        )
        # Then create test-123.txt, test-321.txt, test.txt.
        files.create_file('test-123.txt', 'test-123.txt contents')
        files.create_file('test-321.txt', 'test-321.txt contents')
        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/' % (files.rootdir, shared_bucket))
        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'
            % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)
        # These assertion methods will give better error messages than just
        # checking if the output is empty.
        assert 'download:' not in p.stdout
        assert 'delete:' not in p.stdout
        assert '' == p.stdout

    def test_sync_with_delete_across_sig4_regions(
        self, files, s3_utils, shared_bucket, shared_cross_region_bucket
    ):
        src_region = 'us-west-2'
        dst_region = 'eu-central-1'

        src_bucket = shared_bucket
        dst_bucket = shared_cross_region_bucket

        src_key_name = 'hello.txt'
        files.create_file(src_key_name, contents='hello')

        p = aws(
            's3 sync %s s3://%s --region %s'
            % (files.rootdir, src_bucket, src_region)
        )
        self.assert_no_errors(p)
        assert s3_utils.key_exists(src_bucket, src_key_name)

        files.remove_all()

        dst_key_name = 'goodbye.txt'
        files.create_file(dst_key_name, contents='goodbye')

        p = aws(
            's3 sync %s s3://%s --region %s'
            % (files.rootdir, dst_bucket, dst_region)
        )
        self.assert_no_errors(p)
        assert s3_utils.key_exists(dst_bucket, dst_key_name)
        assert s3_utils.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)

        assert s3_utils.key_exists(src_bucket, src_key_name)
        assert s3_utils.key_exists(dst_bucket, src_key_name)
        assert s3_utils.key_not_exists(src_bucket, dst_key_name)
        assert s3_utils.key_not_exists(dst_bucket, dst_key_name)

    def test_sync_delete_locally(self, files, s3_utils, shared_bucket):
        file_to_delete = files.create_file('foo.txt', contents='foo contents')
        s3_utils.put_object(shared_bucket, 'bar.txt', contents='bar contents')

        p = aws(
            's3 sync s3://%s/ %s --delete' % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)

        # Make sure the uploaded file got downloaded and the previously
        # existing local file got deleted
        assert os.path.exists(os.path.join(files.rootdir, 'bar.txt'))
        assert not os.path.exists(file_to_delete)


class TestSourceRegion(BaseParameterizedS3ClientTest):
    def test_cp_region(
        self,
        files,
        s3_utils,
        shared_non_dns_compatible_bucket,
        shared_non_dns_compatible_us_east_1_bucket,
    ):
        src_region = 'us-west-2'
        src_bucket = shared_non_dns_compatible_bucket
        dest_region = 'us-east-1'
        dest_bucket = shared_non_dns_compatible_us_east_1_bucket
        files.create_file('foo.txt', 'foo')
        p = aws(
            's3 sync %s s3://%s/ --region %s'
            % (files.rootdir, src_bucket, src_region)
        )
        self.assert_no_errors(p)
        p2 = aws(
            's3 cp s3://%s/ s3://%s/ --region %s --source-region %s '
            '--recursive' % (src_bucket, dest_bucket, dest_region, src_region)
        )
        assert p2.rc == 0, p2.stdout
        assert s3_utils.key_exists(dest_bucket, 'foo.txt')

    def test_sync_region(
        self,
        files,
        s3_utils,
        shared_non_dns_compatible_bucket,
        shared_non_dns_compatible_us_east_1_bucket,
    ):
        src_region = 'us-west-2'
        src_bucket = shared_non_dns_compatible_bucket
        dest_region = 'us-east-1'
        dest_bucket = shared_non_dns_compatible_us_east_1_bucket
        files.create_file('foo.txt', 'foo')
        p = aws(
            's3 sync %s s3://%s/ --region %s'
            % (files.rootdir, src_bucket, src_region)
        )
        self.assert_no_errors(p)
        p2 = aws(
            's3 sync s3://%s/ s3://%s/ --region %s --source-region %s '
            % (src_bucket, dest_bucket, dest_region, src_region)
        )
        assert p2.rc == 0, p2.stdout
        assert s3_utils.key_exists(dest_bucket, 'foo.txt')

    def test_mv_region(
        self,
        files,
        s3_utils,
        shared_non_dns_compatible_bucket,
        shared_non_dns_compatible_us_east_1_bucket,
    ):
        src_region = 'us-west-2'
        src_bucket = shared_non_dns_compatible_bucket
        dest_region = 'us-east-1'
        dest_bucket = shared_non_dns_compatible_us_east_1_bucket
        files.create_file('foo.txt', 'foo')
        p = aws(
            's3 sync %s s3://%s/ --region %s'
            % (files.rootdir, src_bucket, src_region)
        )
        self.assert_no_errors(p)
        p2 = aws(
            's3 mv s3://%s/ s3://%s/ --region %s --source-region %s '
            '--recursive' % (src_bucket, dest_bucket, dest_region, src_region)
        )
        assert p2.rc == 0, p2.stdout
        assert s3_utils.key_exists(dest_bucket, 'foo.txt')
        assert s3_utils.key_not_exists(src_bucket, 'foo.txt')

    def test_mv_large_file_region(
        self,
        files,
        s3_utils,
        shared_non_dns_compatible_bucket,
        shared_non_dns_compatible_us_east_1_bucket,
    ):
        src_region = 'us-west-2'
        src_bucket = shared_non_dns_compatible_bucket
        dest_region = 'us-east-1'
        dest_bucket = shared_non_dns_compatible_us_east_1_bucket
        foo_txt = files.create_file('foo.txt', 'a' * 1024 * 1024 * 10)
        p = aws(
            's3 cp %s s3://%s/foo.txt --region %s'
            % (foo_txt, src_bucket, src_region)
        )
        self.assert_no_errors(p)

        p2 = aws(
            's3 mv s3://%s/foo.txt s3://%s/ --region %s --source-region %s '
            % (src_bucket, dest_bucket, dest_region, src_region)
        )
        self.assert_no_errors(p2)
        assert s3_utils.key_exists(dest_bucket, 'foo.txt')
        assert s3_utils.key_not_exists(src_bucket, 'foo.txt')


class TestWarnings(BaseParameterizedS3ClientTest):
    def test_no_exist(self, files, shared_bucket):
        filename = os.path.join(files.rootdir, "no-exists-file")
        p = aws('s3 cp %s s3://%s/' % (filename, shared_bucket))
        # If the local path provided by the user is nonexistant for an
        # upload, this should error out.
        assert p.rc == 255, p.stderr
        assert f'The user-provided path {filename} does not exist.' in p.stderr

    @skip_if_windows('Read permissions tests only supported on mac/linux')
    def test_no_read_access(self, files, shared_bucket):
        if os.geteuid() == 0:
            pytest.skip('Cannot completely remove read access as root user.')
        files.create_file('foo.txt', 'foo')
        filename = os.path.join(files.rootdir, 'foo.txt')
        permissions = stat.S_IMODE(os.stat(filename).st_mode)
        # Remove read permissions
        permissions = permissions ^ stat.S_IREAD
        os.chmod(filename, permissions)
        p = aws('s3 cp %s s3://%s/' % (filename, shared_bucket))
        assert p.rc == 2, p.stderr
        warning_msg = (
            f'warning: Skipping file {filename}. File/Directory is '
            f'not readable.'
        )
        assert warning_msg in p.stderr

    @skip_if_windows('Special files only supported on mac/linux')
    def test_is_special_file(self, files, shared_bucket):
        file_path = os.path.join(files.rootdir, 'foo')
        # Use socket for special file.
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.bind(file_path)
        p = aws('s3 cp %s s3://%s/' % (file_path, shared_bucket))
        assert p.rc == 2, p.stderr
        warning_msg = (
            f"warning: Skipping file {file_path}. File is character "
            f"special device, block special device, FIFO, or "
            f"socket."
        )
        assert warning_msg in p.stderr


class TestUnableToWriteToFile(BaseParameterizedS3ClientTest):
    @skip_if_windows('Write permissions tests only supported on mac/linux')
    def test_no_write_access_small_file(self, files, s3_utils, shared_bucket):
        if os.geteuid() == 0:
            pytest.skip('Cannot completely remove write access as root user.')
        os.chmod(files.rootdir, 0o444)
        s3_utils.put_object(shared_bucket, 'foo.txt', contents='Hello world')
        p = aws(
            's3 cp s3://%s/foo.txt %s'
            % (shared_bucket, os.path.join(files.rootdir, 'foo.txt'))
        )
        assert p.rc == 1
        assert 'download failed' in p.stderr

    @skip_if_windows('Write permissions tests only supported on mac/linux')
    def test_no_write_access_large_file(self, files, s3_utils, shared_bucket):
        if os.geteuid() == 0:
            pytest.skip('Cannot completely remove write access as root user.')
        # We have to use a file like object because using a string
        # would result in the header + body sent as a single packet
        # which effectively disables the expect 100 continue logic.
        # This will result in a test error because we won't follow
        # the temporary redirect for the newly created bucket.
        contents = BytesIO(b'a' * 10 * 1024 * 1024)
        s3_utils.put_object(shared_bucket, 'foo.txt', contents=contents)
        os.chmod(files.rootdir, 0o444)
        p = aws(
            's3 cp s3://%s/foo.txt %s'
            % (shared_bucket, os.path.join(files.rootdir, 'foo.txt'))
        )
        assert p.rc == 1
        assert 'download failed' in p.stderr


@skip_if_windows('Symlink tests only supported on mac/linux')
class TestSymlinks(BaseParameterizedS3ClientTest):
    """
    This class test the ability to follow or not follow symlinks.
    """

    def test_no_follow_symlinks(
        self, files, s3_utils, symlink_files, shared_bucket
    ):
        p = aws(
            's3 sync %s s3://%s/ --no-follow-symlinks'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        assert s3_utils.key_not_exists(shared_bucket, 'a-goodsymlink')
        assert s3_utils.key_not_exists(shared_bucket, 'b-badsymlink')
        assert s3_utils.key_not_exists(shared_bucket, 'c-goodsymlink/foo.txt')
        contents = s3_utils.get_key_contents(
            shared_bucket, 'realfiles/foo.txt'
        )
        assert contents == 'foo.txt contents'

    def test_follow_symlinks(
        self, files, s3_utils, symlink_files, shared_bucket
    ):
        # Get rid of the bad symlink first.
        os.remove(os.path.join(files.rootdir, 'b-badsymlink'))
        p = aws(
            's3 sync %s s3://%s/ --follow-symlinks'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        contents = s3_utils.get_key_contents(shared_bucket, 'a-goodsymlink')
        assert contents == 'foo.txt contents'
        assert s3_utils.key_not_exists(shared_bucket, 'b-badsymlink')
        contents = s3_utils.get_key_contents(
            shared_bucket, 'c-goodsymlink/foo.txt'
        )
        assert contents == 'foo.txt contents'
        contents = s3_utils.get_key_contents(
            shared_bucket, 'realfiles/foo.txt'
        )
        assert contents == 'foo.txt contents'

    def test_follow_symlinks_default(
        self, files, s3_utils, symlink_files, shared_bucket
    ):
        # Get rid of the bad symlink first.
        os.remove(os.path.join(files.rootdir, 'b-badsymlink'))
        p = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)
        contents = s3_utils.get_key_contents(shared_bucket, 'a-goodsymlink')
        assert contents == 'foo.txt contents'
        assert s3_utils.key_not_exists(shared_bucket, 'b-badsymlink')
        contents = s3_utils.get_key_contents(
            shared_bucket, 'c-goodsymlink/foo.txt'
        )
        assert contents == 'foo.txt contents'
        contents = s3_utils.get_key_contents(
            shared_bucket, 'realfiles/foo.txt'
        )
        assert contents == 'foo.txt contents'

    def test_bad_symlink(self, files, symlink_files, shared_bucket):
        p = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        assert p.rc == 2, p.stderr
        warning_msg = (
            'warning: Skipping file %s. File does not exist.'
            % os.path.join(files.rootdir, 'b-badsymlink')
        )
        assert warning_msg in p.stderr


class TestUnicode(BaseParameterizedS3ClientTest):
    """
    The purpose of these tests are to ensure that the commands can handle
    unicode characters in both keyname and from those generated for both
    uploading and downloading files.
    """

    def test_cp(self, files, shared_bucket):
        local_example1_txt = files.create_file(
            '\u00e9xample.txt', 'example1 contents'
        )
        s3_example1_txt = 's3://%s/%s' % (
            shared_bucket,
            os.path.basename(local_example1_txt),
        )
        local_example2_txt = files.full_path('\u00e9xample2.txt')

        p = aws('s3 cp %s %s' % (local_example1_txt, s3_example1_txt))
        self.assert_no_errors(p)

        # Download the file to the second example2.txt filename.
        p = aws('s3 cp %s %s --quiet' % (s3_example1_txt, local_example2_txt))
        self.assert_no_errors(p)
        with open(local_example2_txt, 'rb') as f:
            assert f.read() == b'example1 contents'

    def test_recursive_cp(self, files, shared_bucket):
        local_example1_txt = files.create_file(
            '\u00e9xample.txt', 'example1 contents'
        )
        local_example2_txt = files.create_file(
            '\u00e9xample2.txt', 'example2 contents'
        )
        p = aws(
            's3 cp %s s3://%s --recursive --quiet'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)

        os.remove(local_example1_txt)
        os.remove(local_example2_txt)

        p = aws(
            's3 cp s3://%s %s --recursive --quiet'
            % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)
        assert open(local_example1_txt).read() == 'example1 contents'
        assert open(local_example2_txt).read() == 'example2 contents'


class TestLs(BaseS3IntegrationTest):
    """
    This tests using the ``ls`` command.
    """

    def test_ls_bucket(self):
        p = aws('s3 ls')
        self.assert_no_errors(p)

    def test_ls_with_no_env_vars(self):
        # By default, the aws() function injects
        # an AWS_DEFAULT_REGION into the env var of the
        # process.  We're verifying that a region does *not*
        # need to be set anywhere.  If we provide our
        # own environ dict, then the aws() function won't
        # inject a region.
        env = os.environ.copy()
        p = aws('s3 ls', env_vars=env)
        self.assert_no_errors(p)

    def test_ls_bucket_with_s3_prefix(self):
        p = aws('s3 ls s3://')
        self.assert_no_errors(p)

    def test_ls_non_existent_bucket(self):
        p = aws(f's3 ls s3://{_NON_EXISTENT_BUCKET}')
        assert p.rc == 254
        error_msg = (
            'An error occurred (NoSuchBucket) when calling the '
            'ListObjectsV2 operation: The specified bucket does not exist'
        )
        assert error_msg in p.stderr
        # There should be no stdout if we can't find the bucket.
        assert p.stdout == ''

    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_ls_with_prefix(self, s3_bucket, s3_utils, request):
        shared_bucket = request.getfixturevalue(s3_bucket)
        s3_utils.put_object(shared_bucket, 'foo.txt', 'contents')
        s3_utils.put_object(shared_bucket, 'foo', 'contents')
        s3_utils.put_object(shared_bucket, 'bar.txt', 'contents')
        s3_utils.put_object(shared_bucket, 'subdir/foo.txt', 'contents')
        p = aws('s3 ls s3://%s' % shared_bucket)
        assert 'PRE subdir/' in p.stdout
        assert '8 foo.txt' in p.stdout
        assert '8 foo' in p.stdout
        assert '8 bar.txt' in p.stdout

    @pytest.mark.parametrize(
        's3_bucket', ['shared_bucket', 'shared_dir_bucket']
    )
    def test_ls_recursive(self, s3_bucket, s3_utils, request):
        shared_bucket = request.getfixturevalue(s3_bucket)
        s3_utils.put_object(shared_bucket, 'foo.txt', 'contents')
        s3_utils.put_object(shared_bucket, 'foo', 'contents')
        s3_utils.put_object(shared_bucket, 'bar.txt', 'contents')
        s3_utils.put_object(shared_bucket, 'subdir/foo.txt', 'contents')
        p = aws('s3 ls s3://%s --recursive' % shared_bucket)
        assert '8 foo.txt' in p.stdout
        assert '8 foo' in p.stdout
        assert '8 bar.txt' in p.stdout
        assert '8 subdir/foo.txt' in p.stdout

    def test_ls_without_prefix(self, s3_utils, shared_bucket):
        # The ls command does not require an s3:// prefix,
        # we're always listing s3 contents.
        s3_utils.put_object(shared_bucket, 'foo.txt', 'contents')
        p = aws('s3 ls %s' % shared_bucket)
        assert p.rc == 0
        assert 'foo.txt' in p.stdout

    def test_only_prefix(self, s3_utils, shared_bucket):
        s3_utils.put_object(shared_bucket, 'temp/foo.txt', 'contents')
        p = aws('s3 ls s3://%s/temp/foo.txt' % shared_bucket)
        assert p.rc == 0
        assert 'foo.txt' in p.stdout

    def test_ls_empty_bucket(self, shared_bucket):
        p = aws('s3 ls %s' % shared_bucket)
        # There should not be an error thrown for checking the contents of
        # an empty bucket because no key was specified.
        assert p.rc == 0

    def test_ls_fail(self, shared_bucket):
        p = aws('s3 ls s3://%s/foo' % shared_bucket)
        assert p.rc == 1

    def test_ls_fail_recursive(self, shared_bucket):
        p = aws('s3 ls s3://%s/bar --recursive' % shared_bucket)
        assert p.rc == 1


class TestMbRb(BaseS3IntegrationTest):
    """
    Tests primarily using ``rb`` and ``mb`` command.
    """

    def test_mb_rb(self, s3_utils):
        bucket_name = random_bucket_name()
        p = aws('s3 mb s3://%s' % bucket_name)
        self.assert_no_errors(p)

        # Give the bucket time to form.
        time.sleep(1)
        response = s3_utils.list_buckets()
        assert bucket_name in [b['Name'] for b in response]

        p = aws('s3 rb s3://%s' % bucket_name)
        self.assert_no_errors(p)

    def test_fail_mb_rb(self):
        # Choose a bucket name that already exists.
        p = aws('s3 mb s3://mybucket')
        assert "BucketAlreadyExists" in p.stderr
        assert p.rc == 1


class TestOutput(BaseParameterizedS3ClientTest):
    """
    This ensures that arguments that affect output i.e. ``--quiet`` and
    ``--only-show-errors`` behave as expected.
    """

    def test_normal_output(self, files, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws('s3 cp %s s3://%s/' % (foo_txt, shared_bucket))
        assert p.rc == 0
        # Check that there were no errors and that parts of the expected
        # progress message are written to stdout.
        self.assert_no_errors(p)
        assert 'upload' in p.stdout
        assert 's3://%s/foo.txt' % shared_bucket in p.stdout

    def test_normal_output_quiet(self, files, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws('s3 cp %s s3://%s/ --quiet' % (foo_txt, shared_bucket))
        assert p.rc == 0
        # Check that nothing was printed to stdout.
        assert '' == p.stdout

    def test_normal_output_only_show_errors(self, files, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws(
            's3 cp %s s3://%s/ --only-show-errors' % (foo_txt, shared_bucket)
        )
        assert p.rc == 0
        # Check that nothing was printed to stdout.
        assert '' == p.stdout

    def test_normal_output_no_progress(self, files, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws('s3 cp %s s3://%s/ --no-progress' % (foo_txt, shared_bucket))
        assert p.rc == 0
        # Ensure success message was printed
        assert 'upload' in p.stdout
        assert 's3://%s/foo.txt' % shared_bucket in p.stdout
        assert 'Completed ' not in p.stdout
        assert 'calculating' not in p.stdout

    def test_error_output(self, files):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws(f's3 cp {foo_txt} s3://{_NON_EXISTENT_BUCKET}/')
        # Check that there were errors and that the error was print to stderr.
        assert p.rc == 1
        assert 'upload failed' in p.stderr

    def test_error_ouput_quiet(self, files):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws(f's3 cp {foo_txt} s3://{_NON_EXISTENT_BUCKET}/ --quiet')
        # Check that there were errors and that the error was not
        # print to stderr.
        assert p.rc == 1
        assert '' == p.stderr

    def test_error_output_only_show_errors(self, files):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws(
            f's3 cp {foo_txt} s3://{_NON_EXISTENT_BUCKET}/ --only-show-errors'
        )
        # Check that there were errors and that the error was print to stderr.
        assert p.rc == 1
        assert 'upload failed' in p.stderr

    def test_error_and_success_output_only_show_errors(
        self, files, s3_utils, shared_bucket
    ):
        # Create one file.
        files.create_file('f', 'foo contents')

        # Create another file that has a slightly longer name than the first.
        files.create_file('bar.txt', 'bar contents')

        # Create a prefix that will cause the second created file to have a key
        # longer than 1024 bytes which is not allowed in s3.
        long_prefix = 'd' * 1022

        p = aws(
            's3 cp %s s3://%s/%s/ --only-show-errors --recursive'
            % (files.rootdir, shared_bucket, long_prefix)
        )

        # Check that there was at least one error.
        assert p.rc == 1

        # Check that there was nothing written to stdout for successful upload.
        assert '' == p.stdout

        # Check that the failed message showed up in stderr.
        assert 'upload failed' in p.stderr

        # Ensure the expected successful key exists in the bucket.
        assert s3_utils.key_exists(shared_bucket, long_prefix + '/f')


class TestDryrun(BaseParameterizedS3ClientTest):
    """
    This ensures that dryrun works.
    """

    def test_dryrun(self, files, s3_utils, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'foo contents')

        # Copy file into bucket.
        p = aws('s3 cp %s s3://%s/ --dryrun' % (foo_txt, shared_bucket))
        assert p.rc == 0
        self.assert_no_errors(p)
        assert s3_utils.key_not_exists(shared_bucket, 'foo.txt')

    def test_dryrun_large_files(self, files, s3_utils, shared_bucket):
        foo_txt = files.create_file('foo.txt', 'a' * 1024 * 1024 * 10)

        # Copy file into bucket.
        p = aws('s3 cp %s s3://%s/ --dryrun' % (foo_txt, shared_bucket))
        assert p.rc == 0
        self.assert_no_errors(p)
        assert s3_utils.key_not_exists(shared_bucket, 'foo.txt'), (
            "The key 'foo.txt' exists in S3. It looks like the --dryrun "
            "argument was not obeyed."
        )

    def test_dryrun_download_large_file(self, files, s3_utils, shared_bucket):
        full_path = files.create_file('largefile', 'a' * 1024 * 1024 * 10)
        with open(full_path, 'rb') as body:
            s3_utils.put_object(shared_bucket, 'foo.txt', body)

        foo_txt = files.full_path('foo.txt')
        p = aws('s3 cp s3://%s/foo.txt %s --dryrun' % (shared_bucket, foo_txt))
        assert p.rc == 0
        self.assert_no_errors(p)
        assert not os.path.exists(foo_txt), (
            "The file 'foo.txt' exists locally. It looks like the --dryrun "
            "argument was not obeyed."
        )


@skip_if_windows('Memory tests only supported on mac/linux')
class TestMemoryUtilization(BaseS3IntegrationTest):
    # These tests verify the memory utilization and growth are what we expect.
    num_threads = DEFAULTS['max_concurrent_requests']
    chunk_size = DEFAULTS['multipart_chunksize']
    expected_memory_usage = num_threads * chunk_size
    # margin for things like python VM overhead, botocore service
    # objects, etc.  1.5 is really generous, perhaps over time this can be
    # lowered.
    runtime_margin = 1.5
    max_mem_allowed = runtime_margin * expected_memory_usage

    @pytest.fixture(autouse=True)
    def use_classic_transfer_client(self, aws_config_copy):
        # This test class is only intended for memory utilization with
        # the classic transfer client. This ensures that we are never
        # auto resolved to the CRT transfer client for this test class.
        configure_preferred_transfer_client('classic')

    def assert_max_memory_used(self, process, max_mem_allowed, full_command):
        peak_memory = max(process.memory_usage)
        if peak_memory > max_mem_allowed:
            failure_message = (
                'Exceeded max memory allowed (%s MB) for command '
                '"%s": %s MB'
                % (
                    self.max_mem_allowed / 1024.0 / 1024.0,
                    full_command,
                    peak_memory / 1024.0 / 1024.0,
                )
            )
            self.fail(failure_message)

    def test_transfer_single_large_file(self, files, shared_bucket):
        # 40MB will force a multipart upload.
        file_contents = 'abcdabcd' * (1024 * 1024 * 10)
        foo_txt = files.create_file('foo.txt', file_contents)
        full_command = 's3 mv %s s3://%s/foo.txt' % (foo_txt, shared_bucket)
        p = aws(full_command, collect_memory=True)
        self.assert_no_errors(p)
        self.assert_max_memory_used(p, self.max_mem_allowed, full_command)

        # Verify downloading it back down obeys memory utilization.
        download_full_command = 's3 mv s3://%s/foo.txt %s' % (
            shared_bucket,
            foo_txt,
        )
        p = aws(download_full_command, collect_memory=True)
        self.assert_no_errors(p)
        self.assert_max_memory_used(
            p, self.max_mem_allowed, download_full_command
        )

    # Some versions of RHEL allocate memory in a way where free'd memory isn't
    # given back to the OS.  We haven't seen behavior as bad as RHEL's to the
    # point where this test fails on other distros, so for now we're disabling
    # the test on RHEL until we come up with a better way to collect
    # memory usage.
    @unittest.skipIf(
        _running_on_rhel(), 'Streaming memory tests no supported on RHEL.'
    )
    def test_stream_large_file(self, files, shared_bucket):
        """
        This tests to ensure that streaming files for both uploads and
        downloads do not use too much memory.  Note that streaming uploads
        will use slightly more memory than usual but should not put the
        entire file into memory.
        """
        # Create a 200 MB file that will be streamed
        num_mb = 200
        foo_txt = files.create_file('foo.txt', '')
        with open(foo_txt, 'wb') as f:
            for i in range(num_mb):
                f.write(b'a' * 1024 * 1024)

        # The current memory threshold is set at about the peak amount for
        # performing a streaming upload of a file larger than 100 MB. So
        # this maximum needs to be bumped up.  The maximum memory allowance
        # is increased by two chunksizes because that is the maximum
        # amount of chunks that will be queued while not being operated on
        # by a thread when performing a streaming multipart upload.
        max_mem_allowed = self.max_mem_allowed + 2 * self.chunk_size

        full_command = 's3 cp - s3://%s/foo.txt' % shared_bucket
        with open(foo_txt, 'rb') as f:
            p = aws(full_command, input_file=f, collect_memory=True)
            self.assert_no_errors(p)
            self.assert_max_memory_used(p, max_mem_allowed, full_command)

        # Now perform a streaming download of the file.
        full_command = 's3 cp s3://%s/foo.txt - > %s' % (
            shared_bucket,
            foo_txt,
        )
        p = aws(full_command, collect_memory=True)
        self.assert_no_errors(p)
        # Use the usual bar for maximum memory usage since a streaming
        # download's memory usage should be comparable to non-streaming
        # transfers.
        self.assert_max_memory_used(p, self.max_mem_allowed, full_command)


class TestWebsiteConfiguration(BaseS3IntegrationTest):
    def test_create_website_index_configuration(self, s3_utils, shared_bucket):
        # Supply only --index-document argument.
        full_command = 's3 website %s --index-document index.html' % (
            shared_bucket
        )
        p = aws(full_command)
        assert p.rc == 0
        self.assert_no_errors(p)
        # Verify we have a bucket website configured.
        parsed = s3_utils.get_bucket_website(shared_bucket)
        assert parsed['IndexDocument']['Suffix'] == 'index.html'
        assert 'ErrorDocument' not in parsed
        assert 'RoutingRules' not in parsed
        assert 'RedirectAllRequestsTo' not in parsed

    def test_create_website_index_and_error_configuration(
        self, s3_utils, shared_bucket
    ):
        # Supply both --index-document and --error-document arguments.
        p = aws(
            's3 website %s --index-document index.html '
            '--error-document error.html' % shared_bucket
        )
        assert p.rc == 0
        self.assert_no_errors(p)
        # Verify we have a bucket website configured.
        parsed = s3_utils.get_bucket_website(shared_bucket)
        assert parsed['IndexDocument']['Suffix'] == 'index.html'
        assert parsed['ErrorDocument']['Key'] == 'error.html'
        assert 'RoutingRules' not in parsed
        assert 'RedirectAllRequestsTo' not in parsed


class TestIncludeExcludeFilters(BaseParameterizedS3ClientTest):
    def assert_no_files_would_be_uploaded(self, p):
        self.assert_no_errors(p)
        # There should be no output.
        assert p.stdout == ''
        assert p.stderr == ''

    def test_basic_exclude_filter_for_single_file(self, files):
        full_path = files.create_file('foo.txt', 'this is foo.txt')
        # With no exclude we should upload the file.
        p = aws('s3 cp %s s3://random-bucket-name/ --dryrun' % full_path)
        self.assert_no_errors(p)
        assert '(dryrun) upload:' in p.stdout

        p2 = aws(
            "s3 cp %s s3://random-bucket-name/ --dryrun --exclude '*'"
            % full_path
        )
        self.assert_no_files_would_be_uploaded(p2)

    def test_explicitly_exclude_single_file(self, files):
        full_path = files.create_file('foo.txt', 'this is foo.txt')
        p = aws(
            's3 cp %s s3://random-bucket-name/'
            ' --dryrun --exclude foo.txt' % full_path
        )
        self.assert_no_files_would_be_uploaded(p)

    def test_cwd_doesnt_matter(self, files):
        full_path = files.create_file('foo.txt', 'this is foo.txt')
        with tempfile.TemporaryDirectory() as tempdir:
            with cd(tempdir):
                p = aws(
                    "s3 cp %s s3://random-bucket-name/ --dryrun --exclude '*'"
                    % full_path
                )
        self.assert_no_files_would_be_uploaded(p)

    def test_recursive_exclude(self, files):
        # create test/foo.txt
        nested_dir = os.path.join(files.rootdir, 'test')
        os.mkdir(nested_dir)
        files.create_file(
            os.path.join(nested_dir, 'foo.txt'), contents='foo.txt contents'
        )
        # Then create test-123.txt, test-321.txt, test.txt.
        files.create_file('test-123.txt', 'test-123.txt contents')
        files.create_file('test-321.txt', 'test-321.txt contents')
        files.create_file('test.txt', 'test.txt contents')
        # An --exclude test* should exclude everything here.
        p = aws(
            "s3 cp %s s3://random-bucket-name/ --dryrun --exclude '*' "
            "--recursive" % files.rootdir
        )
        self.assert_no_files_would_be_uploaded(p)

        # We can include the test directory though.
        p = aws(
            "s3 cp %s s3://random-bucket-name/ --dryrun "
            "--exclude '*' --include 'test/*' --recursive" % files.rootdir
        )
        self.assert_no_errors(p)
        assert re.search(r'\(dryrun\) upload:.*test/foo.txt.*', p.stdout)

    def test_s3_filtering(self, s3_utils, shared_bucket):
        # Should behave the same as local file filtering.
        s3_utils.put_object(shared_bucket, key_name='foo.txt')
        s3_utils.put_object(shared_bucket, key_name='bar.txt')
        s3_utils.put_object(shared_bucket, key_name='baz.jpg')
        p = aws(
            "s3 rm s3://%s/ --dryrun --exclude '*' --recursive" % shared_bucket
        )
        self.assert_no_files_would_be_uploaded(p)

        p = aws(
            "s3 rm s3://%s/ --dryrun --exclude '*.jpg' --exclude '*.txt' "
            "--recursive" % shared_bucket
        )
        self.assert_no_files_would_be_uploaded(p)

        p = aws(
            "s3 rm s3://%s/ --dryrun --exclude '*.txt' --recursive"
            % shared_bucket
        )
        self.assert_no_errors(p)
        assert re.search(r'\(dryrun\) delete:.*baz.jpg.*', p.stdout)
        assert 'bar.txt' not in p.stdout
        assert 'foo.txt' not in p.stdout

    def test_exclude_filter_with_delete(self, files, s3_utils, shared_bucket):
        # Test for: https://github.com/aws/aws-cli/issues/778
        files.create_file('foo.txt', 'contents')
        second = files.create_file('bar.py', 'contents')
        p = aws("s3 sync %s s3://%s/" % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, key_name='bar.py')
        os.remove(second)
        # We now have the same state as specified in the bug:
        # local           remote
        # -----           ------
        #
        # foo.txt         foo.txt
        #                 bar.py
        #
        # If we now run --exclude '*.py' --delete, then we should *not*
        # delete bar.py and the remote side.
        p = aws(
            "s3 sync %s s3://%s/ --exclude '*.py' --delete"
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, key_name='bar.py'), (
            "The --delete flag was not applied to the receiving "
            "end, the 'bar.py' file was deleted even though it"
            " was excluded."
        )

    def test_exclude_filter_with_relative_path(
        self, files, s3_utils, shared_bucket
    ):
        # Same test as test_exclude_filter_with_delete, except we don't
        # use an absolute path on the source dir.
        files.create_file('foo.txt', 'contents')
        second = files.create_file('bar.py', 'contents')
        p = aws("s3 sync %s s3://%s/" % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, key_name='bar.py')
        os.remove(second)
        cwd = os.getcwd()
        try:
            os.chdir(files.rootdir)
            # Note how we're using "." for the source directory.
            p = aws(
                "s3 sync . s3://%s/ --exclude '*.py' --delete" % shared_bucket
            )
        finally:
            os.chdir(cwd)
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, key_name='bar.py'), (
            "The --delete flag was not applied to the receiving "
            "end, the 'bar.py' file was deleted even though it"
            " was excluded."
        )

    def test_filter_s3_with_prefix(self, files, s3_utils, shared_bucket):
        s3_utils.put_object(shared_bucket, key_name='temp/test')
        p = aws(
            's3 cp s3://%s/temp/ %s --recursive --exclude test --dryrun'
            % (shared_bucket, files.rootdir)
        )
        self.assert_no_files_would_be_uploaded(p)

    def test_filter_no_resync(self, files, s3_utils, shared_bucket):
        # This specifically tests for the issue described here:
        # https://github.com/aws/aws-cli/issues/794
        dir_name = os.path.join(files.rootdir, 'temp')
        files.create_file(os.path.join(dir_name, 'test.txt'), contents='foo')
        # Sync a local directory to an s3 prefix.
        p = aws('s3 sync %s s3://%s/temp' % (dir_name, shared_bucket))
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, key_name='temp/test.txt')

        # Nothing should be synced down if filters are used.
        p = aws(
            "s3 sync s3://%s/temp %s --exclude '*' --include test.txt"
            % (shared_bucket, dir_name)
        )
        self.assert_no_files_would_be_uploaded(p)


class TestFileWithSpaces(BaseParameterizedS3ClientTest):
    def test_upload_download_file_with_spaces(self, files, shared_bucket):
        filename = files.create_file('with space.txt', 'contents')
        p = aws(
            's3 cp %s s3://%s/ --recursive' % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        os.remove(filename)
        # Now download the file back down locally.
        p = aws(
            's3 cp s3://%s/ %s --recursive' % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)
        assert os.listdir(files.rootdir)[0] == 'with space.txt'

    def test_sync_file_with_spaces(self, files, shared_bucket):
        files.create_file(
            'with space.txt', 'contents', mtime=time.time() - 300
        )
        p = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        self.assert_no_errors(p)
        time.sleep(1)
        # Now syncing again should *not* trigger any uploads (i.e we should
        # get nothing on stdout).
        p2 = aws('s3 sync %s s3://%s/' % (files.rootdir, shared_bucket))
        assert p2.stdout == ''
        assert p2.stderr == ''
        assert p2.rc == 0


class TestStreams(BaseParameterizedS3ClientTest):
    def test_upload(self, s3_utils, shared_bucket):
        """
        This tests uploading a small stream from stdin.
        """
        p = aws(
            's3 cp - s3://%s/stream' % shared_bucket,
            input_data=b'This is a test',
        )
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, 'stream')
        contents = s3_utils.get_key_contents(shared_bucket, 'stream')
        assert contents == 'This is a test'

    def test_unicode_upload(self, s3_utils, shared_bucket):
        """
        This tests being able to upload unicode from stdin.
        """
        unicode_str = '\u00e9 This is a test'
        byte_str = unicode_str.encode('utf-8')
        p = aws('s3 cp - s3://%s/stream' % shared_bucket, input_data=byte_str)
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, 'stream')
        contents = s3_utils.get_key_contents(shared_bucket, 'stream')
        assert contents == unicode_str

    def test_multipart_upload(self, s3_utils, shared_bucket):
        """
        This tests the ability to multipart upload streams from stdin.
        The data has some unicode in it to avoid having to do a separate
        multipart upload test just for unicode.
        """
        data = '\u00e9bcd' * (1024 * 1024 * 10)
        data_encoded = data.encode('utf-8')
        p = aws(
            's3 cp - s3://%s/stream' % shared_bucket, input_data=data_encoded
        )
        self.assert_no_errors(p)
        assert s3_utils.key_exists(shared_bucket, 'stream')
        contents = s3_utils.get_key_contents(shared_bucket, 'stream')
        assert contents == data

    def test_download(self, shared_bucket):
        """
        This tests downloading a small stream from stdout.
        """
        p = aws(
            's3 cp - s3://%s/stream' % shared_bucket,
            input_data=b'This is a test',
        )
        self.assert_no_errors(p)

        p = aws('s3 cp s3://%s/stream -' % shared_bucket)
        self.assert_no_errors(p)
        assert p.stdout == 'This is a test'

    def test_unicode_download(self, shared_bucket):
        """
        This tests downloading a small unicode stream from stdout.
        """
        data = '\u00e9 This is a test'
        data_encoded = data.encode('utf-8')
        p = aws(
            's3 cp - s3://%s/stream' % shared_bucket, input_data=data_encoded
        )
        self.assert_no_errors(p)

        # Downloading the unicode stream to standard out.
        p = aws('s3 cp s3://%s/stream -' % shared_bucket)
        self.assert_no_errors(p)
        assert p.stdout == data_encoded.decode(get_stdout_encoding())

    def test_multipart_download(self, shared_bucket):
        """
        This tests the ability to multipart download streams to stdout.
        The data has some unicode in it to avoid having to do a seperate
        multipart download test just for unicode.
        """
        # First lets upload some data via streaming since
        # its faster and we do not have to write to a file!
        data = '\u00e9bcd' * (1024 * 1024 * 10)
        data_encoded = data.encode('utf-8')
        p = aws(
            's3 cp - s3://%s/stream' % shared_bucket, input_data=data_encoded
        )

        # Download the unicode stream to standard out.
        p = aws('s3 cp s3://%s/stream -' % shared_bucket)
        self.assert_no_errors(p)
        assert p.stdout == data_encoded.decode(get_stdout_encoding())


class TestLSWithProfile(BaseS3IntegrationTest):
    def test_can_ls_with_profile(self, config_with_profile):
        env_vars = os.environ.copy()
        env_vars['AWS_CONFIG_FILE'] = config_with_profile
        p = aws('s3 ls s3:// --profile testprofile', env_vars=env_vars)
        self.assert_no_errors(p)


class TestNoSignRequests(BaseParameterizedS3ClientTest):
    def test_no_sign_request(self, files, s3_utils, shared_bucket, region):
        s3_utils.put_object(
            shared_bucket,
            'foo',
            contents='bar',
            extra_args={'ACL': 'public-read-write'},
        )
        env_vars = os.environ.copy()
        env_vars['AWS_ACCESS_KEY_ID'] = 'foo'
        env_vars['AWS_SECRET_ACCESS_KEY'] = 'bar'
        p = aws(
            's3 cp s3://%s/foo %s/ --region %s'
            % (shared_bucket, files.rootdir, region),
            env_vars=env_vars,
        )
        # Should have credential issues
        assert p.rc == 1

        p = aws(
            's3 cp s3://%s/foo %s/ --region %s --no-sign-request'
            % (shared_bucket, files.rootdir, region),
            env_vars=env_vars,
        )
        # Should be able to download the file when not signing the request.
        self.assert_no_errors(p)


class TestHonorsEndpointUrl(BaseParameterizedS3ClientTest):
    def test_verify_endpoint_url_is_used(self):
        # We're going to verify this indirectly by looking at the
        # debug logs.  The endpoint url we specify should be in the
        # debug logs, and the endpoint url that botocore would have
        # used if we didn't provide the endpoint-url should not
        # be in the debug logs.  The other alternative is to actually
        # watch what connections are made in the process, which is not
        # easy.
        p = aws(
            's3 ls s3://dnscompat/ '
            '--endpoint-url http://localhost:51515 '
            '--debug'
        )
        debug_logs = p.stderr
        original_hostname = 'dnscompat.s3.amazonaws.com'
        expected = 'localhost'
        assert (
            original_hostname not in debug_logs
        ), '--endpoint-url is being ignored in s3 commands.'
        assert expected in debug_logs


class TestSSERelatedParams(BaseParameterizedS3ClientTest):
    def download_and_assert_kms_object_integrity(
        self, bucket, key, contents, files, s3_utils
    ):
        s3_utils.wait_until_key_exists(bucket, key)
        # Ensure the kms object can be download it by downloading it
        # with --sse aws:kms is enabled to ensure sigv4 is used on the
        # download, as it is required for kms.
        download_filename = os.path.join(files.rootdir, 'tmp', key)
        p = aws(
            's3 cp s3://%s/%s %s --sse aws:kms'
            % (bucket, key, download_filename)
        )
        self.assert_no_errors(p)

        assert os.path.isfile(download_filename)
        with open(download_filename) as f:
            assert f.read() == contents

    def test_sse_upload(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload the file using AES256
        p = aws(
            's3 cp %s s3://%s/%s --sse AES256'
            % (file_name, shared_bucket, key)
        )
        self.assert_no_errors(p)

        # Ensure the file was uploaded correctly
        s3_utils.assert_key_contents_equal(shared_bucket, key, contents)

    def test_large_file_sse_upload(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        contents = 'a' * (10 * (1024 * 1024))
        file_name = files.create_file(key, contents)

        # Upload the file using AES256
        p = aws(
            's3 cp %s s3://%s/%s --sse AES256'
            % (file_name, shared_bucket, key)
        )
        self.assert_no_errors(p)

        # Ensure the file was uploaded correctly
        s3_utils.assert_key_contents_equal(shared_bucket, key, contents)

    def test_sse_with_kms_upload(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload the file using KMS
        p = aws(
            's3 cp %s s3://%s/%s --sse aws:kms'
            % (file_name, shared_bucket, key)
        )
        self.assert_no_errors(p)

        self.download_and_assert_kms_object_integrity(
            shared_bucket, key, contents, files, s3_utils
        )

    def test_large_file_sse_kms_upload(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        contents = 'a' * (10 * (1024 * 1024))
        file_name = files.create_file(key, contents)

        # Upload the file using KMS
        p = aws(
            's3 cp %s s3://%s/%s --sse aws:kms'
            % (file_name, shared_bucket, key)
        )
        self.assert_no_errors(p)
        self.download_and_assert_kms_object_integrity(
            shared_bucket, key, contents, files, s3_utils
        )

    def test_sse_copy(self, s3_utils, shared_bucket):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'contents'
        s3_utils.put_object(shared_bucket, key, contents)

        # Copy the file using AES256
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse AES256'
            % (shared_bucket, key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)

        # Ensure the file was copied correctly
        s3_utils.assert_key_contents_equal(shared_bucket, new_key, contents)

    def test_large_file_sse_copy(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'a' * (10 * (1024 * 1024))

        # This is a little faster and more efficient than
        # calling self.put_object()
        file_name = files.create_file(key, contents)
        p = aws('s3 cp %s s3://%s/%s' % (file_name, shared_bucket, key))
        self.assert_no_errors(p)

        # Copy the file using AES256
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse AES256'
            % (shared_bucket, key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)

        # Ensure the file was copied correctly
        s3_utils.assert_key_contents_equal(shared_bucket, new_key, contents)

    def test_sse_kms_copy(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'contents'
        s3_utils.put_object(shared_bucket, key, contents)

        # Copy the file using KMS
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse aws:kms'
            % (shared_bucket, key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)
        self.download_and_assert_kms_object_integrity(
            shared_bucket, key, contents, files, s3_utils
        )

    def test_large_file_sse_kms_copy(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'a' * (10 * (1024 * 1024))

        # This is a little faster and more efficient than
        # calling self.put_object()
        file_name = files.create_file(key, contents)
        p = aws('s3 cp %s s3://%s/%s' % (file_name, shared_bucket, key))
        self.assert_no_errors(p)

        # Copy the file using KMS
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse aws:kms'
            % (shared_bucket, key, shared_bucket, new_key)
        )
        self.assert_no_errors(p)
        self.download_and_assert_kms_object_integrity(
            shared_bucket, key, contents, files, s3_utils
        )

    def test_smoke_sync_sse(self, files, s3_utils, shared_bucket):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload sync
        p = aws(
            's3 sync %s s3://%s/foo/ --sse AES256'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)
        s3_utils.wait_until_key_exists(shared_bucket, 'foo/foo.txt')

        # Copy sync
        p = aws(
            's3 sync s3://%s/foo/ s3://%s/bar/ --sse AES256'
            % (shared_bucket, shared_bucket)
        )
        self.assert_no_errors(p)
        s3_utils.wait_until_key_exists(shared_bucket, 'bar/foo.txt')

        # Remove the original file
        os.remove(file_name)

        # Download sync
        p = aws(
            's3 sync s3://%s/bar/ %s --sse AES256'
            % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)

        assert os.path.isfile(file_name)
        with open(file_name) as f:
            assert f.read() == contents

    def test_smoke_sync_sse_kms(self, files, shared_bucket):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload sync
        p = aws(
            's3 sync %s s3://%s/foo/ --sse aws:kms'
            % (files.rootdir, shared_bucket)
        )
        self.assert_no_errors(p)

        # Copy sync
        p = aws(
            's3 sync s3://%s/foo/ s3://%s/bar/ --sse aws:kms'
            % (shared_bucket, shared_bucket)
        )
        self.assert_no_errors(p)

        # Remove the original file
        os.remove(file_name)

        # Download sync
        p = aws(
            's3 sync s3://%s/bar/ %s --sse aws:kms'
            % (shared_bucket, files.rootdir)
        )
        self.assert_no_errors(p)

        assert os.path.isfile(file_name)
        with open(file_name) as f:
            assert f.read() == contents


class TestSSECRelatedParams(BaseParameterizedS3ClientTest):
    def download_and_assert_sse_c_object_integrity(
        self, bucket, key, encrypt_key, contents, files, s3_utils
    ):
        s3_utils.wait_until_key_exists(
            bucket,
            key,
            {'SSECustomerKey': encrypt_key, 'SSECustomerAlgorithm': 'AES256'},
        )
        download_filename = os.path.join(files.rootdir, 'tmp', key)
        p = aws(
            's3 cp s3://%s/%s %s --sse-c AES256 --sse-c-key %s'
            % (bucket, key, download_filename, encrypt_key)
        )
        self.assert_no_errors(p)

        assert os.path.isfile(download_filename)
        with open(download_filename) as f:
            assert f.read() == contents

    def test_sse_c_upload_and_download(
        self, files, s3_utils, encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload the file using SSE-C
        p = aws(
            's3 cp %s s3://%s --sse-c AES256 --sse-c-key %s'
            % (file_name, shared_bucket, encrypt_key)
        )
        self.assert_no_errors(p)

        self.download_and_assert_sse_c_object_integrity(
            shared_bucket, key, encrypt_key, contents, files, s3_utils
        )

    def test_can_delete_single_sse_c_object(
        self, s3_utils, encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        contents = 'contents'
        s3_utils.put_object(
            shared_bucket,
            key,
            contents,
            extra_args={
                'SSECustomerKey': encrypt_key,
                'SSECustomerAlgorithm': 'AES256',
            },
        )
        p = aws('s3 rm s3://%s/%s' % (shared_bucket, key))
        self.assert_no_errors(p)
        assert not s3_utils.key_exists(shared_bucket, key)

    def test_sse_c_upload_and_download_large_file(
        self, files, s3_utils, encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        contents = 'a' * (10 * (1024 * 1024))
        file_name = files.create_file(key, contents)

        # Upload the file using SSE-C
        p = aws(
            's3 cp %s s3://%s --sse-c AES256 --sse-c-key %s'
            % (file_name, shared_bucket, encrypt_key)
        )
        self.assert_no_errors(p)

        self.download_and_assert_sse_c_object_integrity(
            shared_bucket, key, encrypt_key, contents, files, s3_utils
        )

    def test_sse_c_copy(
        self, files, s3_utils, encrypt_key, other_encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload the file using SSE-C
        p = aws(
            's3 cp %s s3://%s --sse-c AES256 --sse-c-key %s'
            % (file_name, shared_bucket, encrypt_key)
        )
        self.assert_no_errors(p)

        # Copy the file using SSE-C and a new encryption key
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse-c AES256 --sse-c-key %s '
            '--sse-c-copy-source AES256 --sse-c-copy-source-key %s'
            % (
                shared_bucket,
                key,
                shared_bucket,
                new_key,
                other_encrypt_key,
                encrypt_key,
            )
        )
        self.assert_no_errors(p)
        self.download_and_assert_sse_c_object_integrity(
            shared_bucket,
            new_key,
            other_encrypt_key,
            contents,
            files,
            s3_utils,
        )

    def test_sse_c_copy_large_file(
        self, files, s3_utils, encrypt_key, other_encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        new_key = 'bar.txt'
        contents = 'a' * (10 * (1024 * 1024))
        file_name = files.create_file(key, contents)

        # Upload the file using SSE-C
        p = aws(
            's3 cp %s s3://%s --sse-c AES256 --sse-c-key %s'
            % (file_name, shared_bucket, encrypt_key)
        )
        self.assert_no_errors(p)

        # Copy the file using SSE-C and a new encryption key
        p = aws(
            's3 cp s3://%s/%s s3://%s/%s --sse-c AES256 --sse-c-key %s '
            '--sse-c-copy-source AES256 --sse-c-copy-source-key %s'
            % (
                shared_bucket,
                key,
                shared_bucket,
                new_key,
                other_encrypt_key,
                encrypt_key,
            )
        )
        self.assert_no_errors(p)
        self.download_and_assert_sse_c_object_integrity(
            shared_bucket,
            new_key,
            other_encrypt_key,
            contents,
            files,
            s3_utils,
        )

    def test_smoke_sync_sse_c(
        self, files, encrypt_key, other_encrypt_key, shared_bucket
    ):
        key = 'foo.txt'
        contents = 'contents'
        file_name = files.create_file(key, contents)

        # Upload sync
        p = aws(
            's3 sync %s s3://%s/foo/ --sse-c AES256 --sse-c-key %s'
            % (files.rootdir, shared_bucket, encrypt_key)
        )
        self.assert_no_errors(p)

        # Copy sync
        p = aws(
            's3 sync s3://%s/foo/ s3://%s/bar/ --sse-c AES256 '
            '--sse-c-key %s --sse-c-copy-source AES256 '
            '--sse-c-copy-source-key %s'
            % (shared_bucket, shared_bucket, other_encrypt_key, encrypt_key)
        )
        self.assert_no_errors(p)

        # Remove the original file
        os.remove(file_name)

        # Download sync
        p = aws(
            's3 sync s3://%s/bar/ %s --sse-c AES256 --sse-c-key %s'
            % (shared_bucket, files.rootdir, other_encrypt_key)
        )
        self.assert_no_errors(p)

        assert os.path.isfile(file_name)
        with open(file_name) as f:
            assert f.read() == contents


class TestPresignCommand(BaseS3IntegrationTest):
    def test_can_retrieve_presigned_url(self, s3_utils, shared_bucket):
        original_contents = b'this is foo.txt'
        s3_utils.put_object(shared_bucket, 'foo.txt', original_contents)
        p = aws('s3 presign s3://%s/foo.txt' % (shared_bucket,))
        self.assert_no_errors(p)
        url = p.stdout.strip()
        contents = urlopen(url).read()
        assert contents == original_contents