File size: 63,761 Bytes
ac141ed |
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 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 datetime import datetime, timezone, timedelta
import gzip
import os
import pathlib
import subprocess
import sys
import pytest
import weakref
import pyarrow as pa
from pyarrow.tests.test_io import assert_file_not_found
from pyarrow.tests.util import (_filesystem_uri, ProxyHandler,
_configure_s3_limited_user)
from pyarrow.fs import (FileType, FileInfo, FileSelector, FileSystem,
LocalFileSystem, SubTreeFileSystem, _MockFileSystem,
FileSystemHandler, PyFileSystem, FSSpecHandler,
copy_files)
class DummyHandler(FileSystemHandler):
def __init__(self, value=42):
self._value = value
def __eq__(self, other):
if isinstance(other, FileSystemHandler):
return self._value == other._value
return NotImplemented
def __ne__(self, other):
if isinstance(other, FileSystemHandler):
return self._value != other._value
return NotImplemented
def get_type_name(self):
return "dummy"
def normalize_path(self, path):
return path
def get_file_info(self, paths):
info = []
for path in paths:
if "file" in path:
info.append(FileInfo(path, FileType.File))
elif "dir" in path:
info.append(FileInfo(path, FileType.Directory))
elif "notfound" in path:
info.append(FileInfo(path, FileType.NotFound))
elif "badtype" in path:
# Will raise when converting
info.append(object())
else:
raise IOError
return info
def get_file_info_selector(self, selector):
if selector.base_dir != "somedir":
if selector.allow_not_found:
return []
else:
raise FileNotFoundError(selector.base_dir)
infos = [
FileInfo("somedir/file1", FileType.File, size=123),
FileInfo("somedir/subdir1", FileType.Directory),
]
if selector.recursive:
infos += [
FileInfo("somedir/subdir1/file2", FileType.File, size=456),
]
return infos
def create_dir(self, path, recursive):
if path == "recursive":
assert recursive is True
elif path == "non-recursive":
assert recursive is False
else:
raise IOError
def delete_dir(self, path):
assert path == "delete_dir"
def delete_dir_contents(self, path, missing_dir_ok):
if not path.strip("/"):
raise ValueError
assert path == "delete_dir_contents"
def delete_root_dir_contents(self):
pass
def delete_file(self, path):
assert path == "delete_file"
def move(self, src, dest):
assert src == "move_from"
assert dest == "move_to"
def copy_file(self, src, dest):
assert src == "copy_file_from"
assert dest == "copy_file_to"
def open_input_stream(self, path):
if "notfound" in path:
raise FileNotFoundError(path)
data = "{0}:input_stream".format(path).encode('utf8')
return pa.BufferReader(data)
def open_input_file(self, path):
if "notfound" in path:
raise FileNotFoundError(path)
data = "{0}:input_file".format(path).encode('utf8')
return pa.BufferReader(data)
def open_output_stream(self, path, metadata):
if "notfound" in path:
raise FileNotFoundError(path)
return pa.BufferOutputStream()
def open_append_stream(self, path, metadata):
if "notfound" in path:
raise FileNotFoundError(path)
return pa.BufferOutputStream()
@pytest.fixture
def localfs(request, tempdir):
return dict(
fs=LocalFileSystem(),
pathfn=lambda p: (tempdir / p).as_posix(),
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def py_localfs(request, tempdir):
return dict(
fs=PyFileSystem(ProxyHandler(LocalFileSystem())),
pathfn=lambda p: (tempdir / p).as_posix(),
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def mockfs(request):
return dict(
fs=_MockFileSystem(),
pathfn=lambda p: p,
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def py_mockfs(request):
return dict(
fs=PyFileSystem(ProxyHandler(_MockFileSystem())),
pathfn=lambda p: p,
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def localfs_with_mmap(request, tempdir):
return dict(
fs=LocalFileSystem(use_mmap=True),
pathfn=lambda p: (tempdir / p).as_posix(),
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def subtree_localfs(request, tempdir, localfs):
return dict(
fs=SubTreeFileSystem(str(tempdir), localfs['fs']),
pathfn=lambda p: p,
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def gcsfs(request, gcs_server):
request.config.pyarrow.requires('gcs')
from pyarrow.fs import GcsFileSystem
host, port = gcs_server['connection']
bucket = 'pyarrow-filesystem/'
fs = GcsFileSystem(
endpoint_override=f'{host}:{port}',
scheme='http',
# Mock endpoint doesn't check credentials.
anonymous=True,
retry_time_limit=timedelta(seconds=45),
project_id='test-project-id'
)
try:
fs.create_dir(bucket)
except OSError as e:
pytest.skip(f"Could not create directory in {fs}: {e}")
yield dict(
fs=fs,
pathfn=bucket.__add__,
allow_move_dir=False,
allow_append_to_file=False,
)
fs.delete_dir(bucket)
@pytest.fixture
def s3fs(request, s3_server):
request.config.pyarrow.requires('s3')
from pyarrow.fs import S3FileSystem
host, port, access_key, secret_key = s3_server['connection']
bucket = 'pyarrow-filesystem/'
fs = S3FileSystem(
access_key=access_key,
secret_key=secret_key,
endpoint_override='{}:{}'.format(host, port),
scheme='http',
allow_bucket_creation=True,
allow_bucket_deletion=True
)
fs.create_dir(bucket)
yield dict(
fs=fs,
pathfn=bucket.__add__,
allow_move_dir=False,
allow_append_to_file=False,
)
fs.delete_dir(bucket)
@pytest.fixture
def subtree_s3fs(request, s3fs):
prefix = 'pyarrow-filesystem/prefix/'
return dict(
fs=SubTreeFileSystem(prefix, s3fs['fs']),
pathfn=prefix.__add__,
allow_move_dir=False,
allow_append_to_file=False,
)
_minio_limited_policy = """{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:PutObject",
"s3:GetObject",
"s3:ListBucket",
"s3:PutObjectTagging",
"s3:DeleteObject",
"s3:GetObjectVersion"
],
"Resource": [
"arn:aws:s3:::*"
]
}
]
}"""
@pytest.fixture
def azurefs(request, azure_server):
request.config.pyarrow.requires('azure')
from pyarrow.fs import AzureFileSystem
host, port, account_name, account_key = azure_server['connection']
azurite_authority = f"{host}:{port}"
azurite_scheme = "http"
container = 'pyarrow-filesystem/'
fs = AzureFileSystem(account_name=account_name,
account_key=account_key,
blob_storage_authority=azurite_authority,
dfs_storage_authority=azurite_authority,
blob_storage_scheme=azurite_scheme,
dfs_storage_scheme=azurite_scheme)
fs.create_dir(container)
yield dict(
fs=fs,
pathfn=container.__add__,
allow_move_dir=True,
allow_append_to_file=True,
)
fs.delete_dir(container)
@pytest.fixture
def hdfs(request, hdfs_connection):
request.config.pyarrow.requires('hdfs')
if not pa.have_libhdfs():
pytest.skip('Cannot locate libhdfs')
from pyarrow.fs import HadoopFileSystem
host, port, user = hdfs_connection
fs = HadoopFileSystem(host, port=port, user=user)
return dict(
fs=fs,
pathfn=lambda p: p,
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def py_fsspec_localfs(request, tempdir):
fsspec = pytest.importorskip("fsspec")
fs = fsspec.filesystem('file')
return dict(
fs=PyFileSystem(FSSpecHandler(fs)),
pathfn=lambda p: (tempdir / p).as_posix(),
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def py_fsspec_memoryfs(request, tempdir):
fsspec = pytest.importorskip("fsspec", minversion="0.7.5")
if fsspec.__version__ == "0.8.5":
# see https://issues.apache.org/jira/browse/ARROW-10934
pytest.skip("Bug in fsspec 0.8.5 for in-memory filesystem")
fs = fsspec.filesystem('memory')
return dict(
fs=PyFileSystem(FSSpecHandler(fs)),
pathfn=lambda p: p,
allow_move_dir=True,
allow_append_to_file=True,
)
@pytest.fixture
def py_fsspec_s3fs(request, s3_server):
s3fs = pytest.importorskip("s3fs")
host, port, access_key, secret_key = s3_server['connection']
bucket = 'pyarrow-filesystem/'
fs = s3fs.S3FileSystem(
key=access_key,
secret=secret_key,
client_kwargs=dict(endpoint_url='http://{}:{}'.format(host, port))
)
fs = PyFileSystem(FSSpecHandler(fs))
fs.create_dir(bucket)
yield dict(
fs=fs,
pathfn=bucket.__add__,
allow_move_dir=False,
allow_append_to_file=True,
)
fs.delete_dir(bucket)
@pytest.fixture(params=[
pytest.param(
'localfs',
id='LocalFileSystem()'
),
pytest.param(
'localfs_with_mmap',
id='LocalFileSystem(use_mmap=True)'
),
pytest.param(
'subtree_localfs',
id='SubTreeFileSystem(LocalFileSystem())'
),
pytest.param(
's3fs',
id='S3FileSystem',
marks=pytest.mark.s3
),
pytest.param(
'gcsfs',
id='GcsFileSystem',
marks=pytest.mark.gcs
),
pytest.param(
'azurefs',
id='AzureFileSystem',
marks=pytest.mark.azure
),
pytest.param(
'hdfs',
id='HadoopFileSystem',
marks=pytest.mark.hdfs
),
pytest.param(
'mockfs',
id='_MockFileSystem()'
),
pytest.param(
'py_localfs',
id='PyFileSystem(ProxyHandler(LocalFileSystem()))'
),
pytest.param(
'py_mockfs',
id='PyFileSystem(ProxyHandler(_MockFileSystem()))'
),
pytest.param(
'py_fsspec_localfs',
id='PyFileSystem(FSSpecHandler(fsspec.LocalFileSystem()))'
),
pytest.param(
'py_fsspec_memoryfs',
id='PyFileSystem(FSSpecHandler(fsspec.filesystem("memory")))'
),
pytest.param(
'py_fsspec_s3fs',
id='PyFileSystem(FSSpecHandler(s3fs.S3FileSystem()))',
marks=pytest.mark.s3
),
])
def filesystem_config(request):
return request.getfixturevalue(request.param)
@pytest.fixture
def fs(filesystem_config):
return filesystem_config['fs']
@pytest.fixture
def pathfn(filesystem_config):
return filesystem_config['pathfn']
@pytest.fixture
def allow_move_dir(filesystem_config):
return filesystem_config['allow_move_dir']
@pytest.fixture
def allow_append_to_file(filesystem_config):
return filesystem_config['allow_append_to_file']
def check_mtime(file_info):
assert isinstance(file_info.mtime, datetime)
assert isinstance(file_info.mtime_ns, int)
assert file_info.mtime_ns >= 0
assert file_info.mtime_ns == pytest.approx(
file_info.mtime.timestamp() * 1e9)
# It's an aware UTC datetime
tzinfo = file_info.mtime.tzinfo
assert tzinfo is not None
assert tzinfo.utcoffset(None) == timedelta(0)
def check_mtime_absent(file_info):
assert file_info.mtime is None
assert file_info.mtime_ns is None
def check_mtime_or_absent(file_info):
if file_info.mtime is None:
check_mtime_absent(file_info)
else:
check_mtime(file_info)
def skip_fsspec_s3fs(fs):
if fs.type_name == "py::fsspec+('s3', 's3a')":
pytest.xfail(reason="Not working with fsspec's s3fs")
def skip_azure(fs, reason):
if fs.type_name == "abfs":
pytest.skip(reason=reason)
@pytest.mark.s3
def test_s3fs_limited_permissions_create_bucket(s3_server):
from pyarrow.fs import S3FileSystem
_configure_s3_limited_user(s3_server, _minio_limited_policy)
host, port, _, _ = s3_server['connection']
fs = S3FileSystem(
access_key='limited',
secret_key='limited123',
endpoint_override='{}:{}'.format(host, port),
scheme='http'
)
fs.create_dir('existing-bucket/test')
with pytest.raises(pa.ArrowIOError, match="Bucket 'new-bucket' not found"):
fs.create_dir('new-bucket')
with pytest.raises(pa.ArrowIOError, match="Would delete bucket"):
fs.delete_dir('existing-bucket')
def test_file_info_constructor():
dt = datetime.fromtimestamp(1568799826, timezone.utc)
info = FileInfo("foo/bar")
assert info.path == "foo/bar"
assert info.base_name == "bar"
assert info.type == FileType.Unknown
assert info.size is None
check_mtime_absent(info)
info = FileInfo("foo/baz.txt", type=FileType.File, size=123,
mtime=1568799826.5)
assert info.path == "foo/baz.txt"
assert info.base_name == "baz.txt"
assert info.type == FileType.File
assert info.size == 123
assert info.mtime_ns == 1568799826500000000
check_mtime(info)
info = FileInfo("foo", type=FileType.Directory, mtime=dt)
assert info.path == "foo"
assert info.base_name == "foo"
assert info.type == FileType.Directory
assert info.size is None
assert info.mtime == dt
assert info.mtime_ns == 1568799826000000000
check_mtime(info)
def test_cannot_instantiate_base_filesystem():
with pytest.raises(TypeError):
FileSystem()
def test_filesystem_equals():
fs0 = LocalFileSystem()
fs1 = LocalFileSystem()
fs2 = _MockFileSystem()
assert fs0.equals(fs0)
assert fs0.equals(fs1)
with pytest.raises(TypeError):
fs0.equals('string')
assert fs0 == fs0 == fs1
assert fs0 != 4
assert fs2 == fs2
assert fs2 != _MockFileSystem()
assert SubTreeFileSystem('/base', fs0) == SubTreeFileSystem('/base', fs0)
assert SubTreeFileSystem('/base', fs0) != SubTreeFileSystem('/base', fs2)
assert SubTreeFileSystem('/base', fs0) != SubTreeFileSystem('/other', fs0)
def test_filesystem_equals_none(fs):
with pytest.raises(TypeError, match="got NoneType"):
fs.equals(None)
assert fs is not None
def test_subtree_filesystem():
localfs = LocalFileSystem()
subfs = SubTreeFileSystem('/base', localfs)
assert subfs.base_path == '/base/'
assert subfs.base_fs == localfs
assert repr(subfs).startswith('SubTreeFileSystem(base_path=/base/, '
'base_fs=<pyarrow._fs.LocalFileSystem')
subfs = SubTreeFileSystem('/another/base/', LocalFileSystem())
assert subfs.base_path == '/another/base/'
assert subfs.base_fs == localfs
assert repr(subfs).startswith('SubTreeFileSystem(base_path=/another/base/,'
' base_fs=<pyarrow._fs.LocalFileSystem')
def test_filesystem_pickling(fs, pickle_module):
if fs.type_name.split('::')[-1] == 'mock':
pytest.xfail(reason='MockFileSystem is not serializable')
serialized = pickle_module.dumps(fs)
restored = pickle_module.loads(serialized)
assert isinstance(restored, FileSystem)
assert restored.equals(fs)
def test_filesystem_is_functional_after_pickling(fs, pathfn, pickle_module):
if fs.type_name.split('::')[-1] == 'mock':
pytest.xfail(reason='MockFileSystem is not serializable')
skip_fsspec_s3fs(fs)
aaa = pathfn('a/aa/aaa/')
bb = pathfn('a/bb')
c = pathfn('c.txt')
fs.create_dir(aaa)
with fs.open_output_stream(bb):
pass # touch
with fs.open_output_stream(c) as fp:
fp.write(b'test')
restored = pickle_module.loads(pickle_module.dumps(fs))
aaa_info, bb_info, c_info = restored.get_file_info([aaa, bb, c])
assert aaa_info.type == FileType.Directory
assert bb_info.type == FileType.File
assert c_info.type == FileType.File
def test_type_name():
fs = LocalFileSystem()
assert fs.type_name == "local"
fs = _MockFileSystem()
assert fs.type_name == "mock"
def test_normalize_path(fs):
# Trivial path names (without separators) should generally be
# already normalized. Just a sanity check.
assert fs.normalize_path("foo") == "foo"
def test_non_path_like_input_raises(fs):
class Path:
pass
invalid_paths = [1, 1.1, Path(), tuple(), {}, [], lambda: 1,
pathlib.Path()]
for path in invalid_paths:
with pytest.raises(TypeError):
fs.create_dir(path)
def test_get_file_info(fs, pathfn):
aaa = pathfn('a/aa/aaa/')
bb = pathfn('a/bb')
c = pathfn('c.txt')
zzz = pathfn('zzz')
fs.create_dir(aaa)
with fs.open_output_stream(bb):
pass # touch
with fs.open_output_stream(c) as fp:
fp.write(b'test')
aaa_info, bb_info, c_info, zzz_info = fs.get_file_info([aaa, bb, c, zzz])
assert aaa_info.path == aaa
assert 'aaa' in repr(aaa_info)
assert aaa_info.extension == ''
if fs.type_name == "py::fsspec+('s3', 's3a')":
# s3fs doesn't create empty directories
assert aaa_info.type == FileType.NotFound
else:
assert aaa_info.type == FileType.Directory
assert 'FileType.Directory' in repr(aaa_info)
assert aaa_info.size is None
check_mtime_or_absent(aaa_info)
assert bb_info.path == str(bb)
assert bb_info.base_name == 'bb'
assert bb_info.extension == ''
assert bb_info.type == FileType.File
assert 'FileType.File' in repr(bb_info)
assert bb_info.size == 0
if fs.type_name not in ["py::fsspec+memory", "py::fsspec+('s3', 's3a')"]:
check_mtime(bb_info)
assert c_info.path == str(c)
assert c_info.base_name == 'c.txt'
assert c_info.extension == 'txt'
assert c_info.type == FileType.File
assert 'FileType.File' in repr(c_info)
assert c_info.size == 4
if fs.type_name not in ["py::fsspec+memory", "py::fsspec+('s3', 's3a')"]:
check_mtime(c_info)
assert zzz_info.path == str(zzz)
assert zzz_info.base_name == 'zzz'
assert zzz_info.extension == ''
assert zzz_info.type == FileType.NotFound
assert zzz_info.size is None
assert zzz_info.mtime is None
assert 'FileType.NotFound' in repr(zzz_info)
check_mtime_absent(zzz_info)
# with single path
aaa_info2 = fs.get_file_info(aaa)
assert aaa_info.path == aaa_info2.path
assert aaa_info.type == aaa_info2.type
def test_get_file_info_with_selector(fs, pathfn):
base_dir = pathfn('selector-dir/')
file_a = pathfn('selector-dir/test_file_a')
file_b = pathfn('selector-dir/test_file_b')
dir_a = pathfn('selector-dir/test_dir_a')
file_c = pathfn('selector-dir/test_dir_a/test_file_c')
dir_b = pathfn('selector-dir/test_dir_b')
try:
fs.create_dir(base_dir)
with fs.open_output_stream(file_a):
pass
with fs.open_output_stream(file_b):
pass
fs.create_dir(dir_a)
with fs.open_output_stream(file_c):
pass
fs.create_dir(dir_b)
# recursive selector
selector = FileSelector(base_dir, allow_not_found=False,
recursive=True)
assert selector.base_dir == base_dir
infos = fs.get_file_info(selector)
if fs.type_name == "py::fsspec+('s3', 's3a')":
# s3fs only lists directories if they are not empty
len(infos) == 4
else:
assert len(infos) == 5
for info in infos:
if (info.path.endswith(file_a) or info.path.endswith(file_b) or
info.path.endswith(file_c)):
assert info.type == FileType.File
elif (info.path.rstrip("/").endswith(dir_a) or
info.path.rstrip("/").endswith(dir_b)):
assert info.type == FileType.Directory
else:
raise ValueError('unexpected path {}'.format(info.path))
check_mtime_or_absent(info)
# non-recursive selector -> not selecting the nested file_c
selector = FileSelector(base_dir, recursive=False)
infos = fs.get_file_info(selector)
if fs.type_name == "py::fsspec+('s3', 's3a')":
# s3fs only lists directories if they are not empty
assert len(infos) == 3
else:
assert len(infos) == 4
finally:
fs.delete_dir(base_dir)
def test_create_dir(fs, pathfn):
# s3fs fails deleting dir fails if it is empty
# (https://github.com/dask/s3fs/issues/317)
skip_fsspec_s3fs(fs)
d = pathfn('test-directory/')
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(d)
fs.create_dir(d)
fs.delete_dir(d)
d = pathfn('deeply/nested/test-directory/')
fs.create_dir(d, recursive=True)
fs.delete_dir(d)
def test_delete_dir(fs, pathfn):
skip_fsspec_s3fs(fs)
d = pathfn('directory/')
nd = pathfn('directory/nested/')
fs.create_dir(nd)
fs.delete_dir(d)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(nd)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(d)
def test_delete_dir_with_explicit_subdir(fs, pathfn):
# GH-38618: regression with AWS failing to delete directories,
# depending on whether they were created explicitly. Note that
# Minio doesn't reproduce the issue, so this test is not a regression
# test in itself.
skip_fsspec_s3fs(fs)
d = pathfn('directory/')
nd = pathfn('directory/nested/')
# deleting dir with explicit subdir
fs.create_dir(d)
fs.create_dir(nd)
fs.delete_dir(d)
dir_info = fs.get_file_info(d)
assert dir_info.type == FileType.NotFound
# deleting dir with blob in explicit subdir
d = pathfn('directory2')
nd = pathfn('directory2/nested')
f = pathfn('directory2/nested/target-file')
fs.create_dir(d)
fs.create_dir(nd)
with fs.open_output_stream(f) as s:
s.write(b'data')
fs.delete_dir(d)
dir_info = fs.get_file_info(d)
assert dir_info.type == FileType.NotFound
def test_delete_dir_contents(fs, pathfn):
skip_fsspec_s3fs(fs)
d = pathfn('directory/')
nd = pathfn('directory/nested/')
fs.create_dir(nd)
fs.delete_dir_contents(d)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(nd)
fs.delete_dir_contents(nd, missing_dir_ok=True)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir_contents(nd)
fs.delete_dir(d)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(d)
def _check_root_dir_contents(config):
fs = config['fs']
pathfn = config['pathfn']
d = pathfn('directory/')
nd = pathfn('directory/nested/')
fs.create_dir(nd)
with pytest.raises(pa.ArrowInvalid):
fs.delete_dir_contents("")
with pytest.raises(pa.ArrowInvalid):
fs.delete_dir_contents("/")
with pytest.raises(pa.ArrowInvalid):
fs.delete_dir_contents("//")
fs.delete_dir_contents("", accept_root_dir=True)
fs.delete_dir_contents("/", accept_root_dir=True)
fs.delete_dir_contents("//", accept_root_dir=True)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(d)
def test_delete_root_dir_contents(mockfs, py_mockfs):
_check_root_dir_contents(mockfs)
_check_root_dir_contents(py_mockfs)
def test_copy_file(fs, pathfn):
s = pathfn('test-copy-source-file')
t = pathfn('test-copy-target-file')
with fs.open_output_stream(s):
pass
fs.copy_file(s, t)
fs.delete_file(s)
fs.delete_file(t)
def test_move_directory(fs, pathfn, allow_move_dir):
# TODO(GH-40025): Stop skipping this test
skip_azure(fs, "Not implemented yet in for Azure. See GH-40025")
# move directory (doesn't work with S3)
s = pathfn('source-dir/')
t = pathfn('target-dir/')
fs.create_dir(s)
if allow_move_dir:
fs.move(s, t)
with pytest.raises(pa.ArrowIOError):
fs.delete_dir(s)
fs.delete_dir(t)
else:
with pytest.raises(pa.ArrowIOError):
fs.move(s, t)
def test_move_file(fs, pathfn):
# s3fs moving a file with recursive=True on latest 0.5 version
# (https://github.com/dask/s3fs/issues/394)
skip_fsspec_s3fs(fs)
# TODO(GH-40025): Stop skipping this test
skip_azure(fs, "Not implemented yet in for Azure. See GH-40025")
s = pathfn('test-move-source-file')
t = pathfn('test-move-target-file')
with fs.open_output_stream(s):
pass
fs.move(s, t)
with pytest.raises(pa.ArrowIOError):
fs.delete_file(s)
fs.delete_file(t)
def test_delete_file(fs, pathfn):
p = pathfn('test-delete-target-file')
with fs.open_output_stream(p):
pass
fs.delete_file(p)
with pytest.raises(pa.ArrowIOError):
fs.delete_file(p)
d = pathfn('test-delete-nested')
fs.create_dir(d)
f = pathfn('test-delete-nested/target-file')
with fs.open_output_stream(f) as s:
s.write(b'data')
fs.delete_dir(d)
def identity(v):
return v
@pytest.mark.gzip
@pytest.mark.parametrize(
('compression', 'buffer_size', 'compressor'),
[
(None, None, identity),
(None, 64, identity),
('gzip', None, gzip.compress),
('gzip', 256, gzip.compress),
]
)
def test_open_input_stream(fs, pathfn, compression, buffer_size, compressor):
p = pathfn('open-input-stream')
data = b'some data for reading\n' * 512
with fs.open_output_stream(p) as s:
s.write(compressor(data))
with fs.open_input_stream(p, compression, buffer_size) as s:
result = s.read()
assert result == data
def test_open_input_file(fs, pathfn):
p = pathfn('open-input-file')
data = b'some data' * 1024
with fs.open_output_stream(p) as s:
s.write(data)
read_from = len(b'some data') * 512
with fs.open_input_file(p) as f:
result = f.read()
assert result == data
with fs.open_input_file(p) as f:
f.seek(read_from)
result = f.read()
assert result == data[read_from:]
def test_open_input_stream_not_found(fs, pathfn):
# The proper exception should be raised for this common case (ARROW-15896)
p = pathfn('open-input-stream-not-found')
with pytest.raises(FileNotFoundError):
fs.open_input_stream(p)
@pytest.mark.gzip
@pytest.mark.parametrize(
('compression', 'buffer_size', 'decompressor'),
[
(None, None, identity),
(None, 64, identity),
('gzip', None, gzip.decompress),
('gzip', 256, gzip.decompress),
]
)
def test_open_output_stream(fs, pathfn, compression, buffer_size,
decompressor):
p = pathfn('open-output-stream')
data = b'some data for writing' * 1024
with fs.open_output_stream(p, compression, buffer_size) as f:
f.write(data)
with fs.open_input_stream(p, compression, buffer_size) as f:
assert f.read(len(data)) == data
@pytest.mark.gzip
@pytest.mark.parametrize(
('compression', 'buffer_size', 'compressor', 'decompressor'),
[
(None, None, identity, identity),
(None, 64, identity, identity),
('gzip', None, gzip.compress, gzip.decompress),
('gzip', 256, gzip.compress, gzip.decompress),
]
)
def test_open_append_stream(fs, pathfn, compression, buffer_size, compressor,
decompressor, allow_append_to_file):
p = pathfn('open-append-stream')
initial = compressor(b'already existing')
with fs.open_output_stream(p) as s:
s.write(initial)
if allow_append_to_file:
with fs.open_append_stream(p, compression=compression,
buffer_size=buffer_size) as f:
f.write(b'\nnewly added')
with fs.open_input_stream(p) as f:
result = f.read()
result = decompressor(result)
assert result == b'already existing\nnewly added'
else:
with pytest.raises(pa.ArrowNotImplementedError):
fs.open_append_stream(p, compression=compression,
buffer_size=buffer_size)
def test_open_output_stream_metadata(fs, pathfn):
p = pathfn('open-output-stream-metadata')
metadata = {'Content-Type': 'x-pyarrow/test'}
data = b'some data'
with fs.open_output_stream(p, metadata=metadata) as f:
f.write(data)
with fs.open_input_stream(p) as f:
assert f.read() == data
got_metadata = f.metadata()
if fs.type_name in ['s3', 'gcs', 'abfs'] or 'mock' in fs.type_name:
# TODO(GH-40026): Stop skipping this test
skip_azure(
fs, "Azure filesystem currently only returns system metadata not user "
"metadata. See GH-40026")
for k, v in metadata.items():
assert got_metadata[k] == v.encode()
else:
assert got_metadata == {}
def test_localfs_options():
# LocalFileSystem instantiation
LocalFileSystem(use_mmap=False)
with pytest.raises(TypeError):
LocalFileSystem(xxx=False)
def test_localfs_errors(localfs):
# Local filesystem errors should raise the right Python exceptions
# (e.g. FileNotFoundError)
fs = localfs['fs']
with assert_file_not_found():
fs.open_input_stream('/non/existent/file')
with assert_file_not_found():
fs.open_output_stream('/non/existent/file')
with assert_file_not_found():
fs.create_dir('/non/existent/dir', recursive=False)
with assert_file_not_found():
fs.delete_dir('/non/existent/dir')
with assert_file_not_found():
fs.delete_file('/non/existent/dir')
with assert_file_not_found():
fs.move('/non/existent', '/xxx')
with assert_file_not_found():
fs.copy_file('/non/existent', '/xxx')
def test_localfs_file_info(localfs):
fs = localfs['fs']
file_path = pathlib.Path(__file__)
dir_path = file_path.parent
[file_info, dir_info] = fs.get_file_info([file_path.as_posix(),
dir_path.as_posix()])
assert file_info.size == file_path.stat().st_size
assert file_info.mtime_ns == file_path.stat().st_mtime_ns
check_mtime(file_info)
assert dir_info.mtime_ns == dir_path.stat().st_mtime_ns
check_mtime(dir_info)
def test_mockfs_mtime_roundtrip(mockfs):
dt = datetime.fromtimestamp(1568799826, timezone.utc)
fs = _MockFileSystem(dt)
with fs.open_output_stream('foo'):
pass
[info] = fs.get_file_info(['foo'])
assert info.mtime == dt
@pytest.mark.gcs
def test_gcs_options(pickle_module):
from pyarrow.fs import GcsFileSystem
dt = datetime.now()
fs = GcsFileSystem(access_token='abc',
target_service_account='service_account@apache',
credential_token_expiration=dt,
default_bucket_location='us-west2',
scheme='https', endpoint_override='localhost:8999',
project_id='test-project-id')
assert isinstance(fs, GcsFileSystem)
assert fs.default_bucket_location == 'us-west2'
assert fs.project_id == 'test-project-id'
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = GcsFileSystem()
assert isinstance(fs, GcsFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = GcsFileSystem(anonymous=True)
assert isinstance(fs, GcsFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = GcsFileSystem(default_metadata={"ACL": "authenticated-read",
"Content-Type": "text/plain"})
assert isinstance(fs, GcsFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
with pytest.raises(ValueError):
GcsFileSystem(access_token='access')
with pytest.raises(ValueError):
GcsFileSystem(anonymous=True, access_token='secret')
with pytest.raises(ValueError):
GcsFileSystem(anonymous=True, target_service_account='acct')
with pytest.raises(ValueError):
GcsFileSystem(credential_token_expiration=datetime.now())
@pytest.mark.s3
def test_s3_options(pickle_module):
from pyarrow.fs import (AwsDefaultS3RetryStrategy,
AwsStandardS3RetryStrategy, S3FileSystem,
S3RetryStrategy)
fs = S3FileSystem(access_key='access', secret_key='secret',
session_token='token', region='us-east-2',
scheme='https', endpoint_override='localhost:8999')
assert isinstance(fs, S3FileSystem)
assert fs.region == 'us-east-2'
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = S3FileSystem(role_arn='role', session_name='session',
external_id='id', load_frequency=100)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
# Note that the retry strategy won't survive pickling for now
fs = S3FileSystem(
retry_strategy=AwsStandardS3RetryStrategy(max_attempts=5))
assert isinstance(fs, S3FileSystem)
fs = S3FileSystem(
retry_strategy=AwsDefaultS3RetryStrategy(max_attempts=5))
assert isinstance(fs, S3FileSystem)
fs2 = S3FileSystem(role_arn='role')
assert isinstance(fs2, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs2
assert fs2 != fs
fs = S3FileSystem(anonymous=True)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = S3FileSystem(background_writes=True)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs2 = S3FileSystem(background_writes=True,
default_metadata={"ACL": "authenticated-read",
"Content-Type": "text/plain"})
assert isinstance(fs2, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs2
assert fs2 != fs
fs = S3FileSystem(allow_bucket_creation=True, allow_bucket_deletion=True)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = S3FileSystem(request_timeout=0.5, connect_timeout=0.25)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs2 = S3FileSystem(request_timeout=0.25, connect_timeout=0.5)
assert isinstance(fs2, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs2
assert fs2 != fs
fs = S3FileSystem(endpoint_override='localhost:8999', force_virtual_addressing=True)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
with pytest.raises(ValueError):
S3FileSystem(access_key='access')
with pytest.raises(ValueError):
S3FileSystem(secret_key='secret')
with pytest.raises(ValueError):
S3FileSystem(access_key='access', session_token='token')
with pytest.raises(ValueError):
S3FileSystem(secret_key='secret', session_token='token')
with pytest.raises(ValueError):
S3FileSystem(
access_key='access', secret_key='secret', role_arn='arn'
)
with pytest.raises(ValueError):
S3FileSystem(
access_key='access', secret_key='secret', anonymous=True
)
with pytest.raises(ValueError):
S3FileSystem(role_arn="arn", anonymous=True)
with pytest.raises(ValueError):
S3FileSystem(default_metadata=["foo", "bar"])
with pytest.raises(ValueError):
S3FileSystem(retry_strategy=S3RetryStrategy())
@pytest.mark.s3
def test_s3_proxy_options(monkeypatch, pickle_module):
from pyarrow.fs import S3FileSystem
# The following two are equivalent:
proxy_opts_1_dict = {'scheme': 'http', 'host': 'localhost', 'port': 8999}
proxy_opts_1_str = 'http://localhost:8999'
# The following two are equivalent:
proxy_opts_2_dict = {'scheme': 'https', 'host': 'localhost', 'port': 8080}
proxy_opts_2_str = 'https://localhost:8080'
# Check dict case for 'proxy_options'
fs = S3FileSystem(proxy_options=proxy_opts_1_dict)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = S3FileSystem(proxy_options=proxy_opts_2_dict)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
# Check str case for 'proxy_options'
fs = S3FileSystem(proxy_options=proxy_opts_1_str)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
fs = S3FileSystem(proxy_options=proxy_opts_2_str)
assert isinstance(fs, S3FileSystem)
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
# Check that two FSs using the same proxy_options dict are equal
fs1 = S3FileSystem(proxy_options=proxy_opts_1_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_1_dict)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_2_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_dict)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
# Check that two FSs using the same proxy_options str are equal
fs1 = S3FileSystem(proxy_options=proxy_opts_1_str)
fs2 = S3FileSystem(proxy_options=proxy_opts_1_str)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_2_str)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_str)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
# Check that two FSs using equivalent proxy_options
# (one dict, one str) are equal
fs1 = S3FileSystem(proxy_options=proxy_opts_1_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_1_str)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_2_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_str)
assert fs1 == fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs1
# Check that two FSs using nonequivalent proxy_options are not equal
fs1 = S3FileSystem(proxy_options=proxy_opts_1_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_dict)
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_1_dict)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_str)
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_1_str)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_dict)
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_1_str)
fs2 = S3FileSystem(proxy_options=proxy_opts_2_str)
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
# Check that two FSs (one using proxy_options and the other not)
# are not equal
fs1 = S3FileSystem(proxy_options=proxy_opts_1_dict)
fs2 = S3FileSystem()
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_1_str)
fs2 = S3FileSystem()
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_2_dict)
fs2 = S3FileSystem()
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
fs1 = S3FileSystem(proxy_options=proxy_opts_2_str)
fs2 = S3FileSystem()
assert fs1 != fs2
assert pickle_module.loads(pickle_module.dumps(fs1)) != fs2
assert pickle_module.loads(pickle_module.dumps(fs2)) != fs1
# Only dict and str are supported
with pytest.raises(TypeError):
S3FileSystem(proxy_options=('http', 'localhost', 9090))
# Missing scheme
with pytest.raises(KeyError):
S3FileSystem(proxy_options={'host': 'localhost', 'port': 9090})
# Missing host
with pytest.raises(KeyError):
S3FileSystem(proxy_options={'scheme': 'https', 'port': 9090})
# Missing port
with pytest.raises(KeyError):
S3FileSystem(proxy_options={'scheme': 'http', 'host': 'localhost'})
# Invalid proxy URI (invalid scheme httpsB)
with pytest.raises(pa.ArrowInvalid):
S3FileSystem(proxy_options='httpsB://localhost:9000')
# Invalid proxy_options dict (invalid scheme httpA)
with pytest.raises(pa.ArrowInvalid):
S3FileSystem(proxy_options={'scheme': 'httpA', 'host': 'localhost',
'port': 8999})
@pytest.mark.s3
def test_s3fs_wrong_region():
from pyarrow.fs import S3FileSystem
# wrong region for bucket
# anonymous=True incase CI/etc has invalid credentials
fs = S3FileSystem(region='eu-north-1', anonymous=True)
msg = ("When getting information for bucket 'voltrondata-labs-datasets': "
r"AWS Error UNKNOWN \(HTTP status 301\) during HeadBucket "
"operation: No response body. Looks like the configured region is "
"'eu-north-1' while the bucket is located in 'us-east-2'."
"|NETWORK_CONNECTION")
with pytest.raises(OSError, match=msg) as exc:
fs.get_file_info("voltrondata-labs-datasets")
# Sometimes fails on unrelated network error, so next call would also fail.
if 'NETWORK_CONNECTION' in str(exc.value):
return
fs = S3FileSystem(region='us-east-2', anonymous=True)
fs.get_file_info("voltrondata-labs-datasets")
@pytest.mark.azure
def test_azurefs_options(pickle_module):
from pyarrow.fs import AzureFileSystem
fs1 = AzureFileSystem(account_name='fake-account-name')
assert isinstance(fs1, AzureFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs1)) == fs1
fs2 = AzureFileSystem(account_name='fake-account-name',
account_key='fakeaccountkey')
assert isinstance(fs2, AzureFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs2)) == fs2
assert fs2 != fs1
fs3 = AzureFileSystem(account_name='fake-account', account_key='fakeaccount',
blob_storage_authority='fake-blob-authority',
dfs_storage_authority='fake-dfs-authority',
blob_storage_scheme='fake-blob-scheme',
dfs_storage_scheme='fake-dfs-scheme')
assert isinstance(fs3, AzureFileSystem)
assert pickle_module.loads(pickle_module.dumps(fs3)) == fs3
assert fs3 != fs2
with pytest.raises(TypeError):
AzureFileSystem()
@pytest.mark.hdfs
def test_hdfs_options(hdfs_connection, pickle_module):
from pyarrow.fs import HadoopFileSystem
if not pa.have_libhdfs():
pytest.skip('Cannot locate libhdfs')
host, port, user = hdfs_connection
replication = 2
buffer_size = 64*1024
default_block_size = 128*1024**2
uri = ('hdfs://{}:{}/?user={}&replication={}&buffer_size={}'
'&default_block_size={}')
hdfs1 = HadoopFileSystem(host, port, user='libhdfs',
replication=replication, buffer_size=buffer_size,
default_block_size=default_block_size)
hdfs2 = HadoopFileSystem.from_uri(uri.format(
host, port, 'libhdfs', replication, buffer_size, default_block_size
))
hdfs3 = HadoopFileSystem.from_uri(uri.format(
host, port, 'me', replication, buffer_size, default_block_size
))
hdfs4 = HadoopFileSystem.from_uri(uri.format(
host, port, 'me', replication + 1, buffer_size, default_block_size
))
hdfs5 = HadoopFileSystem(host, port)
hdfs6 = HadoopFileSystem.from_uri('hdfs://{}:{}'.format(host, port))
hdfs7 = HadoopFileSystem(host, port, user='localuser')
hdfs8 = HadoopFileSystem(host, port, user='localuser',
kerb_ticket="cache_path")
hdfs9 = HadoopFileSystem(host, port, user='localuser',
kerb_ticket=pathlib.Path("cache_path"))
hdfs10 = HadoopFileSystem(host, port, user='localuser',
kerb_ticket="cache_path2")
hdfs11 = HadoopFileSystem(host, port, user='localuser',
kerb_ticket="cache_path",
extra_conf={'hdfs_token': 'abcd'})
assert hdfs1 == hdfs2
assert hdfs5 == hdfs6
assert hdfs6 != hdfs7
assert hdfs2 != hdfs3
assert hdfs3 != hdfs4
assert hdfs7 != hdfs5
assert hdfs2 != hdfs3
assert hdfs3 != hdfs4
assert hdfs7 != hdfs8
assert hdfs8 == hdfs9
assert hdfs10 != hdfs9
assert hdfs11 != hdfs8
with pytest.raises(TypeError):
HadoopFileSystem()
with pytest.raises(TypeError):
HadoopFileSystem.from_uri(3)
for fs in [hdfs1, hdfs2, hdfs3, hdfs4, hdfs5, hdfs6, hdfs7, hdfs8,
hdfs9, hdfs10, hdfs11]:
assert pickle_module.loads(pickle_module.dumps(fs)) == fs
host, port, user = hdfs_connection
hdfs = HadoopFileSystem(host, port, user=user)
assert hdfs.get_file_info(FileSelector('/'))
hdfs = HadoopFileSystem.from_uri(
"hdfs://{}:{}/?user={}".format(host, port, user)
)
assert hdfs.get_file_info(FileSelector('/'))
@pytest.mark.parametrize(('uri', 'expected_klass', 'expected_path'), [
# leading slashes are removed intentionally, because MockFileSystem doesn't
# have a distinction between relative and absolute paths
('mock:', _MockFileSystem, ''),
('mock:foo/bar', _MockFileSystem, 'foo/bar'),
('mock:/foo/bar', _MockFileSystem, 'foo/bar'),
('mock:///foo/bar', _MockFileSystem, 'foo/bar'),
('mock:///some%20path/%C3%A9', _MockFileSystem, 'some path/é'),
('file:/', LocalFileSystem, '/'),
('file:///', LocalFileSystem, '/'),
('file:/foo/bar', LocalFileSystem, '/foo/bar'),
('file:///foo/bar', LocalFileSystem, '/foo/bar'),
('file:///some%20path/%C3%A9', LocalFileSystem, '/some path/é'),
# no %-decoding for non-URI inputs
('/', LocalFileSystem, '/'),
('/foo/bar', LocalFileSystem, '/foo/bar'),
('/some path/%20é', LocalFileSystem, '/some path/%20é'),
])
def test_filesystem_from_uri(uri, expected_klass, expected_path):
fs, path = FileSystem.from_uri(uri)
assert isinstance(fs, expected_klass)
assert path == expected_path
@pytest.mark.parametrize(
'path',
['', '/', 'foo/bar', '/foo/bar', __file__]
)
def test_filesystem_from_path_object(path):
p = pathlib.Path(path)
fs, path = FileSystem.from_uri(p)
assert isinstance(fs, LocalFileSystem)
assert path == p.resolve().absolute().as_posix()
@pytest.mark.s3
def test_filesystem_from_uri_s3(s3_server):
from pyarrow.fs import S3FileSystem
host, port, access_key, secret_key = s3_server['connection']
uri = "s3://{}:{}@mybucket/foo/bar?scheme=http&endpoint_override={}:{}"\
"&allow_bucket_creation=True" \
.format(access_key, secret_key, host, port)
fs, path = FileSystem.from_uri(uri)
assert isinstance(fs, S3FileSystem)
assert path == "mybucket/foo/bar"
fs.create_dir(path)
[info] = fs.get_file_info([path])
assert info.path == path
assert info.type == FileType.Directory
@pytest.mark.gcs
def test_filesystem_from_uri_gcs(gcs_server):
from pyarrow.fs import GcsFileSystem
host, port = gcs_server['connection']
uri = ("gs://anonymous@" +
f"mybucket/foo/bar?scheme=http&endpoint_override={host}:{port}&" +
"retry_limit_seconds=5&project_id=test-project-id")
fs, path = FileSystem.from_uri(uri)
assert isinstance(fs, GcsFileSystem)
assert path == "mybucket/foo/bar"
fs.create_dir(path)
[info] = fs.get_file_info([path])
assert info.path == path
assert info.type == FileType.Directory
def test_py_filesystem():
handler = DummyHandler()
fs = PyFileSystem(handler)
assert isinstance(fs, PyFileSystem)
assert fs.type_name == "py::dummy"
assert fs.handler is handler
with pytest.raises(TypeError):
PyFileSystem(None)
def test_py_filesystem_equality():
handler1 = DummyHandler(1)
handler2 = DummyHandler(2)
handler3 = DummyHandler(2)
fs1 = PyFileSystem(handler1)
fs2 = PyFileSystem(handler1)
fs3 = PyFileSystem(handler2)
fs4 = PyFileSystem(handler3)
assert fs2 is not fs1
assert fs3 is not fs2
assert fs4 is not fs3
assert fs2 == fs1 # Same handler
assert fs3 != fs2 # Unequal handlers
assert fs4 == fs3 # Equal handlers
assert fs1 != LocalFileSystem()
assert fs1 != object()
def test_py_filesystem_pickling(pickle_module):
handler = DummyHandler()
fs = PyFileSystem(handler)
serialized = pickle_module.dumps(fs)
restored = pickle_module.loads(serialized)
assert isinstance(restored, FileSystem)
assert restored == fs
assert restored.handler == handler
assert restored.type_name == "py::dummy"
def test_py_filesystem_lifetime():
handler = DummyHandler()
fs = PyFileSystem(handler)
assert isinstance(fs, PyFileSystem)
wr = weakref.ref(handler)
handler = None
assert wr() is not None
fs = None
assert wr() is None
# Taking the .handler attribute doesn't wreck reference counts
handler = DummyHandler()
fs = PyFileSystem(handler)
wr = weakref.ref(handler)
handler = None
assert wr() is fs.handler
assert wr() is not None
fs = None
assert wr() is None
def test_py_filesystem_get_file_info():
handler = DummyHandler()
fs = PyFileSystem(handler)
[info] = fs.get_file_info(['some/dir'])
assert info.path == 'some/dir'
assert info.type == FileType.Directory
[info] = fs.get_file_info(['some/file'])
assert info.path == 'some/file'
assert info.type == FileType.File
[info] = fs.get_file_info(['notfound'])
assert info.path == 'notfound'
assert info.type == FileType.NotFound
with pytest.raises(TypeError):
fs.get_file_info(['badtype'])
with pytest.raises(IOError):
fs.get_file_info(['xxx'])
def test_py_filesystem_get_file_info_selector():
handler = DummyHandler()
fs = PyFileSystem(handler)
selector = FileSelector(base_dir="somedir")
infos = fs.get_file_info(selector)
assert len(infos) == 2
assert infos[0].path == "somedir/file1"
assert infos[0].type == FileType.File
assert infos[0].size == 123
assert infos[1].path == "somedir/subdir1"
assert infos[1].type == FileType.Directory
assert infos[1].size is None
selector = FileSelector(base_dir="somedir", recursive=True)
infos = fs.get_file_info(selector)
assert len(infos) == 3
assert infos[0].path == "somedir/file1"
assert infos[1].path == "somedir/subdir1"
assert infos[2].path == "somedir/subdir1/file2"
selector = FileSelector(base_dir="notfound")
with pytest.raises(FileNotFoundError):
fs.get_file_info(selector)
selector = FileSelector(base_dir="notfound", allow_not_found=True)
assert fs.get_file_info(selector) == []
def test_py_filesystem_ops():
handler = DummyHandler()
fs = PyFileSystem(handler)
fs.create_dir("recursive", recursive=True)
fs.create_dir("non-recursive", recursive=False)
with pytest.raises(IOError):
fs.create_dir("foobar")
fs.delete_dir("delete_dir")
fs.delete_dir_contents("delete_dir_contents")
for path in ("", "/", "//"):
with pytest.raises(ValueError):
fs.delete_dir_contents(path)
fs.delete_dir_contents(path, accept_root_dir=True)
fs.delete_file("delete_file")
fs.move("move_from", "move_to")
fs.copy_file("copy_file_from", "copy_file_to")
def test_py_open_input_stream():
fs = PyFileSystem(DummyHandler())
with fs.open_input_stream("somefile") as f:
assert f.read() == b"somefile:input_stream"
with pytest.raises(FileNotFoundError):
fs.open_input_stream("notfound")
def test_py_open_input_file():
fs = PyFileSystem(DummyHandler())
with fs.open_input_file("somefile") as f:
assert f.read() == b"somefile:input_file"
with pytest.raises(FileNotFoundError):
fs.open_input_file("notfound")
def test_py_open_output_stream():
fs = PyFileSystem(DummyHandler())
with fs.open_output_stream("somefile") as f:
f.write(b"data")
def test_py_open_append_stream():
fs = PyFileSystem(DummyHandler())
with fs.open_append_stream("somefile") as f:
f.write(b"data")
@pytest.mark.s3
def test_s3_real_aws():
# Exercise connection code with an AWS-backed S3 bucket.
# This is a minimal integration check for ARROW-9261 and similar issues.
from pyarrow.fs import S3FileSystem
default_region = (os.environ.get('PYARROW_TEST_S3_REGION') or
'us-east-1')
fs = S3FileSystem(anonymous=True)
assert fs.region == default_region
fs = S3FileSystem(anonymous=True, region='us-east-2')
entries = fs.get_file_info(FileSelector(
'voltrondata-labs-datasets/nyc-taxi'))
assert len(entries) > 0
key = 'voltrondata-labs-datasets/nyc-taxi/year=2019/month=6/part-0.parquet'
with fs.open_input_stream(key) as f:
md = f.metadata()
assert 'Content-Type' in md
assert md['Last-Modified'] == b'2022-07-12T23:32:00Z'
# For some reason, the header value is quoted
# (both with AWS and Minio)
assert md['ETag'] == b'"4c6a76826a695c6ac61592bc30cda3df-16"'
@pytest.mark.s3
def test_s3_real_aws_region_selection():
# Taken from a registry of open S3-hosted datasets
# at https://github.com/awslabs/open-data-registry
fs, path = FileSystem.from_uri('s3://mf-nwp-models/README.txt')
assert fs.region == 'eu-west-1'
with fs.open_input_stream(path) as f:
assert b"Meteo-France Atmospheric models on AWS" in f.read(50)
# Passing an explicit region disables auto-selection
fs, path = FileSystem.from_uri(
's3://mf-nwp-models/README.txt?region=us-east-2')
assert fs.region == 'us-east-2'
# Reading from the wrong region may still work for public buckets...
# Nonexistent bucket (hopefully, otherwise need to fix this test)
with pytest.raises(IOError, match="Bucket '.*' not found"):
FileSystem.from_uri('s3://x-arrow-nonexistent-bucket')
fs, path = FileSystem.from_uri(
's3://x-arrow-nonexistent-bucket?region=us-east-3')
assert fs.region == 'us-east-3'
@pytest.mark.s3
def test_resolve_s3_region():
from pyarrow.fs import resolve_s3_region
assert resolve_s3_region('voltrondata-labs-datasets') == 'us-east-2'
assert resolve_s3_region('mf-nwp-models') == 'eu-west-1'
with pytest.raises(ValueError, match="Not a valid bucket name"):
resolve_s3_region('foo/bar')
with pytest.raises(ValueError, match="Not a valid bucket name"):
resolve_s3_region('s3:bucket')
@pytest.mark.s3
def test_copy_files(s3_connection, s3fs, tempdir):
fs = s3fs["fs"]
pathfn = s3fs["pathfn"]
# create test file on S3 filesystem
path = pathfn('c.txt')
with fs.open_output_stream(path) as f:
f.write(b'test')
# create URI for created file
host, port, access_key, secret_key = s3_connection
source_uri = (
f"s3://{access_key}:{secret_key}@{path}"
f"?scheme=http&endpoint_override={host}:{port}"
)
# copy from S3 URI to local file
local_path1 = str(tempdir / "c_copied1.txt")
copy_files(source_uri, local_path1)
localfs = LocalFileSystem()
with localfs.open_input_stream(local_path1) as f:
assert f.read() == b"test"
# copy from S3 path+filesystem to local file
local_path2 = str(tempdir / "c_copied2.txt")
copy_files(path, local_path2, source_filesystem=fs)
with localfs.open_input_stream(local_path2) as f:
assert f.read() == b"test"
# copy to local file with URI
local_path3 = str(tempdir / "c_copied3.txt")
destination_uri = _filesystem_uri(local_path3) # file://
copy_files(source_uri, destination_uri)
with localfs.open_input_stream(local_path3) as f:
assert f.read() == b"test"
# copy to local file with path+filesystem
local_path4 = str(tempdir / "c_copied4.txt")
copy_files(source_uri, local_path4, destination_filesystem=localfs)
with localfs.open_input_stream(local_path4) as f:
assert f.read() == b"test"
# copy with additional options
local_path5 = str(tempdir / "c_copied5.txt")
copy_files(source_uri, local_path5, chunk_size=1, use_threads=False)
with localfs.open_input_stream(local_path5) as f:
assert f.read() == b"test"
def test_copy_files_directory(tempdir):
localfs = LocalFileSystem()
# create source directory with 2 files
source_dir = tempdir / "source"
source_dir.mkdir()
with localfs.open_output_stream(str(source_dir / "file1")) as f:
f.write(b'test1')
with localfs.open_output_stream(str(source_dir / "file2")) as f:
f.write(b'test2')
def check_copied_files(destination_dir):
with localfs.open_input_stream(str(destination_dir / "file1")) as f:
assert f.read() == b"test1"
with localfs.open_input_stream(str(destination_dir / "file2")) as f:
assert f.read() == b"test2"
# Copy directory with local file paths
destination_dir1 = tempdir / "destination1"
# TODO need to create?
destination_dir1.mkdir()
copy_files(str(source_dir), str(destination_dir1))
check_copied_files(destination_dir1)
# Copy directory with path+filesystem
destination_dir2 = tempdir / "destination2"
destination_dir2.mkdir()
copy_files(str(source_dir), str(destination_dir2),
source_filesystem=localfs, destination_filesystem=localfs)
check_copied_files(destination_dir2)
# Copy directory with URI
destination_dir3 = tempdir / "destination3"
destination_dir3.mkdir()
source_uri = _filesystem_uri(str(source_dir)) # file://
destination_uri = _filesystem_uri(str(destination_dir3))
copy_files(source_uri, destination_uri)
check_copied_files(destination_dir3)
# Copy directory with Path objects
destination_dir4 = tempdir / "destination4"
destination_dir4.mkdir()
copy_files(source_dir, destination_dir4)
check_copied_files(destination_dir4)
# copy with additional non-default options
destination_dir5 = tempdir / "destination5"
destination_dir5.mkdir()
copy_files(source_dir, destination_dir5, chunk_size=1, use_threads=False)
check_copied_files(destination_dir5)
@pytest.mark.s3
def test_s3_finalize():
# Once finalize_s3() was called, most/all operations on S3 filesystems
# should raise.
code = """if 1:
import pytest
from pyarrow.fs import (FileSystem, S3FileSystem,
ensure_s3_initialized, finalize_s3)
fs, path = FileSystem.from_uri('s3://mf-nwp-models/README.txt')
assert fs.region == 'eu-west-1'
f = fs.open_input_stream(path)
f.read(50)
finalize_s3()
with pytest.raises(ValueError, match="S3 .* finalized"):
f.read(50)
with pytest.raises(ValueError, match="S3 .* finalized"):
fs.open_input_stream(path)
with pytest.raises(ValueError, match="S3 .* finalized"):
S3FileSystem(anonymous=True)
with pytest.raises(ValueError, match="S3 .* finalized"):
FileSystem.from_uri('s3://mf-nwp-models/README.txt')
"""
subprocess.check_call([sys.executable, "-c", code])
@pytest.mark.s3
def test_s3_finalize_region_resolver():
# Same as test_s3_finalize(), but exercising region resolution
code = """if 1:
import pytest
from pyarrow.fs import resolve_s3_region, ensure_s3_initialized, finalize_s3
resolve_s3_region('mf-nwp-models')
finalize_s3()
# Testing both cached and uncached accesses
with pytest.raises(ValueError, match="S3 .* finalized"):
resolve_s3_region('mf-nwp-models')
with pytest.raises(ValueError, match="S3 .* finalized"):
resolve_s3_region('voltrondata-labs-datasets')
"""
subprocess.check_call([sys.executable, "-c", code])
@pytest.mark.s3
def test_concurrent_s3fs_init():
# GH-39897: lazy concurrent initialization of S3 subsystem should not crash
code = """if 1:
import threading
import pytest
from pyarrow.fs import (FileSystem, S3FileSystem,
ensure_s3_initialized, finalize_s3)
threads = []
fn = lambda: FileSystem.from_uri('s3://mf-nwp-models/README.txt')
for i in range(4):
thread = threading.Thread(target = fn)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
finalize_s3()
"""
subprocess.check_call([sys.executable, "-c", code])
|