Debian Codegraph @

tests/test/test_zipfile/_path/test_path.py

raw
1 import contextlib
2 import io
3 import itertools
4 import pathlib
5 import pickle
6 import stat
7 import sys
8 import unittest
9 from backports.zstd import zipfile
10
11 from test.support.os_helper import FakePath, temp_dir
12
13 from ._functools import compose
14 from ._itertools import Counter
15 from ._test_params import Invoked, parameterize
16
17
18 class jaraco:
19 class itertools:
20 Counter = Counter
21
22
23 def _make_link(info: zipfile.ZipInfo): # type: ignore[name-defined]
24 info.external_attr |= stat.S_IFLNK << 16
25
26
27 def build_alpharep_fixture():
28 """
29 Create a zip file with this structure:
30
31 .
32 ├── a.txt
33 ├── n.txt (-> a.txt)
34 ├── b
35 │ ├── c.txt
36 │ ├── d
37 │ │ └── e.txt
38 │ └── f.txt
39 ├── g
40 │ └── h
41 │ └── i.txt
42 └── j
43 ├── k.bin
44 ├── l.baz
45 └── m.bar
46
47 This fixture has the following key characteristics:
48
49 - a file at the root (a)
50 - a file two levels deep (b/d/e)
51 - multiple files in a directory (b/c, b/f)
52 - a directory containing only a directory (g/h)
53 - a directory with files of different extensions (j/klm)
54 - a symlink (n) pointing to (a)
55
56 "alpha" because it uses alphabet
57 "rep" because it's a representative example
58 """
59 data = io.BytesIO()
60 zf = zipfile.ZipFile(data, "w")
61 zf.writestr("a.txt", b"content of a")
62 zf.writestr("b/c.txt", b"content of c")
63 zf.writestr("b/d/e.txt", b"content of e")
64 zf.writestr("b/f.txt", b"content of f")
65 zf.writestr("g/h/i.txt", b"content of i")
66 zf.writestr("j/k.bin", b"content of k")
67 zf.writestr("j/l.baz", b"content of l")
68 zf.writestr("j/m.bar", b"content of m")
69 zf.writestr("n.txt", b"a.txt")
70 _make_link(zf.infolist()[-1])
71
72 zf.filename = "alpharep.zip"
73 return zf
74
75
76 alpharep_generators = [
77 Invoked.wrap(build_alpharep_fixture),
78 Invoked.wrap(compose(zipfile._path.CompleteDirs.inject, build_alpharep_fixture)),
79 ]
80
81 pass_alpharep = parameterize(['alpharep'], alpharep_generators)
82
83
84 class TestPath(unittest.TestCase):
85 def setUp(self):
86 self.fixtures = contextlib.ExitStack()
87 self.addCleanup(self.fixtures.close)
88
89 def zipfile_ondisk(self, alpharep):
90 tmpdir = pathlib.Path(self.fixtures.enter_context(temp_dir()))
91 buffer = alpharep.fp
92 alpharep.close()
93 path = tmpdir / alpharep.filename
94 with path.open("wb") as strm:
95 strm.write(buffer.getvalue())
96 return path
97
98 @pass_alpharep
99 def test_iterdir_and_types(self, alpharep):
100 root = zipfile.Path(alpharep)
101 assert root.is_dir()
102 a, n, b, g, j = root.iterdir()
103 assert a.is_file()
104 assert b.is_dir()
105 assert g.is_dir()
106 c, f, d = b.iterdir()
107 assert c.is_file() and f.is_file()
108 (e,) = d.iterdir()
109 assert e.is_file()
110 (h,) = g.iterdir()
111 (i,) = h.iterdir()
112 assert i.is_file()
113
114 @pass_alpharep
115 def test_is_file_missing(self, alpharep):
116 root = zipfile.Path(alpharep)
117 assert not root.joinpath('missing.txt').is_file()
118
119 @pass_alpharep
120 def test_iterdir_on_file(self, alpharep):
121 root = zipfile.Path(alpharep)
122 a, n, b, g, j = root.iterdir()
123 with self.assertRaises(ValueError):
124 a.iterdir()
125
126 @pass_alpharep
127 def test_subdir_is_dir(self, alpharep):
128 root = zipfile.Path(alpharep)
129 assert (root / 'b').is_dir()
130 assert (root / 'b/').is_dir()
131 assert (root / 'g').is_dir()
132 assert (root / 'g/').is_dir()
133
134 @pass_alpharep
135 def test_open(self, alpharep):
136 root = zipfile.Path(alpharep)
137 a, n, b, g, j = root.iterdir()
138 with a.open(encoding="utf-8") as strm:
139 data = strm.read()
140 self.assertEqual(data, "content of a")
141 with a.open('r', "utf-8") as strm: # not a kw, no gh-101144 TypeError
142 data = strm.read()
143 self.assertEqual(data, "content of a")
144
145 def test_open_encoding_utf16(self):
146 in_memory_file = io.BytesIO()
147 zf = zipfile.ZipFile(in_memory_file, "w")
148 zf.writestr("path/16.txt", "This was utf-16".encode("utf-16"))
149 zf.filename = "test_open_utf16.zip"
150 root = zipfile.Path(zf)
151 (path,) = root.iterdir()
152 u16 = path.joinpath("16.txt")
153 with u16.open('r', "utf-16") as strm:
154 data = strm.read()
155 assert data == "This was utf-16"
156 with u16.open(encoding="utf-16") as strm:
157 data = strm.read()
158 assert data == "This was utf-16"
159
160 def test_open_encoding_errors(self):
161 in_memory_file = io.BytesIO()
162 zf = zipfile.ZipFile(in_memory_file, "w")
163 zf.writestr("path/bad-utf8.bin", b"invalid utf-8: \xff\xff.")
164 zf.filename = "test_read_text_encoding_errors.zip"
165 root = zipfile.Path(zf)
166 (path,) = root.iterdir()
167 u16 = path.joinpath("bad-utf8.bin")
168
169 # encoding= as a positional argument for gh-101144.
170 data = u16.read_text("utf-8", errors="ignore")
171 assert data == "invalid utf-8: ."
172 with u16.open("r", "utf-8", errors="surrogateescape") as f:
173 assert f.read() == "invalid utf-8: \udcff\udcff."
174
175 # encoding= both positional and keyword is an error; gh-101144.
176 with self.assertRaisesRegex(TypeError, "encoding"):
177 data = u16.read_text("utf-8", encoding="utf-8")
178
179 # both keyword arguments work.
180 with u16.open("r", encoding="utf-8", errors="strict") as f:
181 # error during decoding with wrong codec.
182 with self.assertRaises(UnicodeDecodeError):
183 f.read()
184
185 @unittest.skipIf(
186 not getattr(sys.flags, 'warn_default_encoding', 0),
187 "Requires warn_default_encoding",
188 )
189 @pass_alpharep
190 def test_encoding_warnings(self, alpharep):
191 """EncodingWarning must blame the read_text and open calls."""
192 assert sys.flags.warn_default_encoding
193 root = zipfile.Path(alpharep)
194 with self.assertWarns(EncodingWarning) as wc: # noqa: F821 (astral-sh/ruff#13296)
195 root.joinpath("a.txt").read_text()
196 assert __file__ == wc.filename
197 with self.assertWarns(EncodingWarning) as wc: # noqa: F821 (astral-sh/ruff#13296)
198 root.joinpath("a.txt").open("r").close()
199 assert __file__ == wc.filename
200
201 def test_open_write(self):
202 """
203 If the zipfile is open for write, it should be possible to
204 write bytes or text to it.
205 """
206 zf = zipfile.Path(zipfile.ZipFile(io.BytesIO(), mode='w'))
207 with zf.joinpath('file.bin').open('wb') as strm:
208 strm.write(b'binary contents')
209 with zf.joinpath('file.txt').open('w', encoding="utf-8") as strm:
210 strm.write('text file')
211
212 @pass_alpharep
213 def test_open_extant_directory(self, alpharep):
214 """
215 Attempting to open a directory raises IsADirectoryError.
216 """
217 zf = zipfile.Path(alpharep)
218 with self.assertRaises(IsADirectoryError):
219 zf.joinpath('b').open()
220
221 @pass_alpharep
222 def test_open_binary_invalid_args(self, alpharep):
223 root = zipfile.Path(alpharep)
224 with self.assertRaises(ValueError):
225 root.joinpath('a.txt').open('rb', encoding='utf-8')
226 with self.assertRaises(ValueError):
227 root.joinpath('a.txt').open('rb', 'utf-8')
228
229 @pass_alpharep
230 def test_open_missing_directory(self, alpharep):
231 """
232 Attempting to open a missing directory raises FileNotFoundError.
233 """
234 zf = zipfile.Path(alpharep)
235 with self.assertRaises(FileNotFoundError):
236 zf.joinpath('z').open()
237
238 @pass_alpharep
239 def test_read(self, alpharep):
240 root = zipfile.Path(alpharep)
241 a, n, b, g, j = root.iterdir()
242 assert a.read_text(encoding="utf-8") == "content of a"
243 # Also check positional encoding arg (gh-101144).
244 assert a.read_text("utf-8") == "content of a"
245 assert a.read_bytes() == b"content of a"
246
247 @pass_alpharep
248 def test_joinpath(self, alpharep):
249 root = zipfile.Path(alpharep)
250 a = root.joinpath("a.txt")
251 assert a.is_file()
252 e = root.joinpath("b").joinpath("d").joinpath("e.txt")
253 assert e.read_text(encoding="utf-8") == "content of e"
254
255 @pass_alpharep
256 def test_joinpath_multiple(self, alpharep):
257 root = zipfile.Path(alpharep)
258 e = root.joinpath("b", "d", "e.txt")
259 assert e.read_text(encoding="utf-8") == "content of e"
260
261 @pass_alpharep
262 def test_traverse_truediv(self, alpharep):
263 root = zipfile.Path(alpharep)
264 a = root / "a.txt"
265 assert a.is_file()
266 e = root / "b" / "d" / "e.txt"
267 assert e.read_text(encoding="utf-8") == "content of e"
268
269 @pass_alpharep
270 def test_pathlike_construction(self, alpharep):
271 """
272 zipfile.Path should be constructable from a path-like object
273 """
274 zipfile_ondisk = self.zipfile_ondisk(alpharep)
275 pathlike = FakePath(str(zipfile_ondisk))
276 root = zipfile.Path(pathlike)
277 root.root.close()
278
279 @pass_alpharep
280 def test_traverse_pathlike(self, alpharep):
281 root = zipfile.Path(alpharep)
282 root / FakePath("a")
283
284 @pass_alpharep
285 def test_parent(self, alpharep):
286 root = zipfile.Path(alpharep)
287 assert (root / 'a').parent.at == ''
288 assert (root / 'a' / 'b').parent.at == 'a/'
289
290 @pass_alpharep
291 def test_dir_parent(self, alpharep):
292 root = zipfile.Path(alpharep)
293 assert (root / 'b').parent.at == ''
294 assert (root / 'b/').parent.at == ''
295
296 @pass_alpharep
297 def test_missing_dir_parent(self, alpharep):
298 root = zipfile.Path(alpharep)
299 assert (root / 'missing dir/').parent.at == ''
300
301 @pass_alpharep
302 def test_mutability(self, alpharep):
303 """
304 If the underlying zipfile is changed, the Path object should
305 reflect that change.
306 """
307 root = zipfile.Path(alpharep)
308 a, n, b, g, j = root.iterdir()
309 alpharep.writestr('foo.txt', 'foo')
310 alpharep.writestr('bar/baz.txt', 'baz')
311 assert any(child.name == 'foo.txt' for child in root.iterdir())
312 assert (root / 'foo.txt').read_text(encoding="utf-8") == 'foo'
313 (baz,) = (root / 'bar').iterdir()
314 assert baz.read_text(encoding="utf-8") == 'baz'
315
316 HUGE_ZIPFILE_NUM_ENTRIES = 2**13
317
318 def huge_zipfile(self):
319 """Create a read-only zipfile with a huge number of entries entries."""
320 strm = io.BytesIO()
321 zf = zipfile.ZipFile(strm, "w")
322 for entry in map(str, range(self.HUGE_ZIPFILE_NUM_ENTRIES)):
323 zf.writestr(entry, entry)
324 zf.mode = 'r'
325 return zf
326
327 def test_joinpath_constant_time(self):
328 """
329 Ensure joinpath on items in zipfile is linear time.
330 """
331 root = zipfile.Path(self.huge_zipfile())
332 entries = jaraco.itertools.Counter(root.iterdir())
333 for entry in entries:
334 entry.joinpath('suffix')
335 # Check the file iterated all items
336 assert entries.count == self.HUGE_ZIPFILE_NUM_ENTRIES
337
338 @pass_alpharep
339 def test_read_does_not_close(self, alpharep):
340 alpharep = self.zipfile_ondisk(alpharep)
341 with zipfile.ZipFile(alpharep) as file:
342 for rep in range(2):
343 zipfile.Path(file, 'a.txt').read_text(encoding="utf-8")
344
345 @pass_alpharep
346 def test_subclass(self, alpharep):
347 class Subclass(zipfile.Path):
348 pass
349
350 root = Subclass(alpharep)
351 assert isinstance(root / 'b', Subclass)
352
353 @pass_alpharep
354 def test_filename(self, alpharep):
355 root = zipfile.Path(alpharep)
356 assert root.filename == pathlib.Path('alpharep.zip')
357
358 @pass_alpharep
359 def test_root_name(self, alpharep):
360 """
361 The name of the root should be the name of the zipfile
362 """
363 root = zipfile.Path(alpharep)
364 assert root.name == 'alpharep.zip' == root.filename.name
365
366 @pass_alpharep
367 def test_root_on_disk(self, alpharep):
368 """
369 The name/stem of the root should match the zipfile on disk.
370
371 This condition must hold across platforms.
372 """
373 root = zipfile.Path(self.zipfile_ondisk(alpharep))
374 assert root.name == 'alpharep.zip' == root.filename.name
375 assert root.stem == 'alpharep' == root.filename.stem
376 root.root.close()
377
378 @pass_alpharep
379 def test_suffix(self, alpharep):
380 """
381 The suffix of the root should be the suffix of the zipfile.
382 The suffix of each nested file is the final component's last suffix, if any.
383 Includes the leading period, just like pathlib.Path.
384 """
385 root = zipfile.Path(alpharep)
386 assert root.suffix == '.zip' == root.filename.suffix
387
388 b = root / "b.txt"
389 assert b.suffix == ".txt"
390
391 c = root / "c" / "filename.tar.gz"
392 assert c.suffix == ".gz"
393
394 d = root / "d"
395 assert d.suffix == ""
396
397 @pass_alpharep
398 def test_suffixes(self, alpharep):
399 """
400 The suffix of the root should be the suffix of the zipfile.
401 The suffix of each nested file is the final component's last suffix, if any.
402 Includes the leading period, just like pathlib.Path.
403 """
404 root = zipfile.Path(alpharep)
405 assert root.suffixes == ['.zip'] == root.filename.suffixes
406
407 b = root / 'b.txt'
408 assert b.suffixes == ['.txt']
409
410 c = root / 'c' / 'filename.tar.gz'
411 assert c.suffixes == ['.tar', '.gz']
412
413 d = root / 'd'
414 assert d.suffixes == []
415
416 e = root / '.hgrc'
417 assert e.suffixes == []
418
419 @pass_alpharep
420 def test_suffix_no_filename(self, alpharep):
421 alpharep.filename = None
422 root = zipfile.Path(alpharep)
423 assert root.joinpath('example').suffix == ""
424 assert root.joinpath('example').suffixes == []
425
426 @pass_alpharep
427 def test_stem(self, alpharep):
428 """
429 The final path component, without its suffix
430 """
431 root = zipfile.Path(alpharep)
432 assert root.stem == 'alpharep' == root.filename.stem
433
434 b = root / "b.txt"
435 assert b.stem == "b"
436
437 c = root / "c" / "filename.tar.gz"
438 assert c.stem == "filename.tar"
439
440 d = root / "d"
441 assert d.stem == "d"
442
443 assert (root / ".gitignore").stem == ".gitignore"
444
445 @pass_alpharep
446 def test_root_parent(self, alpharep):
447 root = zipfile.Path(alpharep)
448 assert root.parent == pathlib.Path('.')
449 root.root.filename = 'foo/bar.zip'
450 assert root.parent == pathlib.Path('foo')
451
452 @pass_alpharep
453 def test_root_unnamed(self, alpharep):
454 """
455 It is an error to attempt to get the name
456 or parent of an unnamed zipfile.
457 """
458 alpharep.filename = None
459 root = zipfile.Path(alpharep)
460 with self.assertRaises(TypeError):
461 root.name
462 with self.assertRaises(TypeError):
463 root.parent
464
465 # .name and .parent should still work on subs
466 sub = root / "b"
467 assert sub.name == "b"
468 assert sub.parent
469
470 @pass_alpharep
471 def test_match_and_glob(self, alpharep):
472 root = zipfile.Path(alpharep)
473 assert not root.match("*.txt")
474
475 assert list(root.glob("b/c.*")) == [zipfile.Path(alpharep, "b/c.txt")]
476 assert list(root.glob("b/*.txt")) == [
477 zipfile.Path(alpharep, "b/c.txt"),
478 zipfile.Path(alpharep, "b/f.txt"),
479 ]
480
481 @pass_alpharep
482 def test_glob_recursive(self, alpharep):
483 root = zipfile.Path(alpharep)
484 files = root.glob("**/*.txt")
485 assert all(each.match("*.txt") for each in files)
486
487 assert list(root.glob("**/*.txt")) == list(root.rglob("*.txt"))
488
489 @pass_alpharep
490 def test_glob_dirs(self, alpharep):
491 root = zipfile.Path(alpharep)
492 assert list(root.glob('b')) == [zipfile.Path(alpharep, "b/")]
493 assert list(root.glob('b*')) == [zipfile.Path(alpharep, "b/")]
494
495 @pass_alpharep
496 def test_glob_subdir(self, alpharep):
497 root = zipfile.Path(alpharep)
498 assert list(root.glob('g/h')) == [zipfile.Path(alpharep, "g/h/")]
499 assert list(root.glob('g*/h*')) == [zipfile.Path(alpharep, "g/h/")]
500
501 @pass_alpharep
502 def test_glob_subdirs(self, alpharep):
503 root = zipfile.Path(alpharep)
504
505 assert list(root.glob("*/i.txt")) == []
506 assert list(root.rglob("*/i.txt")) == [zipfile.Path(alpharep, "g/h/i.txt")]
507
508 @pass_alpharep
509 def test_glob_does_not_overmatch_dot(self, alpharep):
510 root = zipfile.Path(alpharep)
511
512 assert list(root.glob("*.xt")) == []
513
514 @pass_alpharep
515 def test_glob_single_char(self, alpharep):
516 root = zipfile.Path(alpharep)
517
518 assert list(root.glob("a?txt")) == [zipfile.Path(alpharep, "a.txt")]
519 assert list(root.glob("a[.]txt")) == [zipfile.Path(alpharep, "a.txt")]
520 assert list(root.glob("a[?]txt")) == []
521
522 @pass_alpharep
523 def test_glob_chars(self, alpharep):
524 root = zipfile.Path(alpharep)
525
526 assert list(root.glob("j/?.b[ai][nz]")) == [
527 zipfile.Path(alpharep, "j/k.bin"),
528 zipfile.Path(alpharep, "j/l.baz"),
529 ]
530
531 def test_glob_empty(self):
532 root = zipfile.Path(zipfile.ZipFile(io.BytesIO(), 'w'))
533 with self.assertRaises(ValueError):
534 root.glob('')
535
536 @pass_alpharep
537 def test_eq_hash(self, alpharep):
538 root = zipfile.Path(alpharep)
539 assert root == zipfile.Path(alpharep)
540
541 assert root != (root / "a.txt")
542 assert (root / "a.txt") == (root / "a.txt")
543
544 root = zipfile.Path(alpharep)
545 assert root in {root}
546
547 @pass_alpharep
548 def test_is_symlink(self, alpharep):
549 root = zipfile.Path(alpharep)
550 assert not root.joinpath('a.txt').is_symlink()
551 assert root.joinpath('n.txt').is_symlink()
552
553 @pass_alpharep
554 def test_relative_to(self, alpharep):
555 root = zipfile.Path(alpharep)
556 relative = root.joinpath("b", "c.txt").relative_to(root / "b")
557 assert str(relative) == "c.txt"
558
559 relative = root.joinpath("b", "d", "e.txt").relative_to(root / "b")
560 assert str(relative) == "d/e.txt"
561
562 @pass_alpharep
563 def test_inheritance(self, alpharep):
564 cls = type('PathChild', (zipfile.Path,), {})
565 file = cls(alpharep).joinpath('some dir').parent
566 assert isinstance(file, cls)
567
568 @parameterize(
569 ['alpharep', 'path_type', 'subpath'],
570 itertools.product(
571 alpharep_generators,
572 [str, FakePath],
573 ['', 'b/'],
574 ),
575 )
576 def test_pickle(self, alpharep, path_type, subpath):
577 zipfile_ondisk = path_type(str(self.zipfile_ondisk(alpharep)))
578 root = zipfile.Path(zipfile_ondisk, at=subpath)
579 saved_1 = pickle.dumps(root)
580 root.root.close()
581 restored_1 = pickle.loads(saved_1)
582 first, *rest = restored_1.iterdir()
583 assert first.read_text(encoding='utf-8').startswith('content of ')
584 restored_1.root.close()
585
586 @pass_alpharep
587 def test_extract_orig_with_implied_dirs(self, alpharep):
588 """
589 A zip file wrapped in a Path should extract even with implied dirs.
590 """
591 source_path = self.zipfile_ondisk(alpharep)
592 zf = zipfile.ZipFile(source_path)
593 # wrap the zipfile for its side effect
594 zipfile.Path(zf)
595 zf.extractall(source_path.parent)
596 zf.close()
597
598 @pass_alpharep
599 def test_getinfo_missing(self, alpharep):
600 """
601 Validate behavior of getinfo on original zipfile after wrapping.
602 """
603 zipfile.Path(alpharep)
604 with self.assertRaises(KeyError):
605 alpharep.getinfo('does-not-exist')
606
607 def test_malformed_paths(self):
608 """
609 Path should handle malformed paths gracefully.
610
611 Paths with leading slashes are not visible.
612
613 Paths with dots are treated like regular files.
614 """
615 data = io.BytesIO()
616 zf = zipfile.ZipFile(data, "w")
617 zf.writestr("/one-slash.txt", b"content")
618 zf.writestr("//two-slash.txt", b"content")
619 zf.writestr("../parent.txt", b"content")
620 zf.filename = ''
621 root = zipfile.Path(zf)
622 assert list(map(str, root.iterdir())) == ['../']
623 assert root.joinpath('..').joinpath('parent.txt').read_bytes() == b'content'
624
625 def test_unsupported_names(self):
626 """
627 Path segments with special characters are readable.
628
629 On some platforms or file systems, characters like
630 ``:`` and ``?`` are not allowed, but they are valid
631 in the zip file.
632 """
633 data = io.BytesIO()
634 zf = zipfile.ZipFile(data, "w")
635 zf.writestr("path?", b"content")
636 zf.writestr("V: NMS.flac", b"fLaC...")
637 zf.filename = ''
638 root = zipfile.Path(zf)
639 contents = root.iterdir()
640 assert next(contents).name == 'path?'
641 assert next(contents).name == 'V: NMS.flac'
642 assert root.joinpath('V: NMS.flac').read_bytes() == b"fLaC..."
643
644 def test_backslash_not_separator(self):
645 """
646 In a zip file, backslashes are not separators.
647 """
648 data = io.BytesIO()
649 zf = zipfile.ZipFile(data, "w")
650 zf.writestr(DirtyZipInfo("foo\\bar")._for_archive(zf), b"content")
651 zf.filename = ''
652 root = zipfile.Path(zf)
653 (first,) = root.iterdir()
654 assert not first.is_dir()
655 assert first.name == 'foo\\bar'
656
657 @unittest.skipIf(sys.version_info < (3, 11), "Requires Python 3.11")
658 @pass_alpharep
659 def test_interface(self, alpharep):
660 from importlib.resources.abc import Traversable
661
662 zf = zipfile.Path(alpharep)
663 assert isinstance(zf, Traversable)
664
665
666 class DirtyZipInfo(zipfile.ZipInfo):
667 """
668 Bypass name sanitization.
669 """
670
671 def __init__(self, filename, *args, **kwargs):
672 super().__init__(filename, *args, **kwargs)
673 self.filename = filename