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
97 _CURRENT_FORMAT = (
98 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
99 )
100
101
102 class TestGenerateOutputDocument(unittest.TestCase):
103 """Characterization tests for the full generate_output document.
104
105 These pin the document assembly (header, blank-line separators, file
106 paragraphs ordered by sort_key, trailing license stanzas) before the
107 Renderer refactor moves that orchestration behind a protocol.
108 """
109
110 def setUp(self):
111 self.tree = tree.RootInfo(root=".")
112
113 def _run(self, groups, copyright_, args):
114 options = cmdoptions.process_options(args)
115 with patch.multiple(
116 sys,
117 stdout=DEFAULT,
118 stderr=DEFAULT,
119 new_callable=io.StringIO,
120 ) as _sys:
121 output.generate_output(
122 groups, self.tree, copyright_, options, Dep5Renderer()
123 )
124 mocks = t.cast(dict, _sys)
125 return (
126 mocks["stdout"].getvalue(),
127 mocks["stderr"].getvalue(),
128 )
129
130 def _two_groups(self, options):
131 """An MIT group (two files under src/) and a GPL-2 group (README)."""
132 root = nodes.DirInfo(parent=None, name="")
133 src = nodes.DirInfo(parent=root, name="src")
134 root.file_list["src"] = src
135 mit = dep5.Group(position=1)
136 for name in ("a.c", "b.c"):
137 f = nodes.FileInfo(parent=src, name=name)
138 f.add_licenses(["MIT"])
139 f.add_copyrights([CopyrightHolder("Alice", "alice@x")])
140 mit.add_file(f)
141 gpl = dep5.Group(position=0)
142 readme = nodes.FileInfo(parent=root, name="README")
143 readme.add_licenses(["GPL-2"])
144 readme.add_copyrights([CopyrightHolder("Bob", "bob@x")])
145 gpl.add_file(readme)
146 return {mit.get_key(options): mit, gpl.get_key(options): gpl}
147
148 def test_full_document_no_glob(self):
149 args = ["--no-progress", "--root", "tests/testdata/one", "--no-glob"]
150 options = cmdoptions.process_options(args)
151 out, err = self._run(self._two_groups(options), None, args)
152 self.assertEqual(err, "")
153 self.assertEqual(
154 out,
155 _CURRENT_FORMAT + "Source: TODO\n"
156 "\n"
157 "Files: src/a.c\n"
158 " src/b.c\n"
159 "Copyright: Alice <alice@x>\n"
160 "License: MIT\n"
161 "\n"
162 "Files: README\n"
163 "Copyright: Bob <bob@x>\n"
164 "License: GPL-2\n"
165 "\n"
166 "License: GPL-2\n"
167 "Comment: Add the corresponding license text here\n"
168 "\n"
169 "License: MIT\n"
170 "Comment: Add the corresponding license text here\n",
171 )
172
173 def test_glob_collapses_full_subtree_to_star(self):
174 args = ["--no-progress", "--root", "tests/testdata/one", "--glob"]
175 options = cmdoptions.process_options(args)
176 root = nodes.DirInfo(parent=None, name="")
177 src = nodes.DirInfo(parent=root, name="src")
178 root.file_list["src"] = src
179 group = dep5.Group(position=0)
180 for name in ("a.c", "b.c"):
181 f = nodes.FileInfo(parent=src, name=name)
182 f.add_licenses(["MIT"])
183 group.add_file(f)
184 out, err = self._run({group.get_key(options): group}, None, args)
185 self.assertEqual(err, "")
186 self.assertIn("Files: *\n", out)
187 self.assertNotIn("src/a.c", out)
188
189 def test_empty_copyright_object_renders_todo_source(self):
190 out, err = self._run(
191 {}, dep5.Copyright(), ["--no-progress", "--root", "tests/testdata/one"]
192 )
193 self.assertEqual(err, "")
194 self.assertEqual(out, _CURRENT_FORMAT + "Source: TODO\n")
195
196 def test_existing_copyright_header_overrides_format_keeps_fields(self):
197 text = (
198 "Format: https://example.org/old-format\n"
199 "Upstream-Name: example\n"
200 "Source: https://example.org/dl\n"
201 )
202 # Build outside the stdout/stderr patch so the loader's "format not
203 # known" warning is not captured by the output assertion.
204 with contextlib.redirect_stderr(io.StringIO()):
205 copyright_ = dep5.Copyright(dc.Copyright(io.StringIO(text), strict=False))
206 out, _ = self._run(
207 {}, copyright_, ["--no-progress", "--root", "tests/testdata/one"]
208 )
209 self.assertEqual(
210 out,
211 _CURRENT_FORMAT + "Upstream-Name: example\n"
212 "Source: https://example.org/dl\n",
213 )
214
215
216 class TestFillLicensesIntegration(unittest.TestCase):
217 """End-to-end: the License-stanza body the resolver fills, driven through
218 generate_output with the real renderer (renderer_for), as main() does."""
219
220 def setUp(self):
221 self.tree = tree.RootInfo(root=".")
222
223 def _run(self, licence, extra_args):
224 args = ["--no-progress", "--root", "tests/testdata/one", "--no-glob"]
225 args += extra_args
226 options = cmdoptions.process_options(args)
227 root = nodes.DirInfo(parent=None, name="")
228 readme = nodes.FileInfo(parent=root, name="README")
229 readme.add_licenses([licence])
230 readme.add_copyrights([CopyrightHolder("Bob", "bob@x")])
231 group = dep5.Group(position=0)
232 group.add_file(readme)
233 groups = {group.get_key(options): group}
234 with patch.multiple(
235 sys, stdout=DEFAULT, stderr=DEFAULT, new_callable=io.StringIO
236 ) as _sys:
237 output.generate_output(
238 groups, self.tree, None, options, renderer_for(options)
239 )
240 mocks = t.cast(dict, _sys)
241 return mocks["stdout"].getvalue(), mocks["stderr"].getvalue()
242
243 def test_gpl2_stanza_carries_common_licenses_reference(self):
244 out, err = self._run("GPL-2", [])
245 self.assertEqual(err, "")
246 self.assertIn("License: GPL-2\n", out)
247 self.assertIn("/usr/share/common-licenses/GPL-2'", out)
248 self.assertNotIn("Add the corresponding license text here", out)
249
250 def test_no_fill_licenses_keeps_placeholder(self):
251 out, err = self._run("GPL-2", ["--no-fill-licenses"])
252 self.assertEqual(err, "")
253 self.assertIn(
254 "License: GPL-2\nComment: Add the corresponding license text here", out
255 )
256 self.assertNotIn("/usr/share/common-licenses", out)
257
258 def test_embedded_full_text_stanza(self):
259 # A short licence not in common-licenses gets its verbatim text embedded.
260 out, err = self._run("Expat", [])
261 self.assertEqual(err, "")
262 self.assertIn("License: Expat\n", out)
263 self.assertIn("Permission is hereby granted, free of charge", out)
264 self.assertNotIn("Add the corresponding license text here", out)
265
266 def test_spdx_converts_name_but_body_keys_on_dep5(self):
267 out, err = self._run("GPL-2", ["--spdx"])
268 self.assertEqual(err, "")
269 # The stanza name is SPDX-converted...
270 self.assertIn("License: GPL-2.0-only\n", out)
271 self.assertNotIn("License: GPL-2\n", out)
272 # ...but the body still resolves from the DEP-5 name (GPL-2 reference).
273 self.assertIn("/usr/share/common-licenses/GPL-2'", out)
274
275
276 class TestGenerateOutputDebugLogging(unittest.TestCase):
277 """The 'Generated ...' debug logs fire only when writing to a real file.
278
279 Writing to stdout must not echo the same text into the log stream.
280 """
281
282 def setUp(self):
283 self.tree = tree.RootInfo(root=".")
284
285 def _one_group(self, options):
286 root = nodes.DirInfo(parent=None, name="")
287 group = dep5.Group(position=0)
288 f = nodes.FileInfo(parent=root, name="README")
289 f.add_licenses(["MIT"])
290 f.add_copyrights([CopyrightHolder("Alice", "alice@x")])
291 group.add_file(f)
292 return {group.get_key(options): group}
293
294 def _generated_labels(self, args):
295 options = cmdoptions.process_options(args)
296 groups = self._one_group(options)
297 with patch.object(output.logger, "debug") as mock_debug:
298 output.generate_output(groups, self.tree, None, options, Dep5Renderer())
299 return [
300 call.args[0] % call.args[1:]
301 for call in mock_debug.call_args_list
302 if call.args and "Generated" in call.args[0]
303 ]
304
305 def test_file_output_logs_every_generated_block(self):
306 with tempfile.TemporaryDirectory() as tmp:
307 path = str(Path(tmp) / "copyright")
308 labels = self._generated_labels(
309 ["--no-progress", "--root", "tests/testdata/one", "-o", path]
310 )
311 joined = "\n".join(labels)
312 self.assertIn("Generated header", joined)
313 self.assertIn("Generated group", joined)
314 self.assertIn("Generated license block", joined)
315
316 def test_stdout_output_logs_no_generated_blocks(self):
317 with patch.multiple(
318 sys, stdout=DEFAULT, stderr=DEFAULT, new_callable=io.StringIO
319 ):
320 labels = self._generated_labels(
321 ["--no-progress", "--root", "tests/testdata/one"]
322 )
323 self.assertEqual(labels, [])
324
325
326 if __name__ == "__main__":
327 unittest.main()