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. debian/copyright is never listed, so the paragraph whose
205 # only file it was does not survive.
206 expected_groups = [
207 {
208 "license": "Unknown",
209 "holders": [],
210 "files": ["test"],
211 "comment": "",
212 },
213 ]
214 self._check_sorted_groups(expected_groups, copyright_.groups, options)
215
216 def test_process_and_license(self):
217 """A 'License: A and B' field is read as both atoms, not one token.
218
219 Regression for the DEP-5 sec 7.2 conjunction handling: the synopsis is
220 parsed into an expression, so the group carries both licences and keeps
221 the parsed expression for faithful re-emission.
222 """
223 from decopy.licensing.license_expr import And, License, parse_dep5_expression
224
225 copyright_, _ = self._process_tree("tests/testdata/andlicense")
226
227 assert copyright_.groups
228 self.assertEqual(len(copyright_.groups), 1)
229 group = copyright_.groups[0]
230 self.assertEqual(set(group.licenses), {"GPL-2+", "BSD-3-clause"})
231 self.assertEqual(
232 group.license_expr,
233 And((License("GPL-2+"), License("BSD-3-clause"))),
234 )
235 self.assertEqual(
236 group.license_expr, parse_dep5_expression("GPL-2+ and BSD-3-clause")
237 )
238
239 def test_render_and_license(self):
240 """A read 'License: A and B' re-emits with 'and', not 'or'.
241
242 The grouping key stays the canonical set join (get_license_key), but the
243 rendered License field comes from the preserved expression.
244 """
245 copyright_, options = self._process_tree("tests/testdata/andlicense")
246 group = copyright_.groups[0]
247
248 # Output field keeps the conjunction ...
249 self.assertEqual(group.license_field, "GPL-2+ and BSD-3-clause")
250 # ... while the grouping key remains the connector-agnostic set join.
251 self.assertEqual(group.get_license_key(), "BSD-3-clause or GPL-2+")
252
253 # And it shows through the renderer's Files paragraph.
254 block = Dep5Renderer().file_block(group, options, ["*"])
255 self.assertIn("License: GPL-2+ and BSD-3-clause", block)
256
257 def test_render_and_license_spdx(self):
258 """--spdx output of a read 'A and B' renders structured SPDX.
259
260 The old string path (dep5_to_spdx) only split on ' or ', so an 'and'
261 field came out mangled; rendering from the expression fixes it.
262 """
263 options = cmdoptions.process_options(
264 ["--no-progress", "--spdx", "--root", "tests/testdata/andlicense"]
265 )
266 filetree = tree.RootInfo.build(options)
267 copyright_ = dep5.read_copyright(options)
268 copyright_.process(filetree)
269 assert copyright_.groups
270 group = copyright_.groups[0]
271
272 block = Dep5Renderer().file_block(group, options, ["*"])
273 self.assertIn("License: GPL-2.0-or-later AND BSD-3-Clause", block)
274
275 def test_process_spdx_in_copyright(self):
276 """A debian/copyright License field in SPDX syntax is read correctly.
277
278 Parentheses mark the SPDX fallback form; it must parse (not yield
279 paren-glued garbage atoms) and normalise to DEP-5 names.
280 """
281 copyright_, _ = self._process_tree("tests/testdata/spdxincopyright")
282 group = copyright_.groups[0]
283 self.assertEqual(set(group.licenses), {"Expat", "Apache-2", "GPL-2+"})
284 # And/Or grouping that DEP-5 can express with one comma comes back as DEP-5.
285 self.assertEqual(group.license_field, "Expat or Apache-2, and GPL-2+")
286
287 def test_process_spdx_names_in_dep5_field(self):
288 """Paren-free SPDX/.0 licence spellings in a License field canonicalise.
289
290 Without parentheses the field takes the DEP-5 read path. Its leaves must
291 still normalise to decopy's canonical names so the group keys match
292 freshly detected files (GPL-2.0-only -> GPL-2, Apache-2.0 -> Apache-2,
293 MIT -> Expat) instead of fragmenting into SPDX-spelled singletons that a
294 detected GPL-2 file would never match.
295 """
296 copyright_, _ = self._process_tree("tests/testdata/spdxnamesincopyright")
297 group = copyright_.groups[0]
298 self.assertEqual(set(group.licenses), {"GPL-2", "Apache-2", "Expat"})
299 # The field re-emits in canonical spelling and the round-trip gate holds
300 # (canonical DEP-5 leaves re-parse to the same expression).
301 self.assertEqual(group.license_field, "GPL-2 or Apache-2 or Expat")
302
303 def test_process_simple(self):
304 """Parses a debian/copyright with two entries (testdata/four)."""
305
306 copyright_, options = self._process_tree("tests/testdata/four")
307
308 expected_groups = [
309 {
310 "license": "LGPL-2+",
311 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
312 "files": ["debian/compat"],
313 "comment": "",
314 },
315 {
316 "license": "GPL-2+",
317 "holders": ["2016, Jane Doe <[email protected]>"],
318 "files": ["test"],
319 "comment": "",
320 },
321 ]
322
323 self._check_sorted_groups(expected_groups, copyright_.groups, options)
324
325 def test_process_complex(self):
326 """Parses a debian/copyright with many entries (testdata/three)."""
327
328 copyright_, options = self._process_tree("tests/testdata/three")
329
330 expected_groups = [
331 {
332 "license": "LGPL-2+",
333 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
334 "files": ["debian/compat", "debian/rules"],
335 "comment": "No real packaging, just empty files.",
336 },
337 {
338 "license": "GPL-2+",
339 "holders": ["1989-2003, Free Software Foundation, Inc"],
340 "files": ["acinclude.m4"],
341 "comment": "",
342 },
343 {
344 "license": "MIT/X11",
345 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
346 "files": ["src/do-something.m", "src/do-something.py"],
347 "comment": "",
348 },
349 {
350 "license": "GPL-2+",
351 "holders": ["2016, Jane Doe <[email protected]>"],
352 "files": ["data/file.txt", "src/main.py", "src/module.py"],
353 "comment": "",
354 },
355 ]
356
357 self._check_sorted_groups(expected_groups, copyright_.groups, options)
358
359 def _check_sorted_groups(self, expected_groups, groups, options):
360 for i, group in enumerate(groups):
361 key = group.get_key(options)
362 expected = expected_groups[i]
363 with self.subTest(msg=f'Checking "{key}"'):
364 self.assertEqual(
365 list(group.copyrights.sorted_members()),
366 expected["holders"],
367 )
368 self.assertEqual(group.license, expected["license"])
369 self.assertEqual(group.files.sorted_members(), expected["files"])
370 self.assertEqual(group.get_comments(), expected["comment"])
371
372 def _process_and_remove(self, path, opts):
373 """Lists the tree, parses the copyright, reads all files, removes
374 misplaced."""
375 options = cmdoptions.process_options(["--no-progress", "--root", path, *opts])
376 filetree = tree.RootInfo.build(options)
377 copyright_ = dep5.read_copyright(options)
378 copyright_.process(filetree)
379 filetree.process(options)
380 # This function removes files from the groups when they should no longer
381 # be there. It does not add them to new or existing groups. So the
382 # effect that we will see is that some files or groups go "missing".
383 copyright_.remove_misplaced_files(options)
384 return copyright_, options
385
386 def _check_expected_groups(self, expected_groups, groups):
387 """Checks that the received and expected groups match."""
388 # Check that we got all expected groups
389 self.longMessage = False
390 for key in expected_groups:
391 with self.subTest(f'Checking "{key}"'):
392 self.assertIn(key, groups, msg=f"missing expected group: {key}")
393 for key in groups:
394 with self.subTest(f'Checking "{key}"'):
395 self.assertIn(
396 key,
397 expected_groups,
398 msg=f"unexpected group: {key}",
399 )
400 self.longMessage = True
401
402 # Check that the groups are what we expected
403 for key, group in groups.items():
404 with self.subTest(msg=f'Checking "{key}"'):
405 expected = expected_groups[key]
406 self.assertEqual(
407 list(group.copyrights.sorted_members()),
408 expected["holders"],
409 )
410 self.assertEqual(group.license, expected["license"])
411 self.assertEqual(group.files.sorted_members(), expected["files"])
412 self.assertEqual(group.get_comments(), expected["comment"])
413
414 def test_remove_misplaced(self):
415 """Removes files from copyright if they were wrong (testdata/three)."""
416
417 copyright_, options = self._process_and_remove("tests/testdata/three", [])
418
419 expected_groups = {
420 ("LGPL-2+", None, "debian"): {
421 "license": "LGPL-2+",
422 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
423 "files": ["debian/compat", "debian/rules"],
424 "comment": "No real packaging, just empty files.",
425 },
426 ("GPL-2+", None, ""): {
427 "license": "GPL-2+",
428 "holders": [
429 "1989-2003, Free Software Foundation, Inc",
430 "2016, Jane Doe <[email protected]>",
431 ],
432 "files": ["acinclude.m4", "src/main.py", "src/module.py"],
433 "comment": "",
434 },
435 ("MIT/X11", None, ""): {
436 "license": "MIT/X11",
437 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
438 "files": ["src/do-something.m", "src/do-something.py"],
439 "comment": "",
440 },
441 }
442 groups = copyright_.get_group_dict(options)
443 self._check_expected_groups(expected_groups, groups)
444
445 def test_remove_misplaced_copyright(self):
446 """Removes files if they were wrong, grouping by copyright."""
447
448 copyright_, options = self._process_and_remove(
449 "tests/testdata/three",
450 ["--group-by", "copyright"],
451 )
452
453 expected_groups = {
454 ("LGPL-2+", ("[email protected]",), "debian"): {
455 "license": "LGPL-2+",
456 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
457 "files": ["debian/compat", "debian/rules"],
458 "comment": "No real packaging, just empty files.",
459 },
460 ("GPL-2+", ("[email protected]",), ""): {
461 "license": "GPL-2+",
462 "holders": ["2016, Jane Doe <[email protected]>"],
463 "files": ["src/main.py", "src/module.py"],
464 "comment": "",
465 },
466 ("MIT/X11", ("[email protected]",), ""): {
467 "license": "MIT/X11",
468 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
469 "files": ["src/do-something.m", "src/do-something.py"],
470 "comment": "",
471 },
472 ("GPL-2+", ("Free Software Foundation, Inc",), ""): {
473 "license": "GPL-2+",
474 "holders": ["1989-2003, Free Software Foundation, Inc"],
475 "files": ["acinclude.m4"],
476 "comment": "",
477 },
478 }
479 groups = copyright_.get_group_dict(options)
480 self._check_expected_groups(expected_groups, groups)
481
482 def test_remove_misplaced_partial(self):
483 """Removes files if they were wrong, grouping by copyright."""
484
485 copyright_, options = self._process_and_remove(
486 "tests/testdata/three",
487 ["--mode", "partial", "tests/testdata/three/debian"],
488 )
489
490 expected_groups = {
491 ("LGPL-2+", None, "debian"): {
492 "license": "LGPL-2+",
493 "holders": ["2014-2016, Maximiliano Curia <[email protected]>"],
494 "files": ["debian/compat", "debian/rules"],
495 "comment": "No real packaging, just empty files.",
496 },
497 ("GPL-2+", None, ""): {
498 "license": "GPL-2+",
499 "holders": ["1989-2003, Free Software Foundation, Inc"],
500 "files": [],
501 "comment": "",
502 },
503 ("MIT/X11", None, ""): {
504 "license": "MIT/X11",
505 "holders": ["1993-2004, Clara Oswald <[email protected]>"],
506 "files": [],
507 "comment": "",
508 },
509 }
510
511 groups = copyright_.get_group_dict(options)
512 self._check_expected_groups(expected_groups, groups)
513
514 def test_get_group_dict_returns_dict_of_groups(self):
515 """get_group_dict returns dict with Group values and tuple keys."""
516 copyright_, options = self._process_tree("tests/testdata/four")
517 groups = copyright_.get_group_dict(options)
518 self.assertIsInstance(groups, dict)
519 for key, value in groups.items():
520 self.assertIsInstance(key, tuple)
521 self.assertIsInstance(value, dep5.Group)
522
523
524 class TestStandaloneLicenseCanonicalisation(unittest.TestCase):
525 """A standalone License paragraph is stored under its canonical key.
526
527 The build owns its own LicenseRegistry, so each test reads stored text from
528 that instance, with no shared state to reset.
529 """
530
531 def test_standalone_spdx_named_license_text_found_under_canonical_key(self):
532 """A standalone `License: GPL-2.0-only` stanza's text reaches the GPL-2 group.
533
534 The Files paragraph reads as the canonical GPL-2, so the group
535 renders its stanza under that key. The standalone licence text must be
536 stored under the same canonical key, or it is silently dropped and the
537 output shows the "add the text here" placeholder instead.
538 """
539 options = cmdoptions.process_options(
540 ["--no-progress", "--root", "tests/testdata/spdxstandalonelicense"]
541 )
542 filetree = tree.RootInfo.build(options)
543 copyright_ = dep5.read_copyright(options)
544 copyright_.process(filetree)
545
546 block = Dep5Renderer().license_block(copyright_.registry.get("GPL-2"), options)
547 self.assertIn("DISTINCTIVE-MARKER-A4", block)
548 self.assertNotIn("Add the corresponding license text here", block)
549
550
551 class TestGroup(unittest.TestCase):
552 def test_unknown_license(self):
553 g = dep5.Group()
554 self.assertEqual(g.license, core_types.UNKNOWN)
555 cg = holders.CopyrightHolders()
556 cg.add(core_types.CopyrightHolder("", "[email protected]"))
557 g.add_copyrights(cg)
558 self.assertEqual(g.license, core_types.UNKNOWN_COPYRIGHTED)
559
560 def test_add_file_records_licenses_without_shared_registry(self):
561 """add_file builds its own License per name, not via a shared global."""
562 root = tree.RootInfo(root=".")
563 first, second = dep5.Group(), dep5.Group()
564 for group in (first, second):
565 fileinfo = nodes.FileInfo(root, "f.c")
566 fileinfo.add_licenses(["MIT"])
567 group.add_file(fileinfo)
568 self.assertEqual(first.licenses["MIT"].name, "MIT")
569 self.assertIsNot(first.licenses["MIT"], second.licenses["MIT"])
570
571 def test_add_copyrights_accepts_copyright_holder_list(self):
572 g = dep5.Group()
573 holders = [
574 core_types.CopyrightHolder("Alice", "[email protected]"),
575 core_types.CopyrightHolder("Bob", "[email protected]"),
576 ]
577 g.add_copyrights(holders)
578 self.assertEqual(len(g.copyrights), 2)
579
580 def test_add_copyrights_accepts_copyright_group(self):
581 g = dep5.Group()
582 cg = holders.CopyrightHolders()
583 cg.add(core_types.CopyrightHolder("Carol", "[email protected]"))
584 g.add_copyrights(cg)
585 self.assertEqual(len(g.copyrights), 1)
586
587 def test_sort_key_returns_five_tuple(self):
588 g = dep5.Group(position=1)
589 g.licenses["MIT"] = core_types.License("MIT")
590 root = tree.RootInfo(root=".")
591 fi = nodes.FileInfo(root, "foo.c")
592 g.files.add_file(fi)
593 options = cmdoptions.process_options(["--no-progress", "--root", "."])
594 key = g.sort_key(options)
595 self.assertIsInstance(key, tuple)
596 self.assertEqual(len(key), 5)
597 self.assertIsInstance(key[0], int)
598 self.assertIsInstance(key[1], int)
599
600
601 class TestGroupCopyrightBlock(unittest.TestCase):
602 """Unit tests for the DEP-5 Files paragraph (Dep5Renderer.file_block).
603
604 These tests construct Group objects directly (no file I/O) so that each
605 test exercises exactly one aspect of the generated DEP-5 block string.
606 group.files.add_file() is used instead of group.add_file() intentionally:
607 the latter merges licenses and copyrights from the FileInfo, which would
608 interfere with the explicit values set by the tests.
609 """
610
611 def _block(self, group, *, glob=True):
612 flag = "--glob" if glob else "--no-glob"
613 opts = cmdoptions.process_options(["--no-progress", flag])
614 if opts.glob:
615 file_patterns = group.files.get_patterns(TallyTracker())
616 else:
617 file_patterns = group.files.sorted_members()
618 return Dep5Renderer().file_block(group, opts, file_patterns)
619
620 def _file(self, name, parent=None):
621 return nodes.FileInfo(parent=parent, name=name)
622
623 def _group_with_file(self, filename, license_name=None):
624 group = dep5.Group()
625 group.files.add_file(self._file(filename))
626 if license_name:
627 group.licenses[license_name] = core_types.License(license_name)
628 return group
629
630 # valid
631
632 def test_valid_empty_group(self):
633 self.assertFalse(dep5.Group().copyright_block_valid())
634
635 def test_valid_single_unnamed_file(self):
636 group = dep5.Group()
637 group.files.add_file(self._file(""))
638 self.assertFalse(group.copyright_block_valid())
639
640 def test_valid_single_named_file(self):
641 group = dep5.Group()
642 group.files.add_file(self._file("src/foo.c"))
643 self.assertTrue(group.copyright_block_valid())
644
645 def test_valid_multiple_files(self):
646 group = dep5.Group()
647 group.files.add_file(self._file("a.c"))
648 group.files.add_file(self._file("b.c"))
649 self.assertTrue(group.copyright_block_valid())
650
651 # returns "" for invalid
652
653 def test_block_empty_group_returns_empty(self):
654 self.assertEqual(self._block(dep5.Group()), "")
655
656 def test_block_single_unnamed_file_returns_empty(self):
657 group = dep5.Group()
658 group.files.add_file(self._file(""))
659 self.assertEqual(self._block(group), "")
660
661 # Files + License, no Copyright
662
663 def test_block_omits_copyright_line_when_no_holders(self):
664 block = self._block(self._group_with_file("src/foo.c", "MIT"))
665 self.assertEqual(block, "Files: src/foo.c\nLicense: MIT")
666 self.assertNotIn("Copyright:", block)
667
668 # full block, all fields
669
670 def test_block_copyright_line_present_with_one_holder(self):
671 group = self._group_with_file("src/foo.c", "MIT")
672 group.add_copyrights(
673 [
674 core_types.CopyrightHolder(
675 "Alice",
676 "[email protected]",
677 core_types.YearRange(2020, 2020),
678 ),
679 ],
680 )
681 self.assertEqual(
682 self._block(group),
683 "Files: src/foo.c\n"
684 "Copyright: 2020, Alice <[email protected]>\n"
685 "License: MIT",
686 )
687
688 def test_block_comment_line_present_when_set(self):
689 group = self._group_with_file("src/foo.c", "MIT")
690 group.add_copyrights(
691 [
692 core_types.CopyrightHolder(
693 "Alice",
694 "[email protected]",
695 core_types.YearRange(2020, 2020),
696 ),
697 ],
698 )
699 group.comments.append("see also COPYING")
700 self.assertEqual(
701 self._block(group),
702 "Files: src/foo.c\n"
703 "Copyright: 2020, Alice <[email protected]>\n"
704 "License: MIT\n"
705 "Comment: see also COPYING",
706 )
707
708 def test_block_omits_comment_line_when_empty(self):
709 block = self._block(self._group_with_file("src/foo.c", "MIT"))
710 self.assertNotIn("Comment:", block)
711
712 # continuation indentation
713
714 def test_block_multiple_files_indented_by_7_spaces(self):
715 group = dep5.Group()
716 for name in ["src/bar.c", "src/foo.c"]:
717 group.files.add_file(self._file(name))
718 group.licenses["MIT"] = core_types.License("MIT")
719 self.assertEqual(
720 self._block(group, glob=False),
721 "Files: src/bar.c\n src/foo.c\nLicense: MIT",
722 )
723
724 def test_block_multiple_holders_indented_by_11_spaces(self):
725 group = self._group_with_file("src/foo.c", "MIT")
726 group.add_copyrights(
727 [
728 core_types.CopyrightHolder(
729 "Alice",
730 "[email protected]",
731 core_types.YearRange(2020, 2020),
732 ),
733 core_types.CopyrightHolder(
734 "Bob",
735 "[email protected]",
736 core_types.YearRange(2021, 2021),
737 ),
738 ],
739 )
740 self.assertEqual(
741 self._block(group),
742 "Files: src/foo.c\n"
743 "Copyright: 2020, Alice <[email protected]>\n"
744 " 2021, Bob <[email protected]>\n"
745 "License: MIT",
746 )
747
748 # glob_=True vs glob_=False routing
749
750 def test_block_glob_produces_directory_wildcard(self):
751 src = nodes.DirInfo(parent=None, name="src")
752 group = dep5.Group()
753 for name in ["a.c", "b.c"]:
754 group.files.add_file(self._file(name, parent=src))
755 group.licenses["MIT"] = core_types.License("MIT")
756 self.assertEqual(
757 self._block(group),
758 "Files: src/*\nLicense: MIT",
759 )
760
761 def test_block_no_glob_lists_individual_filenames(self):
762 src = nodes.DirInfo(parent=None, name="src")
763 group = dep5.Group()
764 for name in ["b.c", "a.c"]:
765 group.files.add_file(self._file(name, parent=src))
766 group.licenses["MIT"] = core_types.License("MIT")
767 self.assertEqual(
768 self._block(group, glob=False),
769 "Files: src/a.c\n src/b.c\nLicense: MIT",
770 )
771
772 # get_inherited_comment
773
774 def test_inherited_comment_no_filenames_returns_none(self):
775 group = dep5.Group()
776 self.assertIsNone(group.get_inherited_comment())
777
778 def test_inherited_comment_with_stored_returns_none(self):
779 group = dep5.Group()
780 group.license_filenames.add("LICENSE")
781 group.stored = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
782 self.assertIsNone(group.get_inherited_comment())
783
784 def test_stored_accepts_files_paragraph(self):
785 group = dep5.Group()
786 paragraph = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
787 group.stored = paragraph
788 self.assertIsInstance(group.stored, dc.FilesParagraph)
789
790 # extra_fields
791
792 def test_extra_fields_empty_without_stored(self):
793 group = dep5.Group()
794 self.assertEqual(list(group.extra_fields()), [])
795
796 def test_extra_fields_yields_non_standard_stored_fields(self):
797 group = dep5.Group()
798 paragraph = dc.FilesParagraph.create(["*"], "2020 Alice", dc.License("MIT"))
799 paragraph["X-Foo"] = "bar"
800 group.stored = paragraph
801 # The standard Files/Copyright/License/Comment fields are rendered by the
802 # renderer itself; extra_fields exposes only the rest.
803 self.assertEqual(list(group.extra_fields()), [("X-Foo", "bar")])
804
805 def test_inherited_comment_with_filenames_no_stored(self):
806 group = dep5.Group()
807 group.license_filenames.add("LICENSE")
808 comment = group.get_inherited_comment()
809 assert comment is not None
810 self.assertIn("LICENSE", comment)
811 self.assertIn("No explicit license found", comment)
812
813 def test_inherited_comment_multiple_filenames_sorted(self):
814 group = dep5.Group()
815 group.license_filenames.update(["COPYING", "LICENSE", "AUTHORS"])
816 comment = group.get_inherited_comment()
817 assert comment is not None
818 lines = comment.splitlines()
819 # First line is the header; remaining lines contain sorted filenames
820 self.assertIn("No explicit license found", lines[0])
821 filenames_in_comment = [line.strip() for line in lines[1:]]
822 self.assertEqual(filenames_in_comment, ["AUTHORS", "COPYING", "LICENSE"])
823
824
825 class TestGroupSortKey(unittest.TestCase):
826 """Unit tests for Group.sort_key() output ordering.
827
828 sort_key() returns a tuple used by an ascending sort in output.py.
829 A smaller sort_key means the group appears earlier (higher) in the output.
830
831 Structure: (debian_group, -position, -n_files, -n_copyrights, group_key)
832 debian_group=0 normal groups → first in output
833 debian_group=1 UNKNOWN* licenses → middle
834 debian_group=2 debian/ when split → last in output
835 """
836
837 def setUp(self):
838 self.root = nodes.DirInfo(parent=None, name="")
839 self.debian_dir = nodes.DirInfo(parent=self.root, name="debian")
840 self.src_dir = nodes.DirInfo(parent=self.root, name="src")
841
842 def _opts(self, *, split_debian=True):
843 flags = ["--no-progress", "--root", "tests/testdata/one"]
844 if not split_debian:
845 flags.append("--no-split-debian")
846 return cmdoptions.process_options(flags)
847
848 def _group(self, license_name=None, position=0, parent=None, n_files=1):
849 """Create a Group with n_files under the given DirInfo parent."""
850 group = dep5.Group(position=position)
851 parent = parent if parent is not None else self.root
852 for i in range(n_files):
853 group.files.add_file(nodes.FileInfo(parent=parent, name=f"f{i}.txt"))
854 if license_name:
855 group.licenses[license_name] = core_types.License(license_name)
856 return group
857
858 # UNKNOWN/UNKNOWN_COPYRIGHTED
859
860 def test_unknown_license_sorts_after_real_license(self):
861 opts = self._opts()
862 real = self._group("MIT")
863 unknown = self._group()
864 self.assertEqual(unknown.license, core_types.UNKNOWN)
865 self.assertGreater(unknown.sort_key(opts), real.sort_key(opts))
866
867 def test_unknown_copyrighted_sorts_after_real_license(self):
868 opts = self._opts()
869 real = self._group("MIT")
870 unk_cop = self._group()
871 unk_cop.add_copyrights([core_types.CopyrightHolder("", "[email protected]")])
872 self.assertEqual(unk_cop.license, core_types.UNKNOWN_COPYRIGHTED)
873 self.assertGreater(unk_cop.sort_key(opts), real.sort_key(opts))
874
875 def test_unknown_and_unknown_copyrighted_share_same_band(self):
876 opts = self._opts()
877 unknown = self._group()
878 unk_cop = self._group()
879 unk_cop.add_copyrights([core_types.CopyrightHolder("", "[email protected]")])
880 # Both land in debian_group=1
881 self.assertEqual(unknown.sort_key(opts)[0], 1)
882 self.assertEqual(unk_cop.sort_key(opts)[0], 1)
883
884 # split_debian flag
885
886 def test_debian_group_sorts_last_with_split_debian(self):
887 opts = self._opts(split_debian=True)
888 debian = self._group("MIT", parent=self.debian_dir)
889 normal = self._group("MIT", parent=self.src_dir)
890 self.assertGreater(debian.sort_key(opts), normal.sort_key(opts))
891
892 def test_debian_group_sorts_after_unknown_with_split_debian(self):
893 opts = self._opts(split_debian=True)
894 debian = self._group("MIT", parent=self.debian_dir)
895 unknown = self._group(parent=self.src_dir)
896 # Full three-way ordering: normal(0) < UNKNOWN(1) < debian(2)
897 self.assertGreater(debian.sort_key(opts), unknown.sort_key(opts))
898
899 def test_debian_group_not_special_without_split_debian(self):
900 opts = self._opts(split_debian=False)
901 debian = self._group("MIT", parent=self.debian_dir)
902 normal = self._group("MIT", parent=self.src_dir)
903 # Both land in debian_group=0 when the flag is off
904 self.assertEqual(debian.sort_key(opts)[0], 0)
905 self.assertEqual(normal.sort_key(opts)[0], 0)
906
907 # position-based secondary sort
908
909 def test_higher_position_sorts_before_lower_position(self):
910 opts = self._opts()
911 low = self._group("MIT", position=0)
912 high = self._group("MIT", position=3)
913 # -3 < 0 → high-position group has smaller sort_key → appears first
914 self.assertLess(high.sort_key(opts), low.sort_key(opts))
915
916 def test_position_ordering_across_multiple_groups(self):
917 opts = self._opts()
918 groups = [self._group("MIT", position=p) for p in [0, 2, 1]]
919 ordered = sorted(groups, key=lambda g: g.sort_key(opts))
920 self.assertEqual([g.position for g in ordered], [2, 1, 0])
921
922 # file-count secondary sort
923
924 def test_more_files_sorts_before_fewer_files(self):
925 opts = self._opts()
926 few = self._group("MIT", n_files=1)
927 many = self._group("MIT", n_files=3)
928 # -3 < -1 → larger group has smaller sort_key → appears first
929 self.assertLess(many.sort_key(opts), few.sort_key(opts))
930
931 # full priority end-to-end sort
932
933 def test_full_sort_order_normal_then_unknown_then_debian(self):
934 opts = self._opts(split_debian=True)
935 g_real = self._group("MIT", position=0, parent=self.src_dir)
936 g_unk = self._group(position=0, parent=self.src_dir)
937 g_deb = self._group("MIT", position=0, parent=self.debian_dir)
938
939 ordered = sorted([g_deb, g_unk, g_real], key=lambda g: g.sort_key(opts))
940
941 self.assertIs(ordered[0], g_real)
942 self.assertIs(ordered[1], g_unk)
943 self.assertIs(ordered[2], g_deb)
944
945
946 class TestGroupKeyIgnoreCopyright(unittest.TestCase):
947 """get_key(ignore_copyright=True) blanks only the copyright slot."""
948
949 def test_ignore_copyright_blanks_only_the_copyright_slot(self):
950 options = cmdoptions.process_options(
951 [
952 "--no-progress",
953 "--root",
954 "tests/testdata/one",
955 "--group-by",
956 "copyright",
957 ]
958 )
959 root = nodes.DirInfo(parent=None, name="")
960 group = Group()
961 fileinfo = nodes.FileInfo(parent=root, name="a.txt")
962 fileinfo.add_licenses(["MIT"])
963 fileinfo.add_copyrights([core_types.CopyrightHolder("Alice", "alice@x")])
964 group.add_file(fileinfo)
965
966 full = group.get_key(options)
967 masked = group.get_key(options, ignore_copyright=True)
968
969 # The copyright slot is populated under copyright grouping...
970 self.assertNotEqual(full[1], ())
971 # ...and masking blanks only that slot, leaving licence and path intact.
972 self.assertEqual(masked, (full[0], (), full[2]))
973
974
975 class TestResolveCopyrightPath(unittest.TestCase):
976 """The single copyright-file path resolver shared by build/_read_header/CLI."""
977
978 @staticmethod
979 def _options(root, copyright_file):
980 return cmdoptions.process_options(
981 ["--no-progress", "--root", root, "--copyright-file", copyright_file]
982 )
983
984 def test_relative_is_joined_to_root(self):
985 with tempfile.TemporaryDirectory() as tmp:
986 options = self._options(tmp, "debian/copyright")
987 self.assertEqual(
988 copyright_processor.resolve_copyright_path(options),
989 Path(options.root) / "debian/copyright",
990 )
991
992 def test_absolute_is_returned_unchanged(self):
993 with tempfile.TemporaryDirectory() as tmp:
994 absolute = str(Path(tmp) / "elsewhere" / "copyright")
995 options = self._options(tmp, absolute)
996 self.assertEqual(
997 copyright_processor.resolve_copyright_path(options),
998 Path(absolute),
999 )
1000
1001 def test_relpath_is_relative_to_root(self):
1002 with tempfile.TemporaryDirectory() as tmp:
1003 options = self._options(tmp, "debian/copyright")
1004 self.assertEqual(
1005 decopy_main._copyright_relpath(options), "debian/copyright"
1006 )
1007
1008 def test_relpath_outside_root_falls_back_to_full_path(self):
1009 with tempfile.TemporaryDirectory() as tmp:
1010 outside = "/some/other/copyright"
1011 options = self._options(tmp, outside)
1012 self.assertEqual(decopy_main._copyright_relpath(options), outside)
1013
1014
1015 if __name__ == "__main__":
1016 unittest.main()