Debian Codegraph @

tests/output_test.py

raw
1 #!/usr/bin/env python3
2
3 # Unit tests for decopy
4 # Copyright: 2016, Maximiliano Curia <[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 contextlib
20 import io
21 import sys
22 import tempfile
23 import typing as t
24 import unittest
25 from pathlib import Path
26 from unittest.mock import DEFAULT, patch
27
28 import debian.copyright as dc
29
30 from decopy import cmdoptions
31 from decopy.common.core_types import CopyrightHolder
32 from decopy.dep5doc import dep5, output
33 from decopy.dep5doc.renderer import Dep5Renderer, renderer_for
34 from decopy.fstree import nodes, tree
35
36
37 class TestOutput(unittest.TestCase):
38 def setUp(self):
39 # Create one root with one dir with one file
40 self.tree = tree.RootInfo(root=".")
41 self.groups = {}
42
43 def test_empty(self):
44 groups: dict = {}
45 copyright_ = None
46 options = cmdoptions.process_options([])
47
48 with patch.multiple(
49 sys,
50 stdout=DEFAULT,
51 stderr=DEFAULT,
52 new_callable=io.StringIO,
53 ) as _sys:
54 output.generate_output(
55 groups, self.tree, copyright_, options, Dep5Renderer()
56 )
57 mocks = t.cast(dict, _sys)
58 out = mocks["stdout"].getvalue()
59 err = mocks["stderr"].getvalue()
60 self.assertFalse(len(err), f"Unexpected stderr: {err}")
61 self.assertEqual(
62 out,
63 "Format: https://www.debian.org/doc/"
64 "packaging-manuals/copyright-format/1.0/\n"
65 "Source: TODO\n",
66 f"Unexpected stdout: {out}",
67 )
68
69 def test_empty_partial(self):
70 groups: dict = {}
71 copyright_ = None
72 options = cmdoptions.process_options(["--mode=partial", "."])
73
74 with patch.multiple(
75 sys,
76 stdout=DEFAULT,
77 stderr=DEFAULT,
78 new_callable=io.StringIO,
79 ) as _sys:
80 output.generate_output(
81 groups, self.tree, copyright_, options, Dep5Renderer()
82 )
83 mocks = t.cast(dict, _sys)
84 out = mocks["stdout"].getvalue()
85 err = mocks["stderr"].getvalue()
86 self.assertFalse(len(err), f"Unexpected stderr: {err}")
87 self.assertEqual(
88 out,
89 "Format: https://www.debian.org/doc/"
90 "packaging-manuals/copyright-format/1.0/\n"
91 "Source: TODO\n"
92 "Comment: *** only: . ***\n",
93 f"Unexpected stdout: {out}",
94 )
95
96 def test_partial_file_missing_from_tree(self):
97 """A scoped run naming a path the tree does not hold must not raise.
98
99 git reports paths the walk prunes by name (.gitignore and friends are
100 in the default exclude_file_regex), so changed mode routinely hands
101 generate_output a file that was never added to the tree.
102 """
103 groups: dict = {}
104 copyright_ = None
105
106 # The path has to exist for the argparse type to accept it, but it
107 # must not come from the source tree: the tests also run from the
108 # build directory, which holds no .gitignore.
109 with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
110 Path(".gitignore").touch()
111 options = cmdoptions.process_options(["--mode=partial", ".gitignore"])
112
113 with patch.multiple(
114 sys,
115 stdout=DEFAULT,
116 stderr=DEFAULT,
117 new_callable=io.StringIO,
118 ) as _sys:
119 output.generate_output(
120 groups, self.tree, copyright_, options, Dep5Renderer()
121 )
122 mocks = t.cast(dict, _sys)
123 out = mocks["stdout"].getvalue()
124 err = mocks["stderr"].getvalue()
125 self.assertFalse(len(err), f"Unexpected stderr: {err}")
126 self.assertEqual(
127 out,
128 "Format: https://www.debian.org/doc/"
129 "packaging-manuals/copyright-format/1.0/\n"
130 "Source: TODO\n"
131 "Comment: *** only: .gitignore ***\n",
132 f"Unexpected stdout: {out}",
133 )
134
135
136 _CURRENT_FORMAT = (
137 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
138 )
139
140
141 class TestGenerateOutputDocument(unittest.TestCase):
142 """Characterization tests for the full generate_output document.
143
144 These pin the document assembly (header, blank-line separators, file
145 paragraphs ordered by sort_key, trailing license stanzas) before the
146 Renderer refactor moves that orchestration behind a protocol.
147 """
148
149 def setUp(self):
150 self.tree = tree.RootInfo(root=".")
151
152 def _run(self, groups, copyright_, args):
153 options = cmdoptions.process_options(args)
154 with patch.multiple(
155 sys,
156 stdout=DEFAULT,
157 stderr=DEFAULT,
158 new_callable=io.StringIO,
159 ) as _sys:
160 output.generate_output(
161 groups, self.tree, copyright_, options, Dep5Renderer()
162 )
163 mocks = t.cast(dict, _sys)
164 return (
165 mocks["stdout"].getvalue(),
166 mocks["stderr"].getvalue(),
167 )
168
169 def _two_groups(self, options):
170 """An MIT group (two files under src/) and a GPL-2 group (README)."""
171 root = nodes.DirInfo(parent=None, name="")
172 src = nodes.DirInfo(parent=root, name="src")
173 root.file_list["src"] = src
174 mit = dep5.Group(position=1)
175 for name in ("a.c", "b.c"):
176 f = nodes.FileInfo(parent=src, name=name)
177 f.add_licenses(["MIT"])
178 f.add_copyrights([CopyrightHolder("Alice", "alice@x")])
179 mit.add_file(f)
180 gpl = dep5.Group(position=0)
181 readme = nodes.FileInfo(parent=root, name="README")
182 readme.add_licenses(["GPL-2"])
183 readme.add_copyrights([CopyrightHolder("Bob", "bob@x")])
184 gpl.add_file(readme)
185 return {mit.get_key(options): mit, gpl.get_key(options): gpl}
186
187 def test_full_document_no_glob(self):
188 args = ["--no-progress", "--root", "tests/testdata/one", "--no-glob"]
189 options = cmdoptions.process_options(args)
190 out, err = self._run(self._two_groups(options), None, args)
191 self.assertEqual(err, "")
192 self.assertEqual(
193 out,
194 _CURRENT_FORMAT + "Source: TODO\n"
195 "\n"
196 "Files: src/a.c\n"
197 " src/b.c\n"
198 "Copyright: Alice <alice@x>\n"
199 "License: MIT\n"
200 "\n"
201 "Files: README\n"
202 "Copyright: Bob <bob@x>\n"
203 "License: GPL-2\n"
204 "\n"
205 "License: GPL-2\n"
206 "Comment: Add the corresponding license text here\n"
207 "\n"
208 "License: MIT\n"
209 "Comment: Add the corresponding license text here\n",
210 )
211
212 def test_glob_collapses_full_subtree_to_star(self):
213 args = ["--no-progress", "--root", "tests/testdata/one", "--glob"]
214 options = cmdoptions.process_options(args)
215 root = nodes.DirInfo(parent=None, name="")
216 src = nodes.DirInfo(parent=root, name="src")
217 root.file_list["src"] = src
218 group = dep5.Group(position=0)
219 for name in ("a.c", "b.c"):
220 f = nodes.FileInfo(parent=src, name=name)
221 f.add_licenses(["MIT"])
222 group.add_file(f)
223 out, err = self._run({group.get_key(options): group}, None, args)
224 self.assertEqual(err, "")
225 self.assertIn("Files: *\n", out)
226 self.assertNotIn("src/a.c", out)
227
228 def test_empty_copyright_object_renders_todo_source(self):
229 out, err = self._run(
230 {}, dep5.Copyright(), ["--no-progress", "--root", "tests/testdata/one"]
231 )
232 self.assertEqual(err, "")
233 self.assertEqual(out, _CURRENT_FORMAT + "Source: TODO\n")
234
235 def test_existing_copyright_header_overrides_format_keeps_fields(self):
236 text = (
237 "Format: https://example.org/old-format\n"
238 "Upstream-Name: example\n"
239 "Source: https://example.org/dl\n"
240 )
241 # Build outside the stdout/stderr patch so the loader's "format not
242 # known" warning is not captured by the output assertion.
243 with contextlib.redirect_stderr(io.StringIO()):
244 copyright_ = dep5.Copyright(dc.Copyright(io.StringIO(text), strict=False))
245 out, _ = self._run(
246 {}, copyright_, ["--no-progress", "--root", "tests/testdata/one"]
247 )
248 self.assertEqual(
249 out,
250 _CURRENT_FORMAT + "Upstream-Name: example\n"
251 "Source: https://example.org/dl\n",
252 )
253
254
255 class TestFillLicensesIntegration(unittest.TestCase):
256 """End-to-end: the License-stanza body the resolver fills, driven through
257 generate_output with the real renderer (renderer_for), as main() does."""
258
259 def setUp(self):
260 self.tree = tree.RootInfo(root=".")
261
262 def _run(self, licence, extra_args):
263 args = ["--no-progress", "--root", "tests/testdata/one", "--no-glob"]
264 args += extra_args
265 options = cmdoptions.process_options(args)
266 root = nodes.DirInfo(parent=None, name="")
267 readme = nodes.FileInfo(parent=root, name="README")
268 readme.add_licenses([licence])
269 readme.add_copyrights([CopyrightHolder("Bob", "bob@x")])
270 group = dep5.Group(position=0)
271 group.add_file(readme)
272 groups = {group.get_key(options): group}
273 with patch.multiple(
274 sys, stdout=DEFAULT, stderr=DEFAULT, new_callable=io.StringIO
275 ) as _sys:
276 output.generate_output(
277 groups, self.tree, None, options, renderer_for(options)
278 )
279 mocks = t.cast(dict, _sys)
280 return mocks["stdout"].getvalue(), mocks["stderr"].getvalue()
281
282 def test_gpl2_stanza_carries_common_licenses_reference(self):
283 out, err = self._run("GPL-2", [])
284 self.assertEqual(err, "")
285 self.assertIn("License: GPL-2\n", out)
286 self.assertIn("/usr/share/common-licenses/GPL-2'", out)
287 self.assertNotIn("Add the corresponding license text here", out)
288
289 def test_no_fill_licenses_keeps_placeholder(self):
290 out, err = self._run("GPL-2", ["--no-fill-licenses"])
291 self.assertEqual(err, "")
292 self.assertIn(
293 "License: GPL-2\nComment: Add the corresponding license text here", out
294 )
295 self.assertNotIn("/usr/share/common-licenses", out)
296
297 def test_embedded_full_text_stanza(self):
298 # A short licence not in common-licenses gets its verbatim text embedded.
299 out, err = self._run("Expat", [])
300 self.assertEqual(err, "")
301 self.assertIn("License: Expat\n", out)
302 self.assertIn("Permission is hereby granted, free of charge", out)
303 self.assertNotIn("Add the corresponding license text here", out)
304
305 def test_spdx_converts_name_but_body_keys_on_dep5(self):
306 out, err = self._run("GPL-2", ["--spdx"])
307 self.assertEqual(err, "")
308 # The stanza name is SPDX-converted...
309 self.assertIn("License: GPL-2.0-only\n", out)
310 self.assertNotIn("License: GPL-2\n", out)
311 # ...but the body still resolves from the DEP-5 name (GPL-2 reference).
312 self.assertIn("/usr/share/common-licenses/GPL-2'", out)
313
314
315 class TestGenerateOutputDebugLogging(unittest.TestCase):
316 """The 'Generated ...' debug logs fire only when writing to a real file.
317
318 Writing to stdout must not echo the same text into the log stream.
319 """
320
321 def setUp(self):
322 self.tree = tree.RootInfo(root=".")
323
324 def _one_group(self, options):
325 root = nodes.DirInfo(parent=None, name="")
326 group = dep5.Group(position=0)
327 f = nodes.FileInfo(parent=root, name="README")
328 f.add_licenses(["MIT"])
329 f.add_copyrights([CopyrightHolder("Alice", "alice@x")])
330 group.add_file(f)
331 return {group.get_key(options): group}
332
333 def _generated_labels(self, args):
334 options = cmdoptions.process_options(args)
335 groups = self._one_group(options)
336 with patch.object(output.logger, "debug") as mock_debug:
337 output.generate_output(groups, self.tree, None, options, Dep5Renderer())
338 return [
339 call.args[0] % call.args[1:]
340 for call in mock_debug.call_args_list
341 if call.args and "Generated" in call.args[0]
342 ]
343
344 def test_file_output_logs_every_generated_block(self):
345 with tempfile.TemporaryDirectory() as tmp:
346 path = str(Path(tmp) / "copyright")
347 labels = self._generated_labels(
348 ["--no-progress", "--root", "tests/testdata/one", "-o", path]
349 )
350 joined = "\n".join(labels)
351 self.assertIn("Generated header", joined)
352 self.assertIn("Generated group", joined)
353 self.assertIn("Generated license block", joined)
354
355 def test_stdout_output_logs_no_generated_blocks(self):
356 with patch.multiple(
357 sys, stdout=DEFAULT, stderr=DEFAULT, new_callable=io.StringIO
358 ):
359 labels = self._generated_labels(
360 ["--no-progress", "--root", "tests/testdata/one"]
361 )
362 self.assertEqual(labels, [])
363
364
365 if __name__ == "__main__":
366 unittest.main()