Spaces:
Runtime error
Runtime error
File size: 13,135 Bytes
63deadc |
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 |
import bz2
import gzip
import lzma
import os
import pickle
import tarfile
import tempfile
import zipfile
from contextlib import contextmanager
from io import BytesIO
import pytest
import fsspec
# The blueprint to create synthesized archive files from.
archive_data = {"a": b"", "b": b"hello", "deeply/nested/path": b"stuff"}
@contextmanager
def tempzip(data=None):
"""
Provide test cases with temporary synthesized Zip archives.
"""
data = data or {}
f = tempfile.mkstemp(suffix=".zip")[1]
with zipfile.ZipFile(f, mode="w") as z:
for k, v in data.items():
z.writestr(k, v)
try:
yield f
finally:
try:
os.remove(f)
except OSError:
pass
@contextmanager
def temparchive(data=None):
"""
Provide test cases with temporary synthesized 7-Zip archives.
"""
data = data or {}
libarchive = pytest.importorskip("libarchive")
f = tempfile.mkstemp(suffix=".7z")[1]
with libarchive.file_writer(f, "7zip") as archive:
for k, v in data.items():
archive.add_file_from_memory(entry_path=k, entry_size=len(v), entry_data=v)
try:
yield f
finally:
try:
os.remove(f)
except OSError:
pass
@contextmanager
def temptar(data=None, mode="w", suffix=".tar"):
"""
Provide test cases with temporary synthesized .tar archives.
"""
data = data or {}
fn = tempfile.mkstemp(suffix=suffix)[1]
with tarfile.TarFile.open(fn, mode=mode) as t:
touched = {}
for name, data in data.items():
# Create directory hierarchy.
# https://bugs.python.org/issue22208#msg225558
if "/" in name and name not in touched:
parts = os.path.dirname(name).split("/")
for index in range(1, len(parts) + 1):
info = tarfile.TarInfo("/".join(parts[:index]))
info.type = tarfile.DIRTYPE
t.addfile(info)
touched[name] = True
# Add file content.
info = tarfile.TarInfo(name=name)
info.size = len(data)
t.addfile(info, BytesIO(data))
try:
yield fn
finally:
try:
os.remove(fn)
except OSError:
pass
@contextmanager
def temptargz(data=None, mode="w", suffix=".tar.gz"):
"""
Provide test cases with temporary synthesized .tar.gz archives.
"""
with temptar(data=data, mode=mode) as tarname:
fn = tempfile.mkstemp(suffix=suffix)[1]
with open(tarname, "rb") as tar:
cf = gzip.GzipFile(filename=fn, mode=mode)
cf.write(tar.read())
cf.close()
try:
yield fn
finally:
try:
os.remove(fn)
except OSError:
pass
@contextmanager
def temptarbz2(data=None, mode="w", suffix=".tar.bz2"):
"""
Provide test cases with temporary synthesized .tar.bz2 archives.
"""
with temptar(data=data, mode=mode) as tarname:
fn = tempfile.mkstemp(suffix=suffix)[1]
with open(tarname, "rb") as tar:
cf = bz2.BZ2File(filename=fn, mode=mode)
cf.write(tar.read())
cf.close()
try:
yield fn
finally:
try:
os.remove(fn)
except OSError:
pass
@contextmanager
def temptarxz(data=None, mode="w", suffix=".tar.xz"):
"""
Provide test cases with temporary synthesized .tar.xz archives.
"""
with temptar(data=data, mode=mode) as tarname:
fn = tempfile.mkstemp(suffix=suffix)[1]
with open(tarname, "rb") as tar:
cf = lzma.open(filename=fn, mode=mode, format=lzma.FORMAT_XZ)
cf.write(tar.read())
cf.close()
try:
yield fn
finally:
try:
os.remove(fn)
except OSError:
pass
class ArchiveTestScenario:
"""
Describe a test scenario for any type of archive.
"""
def __init__(self, protocol=None, provider=None, variant=None):
# The filesystem protocol identifier. Any of "zip", "tar" or "libarchive".
self.protocol = protocol
# A contextmanager function to provide temporary synthesized archives.
self.provider = provider
# The filesystem protocol variant identifier. Any of "gz", "bz2" or "xz".
self.variant = variant
def pytest_generate_tests(metafunc):
"""
Generate test scenario parametrization arguments with appropriate labels (idlist).
On the one hand, this yields an appropriate output like::
fsspec/implementations/tests/test_archive.py::TestArchive::test_empty[zip] PASSED # noqa
On the other hand, it will support perfect test discovery, like::
pytest fsspec -vvv -k "zip or tar or libarchive"
https://docs.pytest.org/en/latest/example/parametrize.html#a-quick-port-of-testscenarios
"""
idlist = []
argnames = ["scenario"]
argvalues = []
for scenario in metafunc.cls.scenarios:
scenario: ArchiveTestScenario = scenario
label = scenario.protocol
if scenario.variant:
label += "-" + scenario.variant
idlist.append(label)
argvalues.append([scenario])
metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
# Define test scenarios.
scenario_zip = ArchiveTestScenario(protocol="zip", provider=tempzip)
scenario_tar = ArchiveTestScenario(protocol="tar", provider=temptar)
scenario_targz = ArchiveTestScenario(protocol="tar", provider=temptargz, variant="gz")
scenario_tarbz2 = ArchiveTestScenario(
protocol="tar", provider=temptarbz2, variant="bz2"
)
scenario_tarxz = ArchiveTestScenario(protocol="tar", provider=temptarxz, variant="xz")
scenario_libarchive = ArchiveTestScenario(protocol="libarchive", provider=temparchive)
class TestAnyArchive:
"""
Validate that all filesystem adapter implementations for archive files
will adhere to the same specification.
"""
scenarios = [
scenario_zip,
scenario_tar,
scenario_targz,
scenario_tarbz2,
scenario_tarxz,
scenario_libarchive,
]
def test_repr(self, scenario: ArchiveTestScenario):
with scenario.provider() as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert repr(fs).startswith("<Archive-like object")
def test_empty(self, scenario: ArchiveTestScenario):
with scenario.provider() as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert fs.find("") == []
assert fs.find("", withdirs=True) == []
with pytest.raises(FileNotFoundError):
fs.info("")
assert fs.ls("") == []
def test_glob(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert fs.glob("*/*/*th") == ["deeply/nested/path"]
def test_mapping(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
m = fs.get_mapper()
assert list(m) == ["a", "b", "deeply/nested/path"]
assert m["b"] == archive_data["b"]
def test_pickle(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
fs2 = pickle.loads(pickle.dumps(fs))
assert fs2.cat("b") == b"hello"
def test_all_dirnames(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
# fx are files, dx are a directories
assert fs._all_dirnames([]) == set()
assert fs._all_dirnames(["f1"]) == set()
assert fs._all_dirnames(["f1", "f2"]) == set()
assert fs._all_dirnames(["f1", "f2", "d1/f1"]) == {"d1"}
assert fs._all_dirnames(["f1", "d1/f1", "d1/f2"]) == {"d1"}
assert fs._all_dirnames(["f1", "d1/f1", "d2/f1"]) == {"d1", "d2"}
assert fs._all_dirnames(["d1/d1/d1/f1"]) == {"d1", "d1/d1", "d1/d1/d1"}
def test_ls(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert fs.ls("", detail=False) == ["a", "b", "deeply"]
assert fs.ls("/") == fs.ls("")
assert fs.ls("deeply", detail=False) == ["deeply/nested"]
assert fs.ls("deeply/") == fs.ls("deeply")
assert fs.ls("deeply/nested", detail=False) == ["deeply/nested/path"]
assert fs.ls("deeply/nested/") == fs.ls("deeply/nested")
def test_find(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert fs.find("") == ["a", "b", "deeply/nested/path"]
assert fs.find("", withdirs=True) == [
"a",
"b",
"deeply",
"deeply/nested",
"deeply/nested/path",
]
assert fs.find("deeply") == ["deeply/nested/path"]
assert fs.find("deeply/") == fs.find("deeply")
@pytest.mark.parametrize("topdown", [True, False])
@pytest.mark.parametrize("prune_nested", [True, False])
def test_walk(self, scenario: ArchiveTestScenario, topdown, prune_nested):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
expected = [
# (dirname, list of subdirs, list of files)
("", ["deeply"], ["a", "b"]),
("deeply", ["nested"], []),
]
if not topdown or not prune_nested:
expected.append(("deeply/nested", [], ["path"]))
if not topdown:
expected.reverse()
result = []
for path, dirs, files in fs.walk("", topdown=topdown):
result.append((path, dirs.copy(), files))
# Bypass the "nested" dir
if prune_nested and "nested" in dirs:
dirs.remove("nested")
# prior py3.10 zip() does not support strict=True, we need
# a manual len check here
assert len(result) == len(expected)
for lhs, rhs in zip(result, expected):
assert lhs[0] == rhs[0]
assert sorted(lhs[1]) == sorted(rhs[1])
assert sorted(lhs[2]) == sorted(rhs[2])
def test_info(self, scenario: ArchiveTestScenario):
# https://github.com/Suor/funcy/blob/1.15/funcy/colls.py#L243-L245
def project(mapping, keys):
"""Leaves only given keys in mapping."""
return {k: mapping[k] for k in keys if k in mapping}
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
with pytest.raises(FileNotFoundError):
fs.info("i-do-not-exist")
# Iterate over all directories.
for d in fs._all_dirnames(archive_data.keys()):
lhs = project(fs.info(d), ["name", "size", "type"])
expected = {"name": f"{d}", "size": 0, "type": "directory"}
assert lhs == expected
# Iterate over all files.
for f, v in archive_data.items():
lhs = fs.info(f)
assert lhs["name"] == f
assert lhs["size"] == len(v)
assert lhs["type"] == "file"
@pytest.mark.parametrize("scale", [128, 512, 4096])
def test_isdir_isfile(self, scenario: ArchiveTestScenario, scale: int):
def make_nested_dir(i):
x = f"{i}"
table = x.maketrans("0123456789", "ABCDEFGHIJ")
return "/".join(x.translate(table))
scaled_data = {f"{make_nested_dir(i)}/{i}": b"" for i in range(1, scale + 1)}
with scenario.provider(scaled_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
lhs_dirs, lhs_files = (
fs._all_dirnames(scaled_data.keys()),
scaled_data.keys(),
)
# Warm-up the Cache, this is done in both cases anyways...
fs._get_dirs()
entries = lhs_files | lhs_dirs
assert lhs_dirs == {e for e in entries if fs.isdir(e)}
assert lhs_files == {e for e in entries if fs.isfile(e)}
def test_read_empty_file(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
assert fs.open("a").read() == b""
|