Debian Codegraph @

tests/archive_test.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Tests for the archive-expansion feature.
18
19 Covers the CLI flags and Options fields that enable expansion; VirtualFileInfo
20 (a file held in memory inside an archive) and ArchiveDirInfo (an expanded
21 archive directory); the expand_archive helper that populates an ArchiveDirInfo
22 from a tar or zip; its integration into RootInfo.build via subtree expansion;
23 and the full pipeline output with and without archive expansion.
24 """
25
26 from __future__ import annotations
27
28 import io
29 import sys
30 import tarfile
31 import tempfile
32 import unittest
33 import zipfile
34 from pathlib import Path
35 from unittest.mock import patch
36
37 from decopy import cmdoptions
38 from decopy.decopy import run_pipeline
39 from decopy.fstree import archives, nodes, tree
40
41 _COPYRIGHT_BYTES = b"# Copyright (C) 2024 Test Author <[email protected]>\n"
42
43 _BASE = ["--no-progress", "--root", "."]
44
45
46 # Helpers
47
48
49 def _make_tar_gz(members: dict[str, bytes]) -> bytes:
50 buf = io.BytesIO()
51 with tarfile.open(fileobj=buf, mode="w:gz") as tar:
52 for name, content in members.items():
53 info = tarfile.TarInfo(name=name)
54 info.size = len(content)
55 tar.addfile(info, io.BytesIO(content))
56 return buf.getvalue()
57
58
59 def _make_zip(members: dict[str, bytes]) -> bytes:
60 buf = io.BytesIO()
61 with zipfile.ZipFile(buf, "w") as zf:
62 for name, content in members.items():
63 zf.writestr(name, content)
64 return buf.getvalue()
65
66
67 def _walk_virtual_files(node: nodes.DirInfo) -> list[nodes.FileInfo]:
68 """Recursively collect non-DirInfo leaves under a DirInfo node."""
69 items = []
70 for child in node.file_list.values():
71 if isinstance(child, nodes.DirInfo):
72 items.extend(_walk_virtual_files(child))
73 else:
74 items.append(child)
75 return items
76
77
78 # Options fields for archive expansion
79
80
81 class TestArchiveOptions(unittest.TestCase):
82 """CLI flags and Options fields for archive expansion."""
83
84 def test_expand_archives_defaults_to_true(self):
85 opts = cmdoptions.process_options(_BASE)
86 self.assertTrue(opts.expand_archives)
87
88 def test_no_expand_archives_flag(self):
89 opts = cmdoptions.process_options([*_BASE, "--no-expand-archives"])
90 self.assertFalse(opts.expand_archives)
91
92 def test_expand_archives_flag_last_wins(self):
93 opts = cmdoptions.process_options(
94 [*_BASE, "--no-expand-archives", "--expand-archives"]
95 )
96 self.assertTrue(opts.expand_archives)
97 opts = cmdoptions.process_options(
98 [*_BASE, "--expand-archives", "--no-expand-archives"]
99 )
100 self.assertFalse(opts.expand_archives)
101
102 def test_max_archive_depth_default(self):
103 opts = cmdoptions.process_options(_BASE)
104 self.assertEqual(opts.max_archive_depth, 1)
105
106 def test_max_archive_depth_flag(self):
107 opts = cmdoptions.process_options([*_BASE, "--max-archive-depth", "3"])
108 self.assertEqual(opts.max_archive_depth, 3)
109
110 def test_max_archive_member_size_default(self):
111 opts = cmdoptions.process_options(_BASE)
112 self.assertEqual(opts.max_archive_member_size, 10 * 1024 * 1024)
113
114 def test_max_archive_member_size_flag(self):
115 opts = cmdoptions.process_options(
116 [*_BASE, "--max-archive-member-size", "1048576"]
117 )
118 self.assertEqual(opts.max_archive_member_size, 1024 * 1024)
119
120
121 # VirtualFileInfo and ArchiveDirInfo
122
123
124 class TestVirtualFileInfo(unittest.TestCase):
125 """VirtualFileInfo holds in-memory bytes and parses them."""
126
127 def _make_vfi(self, name: str, content: bytes) -> nodes.VirtualFileInfo:
128 root = tree.RootInfo(root=".")
129 parent = nodes.ArchiveDirInfo(
130 parent=root, name="arch.tar.gz", archive_path="arch.tar.gz"
131 )
132 return nodes.VirtualFileInfo(parent=parent, name=name, content=content)
133
134 def test_name_is_set(self):
135 vfi = self._make_vfi("src.py", b"")
136 self.assertEqual(vfi.name, "src.py")
137
138 def test_fullname_includes_archive_and_member(self):
139 vfi = self._make_vfi("src.py", b"")
140 self.assertIn("arch.tar.gz", vfi.fullname)
141 self.assertIn("src.py", vfi.fullname)
142
143 def test_process_licenses_finds_copyright(self):
144 opts = cmdoptions.process_options([*_BASE, "--text"])
145 vfi = self._make_vfi("src.py", b"# Copyright 2024 Bob <[email protected]>\n")
146 result = vfi.process_licenses(root=".", options=opts)
147 self.assertIsNotNone(result)
148 self.assertTrue(any("Bob" in str(h) for h in vfi.copyrights))
149
150 def test_process_licenses_returns_none_on_fullname_exclusion(self):
151 opts = cmdoptions.process_options([*_BASE, "--text", "--exclude", r".*\.py$"])
152 vfi = self._make_vfi("src.py", b"# Copyright 2024 X\n")
153 result = vfi.process_licenses(root=".", options=opts)
154 self.assertIsNone(result)
155
156
157 class TestArchiveDirInfo(unittest.TestCase):
158 """ArchiveDirInfo marks an archive expansion root."""
159
160 def test_is_dirinfo_subclass(self):
161 self.assertTrue(issubclass(nodes.ArchiveDirInfo, nodes.DirInfo))
162
163 def test_archive_path_stored(self):
164 root = tree.RootInfo(root=".")
165 adi = nodes.ArchiveDirInfo(
166 parent=root, name="arch.zip", archive_path="/full/path/arch.zip"
167 )
168 self.assertEqual(adi.archive_path, "/full/path/arch.zip")
169
170
171 # FileInfo.is_excluded
172
173
174 class TestFileInfoIsExcluded(unittest.TestCase):
175 """R7: FileInfo.is_excluded(options) -> bool extracts the shared exclusion guard."""
176
177 def _make_fi(self, name: str) -> nodes.FileInfo:
178 root = tree.RootInfo(root=".")
179 return nodes.FileInfo(parent=root, name=name)
180
181 def test_not_excluded_by_default(self):
182 opts = cmdoptions.process_options(_BASE)
183 fi = self._make_fi("src.py")
184 self.assertFalse(fi.is_excluded(opts))
185
186 def test_excluded_by_fullname_re(self):
187 opts = cmdoptions.process_options([*_BASE, "--exclude", r".*\.py$"])
188 fi = self._make_fi("src.py")
189 self.assertTrue(fi.is_excluded(opts))
190
191 def test_not_excluded_when_pattern_mismatches(self):
192 opts = cmdoptions.process_options([*_BASE, "--exclude", r".*\.c$"])
193 fi = self._make_fi("src.py")
194 self.assertFalse(fi.is_excluded(opts))
195
196 def test_excluded_by_special_re(self):
197 opts = cmdoptions.process_options(_BASE)
198 # debian/copyright is always excluded by exclude_special_re
199 root = tree.RootInfo(root=".")
200 debian_dir = nodes.DirInfo(parent=root, name="debian")
201 root.file_list["debian"] = debian_dir
202 fi = nodes.FileInfo(parent=debian_dir, name="copyright")
203 self.assertTrue(fi.is_excluded(opts))
204
205
206 # iter_archive_members
207
208
209 class TestIterArchiveMembers(unittest.TestCase):
210 """R6: iter_archive_members yields (path, bytes) for tar and zip."""
211
212 def _iter_bytes(
213 self,
214 data: bytes,
215 suffix: str,
216 extra_flags: list[str] | None = None,
217 ) -> list[tuple[str, bytes]]:
218 opts = cmdoptions.process_options([*_BASE, *(extra_flags or [])])
219 with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
220 f.write(data)
221 fpath = f.name
222 try:
223 return list(archives.iter_archive_members(fpath, opts))
224 finally:
225 Path(fpath).unlink()
226
227 def test_tar_gz_yields_path_and_bytes(self):
228 members = self._iter_bytes(
229 _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES}), ".tar.gz"
230 )
231 paths = [p for p, _ in members]
232 self.assertIn("src/main.py", paths)
233 content = next(c for p, c in members if p == "src/main.py")
234 self.assertEqual(content, _COPYRIGHT_BYTES)
235
236 def test_zip_yields_path_and_bytes(self):
237 members = self._iter_bytes(_make_zip({"README": _COPYRIGHT_BYTES}), ".zip")
238 paths = [p for p, _ in members]
239 self.assertIn("README", paths)
240
241 def test_tar_symlink_not_yielded(self):
242 buf = io.BytesIO()
243 with tarfile.open(fileobj=buf, mode="w:gz") as tar:
244 link = tarfile.TarInfo(name="link")
245 link.type = tarfile.SYMTYPE
246 link.linkname = "target"
247 tar.addfile(link)
248 real = tarfile.TarInfo(name="real.py")
249 real.size = len(_COPYRIGHT_BYTES)
250 tar.addfile(real, io.BytesIO(_COPYRIGHT_BYTES))
251 members = self._iter_bytes(buf.getvalue(), ".tar.gz")
252 paths = [p for p, _ in members]
253 self.assertNotIn("link", paths)
254 self.assertIn("real.py", paths)
255
256 def test_tar_oversized_not_yielded(self):
257 big = b"x" * 1000
258 members = self._iter_bytes(
259 _make_tar_gz({"big.txt": big, "small.py": _COPYRIGHT_BYTES}),
260 ".tar.gz",
261 ["--max-archive-member-size", "100"],
262 )
263 paths = [p for p, _ in members]
264 self.assertNotIn("big.txt", paths)
265 self.assertIn("small.py", paths)
266
267 def test_zip_oversized_not_yielded(self):
268 big = b"x" * 1000
269 members = self._iter_bytes(
270 _make_zip({"big.txt": big, "small.py": _COPYRIGHT_BYTES}),
271 ".zip",
272 ["--max-archive-member-size", "100"],
273 )
274 paths = [p for p, _ in members]
275 self.assertNotIn("big.txt", paths)
276 self.assertIn("small.py", paths)
277
278 def test_zip_yields_correct_content(self):
279 members = self._iter_bytes(_make_zip({"README": _COPYRIGHT_BYTES}), ".zip")
280 content = next(c for p, c in members if p == "README")
281 self.assertEqual(content, _COPYRIGHT_BYTES)
282
283 def test_zip_directory_entry_not_yielded(self):
284 buf = io.BytesIO()
285 with zipfile.ZipFile(buf, "w") as zf:
286 zf.writestr("pkg/", b"")
287 zf.writestr("pkg/mod.py", _COPYRIGHT_BYTES)
288 members = self._iter_bytes(buf.getvalue(), ".zip")
289 paths = [p for p, _ in members]
290 self.assertNotIn("pkg/", paths)
291 self.assertIn("pkg/mod.py", paths)
292
293 def test_tar_directory_not_yielded(self):
294 buf = io.BytesIO()
295 with tarfile.open(fileobj=buf, mode="w:gz") as tar:
296 directory = tarfile.TarInfo(name="pkg")
297 directory.type = tarfile.DIRTYPE
298 tar.addfile(directory)
299 real = tarfile.TarInfo(name="pkg/mod.py")
300 real.size = len(_COPYRIGHT_BYTES)
301 tar.addfile(real, io.BytesIO(_COPYRIGHT_BYTES))
302 members = self._iter_bytes(buf.getvalue(), ".tar.gz")
303 paths = [p for p, _ in members]
304 self.assertNotIn("pkg", paths)
305 self.assertIn("pkg/mod.py", paths)
306
307 def test_tar_hardlink_yielded(self):
308 buf = io.BytesIO()
309 with tarfile.open(fileobj=buf, mode="w:gz") as tar:
310 real = tarfile.TarInfo(name="a.py")
311 real.size = len(_COPYRIGHT_BYTES)
312 tar.addfile(real, io.BytesIO(_COPYRIGHT_BYTES))
313 link = tarfile.TarInfo(name="b.py")
314 link.type = tarfile.LNKTYPE
315 link.linkname = "a.py"
316 tar.addfile(link)
317 members = self._iter_bytes(buf.getvalue(), ".tar.gz")
318 self.assertIn("b.py", [p for p, _ in members])
319 content = next(c for p, c in members if p == "b.py")
320 self.assertEqual(content, _COPYRIGHT_BYTES)
321
322 def test_plain_uncompressed_tar_yields_path_and_bytes(self):
323 buf = io.BytesIO()
324 with tarfile.open(fileobj=buf, mode="w") as tar:
325 info = tarfile.TarInfo(name="x.py")
326 info.size = len(_COPYRIGHT_BYTES)
327 tar.addfile(info, io.BytesIO(_COPYRIGHT_BYTES))
328 members = self._iter_bytes(buf.getvalue(), ".tar")
329 self.assertIn("x.py", [p for p, _ in members])
330
331 def test_corrupt_archive_raises(self):
332 with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as f:
333 f.write(b"not an archive")
334 fpath = f.name
335 try:
336 with self.assertRaises((tarfile.TarError, zipfile.BadZipFile, OSError)):
337 opts = cmdoptions.process_options(_BASE)
338 list(archives.iter_archive_members(fpath, opts))
339 finally:
340 Path(fpath).unlink()
341
342
343 # Unsupported compression (e.g. zstd) handling
344
345
346 class TestUnsupportedCompression(unittest.TestCase):
347 """A member decopy cannot decompress is skipped with a one-time hint."""
348
349 def setUp(self) -> None:
350 # The "warn once" guard is process-global; reset it per test.
351 archives.warn_unsupported_compression.cache_clear()
352
353 def _iter_with_unreadable(
354 self, unreadable: set[str], members: dict[str, bytes]
355 ) -> tuple[list[tuple[str, bytes]], list[str]]:
356 """Iterate a zip, forcing the named members to fail decompression."""
357 opts = cmdoptions.process_options(_BASE)
358 real_read = zipfile.ZipFile.read
359
360 def fake_read(self, name, pwd=None): # type: ignore[no-untyped-def]
361 if name in unreadable:
362 msg = "That compression method is not supported"
363 raise NotImplementedError(msg)
364 return real_read(self, name, pwd)
365
366 with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as f:
367 f.write(_make_zip(members))
368 fpath = f.name
369 try:
370 with (
371 patch.object(zipfile.ZipFile, "read", fake_read),
372 self.assertLogs("decopy", level="WARNING") as cm,
373 ):
374 result = list(archives.iter_archive_members(fpath, opts))
375 return result, cm.output
376 finally:
377 Path(fpath).unlink()
378
379 def test_unreadable_member_skipped_others_yielded(self):
380 result, _ = self._iter_with_unreadable(
381 {"a.py"}, {"a.py": _COPYRIGHT_BYTES, "b.py": _COPYRIGHT_BYTES}
382 )
383 paths = [p for p, _ in result]
384 self.assertNotIn("a.py", paths)
385 self.assertIn("b.py", paths)
386
387 def test_unreadable_member_does_not_raise(self):
388 # Regression: NotImplementedError previously escaped as a raw traceback.
389 result, _ = self._iter_with_unreadable({"a.py"}, {"a.py": _COPYRIGHT_BYTES})
390 self.assertEqual(result, [])
391
392 def test_warns_about_unsupported_compression(self):
393 _, logs = self._iter_with_unreadable({"a.py"}, {"a.py": _COPYRIGHT_BYTES})
394 if sys.version_info < (3, 14):
395 self.assertTrue(any("zipfile-zstd" in line for line in logs))
396 else:
397 self.assertTrue(any("cannot decode" in line for line in logs))
398
399 def test_warns_only_once(self):
400 _, logs = self._iter_with_unreadable(
401 {"a.py", "b.py"},
402 {"a.py": _COPYRIGHT_BYTES, "b.py": _COPYRIGHT_BYTES},
403 )
404 hint_lines = [line for line in logs if "cannot decode" in line]
405 self.assertEqual(len(hint_lines), 1)
406
407 def test_zstd_member_read_when_dependency_present(self):
408 if not hasattr(zipfile, "ZIP_ZSTANDARD"):
409 self.skipTest("zstd zip compression not supported")
410 buf = io.BytesIO()
411 with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_ZSTANDARD) as zf:
412 zf.writestr("README", _COPYRIGHT_BYTES)
413 opts = cmdoptions.process_options(_BASE)
414 with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as f:
415 f.write(buf.getvalue())
416 fpath = f.name
417 try:
418 members = list(archives.iter_archive_members(fpath, opts))
419 finally:
420 Path(fpath).unlink()
421 content = next(c for p, c in members if p == "README")
422 self.assertEqual(content, _COPYRIGHT_BYTES)
423
424 def test_runtime_error_decompression_skipped_with_warning(self):
425 opts = cmdoptions.process_options(_BASE)
426 real_read = zipfile.ZipFile.read
427
428 def fake_read(self, name, pwd=None): # type: ignore[no-untyped-def]
429 if name == "corrupt.py":
430 msg = "Compression requires the (missing) compression.zstd module"
431 raise RuntimeError(msg)
432 return real_read(self, name, pwd)
433
434 with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as f:
435 f.write(
436 _make_zip({
437 "corrupt.py": _COPYRIGHT_BYTES,
438 "ok.py": _COPYRIGHT_BYTES,
439 })
440 )
441 fpath = f.name
442 try:
443 with (
444 patch.object(zipfile.ZipFile, "read", fake_read),
445 self.assertLogs("decopy", level="WARNING") as cm,
446 ):
447 result = list(archives.iter_archive_members(fpath, opts))
448 paths = [p for p, _ in result]
449 self.assertNotIn("corrupt.py", paths)
450 self.assertIn("ok.py", paths)
451 self.assertTrue(any("cannot decode" in line for line in cm.output))
452 finally:
453 Path(fpath).unlink()
454
455 def test_warn_unsupported_compression_messages(self):
456 archives.warn_unsupported_compression.cache_clear()
457 with (
458 patch("sys.version_info", (3, 13, 0)),
459 self.assertLogs("decopy", level="WARNING") as cm,
460 ):
461 archives.warn_unsupported_compression()
462 self.assertTrue(any("zipfile-zstd" in line for line in cm.output))
463
464 archives.warn_unsupported_compression.cache_clear()
465 with (
466 patch("sys.version_info", (3, 14, 0)),
467 self.assertLogs("decopy", level="WARNING") as cm,
468 ):
469 archives.warn_unsupported_compression()
470 self.assertTrue(any("cannot decode" in line for line in cm.output))
471 self.assertFalse(any("zipfile-zstd" in line for line in cm.output))
472
473
474 # expand_archive
475
476
477 class TestExpandArchive(unittest.TestCase):
478 """expand_archive populates an ArchiveDirInfo from tar or zip."""
479
480 def _make_archive_dir(self, name: str) -> nodes.ArchiveDirInfo:
481 root = tree.RootInfo(root=".")
482 return nodes.ArchiveDirInfo(parent=root, name=name, archive_path="")
483
484 def _expand_bytes(
485 self,
486 data: bytes,
487 suffix: str,
488 extra_flags: list[str] | None = None,
489 ) -> nodes.ArchiveDirInfo:
490 if extra_flags is None:
491 extra_flags = []
492 opts = cmdoptions.process_options([*_BASE, *extra_flags])
493 archive_dir = self._make_archive_dir(f"arch{suffix}")
494 with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
495 f.write(data)
496 fpath = f.name
497 try:
498 archives.expand_archive(fpath, archive_dir, opts, depth=0)
499 finally:
500 Path(fpath).unlink()
501 return archive_dir
502
503 def test_tar_gz_member_becomes_virtual_file(self):
504 data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
505 archive_dir = self._expand_bytes(data, ".tar.gz")
506 names = [f.name for f in _walk_virtual_files(archive_dir)]
507 self.assertIn("main.py", names)
508
509 def test_zip_member_becomes_virtual_file(self):
510 data = _make_zip({"README": _COPYRIGHT_BYTES})
511 archive_dir = self._expand_bytes(data, ".zip")
512 names = [f.name for f in _walk_virtual_files(archive_dir)]
513 self.assertIn("README", names)
514
515 def test_tar_symlink_is_skipped(self):
516 buf = io.BytesIO()
517 with tarfile.open(fileobj=buf, mode="w:gz") as tar:
518 link = tarfile.TarInfo(name="link")
519 link.type = tarfile.SYMTYPE
520 link.linkname = "target"
521 tar.addfile(link)
522 real = tarfile.TarInfo(name="real.py")
523 real.size = len(_COPYRIGHT_BYTES)
524 tar.addfile(real, io.BytesIO(_COPYRIGHT_BYTES))
525 archive_dir = self._expand_bytes(buf.getvalue(), ".tar.gz")
526 names = [f.name for f in _walk_virtual_files(archive_dir)]
527 self.assertNotIn("link", names)
528 self.assertIn("real.py", names)
529
530 def test_oversized_member_is_skipped(self):
531 big = b"x" * 1000 # much larger than _COPYRIGHT_BYTES (52 bytes)
532 data = _make_tar_gz({"big.txt": big, "small.py": _COPYRIGHT_BYTES})
533 archive_dir = self._expand_bytes(
534 data, ".tar.gz", ["--max-archive-member-size", "100"]
535 )
536 names = [f.name for f in _walk_virtual_files(archive_dir)]
537 self.assertNotIn("big.txt", names)
538 self.assertIn("small.py", names)
539
540 def test_corrupt_archive_raises(self):
541 archive_dir = self._make_archive_dir("bad.tar.gz")
542 opts = cmdoptions.process_options(_BASE)
543 with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as f:
544 f.write(b"not a tar file")
545 fpath = f.name
546 try:
547 with self.assertRaises((tarfile.TarError, zipfile.BadZipFile, OSError)):
548 archives.expand_archive(fpath, archive_dir, opts, depth=0)
549 finally:
550 Path(fpath).unlink()
551
552 def test_virtual_file_content_is_parseable(self):
553 data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
554 archive_dir = self._expand_bytes(data, ".tar.gz", ["--text"])
555 opts = cmdoptions.process_options([*_BASE, "--text"])
556 for vfi in _walk_virtual_files(archive_dir):
557 if vfi.name == "main.py":
558 vfi.process_licenses(".", opts)
559 self.assertTrue(any("Test Author" in str(h) for h in vfi.copyrights))
560 break
561 else:
562 self.fail("main.py not found in expanded archive")
563
564
565 # archives.expand_subtree and recompute_total
566
567
568 class TestExpandArchivesInSubtree(unittest.TestCase):
569 """archives.expand_subtree integrates with RootInfo.build."""
570
571 def test_archive_file_replaced_by_archive_dir_info(self):
572 with tempfile.TemporaryDirectory() as tmpdir:
573 archive_data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
574 (Path(tmpdir) / "vendor.tar.gz").write_bytes(archive_data)
575 opts = cmdoptions.process_options(["--no-progress", "--root", tmpdir])
576 filetree = tree.RootInfo.build(opts)
577 self.assertIsInstance(filetree["vendor.tar.gz"], nodes.ArchiveDirInfo)
578
579 def test_corrupt_archive_restores_original_file_info(self):
580 with tempfile.TemporaryDirectory() as tmpdir:
581 (Path(tmpdir) / "bad.tar.gz").write_bytes(b"not a tar")
582 opts = cmdoptions.process_options(["--no-progress", "--root", tmpdir])
583 filetree = tree.RootInfo.build(opts)
584 item = filetree["bad.tar.gz"]
585 self.assertIsInstance(item, nodes.FileInfo)
586 self.assertNotIsInstance(item, nodes.ArchiveDirInfo)
587
588 def test_no_expand_archives_leaves_file_info(self):
589 with tempfile.TemporaryDirectory() as tmpdir:
590 archive_data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
591 (Path(tmpdir) / "vendor.tar.gz").write_bytes(archive_data)
592 opts = cmdoptions.process_options(
593 ["--no-progress", "--root", tmpdir, "--no-expand-archives"]
594 )
595 filetree = tree.RootInfo.build(opts)
596 self.assertNotIsInstance(filetree["vendor.tar.gz"], nodes.ArchiveDirInfo)
597
598 def test_recompute_total_reflects_virtual_files(self):
599 with tempfile.TemporaryDirectory() as tmpdir:
600 archive_data = _make_tar_gz(
601 {
602 "a.py": _COPYRIGHT_BYTES,
603 "b.py": _COPYRIGHT_BYTES,
604 }
605 )
606 (Path(tmpdir) / "vendor.tar.gz").write_bytes(archive_data)
607 opts = cmdoptions.process_options(["--no-progress", "--root", tmpdir])
608 filetree = tree.RootInfo.build(opts)
609 # 1 archive expands to 2 virtual files; total must be > 1
610 self.assertGreater(filetree.total, 1)
611
612
613 # max_archive_depth - nested archive expansion control
614
615
616 def _make_nested_tar() -> bytes:
617 """outer.tar.gz containing inner.tar.gz containing inner.py."""
618 inner = _make_tar_gz({"inner.py": _COPYRIGHT_BYTES})
619 return _make_tar_gz({"inner.tar.gz": inner})
620
621
622 class TestMaxArchiveDepth(unittest.TestCase):
623 """max_archive_depth controls nested archive expansion."""
624
625 def test_default_depth_leaves_nested_archive_as_virtual_file(self):
626 with tempfile.TemporaryDirectory() as tmpdir:
627 (Path(tmpdir) / "outer.tar.gz").write_bytes(_make_nested_tar())
628 opts = cmdoptions.process_options(["--no-progress", "--root", tmpdir])
629 filetree = tree.RootInfo.build(opts)
630 outer = filetree["outer.tar.gz"]
631 self.assertIsInstance(outer, nodes.ArchiveDirInfo)
632 assert isinstance(outer, nodes.DirInfo)
633 inner = outer.file_list.get("inner.tar.gz")
634 self.assertIsInstance(inner, nodes.VirtualFileInfo)
635 self.assertNotIsInstance(inner, nodes.ArchiveDirInfo)
636
637 def test_depth_2_expands_nested_archive(self):
638 with tempfile.TemporaryDirectory() as tmpdir:
639 (Path(tmpdir) / "outer.tar.gz").write_bytes(_make_nested_tar())
640 opts = cmdoptions.process_options(
641 ["--no-progress", "--root", tmpdir, "--max-archive-depth", "2"]
642 )
643 filetree = tree.RootInfo.build(opts)
644 outer = filetree["outer.tar.gz"]
645 self.assertIsInstance(outer, nodes.ArchiveDirInfo)
646 assert isinstance(outer, nodes.DirInfo)
647 inner = outer.file_list.get("inner.tar.gz")
648 self.assertIsInstance(inner, nodes.ArchiveDirInfo)
649
650 def test_depth_2_nested_content_is_accessible(self):
651 with tempfile.TemporaryDirectory() as tmpdir:
652 (Path(tmpdir) / "outer.tar.gz").write_bytes(_make_nested_tar())
653 opts = cmdoptions.process_options(
654 ["--no-progress", "--root", tmpdir, "--max-archive-depth", "2"]
655 )
656 filetree = tree.RootInfo.build(opts)
657 outer = filetree["outer.tar.gz"]
658 assert isinstance(outer, nodes.DirInfo)
659 inner_archive = outer.file_list.get("inner.tar.gz")
660 assert isinstance(inner_archive, nodes.ArchiveDirInfo)
661 inner_file = inner_archive.file_list.get("inner.py")
662 self.assertIsInstance(inner_file, nodes.VirtualFileInfo)
663
664 def test_corrupt_nested_archive_falls_back_to_virtual_file(self):
665 # inner member is corrupt; should fall back to VirtualFileInfo, not crash
666 corrupt_inner = b"not an archive"
667 outer = _make_tar_gz({"bad.tar.gz": corrupt_inner})
668 with tempfile.TemporaryDirectory() as tmpdir:
669 (Path(tmpdir) / "outer.tar.gz").write_bytes(outer)
670 opts = cmdoptions.process_options(
671 ["--no-progress", "--root", tmpdir, "--max-archive-depth", "2"]
672 )
673 filetree = tree.RootInfo.build(opts)
674 outer_dir = filetree["outer.tar.gz"]
675 self.assertIsInstance(outer_dir, nodes.ArchiveDirInfo)
676 assert isinstance(outer_dir, nodes.DirInfo)
677 inner = outer_dir.file_list.get("bad.tar.gz")
678 self.assertIsInstance(inner, nodes.VirtualFileInfo)
679 self.assertNotIsInstance(inner, nodes.ArchiveDirInfo)
680
681
682 # End-to-end integration
683
684
685 class TestArchiveExpansionEndToEnd(unittest.TestCase):
686 """Full pipeline output with/without archive expansion."""
687
688 def _run(self, root: str, extra_flags: list[str] | None = None) -> str:
689 if extra_flags is None:
690 extra_flags = []
691 opts = cmdoptions.process_options(
692 ["--no-progress", "--no-glob", "--root", root, *extra_flags]
693 )
694 buf = io.StringIO()
695 with patch.object(sys, "stdout", buf):
696 run_pipeline(opts)
697 return buf.getvalue()
698
699 def test_default_expands_archives_virtual_paths_in_output(self):
700 with tempfile.TemporaryDirectory() as tmpdir:
701 archive_data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
702 (Path(tmpdir) / "vendor.tar.gz").write_bytes(archive_data)
703 out = self._run(tmpdir)
704 # virtual path vendor.tar.gz/... must appear in the Files: stanza
705 self.assertIn("vendor.tar.gz/", out)
706 self.assertIn("Test Author", out)
707
708 def test_no_expand_archives_treats_archive_as_single_file(self):
709 with tempfile.TemporaryDirectory() as tmpdir:
710 archive_data = _make_tar_gz({"src/main.py": _COPYRIGHT_BYTES})
711 (Path(tmpdir) / "vendor.tar.gz").write_bytes(archive_data)
712 out = self._run(tmpdir, ["--no-expand-archives"])
713 # The sub-path separator must NOT appear
714 self.assertNotIn("vendor.tar.gz/", out)
715
716
717 if __name__ == "__main__":
718 unittest.main()