Debian Codegraph @

tests/explain_cli_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 """End-to-end explain mode: rendered stdout and the staleness exit code.
18
19 These tests build a small tree with a hand-written debian/copyright that is
20 stale in various ways and assert the report printed to stdout plus the
21 run_pipeline exit code. run_pipeline owns its delta sink; tests never inject
22 one.
23 """
24
25 from __future__ import annotations
26
27 import contextlib
28 import io
29 import shutil
30 import tempfile
31 import unittest
32 from pathlib import Path
33
34 from decopy import decopy
35 from decopy.cmdoptions import process_options
36 from decopy.dep5doc.delta import RELICENSED, SUB_LICENSE, DeltaEntry, DeltaReport
37 from decopy.dep5doc.explain_renderer import ExplainRenderer
38
39 _TESTDATA = Path(__file__).parent / "testdata"
40
41
42 def _write_tree(root: Path, copyright_text: str | None) -> None:
43 """Copy known-license fixtures into `root` and write debian/copyright."""
44 src = _TESTDATA / "one"
45 for name in ("art.txt", "bsd.txt", "paren.txt"):
46 shutil.copy(src / name, root / name)
47 if copyright_text is not None:
48 debian = root / "debian"
49 debian.mkdir()
50 (debian / "copyright").write_text(copyright_text, encoding="utf-8")
51
52
53 def _run_explain(
54 copyright_text: str | None, extra_args: list[str] | None = None
55 ) -> tuple[int, str, str]:
56 """Run a non-injected explain pipeline, returning (code, stdout, stderr)."""
57 with tempfile.TemporaryDirectory() as tmp:
58 root = Path(tmp)
59 _write_tree(root, copyright_text)
60 argv = [
61 "--no-progress",
62 "--no-expand-archives",
63 "--explain",
64 "--root",
65 str(root),
66 ]
67 if extra_args:
68 argv.extend(extra_args)
69 options = process_options(argv)
70 out, err = io.StringIO(), io.StringIO()
71 with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
72 code = decopy.run_pipeline(options)
73 return code, out.getvalue(), err.getvalue()
74
75
76 _STALE_COPYRIGHT = """\
77 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
78 Source: TODO
79
80 Files: *
81 License: GPL-3+
82
83 Files: art.txt
84 License: Artistic-1
85
86 Files: b*
87 License: GPL-2+
88 """
89
90 _CLEAN_COPYRIGHT = """\
91 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
92 Source: TODO
93
94 Files: *
95 License: GPL-3+
96 Comment: catch-all
97
98 Files: art.txt
99 License: Artistic-1
100
101 Files: bsd.txt
102 License: BSD-3-clause
103
104 Files: paren.txt
105 License: GPL-3+
106 """
107
108
109 class TestExplainOutput(unittest.TestCase):
110 """run_pipeline renders the report to stdout and returns the exit code."""
111
112 def test_clean_tree_prints_up_to_date_exits_zero(self):
113 code, out, _ = _run_explain(_CLEAN_COPYRIGHT)
114 self.assertEqual(out, "debian/copyright is up to date.\n")
115 self.assertEqual(code, 0)
116
117 def test_stale_tree_prints_report_exits_one(self):
118 code, out, _ = _run_explain(_STALE_COPYRIGHT)
119 self.assertIn("debian/copyright is out of date:", out)
120 self.assertIn("bsd.txt", out)
121 self.assertEqual(code, 1)
122
123 def test_report_on_stdout_not_stderr(self):
124 _, out, err = _run_explain(_STALE_COPYRIGHT)
125 self.assertIn("debian/copyright is out of date:", out)
126 self.assertNotIn("debian/copyright is out of date:", err)
127 self.assertNotIn("no longer match", err)
128
129
130 _UTIL_C = """\
131 // Copyright 2020 Foo Bar
132 //
133 // Licensed under the Apache License, Version 2.0 (the "License");
134 // you may not use this file except in compliance with the License.
135 // You may obtain a copy of the License at
136 //
137 // http://www.apache.org/licenses/LICENSE-2.0
138 """
139
140 _RELICENSE_COPYRIGHT = """\
141 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
142 Source: TODO
143
144 Files: *
145 License: GPL-3+
146
147 Files: art.txt
148 License: Artistic-1
149
150 Files: bsd.txt
151 License: BSD-3-clause
152
153 Files: paren.txt
154 License: GPL-3+
155
156 Files: util.c
157 Copyright: 2010, Someone Else
158 License: GPL-2+
159 """
160
161
162 _APACHE_BODY = """\
163 //
164 // Licensed under the Apache License, Version 2.0 (the "License");
165 // you may not use this file except in compliance with the License.
166 // You may obtain a copy of the License at
167 //
168 // http://www.apache.org/licenses/LICENSE-2.0
169 """
170
171 _FOO_C = "// Copyright 2020 Alice <[email protected]>\n" + _APACHE_BODY
172 _BAR_C = "// Copyright 2021 Bob <[email protected]>\n" + _APACHE_BODY
173
174 _UNION_COPYRIGHT = """\
175 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
176 Source: TODO
177
178 Files: *
179 Copyright: 2020 Alice <[email protected]>
180 2021 Bob <[email protected]>
181 License: Apache-2.0
182 """
183
184
185 def _run_copyright_grouping(args: list[str]) -> tuple[int, str]:
186 """Run a --group-by copyright pipeline over a union-paragraph tree."""
187 with tempfile.TemporaryDirectory() as tmp:
188 root = Path(tmp)
189 (root / "src").mkdir()
190 (root / "src" / "foo.c").write_text(_FOO_C, encoding="utf-8")
191 (root / "src" / "bar.c").write_text(_BAR_C, encoding="utf-8")
192 debian = root / "debian"
193 debian.mkdir()
194 (debian / "copyright").write_text(_UNION_COPYRIGHT, encoding="utf-8")
195 argv = [
196 "--no-progress",
197 "--no-expand-archives",
198 "--group-by",
199 "copyright",
200 "--root",
201 str(root),
202 *args,
203 ]
204 options = process_options(argv)
205 out = io.StringIO()
206 with contextlib.redirect_stdout(out):
207 code = decopy.run_pipeline(options)
208 return code, out.getvalue()
209
210
211 class TestCopyrightGroupingUnionParagraph(unittest.TestCase):
212 """A multi-holder paragraph under --group-by copyright is stable.
213
214 Its Copyright field is the union of its files' holders, so each file carries
215 a subset. Explain must not report the files as changed, and generation must
216 not tear the paragraph into one-paragraph-per-holder.
217 """
218
219 def test_explain_reports_up_to_date(self):
220 code, out = _run_copyright_grouping(["--explain"])
221 self.assertEqual(out, "debian/copyright is up to date.\n")
222 self.assertEqual(code, 0)
223
224 def test_generation_preserves_the_union_paragraph(self):
225 _, out = _run_copyright_grouping(["-o", "-"])
226 # One Files paragraph still covers both files (wildcarded to *), and its
227 # Copyright keeps both holders rather than splitting per holder.
228 self.assertEqual(out.count("Files: src/"), 0)
229 self.assertIn("Files: *", out)
230 self.assertIn("Alice <[email protected]>", out)
231 self.assertIn("Bob <[email protected]>", out)
232
233
234 class TestHolderPopulation(unittest.TestCase):
235 """Under --group-by copyright, relicensed lines show holders."""
236
237 def test_holders_rendered_under_copyright_grouping(self):
238 with tempfile.TemporaryDirectory() as tmp:
239 root = Path(tmp)
240 _write_tree(root, _RELICENSE_COPYRIGHT)
241 (root / "util.c").write_text(_UTIL_C, encoding="utf-8")
242 options = process_options(
243 [
244 "--no-progress",
245 "--no-expand-archives",
246 "--explain",
247 "--group-by",
248 "copyright",
249 "--root",
250 str(root),
251 ]
252 )
253 out = io.StringIO()
254 with contextlib.redirect_stdout(out):
255 decopy.run_pipeline(options)
256 text = out.getvalue()
257 relicensed = [
258 line for line in text.splitlines() if line.strip().startswith("util.c")
259 ]
260 self.assertTrue(relicensed)
261 # Holders render as +/- delta lines below the item line, not inline.
262 self.assertIn("- Someone Else", text)
263 self.assertIn("+ Foo Bar", text)
264
265 def test_added_holder_carries_source_removed_does_not(self):
266 # End-to-end: the relicensed +/- lines come from a real pipeline run.
267 # util.c detects "Foo Bar" (added); the declared "Someone Else" is removed
268 # and, absent from every file, carries no source.
269 with tempfile.TemporaryDirectory() as tmp:
270 root = Path(tmp)
271 _write_tree(root, _RELICENSE_COPYRIGHT)
272 (root / "util.c").write_text(_UTIL_C, encoding="utf-8")
273 options = process_options(
274 [
275 "--no-progress",
276 "--no-expand-archives",
277 "--explain",
278 "--group-by",
279 "copyright",
280 "--root",
281 str(root),
282 ]
283 )
284 out = io.StringIO()
285 with contextlib.redirect_stdout(out):
286 decopy.run_pipeline(options)
287 text = out.getvalue()
288 self.assertIn("+ Foo Bar (in util.c)", text)
289 self.assertIn("- Someone Else", text)
290 self.assertNotIn("- Someone Else (in", text)
291
292 def test_holders_never_leak_under_license_grouping(self):
293 # Under license grouping the copyright slots are masked to None, so even
294 # an entry carrying holders must render no parentheses on its line.
295 report = DeltaReport()
296 report.add(
297 DeltaEntry(
298 kind=RELICENSED,
299 detail="src/util.c",
300 path="src/util.c",
301 was="GPL-2+",
302 now="Apache-2.0",
303 sub_kind=SUB_LICENSE,
304 was_copyright=("Foo",),
305 now_copyright=("Bar",),
306 )
307 )
308 options = process_options(["--group-by", "license"])
309 text = ExplainRenderer().explain(report, options)
310 line = next(
311 ln for ln in text.splitlines() if ln.strip().startswith("src/util.c")
312 )
313 self.assertNotIn("(", line)
314 self.assertIn("was: GPL-2+ -> now: Apache-2.0", line)
315
316
317 def _run_explain_files(files: dict[str, str], copyright_text: str) -> tuple[int, str]:
318 """Run an explain pipeline over an explicit {relpath: content} tree."""
319 with tempfile.TemporaryDirectory() as tmp:
320 root = Path(tmp)
321 for relpath, content in files.items():
322 target = root / relpath
323 target.parent.mkdir(parents=True, exist_ok=True)
324 target.write_text(content, encoding="utf-8")
325 debian = root / "debian"
326 debian.mkdir(exist_ok=True)
327 (debian / "copyright").write_text(copyright_text, encoding="utf-8")
328 options = process_options(
329 [
330 "--no-progress",
331 "--no-expand-archives",
332 "--explain",
333 "--root",
334 str(root),
335 ]
336 )
337 out = io.StringIO()
338 with contextlib.redirect_stdout(out):
339 code = decopy.run_pipeline(options)
340 return code, out.getvalue()
341
342
343 _RELICENSE_SRC = """\
344 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
345 Source: TODO
346
347 Files: src/*
348 License: GPL-2+
349 """
350
351 _RELICENSE_SRC_AND_LIB = """\
352 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
353 Source: TODO
354
355 Files: src/*
356 License: GPL-2+
357
358 Files: lib/*
359 License: Apache-2.0
360 """
361
362
363 class TestRelicensedNewParagraph(unittest.TestCase):
364 """A relicensed file's destination paragraph is reported when it is new.
365
366 Under --group-by license the path slot is empty, so a destination key
367 matches purely on license: a moved file lands in an existing paragraph when
368 one already declares that license, otherwise it seeds a new paragraph.
369 """
370
371 def test_moved_file_into_absent_license_seeds_new_paragraph(self):
372 # src/util.c is matched by the wildcard src/* (declared GPL-2+) but
373 # detects Apache-2, which no paragraph declares: it relicenses AND seeds
374 # a new Apache-2 paragraph naming itself.
375 code, out = _run_explain_files({"src/util.c": _UTIL_C}, _RELICENSE_SRC)
376 self.assertEqual(code, 1)
377 self.assertIn("1 file no longer matches its paragraph:", out)
378 self.assertIn("src/util.c was: GPL-2+ -> now: Apache-2", out)
379 self.assertIn("1 new paragraph would be added:", out)
380 self.assertIn(" Files: src/util.c", out)
381 self.assertIn(" License: Apache-2 (detected in src/util.c)", out)
382
383 def test_moved_file_into_existing_license_seeds_no_new_paragraph(self):
384 # src/util.c relicenses to Apache-2, but the lib/* paragraph already
385 # declares Apache-2 (and lib/keep.c keeps it), so the moved file joins
386 # that existing paragraph rather than seeding a new one.
387 code, out = _run_explain_files(
388 {"src/util.c": _UTIL_C, "lib/keep.c": _UTIL_C},
389 _RELICENSE_SRC_AND_LIB,
390 )
391 self.assertEqual(code, 1)
392 self.assertIn("src/util.c was: GPL-2+ -> now: Apache-2", out)
393 self.assertNotIn("new paragraph", out)
394
395 def test_moved_and_uncovered_files_share_one_new_paragraph(self):
396 # src/util.c (relicensed to Apache-2) and the uncovered new.c (also
397 # Apache-2) share a destination key, so they fold into a single new
398 # paragraph listing both files, sorted.
399 code, out = _run_explain_files(
400 {"src/util.c": _UTIL_C, "new.c": _UTIL_C}, _RELICENSE_SRC
401 )
402 self.assertEqual(code, 1)
403 self.assertIn("1 new paragraph would be added:", out)
404 self.assertIn(" Files: new.c", out)
405 self.assertIn(" src/util.c", out)
406
407
408 _NO_CATCHALL_COPYRIGHT = """\
409 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
410 Source: TODO
411
412 Files: art.txt
413 License: Artistic-1
414
415 Files: bsd.txt
416 License: BSD-3-clause
417
418 Files: paren.txt
419 License: GPL-3+
420 """
421
422
423 class TestCopyrightFileSuppression(unittest.TestCase):
424 """The debian/copyright file is never reported as a new file."""
425
426 def test_only_copyright_uncovered_is_clean(self):
427 # Every source file is covered; the only uncovered file is the
428 # debian/copyright itself, which must not count as staleness.
429 code, out, _ = _run_explain(_NO_CATCHALL_COPYRIGHT)
430 self.assertEqual(out, "debian/copyright is up to date.\n")
431 self.assertEqual(code, 0)
432
433 def test_copyright_file_absent_from_new_file_section(self):
434 code, out, _ = _run_explain(_STALE_COPYRIGHT)
435 self.assertEqual(code, 1)
436 self.assertNotIn("debian/copyright ->", out)
437
438 def test_non_default_copyright_file_is_suppressed(self):
439 # Suppression follows the resolved active copyright path, not a
440 # hard-coded debian/copyright; here the active file is COPYING.meta.
441 with tempfile.TemporaryDirectory() as tmp:
442 root = Path(tmp)
443 for name in ("art.txt", "bsd.txt", "paren.txt"):
444 shutil.copy(_TESTDATA / "one" / name, root / name)
445 (root / "COPYING.meta").write_text(_NO_CATCHALL_COPYRIGHT, encoding="utf-8")
446 options = process_options(
447 [
448 "--no-progress",
449 "--no-expand-archives",
450 "--explain",
451 "--copyright-file",
452 "COPYING.meta",
453 "--root",
454 str(root),
455 ]
456 )
457 out = io.StringIO()
458 with contextlib.redirect_stdout(out):
459 code = decopy.run_pipeline(options)
460 text = out.getvalue()
461 self.assertEqual(text, "debian/copyright is up to date.\n")
462 self.assertEqual(code, 0)
463
464
465 _MULTI_DEAD_PATTERN = """\
466 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
467 Source: TODO
468
469 Files: *
470 License: GPL-3+
471
472 Files: art.txt
473 License: Artistic-1
474
475 Files: bsd.txt old_a.txt old_b.txt
476 paren.txt
477 License: BSD-3-clause
478 """
479
480 _CROSS_PARAGRAPH_DEAD = """\
481 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
482 Source: TODO
483
484 Files: *
485 License: GPL-3+
486
487 Files: art.txt gone_*.txt
488 License: Artistic-1
489
490 Files: bsd.txt gone_*.txt
491 paren.txt
492 License: BSD-3-clause
493 """
494
495
496 class TestStalePatternDedup(unittest.TestCase):
497 """Regression lock for stale-pattern dedup, preserved end-to-end."""
498
499 def test_multiple_dead_patterns_in_one_paragraph(self):
500 _, out, _ = _run_explain(_MULTI_DEAD_PATTERN)
501 self.assertIn("old_a.txt", out)
502 self.assertIn("old_b.txt", out)
503 # The paragraph license rides as a [License: X] tag on the pattern line.
504 self.assertIn("[License: BSD-3-clause]", out)
505 # Two distinct stale-pattern lines, one per dead pattern.
506 stale_lines = [line for line in out.splitlines() if "matches nothing" in line]
507 self.assertEqual(len(stale_lines), 2)
508
509 def test_same_pattern_across_two_paragraphs(self):
510 _, out, _ = _run_explain(_CROSS_PARAGRAPH_DEAD)
511 stale_lines = [line for line in out.splitlines() if "matches nothing" in line]
512 # gone_*.txt is dead in both the Artistic-1 and BSD-3-clause paragraphs,
513 # so it is attributed once per paragraph.
514 self.assertEqual(len(stale_lines), 2)
515
516
517 def _run_generate(root: Path, out_path: Path, extra: list[str] | None = None) -> int:
518 """Run a plain (non-explain) generation writing copyright to out_path."""
519 argv = [
520 "--no-progress",
521 "--no-expand-archives",
522 "-o",
523 str(out_path),
524 "--root",
525 str(root),
526 ]
527 if extra:
528 argv.extend(extra)
529 options = process_options(argv)
530 return decopy.run_pipeline(options)
531
532
533 class TestExplainOutputFile(unittest.TestCase):
534 """-o under explain writes the regenerated copyright, never the report."""
535
536 def test_no_output_writes_no_file_and_leaves_intree_unchanged(self):
537 with tempfile.TemporaryDirectory() as tmp:
538 root = Path(tmp)
539 _write_tree(root, _STALE_COPYRIGHT)
540 before = (root / "debian" / "copyright").read_text(encoding="utf-8")
541 listing_before = sorted(p.name for p in root.iterdir())
542 argv = [
543 "--no-progress",
544 "--no-expand-archives",
545 "--explain",
546 "--root",
547 str(root),
548 ]
549 options = process_options(argv)
550 out = io.StringIO()
551 with contextlib.redirect_stdout(out):
552 code = decopy.run_pipeline(options)
553 after = (root / "debian" / "copyright").read_text(encoding="utf-8")
554 listing_after = sorted(p.name for p in root.iterdir())
555 self.assertEqual(code, 1)
556 self.assertIn("debian/copyright is out of date:", out.getvalue())
557 self.assertEqual(before, after)
558 self.assertEqual(listing_before, listing_after)
559
560 def test_output_writes_regenerated_copyright_keeps_report_on_stdout(self):
561 with tempfile.TemporaryDirectory() as tmp:
562 root = Path(tmp)
563 _write_tree(root, _STALE_COPYRIGHT)
564 intree_before = (root / "debian" / "copyright").read_text(encoding="utf-8")
565 out_path = root / "out.copyright"
566 argv = [
567 "--no-progress",
568 "--no-expand-archives",
569 "--explain",
570 "-o",
571 str(out_path),
572 "--root",
573 str(root),
574 ]
575 options = process_options(argv)
576 out = io.StringIO()
577 with contextlib.redirect_stdout(out):
578 code = decopy.run_pipeline(options)
579 stdout_text = out.getvalue()
580 written = out_path.read_text(encoding="utf-8")
581 intree_after = (root / "debian" / "copyright").read_text(encoding="utf-8")
582
583 # The same -o write under a plain (non-explain) run is the baseline.
584 # Generate it in a fresh identical tree: the explain run's out.copyright
585 # is a non-excluded path now carrying real licence text, so scanning
586 # the same tree would detect licences inside decopy's own output.
587 with tempfile.TemporaryDirectory() as golden_tmp:
588 golden_root = Path(golden_tmp)
589 _write_tree(golden_root, _STALE_COPYRIGHT)
590 golden_path = golden_root / "out.copyright"
591 _run_generate(golden_root, golden_path)
592 golden = golden_path.read_text(encoding="utf-8")
593
594 self.assertEqual(code, 1)
595 self.assertIn("debian/copyright is out of date:", stdout_text)
596 self.assertEqual(written, golden)
597 # The report never lands in the -o file.
598 self.assertNotIn("debian/copyright is out of date:", written)
599 # The regenerated copyright never lands on stdout.
600 self.assertNotIn("Format: https://www.debian.org", stdout_text)
601 # The in-tree copyright is untouched.
602 self.assertEqual(intree_before, intree_after)
603
604 def test_output_dash_under_explain_writes_no_file(self):
605 with tempfile.TemporaryDirectory() as tmp:
606 root = Path(tmp)
607 _write_tree(root, _STALE_COPYRIGHT)
608 listing_before = sorted(p.name for p in root.iterdir())
609 argv = [
610 "--no-progress",
611 "--no-expand-archives",
612 "--explain",
613 "-o",
614 "-",
615 "--root",
616 str(root),
617 ]
618 options = process_options(argv)
619 buf = io.StringIO()
620 with contextlib.redirect_stdout(buf):
621 code = decopy.run_pipeline(options)
622 listing_after = sorted(p.name for p in root.iterdir())
623 self.assertEqual(code, 1)
624 self.assertIn("debian/copyright is out of date:", buf.getvalue())
625 self.assertEqual(listing_before, listing_after)
626
627 def test_unwritable_output_propagates_under_explain(self):
628 # The -o write happens before the staleness return, so an unwritable
629 # target raises rather than being masked by the exit code.
630 with tempfile.TemporaryDirectory() as tmp:
631 root = Path(tmp)
632 _write_tree(root, _STALE_COPYRIGHT)
633 bad = root / "missing-dir" / "out.copyright" # parent does not exist
634 argv = [
635 "--no-progress",
636 "--no-expand-archives",
637 "--explain",
638 "-o",
639 str(bad),
640 "--root",
641 str(root),
642 ]
643 options = process_options(argv)
644 buf = io.StringIO()
645 with contextlib.redirect_stdout(buf), self.assertRaises(OSError):
646 decopy.run_pipeline(options)
647
648
649 _FOUR_KINDS_COPYRIGHT = """\
650 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
651 Source: TODO
652
653 Files: art.txt
654 License: Artistic-1
655
656 Files: bsd.txt old_*.txt
657 License: BSD-3-clause
658
659 Files: paren.txt
660 License: GPL-3+
661
662 Files: legacy/*
663 License: GPL-2+
664
665 Files: u*.c
666 Copyright: 2010, Someone Else
667 License: GPL-2+
668 """
669
670
671 def _write_four_kinds_tree(root: Path) -> None:
672 """A tree stale in all four ways: stale-paragraph (legacy/*), stale-pattern
673 (old_*.txt), a new uncovered file (new.c), and a relicensed file (util.c)."""
674 src = _TESTDATA / "one"
675 for name in ("art.txt", "bsd.txt", "paren.txt"):
676 shutil.copy(src / name, root / name)
677 (root / "util.c").write_text(_UTIL_C, encoding="utf-8")
678 (root / "new.c").write_text(_UTIL_C, encoding="utf-8")
679 debian = root / "debian"
680 debian.mkdir()
681 (debian / "copyright").write_text(_FOUR_KINDS_COPYRIGHT, encoding="utf-8")
682
683
684 def _run_four_kinds(partial_files: list[str]) -> tuple[int, str]:
685 """Run explain over the four-kinds tree; partial_files (basenames) selects
686 partial mode when non-empty, passed as absolute paths argparse can validate."""
687 with tempfile.TemporaryDirectory() as tmp:
688 root = Path(tmp)
689 _write_four_kinds_tree(root)
690 argv = [
691 "--no-progress",
692 "--no-expand-archives",
693 "--explain",
694 "--root",
695 str(root),
696 ]
697 if partial_files:
698 argv.extend(["--mode", "partial"])
699 argv.extend(str(root / name) for name in partial_files)
700 options = process_options(argv)
701 out = io.StringIO()
702 with contextlib.redirect_stdout(out):
703 code = decopy.run_pipeline(options)
704 return code, out.getvalue()
705
706
707 class TestPartialSuppression(unittest.TestCase):
708 """Partial explain reports only new-file and relicensed; full reports all."""
709
710 def test_partial_suppresses_stale_paragraph_and_pattern(self):
711 code, out = _run_four_kinds(["new.c", "util.c"])
712 self.assertEqual(code, 1)
713 # The uncovered file is still reported as a would-be paragraph...
714 self.assertIn("new paragraph would be added", out)
715 self.assertIn(" Files: new.c", out)
716 self.assertIn("util.c", out)
717 # ...but the whole-tree stale-* kinds are dropped for a subset.
718 self.assertNotIn("matches no files", out)
719 self.assertNotIn("matches nothing", out)
720
721 def test_partial_keeps_moved_file_new_paragraph(self):
722 # util.c is in the partial subset, relicenses (u*.c declares GPL-2+, the
723 # file detects Apache-2), and its Apache-2 destination has no paragraph.
724 # The new-paragraph block survives partial mode (NEW_PARAGRAPH is not a
725 # stale-* kind) and lists the moved file alongside the uncovered new.c.
726 code, out = _run_four_kinds(["new.c", "util.c"])
727 self.assertEqual(code, 1)
728 self.assertIn("1 file no longer matches its paragraph:", out)
729 self.assertIn("util.c was: GPL-2+ -> now: Apache-2", out)
730 self.assertIn("1 new paragraph would be added:", out)
731 # The moved file is a continuation line of the bucket's Files field.
732 self.assertIn(" util.c", out)
733 self.assertNotIn("matches no files", out)
734 self.assertNotIn("matches nothing", out)
735
736 def test_full_reports_all_four_kinds(self):
737 code, out = _run_four_kinds([])
738 self.assertEqual(code, 1)
739 self.assertIn("new paragraph would be added", out)
740 self.assertIn("no longer match", out)
741 # The relicensed entry shows the was/now licenses (util.c is declared
742 # GPL-2+ but detects Apache via the u*.c wildcard).
743 self.assertIn("was: GPL-2+ -> now: Apache-2", out)
744 self.assertIn("matches no files", out)
745 self.assertIn("matches nothing", out)
746
747
748 _APACHE_TAIL = """\
749 //
750 // Licensed under the Apache License, Version 2.0 (the "License");
751 // you may not use this file except in compliance with the License.
752 // You may obtain a copy of the License at
753 //
754 // http://www.apache.org/licenses/LICENSE-2.0
755 """
756
757 # util.c detected as Apache-2.0, carrying two holders.
758 _UTIL_C_TWO = (
759 "// Copyright 2020 Foo Bar\n// Copyright 2010 Someone Else\n" + _APACHE_TAIL
760 )
761 # util.c detected as Apache-2.0, carrying only "Foo Bar".
762 _UTIL_C_ONE = "// Copyright 2020 Foo Bar\n" + _APACHE_TAIL
763
764 # Declares only "Someone Else": the kept file adds "Foo Bar" -> added drift.
765 _DRIFT_ADD = """\
766 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
767 Source: TODO
768
769 Files: u*.c
770 Copyright: 2010, Someone Else
771 License: Apache-2.0
772 """
773
774 # Declares both holders: the kept file backs only "Foo Bar" -> removed-only drift.
775 _DRIFT_REMOVE = """\
776 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
777 Source: TODO
778
779 Files: u*.c
780 Copyright: 2020, Foo Bar
781 2010, Someone Else
782 License: Apache-2.0
783 """
784
785
786 def _run_drift(util_c: str, copyright_text: str) -> tuple[int, str]:
787 """Explain over a minimal tree whose only file is util.c (fully covered)."""
788 with tempfile.TemporaryDirectory() as tmp:
789 root = Path(tmp)
790 (root / "util.c").write_text(util_c, encoding="utf-8")
791 debian = root / "debian"
792 debian.mkdir()
793 (debian / "copyright").write_text(copyright_text, encoding="utf-8")
794 argv = [
795 "--no-progress",
796 "--no-expand-archives",
797 "--explain",
798 "--root",
799 str(root),
800 ]
801 options = process_options(argv)
802 out = io.StringIO()
803 with contextlib.redirect_stdout(out):
804 code = decopy.run_pipeline(options)
805 return code, out.getvalue()
806
807
808 class TestCopyrightDriftExitCode(unittest.TestCase):
809 """Drift drives the exit code by direction: added is staleness, removed advisory."""
810
811 def test_added_holder_drift_exits_one(self):
812 code, out = _run_drift(_UTIL_C_TWO, _DRIFT_ADD)
813 self.assertEqual(code, 1)
814 self.assertIn("copyright drift", out)
815 self.assertIn("+ Foo Bar", out)
816
817 def test_removed_only_drift_is_advisory_exits_zero(self):
818 code, out = _run_drift(_UTIL_C_ONE, _DRIFT_REMOVE)
819 # The section still prints (report is non-empty)...
820 self.assertIn("copyright drift", out)
821 self.assertIn("- Someone Else [advisory]", out)
822 # ...but a removed-only drift does not fail the gate.
823 self.assertEqual(code, 0)
824
825 def test_generation_path_unaffected_by_drift(self):
826 # A plain (non-explain) generation run never consults has_staleness and
827 # unions the holders as before; the drift recording (NullDelta) is inert.
828 with tempfile.TemporaryDirectory() as tmp:
829 root = Path(tmp)
830 (root / "util.c").write_text(_UTIL_C_TWO, encoding="utf-8")
831 debian = root / "debian"
832 debian.mkdir()
833 (debian / "copyright").write_text(_DRIFT_ADD, encoding="utf-8")
834 out_path = root / "out.copyright"
835 code = _run_generate(root, out_path)
836 written = out_path.read_text(encoding="utf-8")
837 self.assertEqual(code, 0)
838 self.assertIn("Foo Bar", written)
839 self.assertIn("Someone Else", written)
840
841
842 _ALL_CASES_COPYRIGHT = """\
843 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
844 Source: TODO
845
846 Files: src/*
847 License: GPL-2+
848
849 Files: art.txt old_gone.txt
850 License: Artistic-1
851
852 Files: ancient/*
853 License: Expat
854 """
855
856
857 def _run_all_cases() -> tuple[int, str]:
858 """Build a tree that triggers every staleness section in one run.
859
860 The hand-written copyright is stale four independent ways:
861 * `src/util.c` is matched by the wildcard `src/*` (License: GPL-2+) but its
862 content detects Apache-2, so it relicenses (file no longer matches).
863 * `art.txt`'s paragraph also lists `old_gone.txt`, which matches no file
864 (a stale pattern; the paragraph survives because art.txt matches).
865 * the `ancient/*` paragraph matches nothing at all (a stale paragraph).
866 * `bsd.txt` and `paren.txt` are covered by no paragraph (new files).
867 """
868 with tempfile.TemporaryDirectory() as tmp:
869 root = Path(tmp)
870 _write_tree(root, _ALL_CASES_COPYRIGHT)
871 (root / "src").mkdir()
872 (root / "src" / "util.c").write_text(_UTIL_C, encoding="utf-8")
873 argv = [
874 "--no-progress",
875 "--no-expand-archives",
876 "--explain",
877 "--root",
878 str(root),
879 ]
880 options = process_options(argv)
881 out = io.StringIO()
882 with contextlib.redirect_stdout(out):
883 code = decopy.run_pipeline(options)
884 return code, out.getvalue()
885
886
887 class TestExplainAllCases(unittest.TestCase):
888 """One tree that triggers all four staleness sections at once.
889
890 Locks the current explain output for the new-paragraph, relicensed,
891 stale-paragraph and stale-pattern cases together.
892 """
893
894 def test_every_section_renders_and_exits_one(self):
895 code, out = _run_all_cases()
896 self.assertEqual(code, 1)
897 # Case 1 -- new paragraphs: two uncovered files (bsd.txt, paren.txt) plus
898 # the relicensed src/util.c, whose Apache-2 destination has no existing
899 # paragraph, become three would-be paragraphs, each naming its file,
900 # license and where the license came from.
901 self.assertIn("3 new paragraphs would be added:", out)
902 self.assertIn(" Files: bsd.txt", out)
903 self.assertIn(" License: BSD-3-clause (detected in bsd.txt)", out)
904 self.assertIn(" Files: paren.txt", out)
905 self.assertIn(" License: GPL-3+ (detected in paren.txt)", out)
906 self.assertIn(" Files: src/util.c", out)
907 self.assertIn(" License: Apache-2 (detected in src/util.c)", out)
908 # Case 2 -- relicensed: src/util.c detected Apache, declared GPL-2+. It is
909 # named in both the relicensed and the new-paragraph sections by design.
910 self.assertIn("1 file no longer matches its paragraph:", out)
911 self.assertIn("src/util.c was: GPL-2+ -> now: Apache-2", out)
912 # Case 4 -- stale paragraph: ancient/* matches nothing.
913 self.assertIn("1 paragraph matches no files:", out)
914 self.assertIn("Files: ancient/* [License: Expat]", out)
915 # Case 3 -- stale pattern: old_gone.txt is dead in the Artistic paragraph.
916 self.assertIn("1 stale pattern:", out)
917 self.assertIn("old_gone.txt matches nothing [License: Artistic-1]", out)
918
919 def test_sections_appear_in_fixed_order(self):
920 # Section order: relicensed, copyright drift, new paragraphs, stale
921 # paragraphs, stale patterns. (Copyright drift is absent here.)
922 _, out = _run_all_cases()
923 order = [
924 out.index("no longer matches its paragraph"),
925 out.index("new paragraphs would be added"),
926 out.index("paragraph matches no files"),
927 out.index("stale pattern"),
928 ]
929 self.assertEqual(order, sorted(order))
930
931
932 _HOLDER_C = """\
933 // Copyright 2020 Acme Inc <[email protected]>
934 //
935 // Licensed under the Apache License, Version 2.0 (the "License");
936 // you may not use this file except in compliance with the License.
937 // You may obtain a copy of the License at
938 //
939 // http://www.apache.org/licenses/LICENSE-2.0
940 """
941
942
943 class TestNewParagraphProvenance(unittest.TestCase):
944 """End-to-end provenance for the would-be paragraphs of uncovered files."""
945
946 def test_uncovered_files_bucket_into_one_paragraph_with_sources(self):
947 # No debian/copyright at all, so both Apache files are uncovered. They
948 # share a key, so they form one paragraph naming the license and holder
949 # sources; an uncovered tree fails the gate (exit 1).
950 with tempfile.TemporaryDirectory() as tmp:
951 root = Path(tmp)
952 (root / "src").mkdir()
953 (root / "src" / "a.c").write_text(_HOLDER_C, encoding="utf-8")
954 (root / "src" / "b.c").write_text(_HOLDER_C, encoding="utf-8")
955 argv = [
956 "--no-progress",
957 "--no-expand-archives",
958 "--explain",
959 "--root",
960 str(root),
961 ]
962 buffer = io.StringIO()
963 with contextlib.redirect_stdout(buffer):
964 code = decopy.run_pipeline(process_options(argv))
965 out = buffer.getvalue()
966 self.assertEqual(code, 1)
967 self.assertIn("1 new paragraph would be added:", out)
968 self.assertIn(" Files: src/a.c", out)
969 self.assertIn(" src/b.c", out)
970 self.assertIn(" License: Apache-2 (detected in src/a.c)", out)
971 self.assertIn(" Copyright: [email protected] (in src/a.c, src/b.c)", out)
972
973 def test_generation_path_unaffected_by_new_paragraphs(self):
974 # A plain (non-explain) generation run groups the uncovered files into a
975 # real paragraph; the explain-only new-paragraph recording (NullDelta) is
976 # inert, so the diagnostic phrasing never leaks into the output.
977 with tempfile.TemporaryDirectory() as tmp:
978 root = Path(tmp)
979 (root / "src").mkdir()
980 (root / "src" / "a.c").write_text(_HOLDER_C, encoding="utf-8")
981 out_path = root / "out.copyright"
982 code = _run_generate(root, out_path)
983 written = out_path.read_text(encoding="utf-8")
984 self.assertEqual(code, 0)
985 # The file is grouped and rendered normally (its holder reaches output)...
986 self.assertIn("Acme Inc <[email protected]>", written)
987 # ...with none of the explain-only diagnostic phrasing leaking in.
988 self.assertNotIn("new paragraph would be added", written)
989 self.assertNotIn("detected in", written)
990
991
992 class TestExplainHelp(unittest.TestCase):
993 """The parser help advertises --explain and its staleness exit code."""
994
995 def test_help_mentions_explain_and_exit_one(self):
996 out = io.StringIO()
997 with self.assertRaises(SystemExit), contextlib.redirect_stdout(out):
998 process_options(["--help"])
999 text = out.getvalue()
1000 self.assertIn("--explain", text)
1001 self.assertIn("exits 1", text)
1002
1003
1004 _IGNORE_COPYRIGHT = """\
1005 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1006 Source: TODO
1007
1008 Files: keep.txt
1009 License: Artistic-1
1010 """
1011
1012 _FILES_EXCLUDED_COPYRIGHT = """\
1013 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1014 Files-Excluded: build/*
1015 Source: TODO
1016
1017 Files: keep.txt
1018 License: Artistic-1
1019 """
1020
1021
1022 def _run_in_ignore_tree(copyright_text, *, explain, gitignore=None, extra_args=None):
1023 """Build a tree (keep.txt covered, build/skip.txt uncovered BSD) and run.
1024
1025 Returns (exit_code, stdout). In generation mode stdout is the regenerated
1026 debian/copyright (output defaults to stdout).
1027 """
1028 with tempfile.TemporaryDirectory() as tmp:
1029 root = Path(tmp)
1030 shutil.copy(_TESTDATA / "one" / "art.txt", root / "keep.txt")
1031 (root / "build").mkdir()
1032 shutil.copy(_TESTDATA / "one" / "bsd.txt", root / "build" / "skip.txt")
1033 if gitignore is not None:
1034 (root / ".gitignore").write_text(gitignore, encoding="utf-8")
1035 debian = root / "debian"
1036 debian.mkdir()
1037 (debian / "copyright").write_text(copyright_text, encoding="utf-8")
1038 argv = ["--no-progress", "--no-expand-archives", "--root", str(root)]
1039 if explain:
1040 argv.append("--explain")
1041 if extra_args:
1042 argv.extend(extra_args)
1043 options = process_options(argv)
1044 out = io.StringIO()
1045 with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
1046 code = decopy.run_pipeline(options)
1047 return code, out.getvalue()
1048
1049
1050 class TestIgnoredFilesExplain(unittest.TestCase):
1051 """Files the maintainer excluded never enter the tree, so explain neither
1052 reports them nor lets them fail the gate; --no-gitignore brings them back."""
1053
1054 def test_gitignored_uncovered_file_is_not_reported_exits_zero(self):
1055 code, out = _run_in_ignore_tree(
1056 _IGNORE_COPYRIGHT, explain=True, gitignore="build/\n"
1057 )
1058 self.assertEqual(out, "debian/copyright is up to date.\n")
1059 self.assertEqual(code, 0)
1060
1061 def test_no_gitignore_reports_the_uncovered_file_exits_one(self):
1062 code, out = _run_in_ignore_tree(
1063 _IGNORE_COPYRIGHT,
1064 explain=True,
1065 gitignore="build/\n",
1066 extra_args=["--no-gitignore"],
1067 )
1068 self.assertIn("new paragraph", out)
1069 self.assertIn("build/skip.txt", out)
1070 self.assertIn("BSD-3-clause", out)
1071 self.assertEqual(code, 1)
1072
1073 def test_files_excluded_suppresses_regardless_of_gitignore_flag(self):
1074 code, out = _run_in_ignore_tree(
1075 _FILES_EXCLUDED_COPYRIGHT, explain=True, extra_args=["--no-gitignore"]
1076 )
1077 self.assertNotIn("skip.txt", out)
1078 self.assertEqual(code, 0)
1079
1080 def test_generation_omits_the_gitignored_paragraph(self):
1081 code, out = _run_in_ignore_tree(
1082 _IGNORE_COPYRIGHT, explain=False, gitignore="build/\n"
1083 )
1084 self.assertIn("Artistic", out)
1085 self.assertNotIn("BSD-3-clause", out)
1086 self.assertNotIn("skip.txt", out)
1087 self.assertEqual(code, 0)
1088
1089
1090 if __name__ == "__main__":
1091 unittest.main()