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 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
|
# Copyright (c) 2014 Christian Schwede <christian.schwede@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import unicode_literals
from genericpath import getmtime
import hashlib
import json
import logging
import mock
import os
import tempfile
import unittest
import textwrap
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import six
import swiftclient
from swiftclient.service import SwiftError
import swiftclient.shell
import swiftclient.utils
from os.path import basename, dirname
from .utils import (
CaptureOutput, fake_get_auth_keystone, _make_fake_import_keystone_client,
FakeKeystone, StubResponse, MockHttpTest)
from swiftclient.utils import EMPTY_ETAG
if six.PY2:
BUILTIN_OPEN = '__builtin__.open'
else:
BUILTIN_OPEN = 'builtins.open'
mocked_os_environ = {
'ST_AUTH': 'http://localhost:8080/auth/v1.0',
'ST_USER': 'test:tester',
'ST_KEY': 'testing'
}
clean_os_environ = {}
environ_prefixes = ('ST_', 'OS_')
for key in os.environ:
if any(key.startswith(m) for m in environ_prefixes):
clean_os_environ[key] = ''
def _make_args(cmd, opts, os_opts, separator='-', flags=None, cmd_args=None):
"""
Construct command line arguments for given options.
"""
args = [""]
flags = flags or []
for k, v in opts.items():
args.append("--" + k.replace("_", "-"))
if v is not None:
args.append(v)
for k, v in os_opts.items():
args.append("--os" + separator + k.replace("_", separator))
if v is not None:
args.append(v)
for flag in flags:
args.append('--%s' % flag)
if cmd:
args.append(cmd)
if cmd_args:
args.extend(cmd_args)
return args
def _make_env(opts, os_opts):
"""
Construct a dict of environment variables for given options.
"""
env = {}
for k, v in opts.items():
key = 'ST_' + k.upper().replace('-', '_')
env[key] = v
for k, v in os_opts.items():
key = 'OS_' + k.upper().replace('-', '_')
env[key] = v
return env
def _make_cmd(cmd, opts, os_opts, use_env=False, flags=None, cmd_args=None):
flags = flags or []
if use_env:
# set up fake environment variables and make a minimal command line
env = _make_env(opts, os_opts)
args = _make_args(cmd, {}, {}, separator='-', flags=flags,
cmd_args=cmd_args)
else:
# set up empty environment and make full command line
env = {}
args = _make_args(cmd, opts, os_opts, separator='-', flags=flags,
cmd_args=cmd_args)
return args, env
@mock.patch.dict(os.environ, mocked_os_environ)
class TestShell(unittest.TestCase):
def setUp(self):
super(TestShell, self).setUp()
tmpfile = tempfile.NamedTemporaryFile(delete=False)
self.tmpfile = tmpfile.name
def tearDown(self):
try:
os.remove(self.tmpfile)
except OSError:
pass
super(TestShell, self).tearDown()
@mock.patch('swiftclient.service.Connection')
def test_stat_account(self, connection):
argv = ["", "stat"]
return_headers = {
'x-account-container-count': '1',
'x-account-object-count': '2',
'x-account-bytes-used': '3',
'content-length': 0,
'date': ''}
connection.return_value.head_account.return_value = return_headers
connection.return_value.url = 'http://127.0.0.1/v1/AUTH_account'
with CaptureOutput() as output:
swiftclient.shell.main(argv)
self.assertEqual(output.out,
' Account: AUTH_account\n'
'Containers: 1\n'
' Objects: 2\n'
' Bytes: 3\n')
@mock.patch('swiftclient.service.Connection')
def test_stat_container(self, connection):
return_headers = {
'x-container-object-count': '1',
'x-container-bytes-used': '2',
'x-container-read': 'test2:tester2',
'x-container-write': 'test3:tester3',
'x-container-sync-to': 'other',
'x-container-sync-key': 'secret',
}
argv = ["", "stat", "container"]
connection.return_value.head_container.return_value = return_headers
connection.return_value.url = 'http://127.0.0.1/v1/AUTH_account'
with CaptureOutput() as output:
swiftclient.shell.main(argv)
self.assertEqual(output.out,
' Account: AUTH_account\n'
'Container: container\n'
' Objects: 1\n'
' Bytes: 2\n'
' Read ACL: test2:tester2\n'
'Write ACL: test3:tester3\n'
' Sync To: other\n'
' Sync Key: secret\n')
@mock.patch('swiftclient.service.Connection')
def test_stat_object(self, connection):
return_headers = {
'x-object-manifest': 'manifest',
'etag': 'md5',
'last-modified': 'yesterday',
'content-type': 'text/plain',
'content-length': 42,
}
argv = ["", "stat", "container", "object"]
connection.return_value.head_object.return_value = return_headers
connection.return_value.url = 'http://127.0.0.1/v1/AUTH_account'
with CaptureOutput() as output:
swiftclient.shell.main(argv)
self.assertEqual(output.out,
' Account: AUTH_account\n'
' Container: container\n'
' Object: object\n'
' Content Type: text/plain\n'
'Content Length: 42\n'
' Last Modified: yesterday\n'
' ETag: md5\n'
' Manifest: manifest\n')
@mock.patch('swiftclient.service.Connection')
def test_list_account(self, connection):
# Test account listing
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container'}]],
[None, []],
]
argv = ["", "list"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [mock.call(marker='', prefix=None),
mock.call(marker='container', prefix=None)]
connection.return_value.get_account.assert_has_calls(calls)
self.assertEqual(output.out, 'container\n')
@mock.patch('swiftclient.service.Connection')
def test_list_account_long(self, connection):
# Test account listing
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container', 'bytes': 0, 'count': 0}]],
[None, []],
]
argv = ["", "list", "--lh"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [mock.call(marker='', prefix=None),
mock.call(marker='container', prefix=None)]
connection.return_value.get_account.assert_has_calls(calls)
self.assertEqual(output.out,
' 0 0 1970-01-01 00:00:01 container\n'
' 0 0\n')
# Now test again, this time without returning metadata
connection.return_value.head_container.return_value = {}
# Test account listing
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container', 'bytes': 0, 'count': 0}]],
[None, []],
]
argv = ["", "list", "--lh"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [mock.call(marker='', prefix=None),
mock.call(marker='container', prefix=None)]
connection.return_value.get_account.assert_has_calls(calls)
self.assertEqual(output.out,
' 0 0 ????-??-?? ??:??:?? container\n'
' 0 0\n')
def test_list_account_totals_error(self):
# No --lh provided: expect info message about incorrect --totals use
argv = ["", "list", "--totals"]
with CaptureOutput() as output:
self.assertRaises(SystemExit, swiftclient.shell.main, argv)
self.assertEqual(output.err,
"Listing totals only works with -l or --lh.\n")
@mock.patch('swiftclient.service.Connection')
def test_list_account_totals(self, connection):
# Test account listing, only total count and size
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container1', 'bytes': 1, 'count': 2},
{'name': 'container2', 'bytes': 2, 'count': 4}]],
[None, []],
]
argv = ["", "list", "--lh", "--totals"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [mock.call(marker='', prefix=None)]
connection.return_value.get_account.assert_has_calls(calls)
self.assertEqual(output.out, ' 6 3\n')
@mock.patch('swiftclient.service.Connection')
def test_list_container(self, connection):
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object_a'}]],
[None, []],
]
argv = ["", "list", "container"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [
mock.call('container', marker='', delimiter=None, prefix=None),
mock.call('container', marker='object_a',
delimiter=None, prefix=None)]
connection.return_value.get_container.assert_has_calls(calls)
self.assertEqual(output.out, 'object_a\n')
# Test container listing with --long
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object_a', 'bytes': 0,
'content_type': 'type/content',
'last_modified': '123T456'}]],
[None, []],
]
argv = ["", "list", "container", "--long"]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
calls = [
mock.call('container', marker='', delimiter=None, prefix=None),
mock.call('container', marker='object_a',
delimiter=None, prefix=None)]
connection.return_value.get_container.assert_has_calls(calls)
self.assertEqual(output.out,
' 0 123 456'
' type/content object_a\n'
' 0\n')
@mock.patch('swiftclient.service.makedirs')
@mock.patch('swiftclient.service.Connection')
def test_download(self, connection, makedirs):
objcontent = six.BytesIO(b'objcontent')
connection.return_value.get_object.side_effect = [
({'content-type': 'text/plain',
'etag': '2cbbfe139a744d6abbe695e17f3c1991'},
objcontent),
({'content-type': 'text/plain',
'etag': EMPTY_ETAG},
'')
]
# Test downloading whole container
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}]],
[None, [{'name': 'pseudo/'}]],
[None, []],
]
connection.return_value.auth_end_time = 0
connection.return_value.attempts = 0
with mock.patch(BUILTIN_OPEN) as mock_open:
argv = ["", "download", "container"]
swiftclient.shell.main(argv)
calls = [mock.call('container', 'object',
headers={}, resp_chunk_size=65536,
response_dict={}),
mock.call('container', 'pseudo/',
headers={}, resp_chunk_size=65536,
response_dict={})]
connection.return_value.get_object.assert_has_calls(
calls, any_order=True)
mock_open.assert_called_once_with('object', 'wb')
self.assertEqual([mock.call('pseudo')], makedirs.mock_calls)
makedirs.reset_mock()
# Test downloading single object
objcontent = six.BytesIO(b'objcontent')
connection.return_value.get_object.side_effect = [
({'content-type': 'text/plain',
'etag': '2cbbfe139a744d6abbe695e17f3c1991'},
objcontent)
]
with mock.patch(BUILTIN_OPEN) as mock_open:
argv = ["", "download", "container", "object"]
swiftclient.shell.main(argv)
connection.return_value.get_object.assert_called_with(
'container', 'object', headers={}, resp_chunk_size=65536,
response_dict={})
mock_open.assert_called_with('object', 'wb')
self.assertEqual([], makedirs.mock_calls)
# Test downloading without md5 checks
objcontent = six.BytesIO(b'objcontent')
connection.return_value.get_object.side_effect = [
({'content-type': 'text/plain',
'etag': '2cbbfe139a744d6abbe695e17f3c1991'},
objcontent)
]
with mock.patch(BUILTIN_OPEN) as mock_open, mock.patch(
'swiftclient.service._SwiftReader') as sr:
argv = ["", "download", "container", "object", "--ignore-check"]
swiftclient.shell.main(argv)
connection.return_value.get_object.assert_called_with(
'container', 'object', headers={}, resp_chunk_size=65536,
response_dict={})
mock_open.assert_called_with('object', 'wb')
sr.assert_called_once_with('object', mock.ANY, mock.ANY, False)
self.assertEqual([], makedirs.mock_calls)
# Test downloading single object to stdout
objcontent = six.BytesIO(b'objcontent')
connection.return_value.get_object.side_effect = [
({'content-type': 'text/plain',
'etag': '2cbbfe139a744d6abbe695e17f3c1991'},
objcontent)
]
with CaptureOutput() as output:
argv = ["", "download", "--output", "-", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual('objcontent', output.out)
@mock.patch('swiftclient.service.shuffle')
@mock.patch('swiftclient.service.Connection')
def test_download_shuffle(self, connection, mock_shuffle):
# Test that the container and object lists are shuffled
mock_shuffle.side_effect = lambda l: l
connection.return_value.get_object.return_value = [
{'content-type': 'text/plain',
'etag': EMPTY_ETAG},
'']
connection.return_value.get_container.side_effect = [
(None, [{'name': 'object'}]),
(None, [{'name': 'pseudo/'}]),
(None, []),
]
connection.return_value.auth_end_time = 0
connection.return_value.attempts = 0
connection.return_value.get_account.side_effect = [
(None, [{'name': 'container'}]),
(None, [])
]
with mock.patch(BUILTIN_OPEN) as mock_open:
with mock.patch('swiftclient.service.makedirs') as mock_mkdir:
argv = ["", "download", "--all"]
swiftclient.shell.main(argv)
self.assertEqual(3, mock_shuffle.call_count)
mock_shuffle.assert_any_call(['container'])
mock_shuffle.assert_any_call(['object'])
mock_shuffle.assert_any_call(['pseudo/'])
mock_open.assert_called_once_with('container/object', 'wb')
self.assertEqual([
mock.call('container'),
mock.call('container/pseudo'),
], mock_mkdir.mock_calls)
# Test that the container and object lists are not shuffled
mock_shuffle.reset_mock()
connection.return_value.get_container.side_effect = [
(None, [{'name': 'object'}]),
(None, [{'name': 'pseudo/'}]),
(None, []),
]
connection.return_value.get_account.side_effect = [
(None, [{'name': 'container'}]),
(None, [])
]
with mock.patch(BUILTIN_OPEN) as mock_open:
with mock.patch('swiftclient.service.makedirs') as mock_mkdir:
argv = ["", "download", "--all", "--no-shuffle"]
swiftclient.shell.main(argv)
self.assertEqual(0, mock_shuffle.call_count)
mock_open.assert_called_once_with('container/object', 'wb')
self.assertEqual([
mock.call('container'),
mock.call('container/pseudo'),
], mock_mkdir.mock_calls)
@mock.patch('swiftclient.service.Connection')
def test_download_no_content_type(self, connection):
connection.return_value.get_object.return_value = [
{'etag': EMPTY_ETAG},
'']
# Test downloading whole container
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}]],
[None, [{'name': 'pseudo/'}]],
[None, []],
]
connection.return_value.auth_end_time = 0
connection.return_value.attempts = 0
with mock.patch(BUILTIN_OPEN) as mock_open:
with mock.patch('swiftclient.service.makedirs') as mock_mkdir:
argv = ["", "download", "container"]
swiftclient.shell.main(argv)
calls = [mock.call('container', 'object',
headers={}, resp_chunk_size=65536,
response_dict={}),
mock.call('container', 'pseudo/',
headers={}, resp_chunk_size=65536,
response_dict={})]
connection.return_value.get_object.assert_has_calls(
calls, any_order=True)
mock_open.assert_called_once_with('object', 'wb')
self.assertEqual([
mock.call('pseudo'),
], mock_mkdir.mock_calls)
@mock.patch('swiftclient.shell.walk')
@mock.patch('swiftclient.service.Connection')
def test_upload(self, connection, walk):
connection.return_value.head_object.return_value = {
'content-length': '0'}
connection.return_value.put_object.return_value = EMPTY_ETAG
connection.return_value.attempts = 0
argv = ["", "upload", "container", self.tmpfile,
"-H", "X-Storage-Policy:one"]
swiftclient.shell.main(argv)
connection.return_value.put_container.assert_called_once_with(
'container',
{'X-Storage-Policy': 'one'},
response_dict={})
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY,
'X-Storage-Policy': 'one'},
response_dict={})
# upload to pseudo-folder (via <container> param)
argv = ["", "upload", "container/pseudo-folder/nested", self.tmpfile,
"-H", "X-Storage-Policy:one"]
swiftclient.shell.main(argv)
connection.return_value.put_container.assert_called_with(
'container',
{'X-Storage-Policy': 'one'},
response_dict={})
connection.return_value.put_object.assert_called_with(
'container',
'pseudo-folder/nested' + self.tmpfile,
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY,
'X-Storage-Policy': 'one'},
response_dict={})
# Upload whole directory
argv = ["", "upload", "container", "/tmp"]
_tmpfile = self.tmpfile
_tmpfile_dir = dirname(_tmpfile)
_tmpfile_base = basename(_tmpfile)
walk.return_value = [(_tmpfile_dir, [], [_tmpfile_base])]
swiftclient.shell.main(argv)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY},
response_dict={})
# Upload in segments
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
argv = ["", "upload", "container", self.tmpfile, "-S", "10"]
with open(self.tmpfile, "wb") as fh:
fh.write(b'12345678901234567890')
swiftclient.shell.main(argv)
expected_calls = [mock.call('container',
{'X-Storage-Policy': mock.ANY},
response_dict={}),
mock.call('container_segments',
{'X-Storage-Policy': mock.ANY},
response_dict={})]
connection.return_value.put_container.has_calls(expected_calls)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
'',
content_length=0,
headers={'x-object-manifest': mock.ANY,
'x-object-meta-mtime': mock.ANY},
response_dict={})
# upload in segments to pseudo-folder (via <container> param)
connection.reset_mock()
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
argv = ["", "upload", "container/pseudo-folder/nested",
self.tmpfile, "-S", "10", "--use-slo"]
with open(self.tmpfile, "wb") as fh:
fh.write(b'12345678901234567890')
swiftclient.shell.main(argv)
expected_calls = [mock.call('container',
{},
response_dict={}),
mock.call('container_segments',
{'X-Storage-Policy': 'one'},
response_dict={})]
connection.return_value.put_container.assert_has_calls(expected_calls)
connection.return_value.put_object.assert_called_with(
'container',
'pseudo-folder/nested' + self.tmpfile,
mock.ANY,
headers={
'x-object-meta-mtime': mock.ANY,
'x-static-large-object': 'true'
},
query_string='multipart-manifest=put',
response_dict={})
@mock.patch('swiftclient.service.SwiftService.upload')
def test_upload_object_with_account_readonly(self, upload):
argv = ["", "upload", "container", self.tmpfile]
upload.return_value = [
{"success": False,
"headers": {},
"container": 'container',
"action": 'create_container',
"error": swiftclient.ClientException(
'Container PUT failed',
http_status=403,
http_reason='Forbidden',
http_response_content=b'<html><h1>Forbidden</h1>')
}]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
self.assertTrue(output.err != '')
warning_msg = "Warning: failed to create container 'container': " \
"403 Forbidden"
self.assertTrue(output.err.startswith(warning_msg))
@mock.patch('swiftclient.service.Connection')
def test_upload_delete_slo_segments(self, connection):
# Upload delete existing segments
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
connection.return_value.attempts = 0
argv = ["", "upload", "container", self.tmpfile]
connection.return_value.head_object.side_effect = [
{'x-static-large-object': 'true', # For the upload call
'content-length': '2'},
{'x-static-large-object': 'false', # For the 1st delete call
'content-length': '2'},
{'x-static-large-object': 'false', # For the 2nd delete call
'content-length': '2'}
]
connection.return_value.get_object.return_value = (
{},
b'[{"name": "container1/old_seg1"},'
b' {"name": "container2/old_seg2"}]'
)
connection.return_value.put_object.return_value = EMPTY_ETAG
# create the delete_object child mock here in attempt to fix
# https://bugs.launchpad.net/python-swiftclient/+bug/1480223
connection.return_value.delete_object.return_value = None
swiftclient.shell.main(argv)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY},
response_dict={})
expected_delete_calls = [
mock.call(
b'container1', b'old_seg1',
response_dict={}
),
mock.call(
b'container2', b'old_seg2',
response_dict={}
)
]
self.assertEqual(
sorted(expected_delete_calls),
sorted(connection.return_value.delete_object.mock_calls)
)
@mock.patch('swiftclient.service.Connection')
def test_upload_leave_slo_segments(self, connection):
# Test upload overwriting a manifest respects --leave-segments
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
connection.return_value.attempts = 0
argv = ["", "upload", "container", self.tmpfile, "--leave-segments"]
connection.return_value.head_object.side_effect = [
{'x-static-large-object': 'true', # For the upload call
'content-length': '2'}]
connection.return_value.put_object.return_value = (
'd41d8cd98f00b204e9800998ecf8427e')
swiftclient.shell.main(argv)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY},
response_dict={})
self.assertFalse(connection.return_value.delete_object.mock_calls)
@mock.patch('swiftclient.service.Connection')
def test_upload_delete_dlo_segments(self, connection):
# Upload delete existing segments
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
connection.return_value.attempts = 0
argv = ["", "upload", "container", self.tmpfile]
connection.return_value.head_object.side_effect = [
{'x-object-manifest': 'container1/prefix',
'content-length': '0'},
{},
{}
]
connection.return_value.get_container.side_effect = [
[None, [{'name': 'prefix_a', 'bytes': 0,
'last_modified': '123T456'}]],
# Have multiple pages worth of DLO segments
[None, [{'name': 'prefix_b', 'bytes': 0,
'last_modified': '123T456'}]],
[None, []]
]
connection.return_value.put_object.return_value = EMPTY_ETAG
# create the delete_object child mock here in attempt to fix
# https://bugs.launchpad.net/python-swiftclient/+bug/1480223
connection.return_value.delete_object.return_value = None
swiftclient.shell.main(argv)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY},
response_dict={})
expected_delete_calls = [
mock.call(
'container1', 'prefix_a',
response_dict={}
),
mock.call(
'container1', 'prefix_b',
response_dict={}
)
]
self.assertEqual(
sorted(expected_delete_calls),
sorted(connection.return_value.delete_object.mock_calls)
)
@mock.patch('swiftclient.service.Connection')
def test_upload_leave_dlo_segments(self, connection):
# Upload delete existing segments
connection.return_value.head_container.return_value = {
'x-storage-policy': 'one'}
connection.return_value.attempts = 0
argv = ["", "upload", "container", self.tmpfile, "--leave-segments"]
connection.return_value.head_object.side_effect = [
{'x-object-manifest': 'container1/prefix',
'content-length': '0'}]
connection.return_value.put_object.return_value = (
'd41d8cd98f00b204e9800998ecf8427e')
swiftclient.shell.main(argv)
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
mock.ANY,
content_length=0,
headers={'x-object-meta-mtime': mock.ANY},
response_dict={})
self.assertFalse(connection.return_value.delete_object.mock_calls)
@mock.patch('swiftclient.service.Connection')
def test_upload_segments_to_same_container(self, connection):
# Upload in segments to same container
connection.return_value.head_object.return_value = {
'content-length': '0'}
connection.return_value.attempts = 0
connection.return_value.put_object.return_value = EMPTY_ETAG
argv = ["", "upload", "container", self.tmpfile, "-S", "10",
"-C", "container"]
with open(self.tmpfile, "wb") as fh:
fh.write(b'12345678901234567890')
swiftclient.shell.main(argv)
connection.return_value.put_container.assert_called_once_with(
'container', {}, response_dict={})
connection.return_value.put_object.assert_called_with(
'container',
self.tmpfile.lstrip('/'),
'',
content_length=0,
headers={'x-object-manifest': mock.ANY,
'x-object-meta-mtime': mock.ANY},
response_dict={})
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_delete_bad_threads(self, mock_connection):
mock_connection.return_value.get_container.return_value = (None, [])
mock_connection.return_value.attempts = 0
def check_bad(argv):
args, env = _make_cmd(
'delete', {}, {}, cmd_args=['cont'] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertIn(
'ERROR: option %s should be a positive integer.' % argv[0],
output.err)
def check_good(argv):
args, env = _make_cmd(
'delete', {}, {}, cmd_args=['cont'] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
swiftclient.shell.main(args)
self.assertEqual('', output.err)
check_bad(["--object-threads", "-1"])
check_bad(["--object-threads", "0"])
check_bad(["--container-threads", "-1"])
check_bad(["--container-threads", "0"])
check_good(["--object-threads", "1"])
check_good(["--container-threads", "1"])
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_delete_account(self, connection):
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container'}, {'name': 'container2'}]],
[None, [{'name': 'empty_container'}]],
[None, []],
]
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}, {'name': 'obj\xe9ct2'}]],
[None, []],
[None, [{'name': 'object'}]],
[None, []],
[None, []],
]
connection.return_value.attempts = 0
argv = ["", "delete", "--all"]
connection.return_value.head_object.return_value = {}
connection.return_value.delete_object.return_value = None
swiftclient.shell.main(argv)
connection.return_value.delete_object.assert_has_calls([
mock.call('container', 'object', query_string=None,
response_dict={}),
mock.call('container', 'obj\xe9ct2', query_string=None,
response_dict={}),
mock.call('container2', 'object', query_string=None,
response_dict={})], any_order=True)
self.assertEqual(3, connection.return_value.delete_object.call_count,
'Expected 3 calls but found\n%r'
% connection.return_value.delete_object.mock_calls)
self.assertEqual(
connection.return_value.delete_container.mock_calls, [
mock.call('container', response_dict={}),
mock.call('container2', response_dict={}),
mock.call('empty_container', response_dict={})])
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: True)
@mock.patch('swiftclient.service.Connection')
def test_delete_bulk_account(self, connection):
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container'}, {'name': 'container2'}]],
[None, [{'name': 'empty_container'}]],
[None, []],
]
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}, {'name': 'obj\xe9ct2'},
{'name': 'object3'}]],
[None, []],
[None, [{'name': 'object'}]],
[None, []],
[None, []],
]
connection.return_value.attempts = 0
argv = ["", "delete", "--all", "--object-threads", "2"]
connection.return_value.post_account.return_value = {}, (
b'{"Number Not Found": 0, "Response Status": "200 OK", '
b'"Errors": [], "Number Deleted": 1, "Response Body": ""}')
swiftclient.shell.main(argv)
self.assertEqual(
3, len(connection.return_value.post_account.mock_calls),
'Expected 3 calls but found\n%r'
% connection.return_value.post_account.mock_calls)
# POSTs for same container are made in parallel so expect any order
for expected in [
mock.call(query_string='bulk-delete',
data=b'/container/object\n/container/obj%C3%A9ct2\n',
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={}),
mock.call(query_string='bulk-delete',
data=b'/container/object3\n',
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={})]:
self.assertIn(expected,
connection.return_value.post_account.mock_calls[:2])
# POSTs for different containers are made sequentially so expect order
self.assertEqual(
mock.call(query_string='bulk-delete',
data=b'/container2/object\n',
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={}),
connection.return_value.post_account.mock_calls[2])
self.assertEqual(
connection.return_value.delete_container.mock_calls, [
mock.call('container', response_dict={}),
mock.call('container2', response_dict={}),
mock.call('empty_container', response_dict={})])
@mock.patch('swiftclient.service.Connection')
def test_delete_bulk_account_with_capabilities(self, connection):
connection.return_value.get_capabilities.return_value = {
'bulk_delete': {
'max_deletes_per_request': 10000,
'max_failed_deletes': 1000,
},
}
connection.return_value.get_account.side_effect = [
[None, [{'name': 'container'}]],
[None, [{'name': 'container2'}]],
[None, [{'name': 'empty_container'}]],
[None, []],
]
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}, {'name': 'obj\xe9ct2'},
{'name': 'z_object'}, {'name': 'z_obj\xe9ct2'}]],
[None, []],
[None, [{'name': 'object'}, {'name': 'obj\xe9ct2'},
{'name': 'z_object'}, {'name': 'z_obj\xe9ct2'}]],
[None, []],
[None, []],
]
connection.return_value.attempts = 0
argv = ["", "delete", "--all", "--object-threads", "1"]
connection.return_value.post_account.return_value = {}, (
b'{"Number Not Found": 0, "Response Status": "200 OK", '
b'"Errors": [], "Number Deleted": 1, "Response Body": ""}')
swiftclient.shell.main(argv)
self.assertEqual(
connection.return_value.post_account.mock_calls, [
mock.call(query_string='bulk-delete',
data=b''.join([
b'/container/object\n',
b'/container/obj%C3%A9ct2\n',
b'/container/z_object\n',
b'/container/z_obj%C3%A9ct2\n'
]),
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={}),
mock.call(query_string='bulk-delete',
data=b''.join([
b'/container2/object\n',
b'/container2/obj%C3%A9ct2\n',
b'/container2/z_object\n',
b'/container2/z_obj%C3%A9ct2\n'
]),
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={})])
self.assertEqual(
connection.return_value.delete_container.mock_calls, [
mock.call('container', response_dict={}),
mock.call('container2', response_dict={}),
mock.call('empty_container', response_dict={})])
self.assertEqual(connection.return_value.get_capabilities.mock_calls,
[mock.call(None)]) # only one /info request
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_delete_container(self, connection):
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}]],
[None, []],
]
connection.return_value.attempts = 0
argv = ["", "delete", "container"]
connection.return_value.head_object.return_value = {}
swiftclient.shell.main(argv)
connection.return_value.delete_container.assert_called_with(
'container', response_dict={})
connection.return_value.delete_object.assert_called_with(
'container', 'object', query_string=None, response_dict={})
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: True)
@mock.patch('swiftclient.service.Connection')
def test_delete_bulk_container(self, connection):
connection.return_value.get_container.side_effect = [
[None, [{'name': 'object'}]],
[None, []],
]
connection.return_value.attempts = 0
argv = ["", "delete", "container"]
connection.return_value.post_account.return_value = {}, (
b'{"Number Not Found": 0, "Response Status": "200 OK", '
b'"Errors": [], "Number Deleted": 1, "Response Body": ""}')
swiftclient.shell.main(argv)
connection.return_value.post_account.assert_called_with(
query_string='bulk-delete', data=b'/container/object\n',
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={})
connection.return_value.delete_container.assert_called_with(
'container', response_dict={})
def test_delete_verbose_output_utf8(self):
container = 't\u00e9st_c'
base_argv = ['', '--verbose', 'delete']
# simulate container having an object with utf-8 code points in name,
# just returning the object delete result
res = {'success': True, 'response_dict': {}, 'attempts': 2,
'container': container, 'action': 'delete_object',
'object': 'obj_t\u00east_o'}
with mock.patch('swiftclient.shell.SwiftService.delete') as mock_func:
with CaptureOutput() as out:
mock_func.return_value = [res]
swiftclient.shell.main(base_argv + [container.encode('utf-8')])
mock_func.assert_called_once_with(container=container)
self.assertTrue(out.out.find(
'obj_t\u00east_o [after 2 attempts]') >= 0, out)
# simulate empty container
res = {'success': True, 'response_dict': {}, 'attempts': 2,
'container': container, 'action': 'delete_container'}
with mock.patch('swiftclient.shell.SwiftService.delete') as mock_func:
with CaptureOutput() as out:
mock_func.return_value = [res]
swiftclient.shell.main(base_argv + [container.encode('utf-8')])
mock_func.assert_called_once_with(container=container)
self.assertTrue(out.out.find(
't\u00e9st_c [after 2 attempts]') >= 0, out)
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_delete_per_object(self, connection):
argv = ["", "delete", "container", "object"]
connection.return_value.head_object.return_value = {}
connection.return_value.attempts = 0
swiftclient.shell.main(argv)
connection.return_value.delete_object.assert_called_with(
'container', 'object', query_string=None, response_dict={})
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: True)
@mock.patch('swiftclient.service.Connection')
def test_delete_bulk_object(self, connection):
argv = ["", "delete", "container", "object"]
connection.return_value.post_account.return_value = {}, (
b'{"Number Not Found": 0, "Response Status": "200 OK", '
b'"Errors": [], "Number Deleted": 1, "Response Body": ""}')
connection.return_value.attempts = 0
swiftclient.shell.main(argv)
connection.return_value.post_account.assert_called_with(
query_string='bulk-delete', data=b'/container/object\n',
headers={'Content-Type': 'text/plain',
'Accept': 'application/json'},
response_dict={})
def test_delete_verbose_output(self):
del_obj_res = {'success': True, 'response_dict': {}, 'attempts': 2,
'container': 't\xe9st_c', 'action': 'delete_object',
'object': 't\xe9st_o'}
del_seg_res = del_obj_res.copy()
del_seg_res.update({'action': 'delete_segment'})
del_con_res = del_obj_res.copy()
del_con_res.update({'action': 'delete_container', 'object': None})
test_exc = Exception('t\xe9st_exc')
error_res = del_obj_res.copy()
error_res.update({'success': False, 'error': test_exc, 'object': None})
mock_delete = mock.Mock()
base_argv = ['', '--verbose', 'delete']
with mock.patch('swiftclient.shell.SwiftService.delete', mock_delete):
with CaptureOutput() as out:
mock_delete.return_value = [del_obj_res]
swiftclient.shell.main(base_argv + ['t\xe9st_c', 't\xe9st_o'])
mock_delete.assert_called_once_with(container='t\xe9st_c',
objects=['t\xe9st_o'])
self.assertTrue(out.out.find(
't\xe9st_o [after 2 attempts]') >= 0)
with CaptureOutput() as out:
mock_delete.return_value = [del_seg_res]
swiftclient.shell.main(base_argv + ['t\xe9st_c', 't\xe9st_o'])
mock_delete.assert_called_with(container='t\xe9st_c',
objects=['t\xe9st_o'])
self.assertTrue(out.out.find(
't\xe9st_c/t\xe9st_o [after 2 attempts]') >= 0)
with CaptureOutput() as out:
mock_delete.return_value = [del_con_res]
swiftclient.shell.main(base_argv + ['t\xe9st_c'])
mock_delete.assert_called_with(container='t\xe9st_c')
self.assertTrue(out.out.find(
't\xe9st_c [after 2 attempts]') >= 0)
with CaptureOutput() as out:
mock_delete.return_value = [error_res]
self.assertRaises(SystemExit,
swiftclient.shell.main,
base_argv + ['t\xe9st_c'])
mock_delete.assert_called_with(container='t\xe9st_c')
self.assertTrue(out.err.find(
'Error Deleting: t\xe9st_c: t\xe9st_exc') >= 0)
@mock.patch('swiftclient.service.Connection')
def test_post_account(self, connection):
argv = ["", "post"]
swiftclient.shell.main(argv)
connection.return_value.post_account.assert_called_with(
headers={}, response_dict={})
@mock.patch('swiftclient.service.Connection')
def test_post_account_bad_auth(self, connection):
argv = ["", "post"]
connection.return_value.post_account.side_effect = \
swiftclient.ClientException(
'bad auth', http_response_headers={'X-Trans-Id': 'trans_id'})
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err,
'bad auth\nFailed Transaction ID: trans_id\n')
# do it again with a unicode token
connection.return_value.post_account.side_effect = \
swiftclient.ClientException(
'bad auth', http_response_headers={
'X-Trans-Id': 'non\u2011utf8'})
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err,
'bad auth\n'
'Failed Transaction ID: non\u2011utf8\n')
# do it again with a wonky token
connection.return_value.post_account.side_effect = \
swiftclient.ClientException(
'bad auth', http_response_headers={
'X-Trans-Id': b'non\xffutf8'})
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err,
'bad auth\nFailed Transaction ID: non%FFutf8\n')
@mock.patch('swiftclient.service.Connection')
def test_post_account_not_found(self, connection):
argv = ["", "post"]
connection.return_value.post_account.side_effect = \
swiftclient.ClientException('test', http_status=404)
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err, 'Account not found\n')
@mock.patch('swiftclient.service.Connection')
def test_post_container(self, connection):
argv = ["", "post", "container"]
swiftclient.shell.main(argv)
connection.return_value.post_container.assert_called_with(
'container', headers={}, response_dict={})
@mock.patch('swiftclient.service.Connection')
def test_post_container_bad_auth(self, connection):
argv = ["", "post", "container"]
connection.return_value.post_container.side_effect = \
swiftclient.ClientException('bad auth')
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err, 'bad auth\n')
@mock.patch('swiftclient.service.Connection')
def test_post_container_not_found_causes_put(self, connection):
argv = ["", "post", "container"]
connection.return_value.post_container.side_effect = \
swiftclient.ClientException('test', http_status=404)
swiftclient.shell.main(argv)
self.assertEqual('container',
connection.return_value.put_container.call_args[0][0])
def test_post_container_with_bad_name(self):
argv = ["", "post", "conta/iner"]
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertTrue(output.err != '')
self.assertTrue(output.err.startswith('WARNING: / in'))
@mock.patch('swiftclient.service.Connection')
def test_post_container_with_options(self, connection):
argv = ["", "post", "container",
"--read-acl", "test2:tester2",
"--write-acl", "test3:tester3 test4",
"--sync-to", "othersite",
"--sync-key", "secret",
]
swiftclient.shell.main(argv)
connection.return_value.post_container.assert_called_with(
'container', headers={
'X-Container-Write': 'test3:tester3 test4',
'X-Container-Read': 'test2:tester2',
'X-Container-Sync-Key': 'secret',
'X-Container-Sync-To': 'othersite'}, response_dict={})
@mock.patch('swiftclient.service.Connection')
def test_post_object(self, connection):
argv = ["", "post", "container", "object",
"--meta", "Color:Blue",
"--header", "content-type:text/plain"
]
swiftclient.shell.main(argv)
connection.return_value.post_object.assert_called_with(
'container', 'object', headers={
'Content-Type': 'text/plain',
'X-Object-Meta-Color': 'Blue'}, response_dict={})
@mock.patch('swiftclient.service.Connection')
def test_post_object_bad_auth(self, connection):
argv = ["", "post", "container", "object"]
connection.return_value.post_object.side_effect = \
swiftclient.ClientException("bad auth")
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err, 'bad auth\n')
def test_post_object_too_many_args(self):
argv = ["", "post", "container", "object", "bad_arg"]
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertTrue(output.err != '')
self.assertTrue(output.err.startswith('Usage'))
@mock.patch('swiftclient.service.Connection')
def test_copy_object_no_destination(self, connection):
argv = ["", "copy", "container", "object",
"--meta", "Color:Blue",
"--header", "content-type:text/plain"
]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
connection.return_value.copy_object.assert_called_with(
'container', 'object', destination=None, fresh_metadata=False,
headers={
'Content-Type': 'text/plain',
'X-Object-Meta-Color': 'Blue'}, response_dict={})
self.assertEqual(output.out, 'container/object copied to <self>\n')
@mock.patch('swiftclient.service.Connection')
def test_copy_object(self, connection):
argv = ["", "copy", "container", "object",
"--meta", "Color:Blue",
"--header", "content-type:text/plain",
"--destination", "/c/o"
]
with CaptureOutput() as output:
swiftclient.shell.main(argv)
connection.return_value.copy_object.assert_called_with(
'container', 'object', destination="/c/o",
fresh_metadata=False,
headers={
'Content-Type': 'text/plain',
'X-Object-Meta-Color': 'Blue'}, response_dict={})
self.assertEqual(
output.out,
'created container c\ncontainer/object copied to /c/o\n'
)
@mock.patch('swiftclient.service.Connection')
def test_copy_object_fresh_metadata(self, connection):
argv = ["", "copy", "container", "object",
"--meta", "Color:Blue", "--fresh-metadata",
"--header", "content-type:text/plain",
"--destination", "/c/o"
]
swiftclient.shell.main(argv)
connection.return_value.copy_object.assert_called_with(
'container', 'object', destination="/c/o", fresh_metadata=True,
headers={
'Content-Type': 'text/plain',
'X-Object-Meta-Color': 'Blue'}, response_dict={})
@mock.patch('swiftclient.service.Connection')
def test_copy_two_objects(self, connection):
argv = ["", "copy", "container", "object", "object2",
"--meta", "Color:Blue"]
connection.return_value.copy_object.return_value = None
swiftclient.shell.main(argv)
calls = [
mock.call(
'container', 'object', destination=None,
fresh_metadata=False, headers={'X-Object-Meta-Color': 'Blue'},
response_dict={}),
mock.call(
'container', 'object2', destination=None,
fresh_metadata=False, headers={'X-Object-Meta-Color': 'Blue'},
response_dict={})
]
for call in calls:
self.assertIn(call, connection.return_value.copy_object.mock_calls)
self.assertEqual(len(connection.return_value.copy_object.mock_calls),
len(calls))
@mock.patch('swiftclient.service.Connection')
def test_copy_two_objects_destination(self, connection):
argv = ["", "copy", "container", "object", "object2",
"--meta", "Color:Blue", "--destination", "/c"]
swiftclient.shell.main(argv)
calls = [
mock.call(
'container', 'object', destination="/c/object",
fresh_metadata=False, headers={'X-Object-Meta-Color': 'Blue'},
response_dict={}),
mock.call(
'container', 'object2', destination="/c/object2",
fresh_metadata=False, headers={'X-Object-Meta-Color': 'Blue'},
response_dict={})
]
connection.return_value.copy_object.assert_has_calls(calls)
@mock.patch('swiftclient.service.Connection')
def test_copy_two_objects_bad_destination(self, connection):
argv = ["", "copy", "container", "object", "object2",
"--meta", "Color:Blue", "--destination", "/c/o"]
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(
output.err,
'Combination of multiple objects and destination '
'including object is invalid\n')
@mock.patch('swiftclient.service.Connection')
def test_copy_object_bad_auth(self, connection):
argv = ["", "copy", "container", "object"]
connection.return_value.copy_object.side_effect = \
swiftclient.ClientException("bad auth")
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertEqual(output.err, 'bad auth\n')
def test_copy_object_not_enough_args(self):
argv = ["", "copy", "container"]
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertTrue(output.err != '')
self.assertTrue(output.err.startswith('Usage'))
def test_copy_bad_container(self):
argv = ["", "copy", "cont/ainer", "object"]
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
swiftclient.shell.main(argv)
self.assertTrue(output.err != '')
self.assertTrue(output.err.startswith('WARN'))
@mock.patch('swiftclient.shell.generate_temp_url', return_value='')
def test_temp_url(self, temp_url):
argv = ["", "tempurl", "GET", "60", "/v1/AUTH_account/c/o",
"secret_key"]
swiftclient.shell.main(argv)
temp_url.assert_called_with(
'/v1/AUTH_account/c/o', 60, 'secret_key', 'GET', absolute=False)
@mock.patch('swiftclient.shell.generate_temp_url', return_value='')
def test_absolute_expiry_temp_url(self, temp_url):
argv = ["", "tempurl", "GET", "60", "/v1/AUTH_account/c/o",
"secret_key", "--absolute"]
swiftclient.shell.main(argv)
temp_url.assert_called_with(
'/v1/AUTH_account/c/o', 60, 'secret_key', 'GET', absolute=True)
@mock.patch('swiftclient.service.Connection')
def test_capabilities(self, connection):
argv = ["", "capabilities"]
connection.return_value.get_capabilities.return_value = {'swift': None}
swiftclient.shell.main(argv)
connection.return_value.get_capabilities.assert_called_with(None)
@mock.patch('swiftclient.service.Connection')
def test_capabilities_json(self, connection):
capabilities = {
'slo': {'min_segment_size': 1000000},
'some': [{'arbitrary': 'nested'}, {'crazy': 'structure'}],
'swift': {'version': '2.5.0'}}
connection.return_value.get_capabilities.return_value = capabilities
argv = ["", "capabilities", "--json"]
with CaptureOutput(suppress_systemexit=True) as output:
swiftclient.shell.main(argv)
expected = json.dumps(capabilities, sort_keys=True, indent=2) + '\n'
self.assertEqual(expected, output.out)
connection.return_value.get_capabilities.assert_called_with(None)
def test_human_readable_upload_segment_size(self):
def _check_expected(x, expected):
actual = x.call_args_list[-1][1]["options"]["segment_size"]
self.assertEqual(int(actual), expected)
mock_swift = mock.MagicMock(spec=swiftclient.shell.SwiftService)
with mock.patch("swiftclient.shell.SwiftService", mock_swift):
with CaptureOutput(suppress_systemexit=True) as output:
# Test new behaviour with both upper and lower case
# trailing characters
argv = ["", "upload", "-S", "1B", "container", "object"]
swiftclient.shell.main(argv)
_check_expected(mock_swift, 1)
argv = ["", "upload", "-S", "1K", "container", "object"]
swiftclient.shell.main(argv)
_check_expected(mock_swift, 1024)
argv = ["", "upload", "-S", "1m", "container", "object"]
swiftclient.shell.main(argv)
_check_expected(mock_swift, 1048576)
argv = ["", "upload", "-S", "1G", "container", "object"]
swiftclient.shell.main(argv)
_check_expected(mock_swift, 1073741824)
# Test old behaviour is not affected
argv = ["", "upload", "-S", "12345", "container", "object"]
swiftclient.shell.main(argv)
_check_expected(mock_swift, 12345)
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
# Test invalid states
argv = ["", "upload", "-S", "1234X", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "Invalid segment size\n")
output.clear()
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S", "K1234", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "Invalid segment size\n")
output.clear()
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S", "K", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "Invalid segment size\n")
def test_negative_upload_segment_size(self):
with CaptureOutput() as output:
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S", "-40", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "segment-size should be positive\n")
output.clear()
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S=-40K", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "segment-size should be positive\n")
output.clear()
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S=-40M", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "segment-size should be positive\n")
output.clear()
with self.assertRaises(SystemExit):
argv = ["", "upload", "-S=-40G", "container", "object"]
swiftclient.shell.main(argv)
self.assertEqual(output.err, "segment-size should be positive\n")
output.clear()
class TestSubcommandHelp(unittest.TestCase):
def test_subcommand_help(self):
for command in swiftclient.shell.commands:
help_var = 'st_%s_help' % command
self.assertTrue(hasattr(swiftclient.shell, help_var))
with CaptureOutput() as out:
argv = ['', command, '--help']
self.assertRaises(SystemExit, swiftclient.shell.main, argv)
expected = vars(swiftclient.shell)[help_var]
self.assertEqual(out.strip('\n'), expected)
def test_no_help(self):
with CaptureOutput() as out:
argv = ['', 'bad_command', '--help']
self.assertRaises(SystemExit, swiftclient.shell.main, argv)
expected = 'no help for bad_command'
self.assertEqual(out.strip('\n'), expected)
@mock.patch.dict(os.environ, mocked_os_environ)
class TestDebugAndInfoOptions(unittest.TestCase):
@mock.patch('logging.basicConfig')
@mock.patch('swiftclient.service.Connection')
def test_option_after_posarg(self, connection, mock_logging):
argv = ["", "stat", "--info"]
swiftclient.shell.main(argv)
mock_logging.assert_called_with(level=logging.INFO)
argv = ["", "stat", "--debug"]
swiftclient.shell.main(argv)
mock_logging.assert_called_with(level=logging.DEBUG)
@mock.patch('logging.basicConfig')
@mock.patch('swiftclient.service.Connection')
def test_debug_trumps_info(self, connection, mock_logging):
argv_scenarios = (["", "stat", "--info", "--debug"],
["", "stat", "--debug", "--info"],
["", "--info", "stat", "--debug"],
["", "--debug", "stat", "--info"],
["", "--info", "--debug", "stat"],
["", "--debug", "--info", "stat"])
for argv in argv_scenarios:
mock_logging.reset_mock()
swiftclient.shell.main(argv)
try:
mock_logging.assert_called_once_with(level=logging.DEBUG)
except AssertionError:
self.fail('Unexpected call(s) %r for args %r'
% (mock_logging.call_args_list, argv))
class TestBase(unittest.TestCase):
"""
Provide some common methods to subclasses
"""
def _remove_swift_env_vars(self):
self._environ_vars = {}
keys = list(os.environ.keys())
for k in keys:
if (k in ('ST_KEY', 'ST_USER', 'ST_AUTH')
or k.startswith('OS_')):
self._environ_vars[k] = os.environ.pop(k)
def _replace_swift_env_vars(self):
os.environ.update(self._environ_vars)
class TestParsing(TestBase):
def setUp(self):
super(TestParsing, self).setUp()
self._remove_swift_env_vars()
def tearDown(self):
self._replace_swift_env_vars()
super(TestParsing, self).tearDown()
def _make_fake_command(self, result):
def fake_command(parser, args, thread_manager):
result[0], result[1] = swiftclient.shell.parse_args(parser, args)
return fake_command
def _verify_opts(self, actual_opts, expected_opts, expected_os_opts=None,
expected_os_opts_dict=None):
"""
Check parsed options are correct.
:param expected_opts: v1 style options.
:param expected_os_opts: openstack style options.
:param expected_os_opts_dict: openstack options that should be found in
the os_options dict.
"""
expected_os_opts = expected_os_opts or {}
expected_os_opts_dict = expected_os_opts_dict or {}
# check the expected opts are set
for key, v in expected_opts.items():
actual = actual_opts.get(key)
self.assertEqual(v, actual, 'Expected %s for key %s, found %s' %
(v, key, actual))
for key, v in expected_os_opts.items():
actual = actual_opts.get("os_" + key)
self.assertEqual(v, actual, 'Expected %s for key %s, found %s' %
(v, key, actual))
# check the os_options dict values are set
self.assertIn('os_options', actual_opts)
actual_os_opts_dict = actual_opts['os_options']
expected_os_opts_keys = ['project_name', 'region_name',
'tenant_name',
'user_domain_name', 'endpoint_type',
'object_storage_url', 'project_domain_id',
'user_id', 'user_domain_id', 'tenant_id',
'service_type', 'project_id', 'auth_token',
'project_domain_name']
for key in expected_os_opts_keys:
self.assertIn(key, actual_os_opts_dict)
cli_key = key
if key == 'object_storage_url':
# exceptions to the pattern...
cli_key = 'storage_url'
if cli_key in expected_os_opts_dict:
expect = expected_os_opts_dict[cli_key]
else:
expect = None
actual = actual_os_opts_dict[key]
self.assertEqual(expect, actual, 'Expected %s for %s, got %s'
% (expect, key, actual))
for key in actual_os_opts_dict:
self.assertIn(key, expected_os_opts_keys)
# check that equivalent keys have equal values
equivalents = [('os_username', 'user'),
('os_auth_url', 'auth'),
('os_password', 'key')]
for pair in equivalents:
self.assertEqual(actual_opts.get(pair[0]),
actual_opts.get(pair[1]))
def test_minimum_required_args_v3(self):
opts = {"auth_version": "3"}
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
# username with domain is sufficient in args because keystone will
# assume user is in default domain
args = _make_args("stat", opts, os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, {})
# check its ok to have user_id instead of username
os_opts = {"password": "secret",
"auth_url": "http://example.com:5000/v3"}
os_opts_dict = {"user_id": "user_ID"}
all_os_opts = os_opts.copy()
all_os_opts.update(os_opts_dict)
args = _make_args("stat", opts, all_os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
# check no user credentials required if token and url supplied
os_opts = {}
os_opts_dict = {"storage_url": "http://example.com:8080/v1",
"auth_token": "0123abcd"}
args = _make_args("stat", opts, os_opts_dict, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
def test_sloppy_versions(self):
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3",
"identity-api-version": "3.0"}
# check os_identity_api_version=3.0 is mapped to auth_version=3
args = _make_args("stat", {}, os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, {}):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '3'} # NB: not '3.0'
expected_os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check os_identity_api_version=2 is mapped to auth_version=2.0
# A somewhat contrived scenario - we need to pass in the v1 style opts
# to prevent auth version defaulting to 2.0 due to lack of v1 style
# options. That way we can actually verify that the sloppy 2 was
# interpreted and mapped to 2.0
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v2.0",
"identity-api-version": "2"}
opts = {"key": "secret",
"user": "user",
"auth": "http://example.com:5000/v2.0"}
args = _make_args("stat", opts, os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, {}):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '2.0'} # NB: not '2'
expected_os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v2.0"}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
def test_os_identity_api_version(self):
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3",
"identity-api-version": "3"}
# check os_identity_api_version is sufficient in place of auth_version
args = _make_args("stat", {}, os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, {}):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '3'}
expected_os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check again using environment variables
args = _make_args("stat", {}, {})
env = _make_env({}, os_opts)
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check that last of auth-version, os-identity-api-version is preferred
args = _make_args("stat", {}, os_opts, '-') + ['--auth-version', '2.0']
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, {}):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '2.0'}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# now put auth_version ahead of os-identity-api-version
args = _make_args("stat", {"auth_version": "2.0"}, os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, {}):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '3'}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check that OS_AUTH_VERSION overrides OS_IDENTITY_API_VERSION
args = _make_args("stat", {}, {})
env = _make_env({}, os_opts)
env.update({'OS_AUTH_VERSION': '2.0'})
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
expected_opts = {'auth_version': '2.0'}
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check that ST_AUTH_VERSION overrides OS_IDENTITY_API_VERSION
args = _make_args("stat", {}, {})
env = _make_env({}, os_opts)
env.update({'ST_AUTH_VERSION': '2.0'})
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
# check that ST_AUTH_VERSION overrides OS_AUTH_VERSION
args = _make_args("stat", {}, {})
env = _make_env({}, os_opts)
env.update({'ST_AUTH_VERSION': '2.0', 'OS_AUTH_VERSION': '3'})
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], expected_opts, expected_os_opts, {})
def test_args_v3(self):
opts = {"auth_version": "3"}
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
os_opts_dict = {"user_id": "user_ID",
"project_id": "project_ID",
"tenant_id": "tenant_ID",
"project_domain_id": "project_domain_ID",
"user_domain_id": "user_domain_ID",
"tenant_name": "tenant",
"project_name": "project",
"project_domain_name": "project_domain",
"user_domain_name": "user_domain",
"auth_token": "token",
"storage_url": "http://example.com:8080/v1",
"region_name": "region",
"service_type": "service",
"endpoint_type": "endpoint"}
all_os_opts = os_opts.copy()
all_os_opts.update(os_opts_dict)
# check using hyphen separator
args = _make_args("stat", opts, all_os_opts, '-')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
# check using underscore separator
args = _make_args("stat", opts, all_os_opts, '_')
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
# check using environment variables
args = _make_args("stat", {}, {})
env = _make_env(opts, all_os_opts)
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
# check again using OS_AUTH_VERSION instead of ST_AUTH_VERSION
env = _make_env({}, all_os_opts)
env.update({'OS_AUTH_VERSION': '3'})
result = [None, None]
fake_command = self._make_fake_command(result)
with mock.patch.dict(os.environ, env):
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self._verify_opts(result[0], opts, os_opts, os_opts_dict)
def test_command_args_v3(self):
result = [None, None]
fake_command = self._make_fake_command(result)
opts = {"auth_version": "3"}
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
args = _make_args("stat", opts, os_opts)
with mock.patch('swiftclient.shell.st_stat', fake_command):
swiftclient.shell.main(args)
self.assertEqual(['stat'], result[1])
with mock.patch('swiftclient.shell.st_stat', fake_command):
args = args + ["container_name"]
swiftclient.shell.main(args)
self.assertEqual(["stat", "container_name"], result[1])
def test_insufficient_args_v3(self):
opts = {"auth_version": "3"}
os_opts = {"password": "secret",
"auth_url": "http://example.com:5000/v3"}
args = _make_args("stat", opts, os_opts)
self.assertRaises(SystemExit, swiftclient.shell.main, args)
os_opts = {"username": "user",
"auth_url": "http://example.com:5000/v3"}
args = _make_args("stat", opts, os_opts)
self.assertRaises(SystemExit, swiftclient.shell.main, args)
os_opts = {"username": "user",
"password": "secret"}
args = _make_args("stat", opts, os_opts)
self.assertRaises(SystemExit, swiftclient.shell.main, args)
def test_no_tenant_name_or_id_v2(self):
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3",
"tenant_name": "",
"tenant_id": ""}
with CaptureOutput() as output:
args = _make_args("stat", {}, os_opts)
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertEqual(output.err.strip(), 'No tenant specified')
with CaptureOutput() as output:
args = _make_args("stat", {}, os_opts, cmd_args=["testcontainer"])
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertEqual(output.err.strip(), 'No tenant specified')
def test_no_tenant_name_or_id_v3(self):
os_opts = {"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3",
"tenant_name": "",
"tenant_id": ""}
with CaptureOutput() as output:
args = _make_args("stat", {"auth_version": "3"}, os_opts)
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertEqual(output.err.strip(),
'No project name or project id specified.')
with CaptureOutput() as output:
args = _make_args("stat", {"auth_version": "3"},
os_opts, cmd_args=["testcontainer"])
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertEqual(output.err.strip(),
'No project name or project id specified.')
def test_insufficient_env_vars_v3(self):
args = _make_args("stat", {}, {})
opts = {"auth_version": "3"}
os_opts = {"password": "secret",
"auth_url": "http://example.com:5000/v3"}
env = _make_env(opts, os_opts)
with mock.patch.dict(os.environ, env):
self.assertRaises(SystemExit, swiftclient.shell.main, args)
os_opts = {"username": "user",
"auth_url": "http://example.com:5000/v3"}
env = _make_env(opts, os_opts)
with mock.patch.dict(os.environ, env):
self.assertRaises(SystemExit, swiftclient.shell.main, args)
os_opts = {"username": "user",
"password": "secret"}
env = _make_env(opts, os_opts)
with mock.patch.dict(os.environ, env):
self.assertRaises(SystemExit, swiftclient.shell.main, args)
def test_help(self):
# --help returns condensed help message
opts = {"help": None}
os_opts = {}
args = _make_args(None, opts, os_opts)
with CaptureOutput() as out:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertTrue(out.find('[--key <api_key>]') > 0)
self.assertEqual(-1, out.find('--os-username=<auth-user-name>'))
# --help returns condensed help message, overrides --os-help
opts = {"help": None}
os_opts = {"help": None}
args = _make_args("", opts, os_opts)
with CaptureOutput() as out:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertTrue(out.find('[--key <api_key>]') > 0)
self.assertEqual(-1, out.find('--os-username=<auth-user-name>'))
# --os-password, --os-username and --os-auth_url should be ignored
# because --help overrides it
opts = {"help": None}
os_opts = {"help": None,
"password": "secret",
"username": "user",
"auth_url": "http://example.com:5000/v3"}
args = _make_args("", opts, os_opts)
with CaptureOutput() as out:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertTrue(out.find('[--key <api_key>]') > 0)
self.assertEqual(-1, out.find('--os-username=<auth-user-name>'))
# --os-help return os options help
opts = {}
args = _make_args("", opts, os_opts)
with CaptureOutput() as out:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertTrue(out.find('[--key <api_key>]') > 0)
self.assertTrue(out.find('--os-username=<auth-user-name>') > 0)
class TestKeystoneOptions(MockHttpTest):
"""
Tests to check that options are passed from the command line or
environment variables through to the keystone client interface.
"""
all_os_opts = {'password': 'secret',
'username': 'user',
'auth-url': 'http://example.com:5000/v3',
'user-domain-name': 'userdomain',
'user-id': 'userid',
'user-domain-id': 'userdomainid',
'tenant-name': 'tenantname',
'tenant-id': 'tenantid',
'project-name': 'projectname',
'project-id': 'projectid',
'project-domain-id': 'projectdomainid',
'project-domain-name': 'projectdomain',
'cacert': 'foo',
'cert': 'minnie',
'key': 'mickey'}
catalog_opts = {'service-type': 'my-object-store',
'endpoint-type': 'public',
'region-name': 'my-region'}
flags = ['insecure', 'debug']
# options that are given default values in code if missing from CLI
defaults = {'auth-version': '2.0',
'service-type': 'object-store',
'endpoint-type': 'publicURL'}
def _build_os_opts(self, keys):
os_opts = {}
for k in keys:
os_opts[k] = self.all_os_opts.get(k, self.catalog_opts.get(k))
return os_opts
def _test_options_passed_to_keystone(self, cmd, opts, os_opts,
flags=None, use_env=False,
cmd_args=None, no_auth=False):
flags = flags or []
if use_env:
# set up fake environment variables and make a minimal command line
env = _make_env(opts, os_opts)
args = _make_args(cmd, {}, {}, separator='-', flags=flags,
cmd_args=cmd_args)
else:
# set up empty environment and make full command line
env = {}
args = _make_args(cmd, opts, os_opts, separator='-', flags=flags,
cmd_args=cmd_args)
ks_endpoint = 'http://example.com:8080/v1/AUTH_acc'
ks_token = 'fake_auth_token'
fake_ks = FakeKeystone(endpoint=ks_endpoint, token=ks_token)
# fake_conn will check that storage_url and auth_token are as expected
endpoint = os_opts.get('storage-url', ks_endpoint)
token = os_opts.get('auth-token', ks_token)
fake_conn = self.fake_http_connection(204, headers={},
storage_url=endpoint,
auth_token=token)
with mock.patch('swiftclient.client._import_keystone_client',
_make_fake_import_keystone_client(fake_ks)), \
mock.patch('swiftclient.client.http_connection', fake_conn), \
mock.patch.dict(os.environ, env, clear=True), \
mock.patch('requests.packages.urllib3.disable_warnings') as \
mock_disable_warnings:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
except SwiftError as err:
self.fail('Unexpected SwiftError: %s' % err)
if 'insecure' in flags:
self.assertEqual([mock.call(InsecureRequestWarning)],
mock_disable_warnings.mock_calls)
else:
self.assertEqual([], mock_disable_warnings.mock_calls)
if no_auth:
# check that keystone client was not used and terminate tests
self.assertIsNone(getattr(fake_ks, 'auth_version'))
self.assertEqual(len(fake_ks.calls), 0)
return
# check correct auth version was passed to _import_keystone_client
key = 'auth-version'
expected = opts.get(key, self.defaults.get(key))
self.assertEqual(expected, fake_ks.auth_version)
# check args passed to keystone Client __init__
self.assertEqual(len(fake_ks.calls), 1)
actual_args = fake_ks.calls[0]
for key in self.all_os_opts.keys():
expected = os_opts.get(key, self.defaults.get(key))
key = key.replace('-', '_')
self.assertIn(key, actual_args)
self.assertEqual(expected, actual_args[key],
'Expected %s for key %s, found %s'
% (expected, key, actual_args[key]))
for flag in flags:
self.assertTrue(flag in actual_args)
self.assertTrue(actual_args[flag])
check_attr = True
# check args passed to ServiceCatalog.url_for() method
self.assertEqual(len(fake_ks.client.service_catalog.calls), 1)
actual_args = fake_ks.client.service_catalog.calls[0]
for key in self.catalog_opts.keys():
expected = os_opts.get(key, self.defaults.get(key))
key = key.replace('-', '_')
if key == 'region_name':
key = 'filter_value'
if expected is None:
check_attr = False
self.assertNotIn(key, actual_args)
self.assertNotIn('attr', actual_args)
continue
self.assertIn(key, actual_args)
self.assertEqual(expected, actual_args[key],
'Expected %s for key %s, found %s'
% (expected, key, actual_args[key]))
if check_attr:
key, v = 'attr', 'region'
self.assertIn(key, actual_args)
self.assertEqual(v, actual_args[key],
'Expected %s for key %s, found %s'
% (v, key, actual_args[key]))
def _test_options(self, opts, os_opts, flags=None, no_auth=False):
# repeat test for different commands using env and command line options
for cmd in ('stat', 'post'):
self._test_options_passed_to_keystone(cmd, opts, os_opts,
flags=flags, no_auth=no_auth)
self._test_options_passed_to_keystone(cmd, opts, os_opts,
flags=flags, use_env=True,
no_auth=no_auth)
def test_all_args_passed_to_keystone(self):
# check that all possible command line args are passed to keystone
opts = {'auth-version': '3'}
os_opts = dict(self.all_os_opts)
os_opts.update(self.catalog_opts)
self._test_options(opts, os_opts, flags=self.flags)
opts = {'auth-version': '2.0'}
self._test_options(opts, os_opts, flags=self.flags)
opts = {}
self.defaults['auth-version'] = '3'
self._test_options(opts, os_opts, flags=self.flags)
for o in ('user-domain-name', 'user-domain-id',
'project-domain-name', 'project-domain-id'):
os_opts.pop(o)
self.defaults['auth-version'] = '2.0'
self._test_options(opts, os_opts, flags=self.flags)
def test_catalog_options_and_flags_not_required_v3(self):
# check that all possible command line args are passed to keystone
opts = {'auth-version': '3'}
os_opts = dict(self.all_os_opts)
self._test_options(opts, os_opts, flags=None)
def test_ok_option_combinations_v3(self):
opts = {'auth-version': '3'}
keys = ('username', 'password', 'tenant-name', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('user-id', 'password', 'tenant-name', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('user-id', 'password', 'tenant-id', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('user-id', 'password', 'project-name', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('user-id', 'password', 'project-id', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
def test_ok_option_combinations_v2(self):
opts = {'auth-version': '2.0'}
keys = ('username', 'password', 'tenant-name', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('username', 'password', 'tenant-id', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
# allow auth_version to default to 2.0
opts = {}
keys = ('username', 'password', 'tenant-name', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('username', 'password', 'tenant-id', 'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
# ...except when it should be 3
self.defaults['auth-version'] = '3'
keys = ('username', 'user-domain-name', 'password', 'project-name',
'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('username', 'user-domain-id', 'password', 'project-name',
'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('username', 'project-domain-name', 'password', 'project-name',
'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
keys = ('username', 'project-domain-id', 'password', 'project-name',
'auth-url')
os_opts = self._build_os_opts(keys)
self._test_options(opts, os_opts)
def test_url_and_token_provided_on_command_line(self):
endpoint = 'http://alternate.com:8080/v1/AUTH_another'
token = 'alternate_auth_token'
os_opts = {'auth-token': token,
'storage-url': endpoint}
opts = {'auth-version': '3'}
self._test_options(opts, os_opts, no_auth=True)
opts = {'auth-version': '2.0'}
self._test_options(opts, os_opts, no_auth=True)
def test_url_provided_on_command_line(self):
endpoint = 'http://alternate.com:8080/v1/AUTH_another'
os_opts = {'username': 'username',
'password': 'password',
'project-name': 'projectname',
'auth-url': 'http://example.com:5000/v3',
'storage-url': endpoint}
opts = {'auth-version': '3'}
self._test_options(opts, os_opts)
opts = {'auth-version': '2.0'}
self._test_options(opts, os_opts)
@mock.patch.dict(os.environ, clean_os_environ)
class TestAuth(MockHttpTest):
def test_pre_authed_request(self):
url = 'https://swift.storage.example.com/v1/AUTH_test'
token = 'AUTH_tk5b6b12'
pre_auth_env = {
'OS_STORAGE_URL': url,
'OS_AUTH_TOKEN': token,
}
fake_conn = self.fake_http_connection(200)
with mock.patch('swiftclient.client.http_connection', new=fake_conn):
with mock.patch.dict(os.environ, pre_auth_env):
argv = ['', 'stat']
swiftclient.shell.main(argv)
self.assertRequests([
('HEAD', url, '', {'x-auth-token': token}),
])
# and again with re-auth
pre_auth_env.update(mocked_os_environ)
pre_auth_env['OS_AUTH_TOKEN'] = 'expired'
fake_conn = self.fake_http_connection(401, 200, 200, headers={
'x-auth-token': token + '_new',
'x-storage-url': url + '_not_used',
})
with mock.patch.multiple('swiftclient.client',
http_connection=fake_conn,
sleep=mock.DEFAULT):
with mock.patch.dict(os.environ, pre_auth_env):
argv = ['', 'stat']
swiftclient.shell.main(argv)
self.assertRequests([
('HEAD', url, '', {
'x-auth-token': 'expired',
}),
('GET', mocked_os_environ['ST_AUTH'], '', {
'x-auth-user': mocked_os_environ['ST_USER'],
'x-auth-key': mocked_os_environ['ST_KEY'],
}),
('HEAD', url, '', {
'x-auth-token': token + '_new',
}),
])
def test_os_pre_authed_request(self):
url = 'https://swift.storage.example.com/v1/AUTH_test'
token = 'AUTH_tk5b6b12'
pre_auth_env = {
'OS_STORAGE_URL': url,
'OS_AUTH_TOKEN': token,
}
fake_conn = self.fake_http_connection(200)
with mock.patch('swiftclient.client.http_connection', new=fake_conn):
with mock.patch.dict(os.environ, pre_auth_env):
argv = ['', 'stat']
swiftclient.shell.main(argv)
self.assertRequests([
('HEAD', url, '', {'x-auth-token': token}),
])
# and again with re-auth
os_environ = {
'OS_AUTH_URL': 'https://keystone.example.com/v2.0/',
'OS_TENANT_NAME': 'demo',
'OS_USERNAME': 'demo',
'OS_PASSWORD': 'admin',
}
os_environ.update(pre_auth_env)
os_environ['OS_AUTH_TOKEN'] = 'expired'
fake_conn = self.fake_http_connection(401, 200)
fake_keystone = fake_get_auth_keystone(storage_url=url + '_not_used',
token=token + '_new')
with mock.patch.multiple('swiftclient.client',
http_connection=fake_conn,
get_auth_keystone=fake_keystone,
sleep=mock.DEFAULT):
with mock.patch.dict(os.environ, os_environ):
argv = ['', 'stat']
swiftclient.shell.main(argv)
self.assertRequests([
('HEAD', url, '', {
'x-auth-token': 'expired',
}),
('HEAD', url, '', {
'x-auth-token': token + '_new',
}),
])
def test_auth(self):
headers = {
'x-auth-token': 'AUTH_tk5b6b12',
'x-storage-url': 'https://swift.storage.example.com/v1/AUTH_test',
}
mock_resp = self.fake_http_connection(200, headers=headers)
with mock.patch('swiftclient.client.http_connection', new=mock_resp):
stdout = six.StringIO()
with mock.patch('sys.stdout', new=stdout):
argv = [
'',
'auth',
'--auth', 'https://swift.storage.example.com/auth/v1.0',
'--user', 'test:tester', '--key', 'testing',
]
swiftclient.shell.main(argv)
expected = """
export OS_STORAGE_URL=https://swift.storage.example.com/v1/AUTH_test
export OS_AUTH_TOKEN=AUTH_tk5b6b12
"""
self.assertEqual(textwrap.dedent(expected).lstrip(),
stdout.getvalue())
def test_auth_verbose(self):
with mock.patch('swiftclient.client.http_connection') as mock_conn:
stdout = six.StringIO()
with mock.patch('sys.stdout', new=stdout):
argv = [
'',
'auth',
'--auth', 'https://swift.storage.example.com/auth/v1.0',
'--user', 'test:tester', '--key', 'te$tin&',
'--verbose',
]
swiftclient.shell.main(argv)
expected = """
export ST_AUTH=https://swift.storage.example.com/auth/v1.0
export ST_USER=test:tester
export ST_KEY='te$tin&'
"""
self.assertEqual(textwrap.dedent(expected).lstrip(),
stdout.getvalue())
self.assertEqual([], mock_conn.mock_calls)
def test_auth_v2(self):
os_options = {'tenant_name': 'demo'}
with mock.patch('swiftclient.client.get_auth_keystone',
new=fake_get_auth_keystone(os_options)):
stdout = six.StringIO()
with mock.patch('sys.stdout', new=stdout):
argv = [
'',
'auth', '-V2',
'--auth', 'https://keystone.example.com/v2.0/',
'--os-tenant-name', 'demo',
'--os-username', 'demo', '--os-password', 'admin',
]
swiftclient.shell.main(argv)
expected = """
export OS_STORAGE_URL=http://url/
export OS_AUTH_TOKEN=token
"""
self.assertEqual(textwrap.dedent(expected).lstrip(),
stdout.getvalue())
def test_auth_verbose_v2(self):
with mock.patch('swiftclient.client.get_auth_keystone') \
as mock_keystone:
stdout = six.StringIO()
with mock.patch('sys.stdout', new=stdout):
argv = [
'',
'auth', '-V2',
'--auth', 'https://keystone.example.com/v2.0/',
'--os-tenant-name', 'demo',
'--os-username', 'demo', '--os-password', '$eKr3t',
'--verbose',
]
swiftclient.shell.main(argv)
expected = """
export OS_IDENTITY_API_VERSION=2.0
export OS_AUTH_VERSION=2.0
export OS_AUTH_URL=https://keystone.example.com/v2.0/
export OS_PASSWORD='$eKr3t'
export OS_TENANT_NAME=demo
export OS_USERNAME=demo
"""
self.assertEqual(textwrap.dedent(expected).lstrip(),
stdout.getvalue())
self.assertEqual([], mock_keystone.mock_calls)
class TestCrossAccountObjectAccess(TestBase, MockHttpTest):
"""
Tests to verify use of --os-storage-url will actually
result in the object request being sent despite account
read/write access and container write access being denied.
"""
def setUp(self):
super(TestCrossAccountObjectAccess, self).setUp()
self._remove_swift_env_vars()
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.file.write(b'01234567890123456789')
temp_file.file.flush()
self.obj = temp_file.name
self.url = 'http://alternate.com:8080/v1'
# account tests will attempt to access
self.account = 'AUTH_alice'
# keystone returns endpoint for another account
fake_ks = FakeKeystone(endpoint='http://example.com:8080/v1/AUTH_bob',
token='bob_token')
self.fake_ks_import = _make_fake_import_keystone_client(fake_ks)
self.cont = 'c1'
self.cont_path = '/v1/%s/%s' % (self.account, self.cont)
self.obj_path = '%s%s' % (self.cont_path, self.obj)
self.os_opts = {'username': 'bob',
'password': 'password',
'project-name': 'proj_bob',
'auth-url': 'http://example.com:5000/v3',
'storage-url': '%s/%s' % (self.url, self.account)}
self.opts = {'auth-version': '3'}
def tearDown(self):
try:
os.remove(self.obj)
except OSError:
pass
self._replace_swift_env_vars()
super(TestCrossAccountObjectAccess, self).tearDown()
def _make_cmd(self, cmd, cmd_args=None):
return _make_cmd(cmd, self.opts, self.os_opts, cmd_args=cmd_args)
def _fake_cross_account_auth(self, read_ok, write_ok):
def on_request(method, path, *args, **kwargs):
"""
Modify response code to 200 if cross account permissions match.
"""
status = 403
if (path.startswith('/v1/%s/%s' % (self.account, self.cont))
and read_ok and method in ('GET', 'HEAD')):
status = 200
elif (path.startswith('/v1/%s/%s%s'
% (self.account, self.cont, self.obj))
and write_ok and method in ('PUT', 'POST', 'DELETE')):
status = 200
return status
return on_request
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_upload_bad_threads(self, mock_connection):
mock_connection.return_value.put_object.return_value = EMPTY_ETAG
mock_connection.return_value.attempts = 0
def check_bad(argv):
args, env = self._make_cmd(
'upload', cmd_args=[self.cont, self.obj] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertIn(
'ERROR: option %s should be a positive integer.' % argv[0],
output.err)
def check_good(argv):
args, env = self._make_cmd(
'upload',
cmd_args=[self.cont, self.obj, '--leave-segments'] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
swiftclient.shell.main(args)
self.assertEqual('', output.err)
check_bad(["--object-threads", "-1"])
check_bad(["--object-threads", "0"])
check_bad(["--segment-threads", "-1"])
check_bad(["--segment-threads", "0"])
check_good(["--object-threads", "1"])
check_good(["--segment-threads", "1"])
def test_upload_with_read_write_access(self):
req_handler = self._fake_cross_account_auth(True, True)
fake_conn = self.fake_http_connection(403, 403,
on_request=req_handler)
args, env = self._make_cmd('upload', cmd_args=[self.cont, self.obj,
'--leave-segments'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
self.assertRequests([('PUT', self.cont_path),
('PUT', self.obj_path)])
self.assertEqual(self.obj[1:], out.strip())
expected_err = "Warning: failed to create container '%s': 403 Fake" \
% self.cont
self.assertEqual(expected_err, out.err.strip())
def test_upload_with_write_only_access(self):
req_handler = self._fake_cross_account_auth(False, True)
fake_conn = self.fake_http_connection(403, 403,
on_request=req_handler)
args, env = self._make_cmd('upload', cmd_args=[self.cont, self.obj,
'--leave-segments'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
self.assertRequests([('PUT', self.cont_path),
('PUT', self.obj_path)])
self.assertEqual(self.obj[1:], out.strip())
expected_err = "Warning: failed to create container '%s': 403 Fake" \
% self.cont
self.assertEqual(expected_err, out.err.strip())
def test_segment_upload_with_write_only_access(self):
req_handler = self._fake_cross_account_auth(False, True)
fake_conn = self.fake_http_connection(403, 403, 403, 403,
on_request=req_handler)
args, env = self._make_cmd('upload',
cmd_args=[self.cont, self.obj,
'--leave-segments',
'--segment-size=10',
'--segment-container=%s'
% self.cont])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
segment_time = getmtime(self.obj)
segment_path_0 = '%s/%f/20/10/00000000' % (self.obj_path, segment_time)
segment_path_1 = '%s/%f/20/10/00000001' % (self.obj_path, segment_time)
# Note that the order of segment PUTs cannot be asserted, so test for
# existence in request log individually
self.assert_request(('PUT', self.cont_path))
self.assert_request(('PUT', segment_path_0))
self.assert_request(('PUT', segment_path_1))
self.assert_request(('PUT', self.obj_path))
self.assertTrue(self.obj[1:] in out.out)
expected_err = "Warning: failed to create container '%s': 403 Fake" \
% self.cont
self.assertEqual(expected_err, out.err.strip())
def test_segment_upload_with_write_only_access_segments_container(self):
fake_conn = self.fake_http_connection(
403, # PUT c1
# HEAD c1 to get storage policy
StubResponse(200, headers={'X-Storage-Policy': 'foo'}),
403, # PUT c1_segments
201, # PUT c1_segments/...00
201, # PUT c1_segments/...01
201, # PUT c1/...
)
args, env = self._make_cmd('upload',
cmd_args=[self.cont, self.obj,
'--leave-segments',
'--segment-size=10'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
segment_time = getmtime(self.obj)
segment_path_0 = '%s_segments%s/%f/20/10/00000000' % (
self.cont_path, self.obj, segment_time)
segment_path_1 = '%s_segments%s/%f/20/10/00000001' % (
self.cont_path, self.obj, segment_time)
# Note that the order of segment PUTs cannot be asserted, so test for
# existence in request log individually
self.assert_request(('PUT', self.cont_path))
self.assert_request(('PUT', self.cont_path + '_segments', '', {
'X-Auth-Token': 'bob_token',
'X-Storage-Policy': 'foo',
'Content-Length': '0',
}))
self.assert_request(('PUT', segment_path_0))
self.assert_request(('PUT', segment_path_1))
self.assert_request(('PUT', self.obj_path))
self.assertTrue(self.obj[1:] in out.out)
expected_err = ("Warning: failed to create container '%s': 403 Fake\n"
"Warning: failed to create container '%s': 403 Fake"
) % (self.cont, self.cont + '_segments')
self.assertEqual(expected_err, out.err.strip())
def test_upload_with_no_access(self):
fake_conn = self.fake_http_connection(403, 403)
args, env = self._make_cmd('upload', cmd_args=[self.cont, self.obj,
'--leave-segments'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
self.fail('Expected SystemExit')
except SystemExit:
pass
self.assertRequests([('PUT', self.cont_path),
('PUT', self.obj_path)])
expected_err = 'Object PUT failed: http://1.2.3.4%s 403 Fake' \
% self.obj_path
self.assertTrue(expected_err in out.err)
self.assertEqual('', out)
@mock.patch.object(swiftclient.service.SwiftService, '_should_bulk_delete',
lambda *a: False)
@mock.patch('swiftclient.service.Connection')
def test_download_bad_threads(self, mock_connection):
mock_connection.return_value.get_object.return_value = [{}, '']
mock_connection.return_value.attempts = 0
def check_bad(argv):
args, env = self._make_cmd(
'download', cmd_args=[self.cont, self.obj] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
self.assertRaises(SystemExit, swiftclient.shell.main, args)
self.assertIn(
'ERROR: option %s should be a positive integer.' % argv[0],
output.err)
def check_good(argv):
args, env = self._make_cmd(
'download',
cmd_args=[self.cont, self.obj, '--no-download'] + argv)
with mock.patch.dict(os.environ, env):
with CaptureOutput() as output:
swiftclient.shell.main(args)
self.assertEqual('', output.err)
check_bad(["--object-threads", "-1"])
check_bad(["--object-threads", "0"])
check_bad(["--container-threads", "-1"])
check_bad(["--container-threads", "0"])
check_good(["--object-threads", "1"])
check_good(["--container-threads", "1"])
def test_download_with_read_write_access(self):
req_handler = self._fake_cross_account_auth(True, True)
fake_conn = self.fake_http_connection(403, on_request=req_handler,
etags=[EMPTY_ETAG])
args, env = self._make_cmd('download', cmd_args=[self.cont,
self.obj.lstrip('/'),
'--no-download'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
self.assertRequests([('GET', self.obj_path)])
self.assertTrue(out.out.startswith(self.obj.lstrip('/')))
self.assertEqual('', out.err)
def test_download_with_read_only_access(self):
req_handler = self._fake_cross_account_auth(True, False)
fake_conn = self.fake_http_connection(403, on_request=req_handler,
etags=[EMPTY_ETAG])
args, env = self._make_cmd('download', cmd_args=[self.cont,
self.obj.lstrip('/'),
'--no-download'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
self.assertRequests([('GET', self.obj_path)])
self.assertTrue(out.out.startswith(self.obj.lstrip('/')))
self.assertEqual('', out.err)
def test_download_with_no_access(self):
fake_conn = self.fake_http_connection(403)
args, env = self._make_cmd('download', cmd_args=[self.cont,
self.obj.lstrip('/'),
'--no-download'])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
self.fail('Expected SystemExit')
except SystemExit:
pass
self.assertRequests([('GET', self.obj_path)])
path = '%s%s' % (self.cont, self.obj)
expected_err = "Error downloading object '%s'" % path
self.assertTrue(out.err.startswith(expected_err))
self.assertEqual('', out)
def test_list_with_read_access(self):
req_handler = self._fake_cross_account_auth(True, False)
resp_body = b'{}'
resp = StubResponse(403, resp_body, {
'etag': hashlib.md5(resp_body).hexdigest()})
fake_conn = self.fake_http_connection(resp, on_request=req_handler)
args, env = self._make_cmd('download', cmd_args=[self.cont])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
except SystemExit as e:
self.fail('Unexpected SystemExit: %s' % e)
self.assertRequests([('GET', '%s?format=json' % self.cont_path)])
self.assertEqual('', out)
self.assertEqual('', out.err)
def test_list_with_no_access(self):
fake_conn = self.fake_http_connection(403)
args, env = self._make_cmd('download', cmd_args=[self.cont])
with mock.patch('swiftclient.client._import_keystone_client',
self.fake_ks_import):
with mock.patch('swiftclient.client.http_connection', fake_conn):
with mock.patch.dict(os.environ, env):
with CaptureOutput() as out:
try:
swiftclient.shell.main(args)
self.fail('Expected SystemExit')
except SystemExit:
pass
self.assertRequests([('GET', '%s?format=json' % self.cont_path)])
self.assertEqual('', out)
self.assertTrue(out.err.startswith('Container GET failed:'))
class TestCrossAccountObjectAccessUsingEnv(TestCrossAccountObjectAccess):
"""
Repeat super-class tests using environment variables rather than command
line to set options.
"""
def _make_cmd(self, cmd, cmd_args=None):
return _make_cmd(cmd, self.opts, self.os_opts, cmd_args=cmd_args,
use_env=True)
|