Debian Codegraph @

tests/dep5_test.py

raw
1 #!/usr/bin/env python3
2
3 # Unit tests for decopy
4 # Copyright: 2016, Margarita Manterola <[email protected]>
5 #
6 # License: ISC
7 # Permission to use, copy, modify, and/or distribute this software for any
8 # purpose with or without fee is hereby granted, provided that the above
9 # copyright notice and this permission notice appear in all copies.
10 # .
11 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 # PERFORMANCE OF THIS SOFTWARE.
18
19 import tempfile
20 import unittest
21 from pathlib import Path
22
23 import debian.copyright as dc
24
25 from decopy import cmdoptions
26 from decopy import decopy as decopy_main
27 from decopy.common import core_types
28 from decopy.dep5doc import copyright_processor, dep5
29 from decopy.dep5doc.renderer import Dep5Renderer
30 from decopy.fstree import nodes, tree
31 from decopy.grouping.group import Group, TallyTracker
32 from decopy.grouping.group_contracts import GroupProtocol
33 from decopy.licensing import holders
34 from decopy.licensing.license_expr import And, License, Or
35
36
37 class TestGroupLicenseField(unittest.TestCase):
38 """Group.license_field: the rendered License field."""
39
40 def test_none_falls_back_to_canonical_join(self):
41 # A synthesised group (no expression) renders the canonical set join.
42 group = Group()
43 group.licenses = {"GPL-2+": core_types.License("GPL-2+")}
44 self.assertIsNone(group.license_expr)
45 self.assertEqual(group.license_field, "GPL-2+")
46 self.assertEqual(group.license_field, group.license)
47
48 def test_expression_round_trips_to_dep5(self):
49 group = Group()
50 group.license_expr = And((License("GPL-2+"), License("BSD-3-clause")))
51 self.assertEqual(group.license_field, "GPL-2+ and BSD-3-clause")
52
53 def test_inexpressible_tree_falls_back_to_spdx(self):
54 # A tree DEP-5 cannot hold without changing meaning -> SPDX form.
55 group = Group()
56 group.license_expr = Or(
57 (License("A"), And((Or((License("B"), License("C"))), License("D"))))
58 )
59 self.assertEqual(group.license_field, "A OR ((B OR C) AND D)")
60
61 def test_spdx_fallback_field_reads_back_to_same_tree(self):
62 """A group's SPDX-fallback output parses back to the same expression.
63
64 Guards the round-trip: decopy must read the SPDX License field it emits
65 for trees DEP-5 cannot express.
66 """
67 from decopy.licensing.spdx import parse_license_synopsis
68
69 expr = Or(
70 (
71 And(
72 (Or((License("Expat"), License("BSD-3-clause"))), License("GPL-2+"))
73 ),
74 And((Or((License("Apache-2"), License("ISC"))), License("LGPL-2+"))),
75 )
76 )
77 group = Group()
78 group.license_expr = expr
79 field = group.license_field
80 self.assertIn("(", field) # it is the SPDX fallback form
81 self.assertEqual(parse_license_synopsis(field), expr)
82
83
84 class TestLoadFilesExcluded(unittest.TestCase):
85 """read_files_excluded reads the repack list from the header."""
86
87 def _options_for(self, copyright_text):
88 tmp = tempfile.mkdtemp()
89 if copyright_text is not None:
90 debian = Path(tmp) / "debian"
91 debian.mkdir()
92 (debian / "copyright").write_text(copyright_text, encoding="utf-8")
93 return cmdoptions.process_options(["--no-progress", "--root", tmp])
94
95 def test_whitespace_and_continuation_split_into_patterns(self):
96 text = (
97 "Format: https://www.debian.org/doc/packaging-manuals/"
98 "copyright-format/1.0/\n"
99 "Files-Excluded: a/* b.c\n third/*\n\n"
100 "Files: *\nCopyright: 2020 X\nLicense: ISC\n"
101 )
102 options = self._options_for(text)
103 self.assertEqual(dep5.read_files_excluded(options), ("a/*", "b.c", "third/*"))
104
105 def test_missing_copyright_file_is_empty(self):
106 options = self._options_for(None)
107 self.assertEqual(dep5.read_files_excluded(options), ())
108
109 def test_unparseable_copyright_file_is_empty(self):
110 options = self._options_for("garbage not a paragraph\n")
111 self.assertEqual(dep5.read_files_excluded(options), ())
112
113 def test_no_files_excluded_field_is_empty(self):
114 text = "Format: x\n\nFiles: *\nCopyright: a\nLicense: ISC\n"
115 options = self._options_for(text)
116 self.assertEqual(dep5.read_files_excluded(options), ())
117
118
119 class TestCopyright(unittest.TestCase):
120 def _process_tree(self, path):
121 """Process the received tree and parse the copyright file."""
122 options = cmdoptions.process_options(["--no-progress", "--root", path])
123 filetree = tree.RootInfo.build(options)
124 copyright_ = dep5.read_copyright(options)
125 copyright_.process(filetree)
126 return copyright_, options
127
128 def test_process_empty(self):
129 """Parses a tree with no debian/copyright file."""
130
131 copyright_, _ = self._process_tree("tests/testdata/two")
132
133 # An empty copyright file should yield no groups after processing
134 self.assertEqual(copyright_.groups, [])
135
136 def test_process_malformed(self):
137 """Parses a tree with a malformed debian/copyright file."""
138
139 copyright_, _ = self._process_tree("tests/testdata/malformed")
140
141 # An empty copyright file should yield no groups after processing
142 self.assertEqual(copyright_.groups, [])
143
144 def test_build_uses_supplied_registry(self):
145 """read_copyright threads a caller-supplied registry onto the instance."""
146 options = cmdoptions.process_options(
147 ["--no-progress", "--root", "tests/testdata/four"]
148 )
149 registry = core_types.LicenseRegistry()
150 copyright_ = dep5.read_copyright(options, registry)
151 self.assertIs(copyright_.registry, registry)
152
153 def test_build_defaults_to_isolated_registry(self):
154 """Each build with no registry gets its own, not a shared global."""
155 options = cmdoptions.process_options(
156 ["--no-progress", "--root", "tests/testdata/four"]
157 )
158 first = dep5.read_copyright(options)
159 second = dep5.read_copyright(options)
160 self.assertIsNot(first.registry, second.registry)
161
162 def test_process_stores_license_text_in_own_registry(self):
163 """Processing populates the instance registry's stored text, not a global."""
164 options = cmdoptions.process_options(
165 ["--no-progress", "--root", "tests/testdata/four"]
166 )
167 filetree = tree.RootInfo.build(options)
168 copyright_ = dep5.read_copyright(options)
169 copyright_.process(filetree)
170 self.assertIsNotNone(copyright_.registry.get("GPL-2+").stored)
171 # A separate registry does not see that stored text.
172 self.assertIsNone(core_types.LicenseRegistry().get("GPL-2+").stored)
173
174 def test_groups_are_group_protocol_instances(self):
175 """After processing, every element of groups implements GroupProtocol."""
176 copyright_, _ = self._process_tree("tests/testdata/incomplete")
177 assert copyright_.groups is not None
178 for group in copyright_.groups:
179 self.assertIsInstance(group, GroupProtocol)
180
181 def test_accepts_any_document_exposing_the_reader_api(self):
182 """Composition seam: Copyright wraps any doc with the reader API, not
183 only a dc.Copyright it inherits from. A subclass could not do this."""
184
185 class FakeDoc:
186 header = "HEADER-SENTINEL"
187
188 def all_files_paragraphs(self):
189 return iter(())
190
191 def all_license_paragraphs(self):
192 return iter(())
193
194 copyright_ = dep5.Copyright(FakeDoc()) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
195 self.assertEqual(copyright_.header, "HEADER-SENTINEL")
196 self.assertEqual(list(copyright_.all_files_paragraphs()), [])
197
198 def test_process_incomplete(self):
199 """Parses a tree with an incomplete debian/copyright file."""
200
201 copyright_, options = self._process_tree("tests/testdata/incomplete")
202
203 # An incomplete copyright file should yield the incomplete groups after
204 # processing
205 expected_groups = [
206 {
207 "license": "Unknown",
208 "holders": [],
209 "files": ["debian/copyright"],
210 "comment": "",
211 },
212 {
213 "license": "Unknown",
214 "holders": [],
215 "files": ["test"],
216 "comment": "",
217 },
218 ]
219 self._check_sorted_groups(expected_groups, copyright_.groups, options)
220
221 def test_process_and_license(self):
222 """A 'License: A and B' field is read as both atoms, not one token.
223
224 Regression for the DEP-5 sec 7.2 conjunction handling: the synopsis is
225 parsed into an expression, so the group carries both licences and keeps
226 the parsed expression for faithful re-emission.
227 """
228 from decopy.licensing.license_expr import And, License, parse_dep5_expression
229
230 copyright_, _ = self._process_tree("tests/testdata/andlicense")
231
232 assert copyright_.groups
233 self.assertEqual(len(copyright_.groups), 1)
234 group = copyright_.groups[0]
235 self.assertEqual(set(group.licenses), {"GPL-2+", "BSD-3-clause"})
236 self.assertEqual(
237 group.license_expr,
238 And((License("GPL-2+"), License("BSD-3-clause"))),
239 )
240 self.assertEqual(
241 group.license_expr, parse_dep5_expression("GPL-2+ and BSD-3-clause")
242 )
243
244 def test_render_and_license(self):
245 """A read 'License: A and B' re-emits with 'and', not 'or'.
246
247 The grouping key stays the canonical set join (get_license_key), but the
248 rendered License field comes from the preserved expression.
249 """
250 copyright_, options = self._process_tree("tests/testdata/andlicense")
251 group = copyright_.groups[0]
252
253 # Output field keeps the conjunction ...
254 self.assertEqual(group.license_field, "GPL-2+ and BSD-3-clause")
255 # ... while the grouping key remains the connector-agnostic set join.
256 self.assertEqual(group.get_license_key(), "BSD-3-clause or GPL-2+")
257
258 # And it shows through the renderer's Files paragraph.
259 block = Dep5Renderer().file_block(group, options, ["*"])
260 self.assertIn("License: GPL-2+ and BSD-3-clause", block)
261
262 def test_render_and_license_spdx(self):
263 """--spdx output of a read 'A and B' renders structured SPDX.
264
265 The old string path (dep5_to_spdx) only split on ' or ', so an 'and'
266 field came out mangled; rendering from the expression fixes it.
267 """
268 options = cmdoptions.process_options(
269 ["--no-progress", "--spdx", "--root", "tests/testdata/andlicense"]
270 )
271 filetree = tree.RootInfo.build(options)
272 copyright_ = dep5.read_copyright(options)
273 copyright_.process(filetree)
274 assert copyright_.groups
275 group = copyright_.groups[0]
276
277 block = Dep5Renderer().file_block(group, options, ["*"])
278 self.assertIn("License: GPL-2.0-or-later AND BSD-3-Clause", block)
279
280 def test_process_spdx_in_copyright(self):
281 """A debian/copyright License field in SPDX syntax is read correctly.
282
283 Parentheses mark the SPDX fallback form; it must parse (not yield
284 paren-glued garbage atoms) and normalise to DEP-5 names.
285 """
286 copyright_, _ = self._process_tree("tests/testdata/spdxincopyright")
287 group = copyright_.groups[0]
288 self.assertEqual(set(group.licenses), {"Expat", "Apache-2", "GPL-2+"})
289 # And/Or grouping that DEP-5 can express with one comma comes back as DEP-5.
290 self.assertEqual(group.license_field, "Expat or Apache-2, and GPL-2+")
291
292 def test_process_spdx_names_in_dep5_field(self):
293 """Paren-free SPDX/.0 licence spellings in a License field canonicalise.
294
295 Without parentheses the field takes the DEP-5 read path. Its leaves must
296 still normalise to decopy's canonical names so the group keys match
297 freshly detected files (GPL-2.0-only -> GPL-2, Apache-2.0 -> Apache-2,
298 MIT -> Expat) instead of fragmenting into SPDX-spelled singletons that a
299 detected GPL-2 file would never match.
300 """
301 copyright_, _ = self._process_tree("tests/testdata/spdxnamesincopyright")
302 group = copyright_.groups[0]
303 self.assertEqual(set(group.licenses), {"GPL-2", "Apache-2", "Expat"})
304 # The field re-emits in canonical spelling and the round-trip gate holds
305 # (canonical DEP-5 leaves re-parse to the same expression).
306 self.assertEqual(group.license_field, "GPL-2 or Apache-2 or Expat")
307
308 def test_process_simple(self):
309 """Parses a debian/copyright with two entries (testdata/four)."""
310
311 copyright_, options = self._process_tree("tests/testdata/four")
312
313 expected_groups = [
314 {
315 "license": "LGPL-2+",
316 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
317 "files": ["debian/compat", "debian/copyright"],
318 "comment": "",
319 },
320 {
321 "license": "GPL-2+",
322 "holders": ["2016, Jane Doe <[email protected]>"],
323 "files": ["test"],
324 "comment": "",
325 },
326 ]
327
328 self._check_sorted_groups(expected_groups, copyright_.groups, options)
329
330 def test_process_complex(self):
331 """Parses a debian/copyright with many entries (testdata/three)."""
332
333 copyright_, options = self._process_tree("tests/testdata/three")
334
335 expected_groups = [
336 {
337 "license": "LGPL-2+",
338 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
339 "files": ["debian/compat", "debian/copyright", "debian/rules"],
340 "comment": "No real packaging, just empty files.",
341 },
342 {
343 "license": "GPL-2+",
344 "holders": ["1989-2003, Free Software Foundation, Inc"],
345 "files": ["acinclude.m4"],
346 "comment": "",
347 },
348 {
349 "license": "MIT/X11",
350 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
351 "files": ["src/do-something.m", "src/do-something.py"],
352 "comment": "",
353 },
354 {
355 "license": "GPL-2+",
356 "holders": ["2016, Jane Doe <[email protected]>"],
357 "files": ["COPYING", "data/file.txt", "src/main.py", "src/module.py"],
358 "comment": "",
359 },
360 ]
361
362 self._check_sorted_groups(expected_groups, copyright_.groups, options)
363
364 def _check_sorted_groups(self, expected_groups, groups, options):
365 for i, group in enumerate(groups):
366 key = group.get_key(options)
367 expected = expected_groups[i]
368 with self.subTest(msg=f'Checking "{key}"'):
369 self.assertEqual(
370 list(group.copyrights.sorted_members()),
371 expected["holders"],
372 )
373 self.assertEqual(group.license, expected["license"])
374 self.assertEqual(group.files.sorted_members(), expected["files"])
375 self.assertEqual(group.get_comments(), expected["comment"])
376
377 def _process_and_remove(self, path, opts):
378 """Lists the tree, parses the copyright, reads all files, removes
379 misplaced."""
380 options = cmdoptions.process_options(["--no-progress", "--root", path, *opts])
381 filetree = tree.RootInfo.build(options)
382 copyright_ = dep5.read_copyright(options)
383 copyright_.process(filetree)
384 filetree.process(options)
385 # This function removes files from the groups when they should no longer
386 # be there. It does not add them to new or existing groups. So the
387 # effect that we will see is that some files or groups go "missing".
388 copyright_.remove_misplaced_files(options)
389 return copyright_, options
390
391 def _check_expected_groups(self, expected_groups, groups):
392 """Checks that the received and expected groups match."""
393 # Check that we got all expected groups
394 self.longMessage = False
395 for key in expected_groups:
396 with self.subTest(f'Checking "{key}"'):
397 self.assertIn(key, groups, msg=f"missing expected group: {key}")
398 for key in groups:
399 with self.subTest(f'Checking "{key}"'):
400 self.assertIn(
401 key,
402 expected_groups,
403 msg=f"unexpected group: {key}",
404 )
405 self.longMessage = True
406
407 # Check that the groups are what we expected
408 for key, group in groups.items():
409 with self.subTest(msg=f'Checking "{key}"'):
410 expected = expected_groups[key]
411 self.assertEqual(
412 list(group.copyrights.sorted_members()),
413 expected["holders"],
414 )
415 self.assertEqual(group.license, expected["license"])
416 self.assertEqual(group.files.sorted_members(), expected["files"])
417 self.assertEqual(group.get_comments(), expected["comment"])
418
419 def test_remove_misplaced(self):
420 """Removes files from copyright if they were wrong (testdata/three)."""
421
422 copyright_, options = self._process_and_remove("tests/testdata/three", [])
423
424 expected_groups = {
425 ("LGPL-2+", None, "debian"): {
426 "license": "LGPL-2+",
427 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
428 "files": ["debian/compat", "debian/copyright", "debian/rules"],
429 "comment": "No real packaging, just empty files.",
430 },
431 ("GPL-2+", None, ""): {
432 "license": "GPL-2+",
433 "holders": [
434 "1989-2003, Free Software Foundation, Inc",
435 "2016, Jane Doe <[email protected]>",
436 ],
437 "files": ["COPYING", "acinclude.m4", "src/main.py", "src/module.py"],
438 "comment": "",
439 },
440 ("MIT/X11", None, ""): {
441 "license": "MIT/X11",
442 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
443 "files": ["src/do-something.m", "src/do-something.py"],
444 "comment": "",
445 },
446 }
447 groups = copyright_.get_group_dict(options)
448 self._check_expected_groups(expected_groups, groups)
449
450 def test_remove_misplaced_copyright(self):
451 """Removes files if they were wrong, grouping by copyright."""
452
453 copyright_, options = self._process_and_remove(
454 "tests/testdata/three",
455 ["--group-by", "copyright"],
456 )
457
458 expected_groups = {
459 ("LGPL-2+", ("[email protected]",), "debian"): {
460 "license": "LGPL-2+",
461 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
462 "files": ["debian/compat", "debian/copyright", "debian/rules"],
463 "comment": "No real packaging, just empty files.",
464 },
465 ("GPL-2+", ("[email protected]",), ""): {
466 "license": "GPL-2+",
467 "holders": ["2016, Jane Doe <[email protected]>"],
468 "files": ["COPYING", "src/main.py", "src/module.py"],
469 "comment": "",
470 },
471 ("MIT/X11", ("[email protected]",), ""): {
472 "license": "MIT/X11",
473 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
474 "files": ["src/do-something.m", "src/do-something.py"],
475 "comment": "",
476 },
477 ("GPL-2+", ("Free Software Foundation, Inc",), ""): {
478 "license": "GPL-2+",
479 "holders": ["1989-2003, Free Software Foundation, Inc"],
480 "files": ["acinclude.m4"],
481 "comment": "",
482 },
483 }
484 groups = copyright_.get_group_dict(options)
485 self._check_expected_groups(expected_groups, groups)
486
487 def test_remove_misplaced_partial(self):
488 """Removes files if they were wrong, grouping by copyright."""
489
490 copyright_, options = self._process_and_remove(
491 "tests/testdata/three",
492 ["--mode", "partial", "tests/testdata/three/debian"],
493 )
494
495 expected_groups = {
496 ("LGPL-2+", None, "debian"): {
497 "license": "LGPL-2+",
498 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
499 "files": ["debian/compat", "debian/copyright", "debian/rules"],
500 "comment": "No real packaging, just empty files.",
501 },
502 ("GPL-2+", None, ""): {
503 "license": "GPL-2+",
504 "holders": ["1989-2003, Free Software Foundation, Inc"],
505 "files": [],
506 "comment": "",
507 },
508 ("MIT/X11", None, ""): {
509 "license": "MIT/X11",
510 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
511 "files": [],
512 "comment": "",
513 },
514 }
515
516 groups = copyright_.get_group_dict(options)
517 self._check_expected_groups(expected_groups, groups)
518
519 def test_get_group_dict_returns_dict_of_groups(self):
520 """get_group_dict returns dict with Group values and tuple keys."""
521 copyright_, options = self._process_tree("tests/testdata/four")
522 groups = copyright_.get_group_dict(options)
523 self.assertIsInstance(groups, dict)
524 for key, value in groups.items():
525 self.assertIsInstance(key, tuple)
526 self.assertIsInstance(value, dep5.Group)
527
528
529 class TestStandaloneLicenseCanonicalisation(unittest.TestCase):
530 """A standalone License paragraph is stored under its canonical key.
531
532 The build owns its own LicenseRegistry, so each test reads stored text from
533 that instance, with no shared state to reset.
534 """
535
536 def test_standalone_spdx_named_license_text_found_under_canonical_key(self):
537 """A standalone `License: GPL-2.0-only` stanza's text reaches the GPL-2 group.
538
539 The Files paragraph reads as the canonical GPL-2, so the group
540 renders its stanza under that key. The standalone licence text must be
541 stored under the same canonical key, or it is silently dropped and the
542 output shows the "add the text here" placeholder instead.
543 """
544 options = cmdoptions.process_options(
545 ["--no-progress", "--root", "tests/testdata/spdxstandalonelicense"]
546 )
547 filetree = tree.RootInfo.build(options)
548 copyright_ = dep5.read_copyright(options)
549 copyright_.process(filetree)
550
551 block = Dep5Renderer().license_block(copyright_.registry.get("GPL-2"), options)
552 self.assertIn("DISTINCTIVE-MARKER-A4", block)
553 self.assertNotIn("Add the corresponding license text here", block)
554
555
556 class TestGroup(unittest.TestCase):
557 def test_unknown_license(self):
558 g = dep5.Group()
559 self.assertEqual(g.license, core_types.UNKNOWN)
560 cg = holders.CopyrightHolders()
561 cg.add(core_types.CopyrightHolder("", "[email protected]"))
562 g.add_copyrights(cg)
563 self.assertEqual(g.license, core_types.UNKNOWN_COPYRIGHTED)
564
565 def test_add_file_records_licenses_without_shared_registry(self):
566 """add_file builds its own License per name, not via a shared global."""
567 root = tree.RootInfo(root=".")
568 first, second = dep5.Group(), dep5.Group()
569 for group in (first, second):
570 fileinfo = nodes.FileInfo(root, "f.c")
571 fileinfo.add_licenses(["MIT"])
572 group.add_file(fileinfo)
573 self.assertEqual(first.licenses["MIT"].name, "MIT")
574 self.assertIsNot(first.licenses["MIT"], second.licenses["MIT"])
575
576 def test_add_copyrights_accepts_copyright_holder_list(self):
577 g = dep5.Group()
578 holders = [
579 core_types.CopyrightHolder("Alice", "[email protected]"),
580 core_types.CopyrightHolder("Bob", "[email protected]"),
581 ]
582 g.add_copyrights(holders)
583 self.assertEqual(len(g.copyrights), 2)
584
585 def test_add_copyrights_accepts_copyright_group(self):
586 g = dep5.Group()
587 cg = holders.CopyrightHolders()
588 cg.add(core_types.CopyrightHolder("Carol", "[email protected]"))
589 g.add_copyrights(cg)
590 self.assertEqual(len(g.copyrights), 1)
591
592 def test_sort_key_returns_five_tuple(self):
593 g = dep5.Group(position=1)
594 g.licenses["MIT"] = core_types.License("MIT")
595 root = tree.RootInfo(root=".")
596 fi = nodes.FileInfo(root, "foo.c")
597 g.files.add_file(fi)
598 options = cmdoptions.process_options(["--no-progress", "--root", "."])
599 key = g.sort_key(options)
600 self.assertIsInstance(key, tuple)
601 self.assertEqual(len(key), 5)
602 self.assertIsInstance(key[0], int)
603 self.assertIsInstance(key[1], int)
604
605
606 class TestGroupCopyrightBlock(unittest.TestCase):
607 """Unit tests for the DEP-5 Files paragraph (Dep5Renderer.file_block).
608
609 These tests construct Group objects directly (no file I/O) so that each
610 test exercises exactly one aspect of the generated DEP-5 block string.
611 group.files.add_file() is used instead of group.add_file() intentionally:
612 the latter merges licenses and copyrights from the FileInfo, which would
613 interfere with the explicit values set by the tests.
614 """
615
616 def _block(self, group, *, glob=True):
617 flag = "--glob" if glob else "--no-glob"
618 opts = cmdoptions.process_options(["--no-progress", flag])
619 if opts.glob:
620 file_patterns = group.files.get_patterns(TallyTracker())
621 else:
622 file_patterns = group.files.sorted_members()
623 return Dep5Renderer().file_block(group, opts, file_patterns)
624
625 def _file(self, name, parent=None):
626 return nodes.FileInfo(parent=parent, name=name)
627
628 def _group_with_file(self, filename, license_name=None):
629 group = dep5.Group()
630 group.files.add_file(self._file(filename))
631 if license_name:
632 group.licenses[license_name] = core_types.License(license_name)
633 return group
634
635 # valid
636
637 def test_valid_empty_group(self):
638 self.assertFalse(dep5.Group().copyright_block_valid())
639
640 def test_valid_single_unnamed_file(self):
641 group = dep5.Group()
642 group.files.add_file(self._file(""))
643 self.assertFalse(group.copyright_block_valid())
644
645 def test_valid_single_named_file(self):
646 group = dep5.Group()
647 group.files.add_file(self._file("src/foo.c"))
648 self.assertTrue(group.copyright_block_valid())
649
650 def test_valid_multiple_files(self):
651 group = dep5.Group()
652 group.files.add_file(self._file("a.c"))
653 group.files.add_file(self._file("b.c"))
654 self.assertTrue(group.copyright_block_valid())
655
656 # returns "" for invalid
657
658 def test_block_empty_group_returns_empty(self):
659 self.assertEqual(self._block(dep5.Group()), "")
660
661 def test_block_single_unnamed_file_returns_empty(self):
662 group = dep5.Group()
663 group.files.add_file(self._file(""))
664 self.assertEqual(self._block(group), "")
665
666 # Files + License, no Copyright
667
668 def test_block_omits_copyright_line_when_no_holders(self):
669 block = self._block(self._group_with_file("src/foo.c", "MIT"))
670 self.assertEqual(block, "Files: src/foo.c\nLicense: MIT")
671 self.assertNotIn("Copyright:", block)
672
673 # full block, all fields
674
675 def test_block_copyright_line_present_with_one_holder(self):
676 group = self._group_with_file("src/foo.c", "MIT")
677 group.add_copyrights(
678 [
679 core_types.CopyrightHolder(
680 "Alice",
681 "[email protected]",
682 core_types.YearRange(2020, 2020),
683 ),
684 ],
685 )
686 self.assertEqual(
687 self._block(group),
688 "Files: src/foo.c\n"
689 "Copyright: 2020, Alice <[email protected]>\n"
690 "License: MIT",
691 )
692
693 def test_block_comment_line_present_when_set(self):
694 group = self._group_with_file("src/foo.c", "MIT")
695 group.add_copyrights(
696 [
697 core_types.CopyrightHolder(
698 "Alice",
699 "[email protected]",
700 core_types.YearRange(2020, 2020),
701 ),
702 ],
703 )
704 group.comments.append("see also COPYING")
705 self.assertEqual(
706 self._block(group),
707 "Files: src/foo.c\n"
708 "Copyright: 2020, Alice <[email protected]>\n"
709 "License: MIT\n"
710 "Comment: see also COPYING",
711 )
712
713 def test_block_omits_comment_line_when_empty(self):
714 block = self._block(self._group_with_file("src/foo.c", "MIT"))
715 self.assertNotIn("Comment:", block)
716
717 # continuation indentation
718
719 def test_block_multiple_files_indented_by_7_spaces(self):
720 group = dep5.Group()
721 for name in ["src/bar.c", "src/foo.c"]:
722 group.files.add_file(self._file(name))
723 group.licenses["MIT"] = core_types.License("MIT")
724 self.assertEqual(
725 self._block(group, glob=False),
726 "Files: src/bar.c\n src/foo.c\nLicense: MIT",
727 )
728
729 def test_block_multiple_holders_indented_by_11_spaces(self):
730 group = self._group_with_file("src/foo.c", "MIT")
731 group.add_copyrights(
732 [
733 core_types.CopyrightHolder(
734 "Alice",
735 "[email protected]",
736 core_types.YearRange(2020, 2020),
737 ),
738 core_types.CopyrightHolder(
739 "Bob",
740 "[email protected]",
741 core_types.YearRange(2021, 2021),
742 ),
743 ],
744 )
745 self.assertEqual(
746 self._block(group),
747 "Files: src/foo.c\n"
748 "Copyright: 2020, Alice <[email protected]>\n"
749 " 2021, Bob <[email protected]>\n"
750 "License: MIT",
751 )
752
753 # glob_=True vs glob_=False routing
754
755 def test_block_glob_produces_directory_wildcard(self):
756 src = nodes.DirInfo(parent=None, name="src")
757 group = dep5.Group()
758 for name in ["a.c", "b.c"]:
759 group.files.add_file(self._file(name, parent=src))
760 group.licenses["MIT"] = core_types.License("MIT")
761 self.assertEqual(
762 self._block(group),
763 "Files: src/*\nLicense: MIT",
764 )
765
766 def test_block_no_glob_lists_individual_filenames(self):
767 src = nodes.DirInfo(parent=None, name="src")
768 group = dep5.Group()
769 for name in ["b.c", "a.c"]:
770 group.files.add_file(self._file(name, parent=src))
771 group.licenses["MIT"] = core_types.License("MIT")
772 self.assertEqual(
773 self._block(group, glob=False),
774 "Files: src/a.c\n src/b.c\nLicense: MIT",
775 )
776
777 # get_inherited_comment
778
779 def test_inherited_comment_no_filenames_returns_none(self):
780 group = dep5.Group()
781 self.assertIsNone(group.get_inherited_comment())
782
783 def test_inherited_comment_with_stored_returns_none(self):
784 group = dep5.Group()
785 group.license_filenames.add("LICENSE")
786 group.stored = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
787 self.assertIsNone(group.get_inherited_comment())
788
789 def test_stored_accepts_files_paragraph(self):
790 group = dep5.Group()
791 paragraph = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
792 group.stored = paragraph
793 self.assertIsInstance(group.stored, dc.FilesParagraph)
794
795 # extra_fields
796
797 def test_extra_fields_empty_without_stored(self):
798 group = dep5.Group()
799 self.assertEqual(list(group.extra_fields()), [])
800
801 def test_extra_fields_yields_non_standard_stored_fields(self):
802 group = dep5.Group()
803 paragraph = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
804 paragraph["X-Foo"] = "bar"
805 group.stored = paragraph
806 # The standard Files/Copyright/License/Comment fields are rendered by the
807 # renderer itself; extra_fields exposes only the rest.
808 self.assertEqual(list(group.extra_fields()), [("X-Foo", "bar")])
809
810 def test_inherited_comment_with_filenames_no_stored(self):
811 group = dep5.Group()
812 group.license_filenames.add("LICENSE")
813 comment = group.get_inherited_comment()
814 assert comment is not None
815 self.assertIn("LICENSE", comment)
816 self.assertIn("No explicit license found", comment)
817
818 def test_inherited_comment_multiple_filenames_sorted(self):
819 group = dep5.Group()
820 group.license_filenames.update(["COPYING", "LICENSE", "AUTHORS"])
821 comment = group.get_inherited_comment()
822 assert comment is not None
823 lines = comment.splitlines()
824 # First line is the header; remaining lines contain sorted filenames
825 self.assertIn("No explicit license found", lines[0])
826 filenames_in_comment = [line.strip() for line in lines[1:]]
827 self.assertEqual(filenames_in_comment, ["AUTHORS", "COPYING", "LICENSE"])
828
829
830 class TestGroupSortKey(unittest.TestCase):
831 """Unit tests for Group.sort_key() output ordering.
832
833 sort_key() returns a tuple used by an ascending sort in output.py.
834 A smaller sort_key means the group appears earlier (higher) in the output.
835
836 Structure: (debian_group, -position, -n_files, -n_copyrights, group_key)
837 debian_group=0 normal groups → first in output
838 debian_group=1 UNKNOWN* licenses → middle
839 debian_group=2 debian/ when split → last in output
840 """
841
842 def setUp(self):
843 self.root = nodes.DirInfo(parent=None, name="")
844 self.debian_dir = nodes.DirInfo(parent=self.root, name="debian")
845 self.src_dir = nodes.DirInfo(parent=self.root, name="src")
846
847 def _opts(self, *, split_debian=True):
848 flags = ["--no-progress", "--root", "tests/testdata/one"]
849 if not split_debian:
850 flags.append("--no-split-debian")
851 return cmdoptions.process_options(flags)
852
853 def _group(self, license_name=None, position=0, parent=None, n_files=1):
854 """Create a Group with n_files under the given DirInfo parent."""
855 group = dep5.Group(position=position)
856 parent = parent if parent is not None else self.root
857 for i in range(n_files):
858 group.files.add_file(nodes.FileInfo(parent=parent, name=f"f{i}.txt"))
859 if license_name:
860 group.licenses[license_name] = core_types.License(license_name)
861 return group
862
863 # UNKNOWN/UNKNOWN_COPYRIGHTED
864
865 def test_unknown_license_sorts_after_real_license(self):
866 opts = self._opts()
867 real = self._group("MIT")
868 unknown = self._group()
869 self.assertEqual(unknown.license, core_types.UNKNOWN)
870 self.assertGreater(unknown.sort_key(opts), real.sort_key(opts))
871
872 def test_unknown_copyrighted_sorts_after_real_license(self):
873 opts = self._opts()
874 real = self._group("MIT")
875 unk_cop = self._group()
876 unk_cop.add_copyrights([core_types.CopyrightHolder("", "[email protected]")])
877 self.assertEqual(unk_cop.license, core_types.UNKNOWN_COPYRIGHTED)
878 self.assertGreater(unk_cop.sort_key(opts), real.sort_key(opts))
879
880 def test_unknown_and_unknown_copyrighted_share_same_band(self):
881 opts = self._opts()
882 unknown = self._group()
883 unk_cop = self._group()
884 unk_cop.add_copyrights([core_types.CopyrightHolder("", "[email protected]")])
885 # Both land in debian_group=1
886 self.assertEqual(unknown.sort_key(opts)[0], 1)
887 self.assertEqual(unk_cop.sort_key(opts)[0], 1)
888
889 # split_debian flag
890
891 def test_debian_group_sorts_last_with_split_debian(self):
892 opts = self._opts(split_debian=True)
893 debian = self._group("MIT", parent=self.debian_dir)
894 normal = self._group("MIT", parent=self.src_dir)
895 self.assertGreater(debian.sort_key(opts), normal.sort_key(opts))
896
897 def test_debian_group_sorts_after_unknown_with_split_debian(self):
898 opts = self._opts(split_debian=True)
899 debian = self._group("MIT", parent=self.debian_dir)
900 unknown = self._group(parent=self.src_dir)
901 # Full three-way ordering: normal(0) < UNKNOWN(1) < debian(2)
902 self.assertGreater(debian.sort_key(opts), unknown.sort_key(opts))
903
904 def test_debian_group_not_special_without_split_debian(self):
905 opts = self._opts(split_debian=False)
906 debian = self._group("MIT", parent=self.debian_dir)
907 normal = self._group("MIT", parent=self.src_dir)
908 # Both land in debian_group=0 when the flag is off
909 self.assertEqual(debian.sort_key(opts)[0], 0)
910 self.assertEqual(normal.sort_key(opts)[0], 0)
911
912 # position-based secondary sort
913
914 def test_higher_position_sorts_before_lower_position(self):
915 opts = self._opts()
916 low = self._group("MIT", position=0)
917 high = self._group("MIT", position=3)
918 # -3 < 0 → high-position group has smaller sort_key → appears first
919 self.assertLess(high.sort_key(opts), low.sort_key(opts))
920
921 def test_position_ordering_across_multiple_groups(self):
922 opts = self._opts()
923 groups = [self._group("MIT", position=p) for p in [0, 2, 1]]
924 ordered = sorted(groups, key=lambda g: g.sort_key(opts))
925 self.assertEqual([g.position for g in ordered], [2, 1, 0])
926
927 # file-count secondary sort
928
929 def test_more_files_sorts_before_fewer_files(self):
930 opts = self._opts()
931 few = self._group("MIT", n_files=1)
932 many = self._group("MIT", n_files=3)
933 # -3 < -1 → larger group has smaller sort_key → appears first
934 self.assertLess(many.sort_key(opts), few.sort_key(opts))
935
936 # full priority end-to-end sort
937
938 def test_full_sort_order_normal_then_unknown_then_debian(self):
939 opts = self._opts(split_debian=True)
940 g_real = self._group("MIT", position=0, parent=self.src_dir)
941 g_unk = self._group(position=0, parent=self.src_dir)
942 g_deb = self._group("MIT", position=0, parent=self.debian_dir)
943
944 ordered = sorted([g_deb, g_unk, g_real], key=lambda g: g.sort_key(opts))
945
946 self.assertIs(ordered[0], g_real)
947 self.assertIs(ordered[1], g_unk)
948 self.assertIs(ordered[2], g_deb)
949
950
951 class TestGroupKeyIgnoreCopyright(unittest.TestCase):
952 """get_key(ignore_copyright=True) blanks only the copyright slot."""
953
954 def test_ignore_copyright_blanks_only_the_copyright_slot(self):
955 options = cmdoptions.process_options(
956 [
957 "--no-progress",
958 "--root",
959 "tests/testdata/one",
960 "--group-by",
961 "copyright",
962 ]
963 )
964 root = nodes.DirInfo(parent=None, name="")
965 group = Group()
966 fileinfo = nodes.FileInfo(parent=root, name="a.txt")
967 fileinfo.add_licenses(["MIT"])
968 fileinfo.add_copyrights([core_types.CopyrightHolder("Alice", "alice@x")])
969 group.add_file(fileinfo)
970
971 full = group.get_key(options)
972 masked = group.get_key(options, ignore_copyright=True)
973
974 # The copyright slot is populated under copyright grouping...
975 self.assertNotEqual(full[1], ())
976 # ...and masking blanks only that slot, leaving licence and path intact.
977 self.assertEqual(masked, (full[0], (), full[2]))
978
979
980 class TestResolveCopyrightPath(unittest.TestCase):
981 """The single copyright-file path resolver shared by build/_read_header/CLI."""
982
983 @staticmethod
984 def _options(root, copyright_file):
985 return cmdoptions.process_options(
986 ["--no-progress", "--root", root, "--copyright-file", copyright_file]
987 )
988
989 def test_relative_is_joined_to_root(self):
990 with tempfile.TemporaryDirectory() as tmp:
991 options = self._options(tmp, "debian/copyright")
992 self.assertEqual(
993 copyright_processor.resolve_copyright_path(options),
994 Path(options.root) / "debian/copyright",
995 )
996
997 def test_absolute_is_returned_unchanged(self):
998 with tempfile.TemporaryDirectory() as tmp:
999 absolute = str(Path(tmp) / "elsewhere" / "copyright")
1000 options = self._options(tmp, absolute)
1001 self.assertEqual(
1002 copyright_processor.resolve_copyright_path(options),
1003 Path(absolute),
1004 )
1005
1006 def test_relpath_is_relative_to_root(self):
1007 with tempfile.TemporaryDirectory() as tmp:
1008 options = self._options(tmp, "debian/copyright")
1009 self.assertEqual(
1010 decopy_main._copyright_relpath(options), "debian/copyright"
1011 )
1012
1013 def test_relpath_outside_root_falls_back_to_full_path(self):
1014 with tempfile.TemporaryDirectory() as tmp:
1015 outside = "/some/other/copyright"
1016 options = self._options(tmp, outside)
1017 self.assertEqual(decopy_main._copyright_relpath(options), outside)
1018
1019
1020 if __name__ == "__main__":
1021 unittest.main()