Debian Codegraph @

tests/parsers_test.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Tests for parsers.py - verifies return shapes and helper behaviour."""
18
19 import bz2
20 import gzip
21 import lzma
22 import re
23 import shutil
24 import subprocess
25 import tempfile
26 import unittest
27 import warnings
28 from pathlib import Path
29
30 import xdg.Mime
31
32 from decopy.common.core_types import CopyrightHolder, Options
33 from decopy.fstree import parsers
34
35
36 def _make_options(**kwargs) -> Options:
37 defaults: dict = {
38 "mode": "full",
39 "copyright_file": "debian/copyright",
40 "debug": False,
41 "text": True,
42 "group_by": "license",
43 "split_on_license": False,
44 "split_debian": False,
45 "glob": False,
46 "progress": False,
47 "jobs": 1,
48 "output": "",
49 "root": ".",
50 "files": [],
51 "exclude_fullname_re": re.compile(""),
52 "exclude_special_re": re.compile(""),
53 "exclude_file_re": re.compile(""),
54 "exclude_directory_re": re.compile(""),
55 }
56 defaults.update(kwargs)
57 return Options(**defaults)
58
59
60 class TestParseFile(unittest.TestCase):
61 """parse_file returns (list[CopyrightHolder], ValuesView[str])."""
62
63 def test_returns_tuple_of_list_and_iterable_of_strings(self):
64 options = _make_options(text=True)
65 holders, licenses = parsers.parse_file("tests/testdata/one/bsd.txt", options)
66 self.assertIsInstance(holders, list)
67 for lic in licenses:
68 self.assertIsInstance(lic, str)
69
70 def test_holders_are_copyright_holder_instances(self):
71 options = _make_options(text=True)
72 # decopy source files carry copyright headers and are always available;
73 # use the imported module's own file so this works both in-tree and
74 # when running against the installed package (e.g. autopkgtest).
75 assert parsers.__file__ is not None
76 holders, _ = parsers.parse_file(parsers.__file__, options)
77 self.assertGreater(len(holders), 0)
78 for holder in holders:
79 self.assertIsInstance(holder, CopyrightHolder)
80
81 def test_empty_file_returns_empty_holders(self):
82 options = _make_options(text=True)
83 holders, _ = parsers.parse_file("tests/testdata/one/empty.txt", options)
84 self.assertIsInstance(holders, list)
85 self.assertEqual(holders, [])
86
87 def test_binary_file_is_skipped(self):
88 options = _make_options(text=False)
89 with tempfile.NamedTemporaryFile(suffix=".o", delete=False) as f:
90 f.write(b"\x7fELF\x00\x00Copyright 2024 Ghost <[email protected]>\x00")
91 path = f.name
92 try:
93 holders, _ = parsers.parse_file(path, options)
94 self.assertEqual(holders, [])
95 finally:
96 Path(path).unlink()
97
98
99 class TestHasControlChars(unittest.TestCase):
100 """has_control_chars identifies binary-like byte sequences."""
101
102 def test_printable_bytes_returns_false(self):
103 self.assertFalse(parsers.has_control_chars(b"hello world\n"))
104
105 def test_tab_lf_cr_are_allowed(self):
106 self.assertFalse(parsers.has_control_chars(b"\t\n\r"))
107
108 def test_null_byte_returns_true(self):
109 self.assertTrue(parsers.has_control_chars(b"hello\x00world"))
110
111 def test_del_returns_true(self):
112 self.assertTrue(parsers.has_control_chars(b"hello\x7fworld"))
113
114 def test_other_control_char_returns_true(self):
115 self.assertTrue(parsers.has_control_chars(b"hello\x01world"))
116
117
118 _COPYRIGHT_BYTES = (
119 b"# Copyright (C) 2024 Test Author <[email protected]>\n"
120 b"# SPDX-License-Identifier: MIT\n"
121 )
122
123
124 class TestParserDispatch(unittest.TestCase):
125 """lookup_mimetypes routes each compression MIME type to the correct parser."""
126
127 def _lookup(self, ext: str) -> parsers.ParserFunc:
128 return parsers.lookup_mimetypes(xdg.Mime.get_type(f"dummy{ext}"))
129
130 def test_gz_uses_zcat(self):
131 self.assertIs(self._lookup(".gz"), parsers.cmd_parser_factory("zcat"))
132
133 def test_bz2_uses_bzcat(self):
134 self.assertIs(self._lookup(".bz2"), parsers.cmd_parser_factory("bzcat"))
135
136 def test_xz_uses_xzcat(self):
137 self.assertIs(self._lookup(".xz"), parsers.cmd_parser_factory("xzcat"))
138
139 def test_lzma_uses_xzcat(self):
140 self.assertIs(self._lookup(".lzma"), parsers.cmd_parser_factory("xzcat"))
141
142 def test_zst_uses_zstdcat(self):
143 self.assertIs(self._lookup(".zst"), parsers.cmd_parser_factory("zstdcat"))
144
145 def test_lz_uses_lzip(self):
146 self.assertIs(
147 self._lookup(".lz"), parsers.cmd_parser_factory("lzip", "-d", "-c")
148 )
149
150 def test_bz3_uses_bzip3(self):
151 self.assertIs(self._lookup(".bz3"), parsers.cmd_parser_factory("bzip3", "-d"))
152
153
154 class TestCompressedFileParsing(unittest.TestCase):
155 """parse_file decompresses and extracts copyright info from compressed files."""
156
157 def _parse(self, suffix: str, data: bytes) -> tuple:
158 options = _make_options(text=False)
159 with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
160 f.write(data)
161 fname = f.name
162 try:
163 return parsers.parse_file(fname, options)
164 finally:
165 Path(fname).unlink()
166
167 def _has_author(self, holders: list) -> bool:
168 return any("Test Author" in str(h) for h in holders)
169
170 def test_gz(self):
171 holders, _ = self._parse(".gz", gzip.compress(_COPYRIGHT_BYTES))
172 self.assertTrue(self._has_author(holders))
173
174 def test_bz2(self):
175 holders, _ = self._parse(".bz2", bz2.compress(_COPYRIGHT_BYTES))
176 self.assertTrue(self._has_author(holders))
177
178 def test_xz(self):
179 data = lzma.compress(_COPYRIGHT_BYTES, format=lzma.FORMAT_XZ)
180 holders, _ = self._parse(".xz", data)
181 self.assertTrue(self._has_author(holders))
182
183 def test_lzma(self):
184 data = lzma.compress(_COPYRIGHT_BYTES, format=lzma.FORMAT_ALONE)
185 holders, _ = self._parse(".lzma", data)
186 self.assertTrue(self._has_author(holders))
187
188 @unittest.skipUnless(
189 shutil.which("zstd") and shutil.which("zstdcat"), "zstd not installed"
190 )
191 def test_zst(self):
192 zstd = shutil.which("zstd")
193 assert zstd is not None
194 result = subprocess.run( # noqa: S603
195 [zstd, "--quiet", "--stdout"],
196 input=_COPYRIGHT_BYTES,
197 capture_output=True,
198 check=True,
199 )
200 holders, _ = self._parse(".zst", result.stdout)
201 self.assertTrue(self._has_author(holders))
202
203 @unittest.skipUnless(shutil.which("lzip"), "lzip not installed")
204 def test_lz(self):
205 lzip = shutil.which("lzip")
206 assert lzip is not None
207 result = subprocess.run( # noqa: S603
208 [lzip, "-c"],
209 input=_COPYRIGHT_BYTES,
210 capture_output=True,
211 check=True,
212 )
213 holders, _ = self._parse(".lz", result.stdout)
214 self.assertTrue(self._has_author(holders))
215
216
217 _PY_SNIPPET = b"# Copyright (C) 2024 Alice <[email protected]>\n"
218 _HTML_SNIPPET = b"<!-- Copyright 2024 Bob <[email protected]> -->\n<html></html>"
219 _PO_SNIPPET = (
220 b"# Copyright 2024 Carol <[email protected]>\n"
221 b"# Translator: Dave\n"
222 b'msgid "hello"\n'
223 b'msgstr ""\n'
224 )
225
226
227 class TestDetectMimeByMagic(unittest.TestCase):
228 """detect_mime_by_magic identifies format from header bytes."""
229
230 def test_python_shebang(self):
231 self.assertEqual(
232 parsers.detect_mime_by_magic(b"#!/usr/bin/python3\n"), "text/x-python"
233 )
234
235 def test_env_python_shebang(self):
236 self.assertEqual(
237 parsers.detect_mime_by_magic(b"#!/usr/bin/env python3\n"), "text/x-python"
238 )
239
240 def test_perl_shebang(self):
241 self.assertEqual(
242 parsers.detect_mime_by_magic(b"#!/usr/bin/perl\n"), "text/x-perl"
243 )
244
245 def test_xml_declaration(self):
246 self.assertEqual(
247 parsers.detect_mime_by_magic(b"<?xml version='1.0'?>"), "text/xml"
248 )
249
250 def test_html_doctype(self):
251 self.assertEqual(parsers.detect_mime_by_magic(b"<!DOCTYPE html>"), "text/html")
252
253 def test_html_tag(self):
254 self.assertEqual(parsers.detect_mime_by_magic(b"<html>"), "text/html")
255
256 def test_html_tag_case_insensitive(self):
257 self.assertEqual(parsers.detect_mime_by_magic(b"<HTML>"), "text/html")
258
259 def test_leading_whitespace_before_html(self):
260 self.assertEqual(parsers.detect_mime_by_magic(b" <html>"), "text/html")
261
262 def test_non_python_shebang_returns_none(self):
263 self.assertIsNone(parsers.detect_mime_by_magic(b"#!/bin/bash\necho hello"))
264
265 def test_unknown_returns_none(self):
266 self.assertIsNone(parsers.detect_mime_by_magic(b"Hello, world!"))
267
268 def test_empty_returns_none(self):
269 self.assertIsNone(parsers.detect_mime_by_magic(b""))
270
271
272 class TestContentParsers(unittest.TestCase):
273 """Unit tests for the _*_content_parser helpers."""
274
275 def test_generic_extracts_copyright(self):
276 data = b"# Copyright 2024 Eve <[email protected]>\n"
277 holders, _ = parsers.generic_content_parser("test.txt", data)
278 self.assertTrue(any("Eve" in str(h) for h in holders))
279
280 def test_html_extracts_copyright_from_comment(self):
281 holders, _ = parsers.html_content_parser("test.html", _HTML_SNIPPET)
282 self.assertTrue(any("Bob" in str(h) for h in holders))
283
284 def test_html_does_not_crash_on_bad_entities(self):
285 holders, _ = parsers.html_content_parser(
286 "test.html", b"<!-- Copyright &amp;&amp; -->\n"
287 )
288 self.assertIsInstance(holders, list)
289
290 def test_po_extracts_copyright_from_comment(self):
291 holders, _ = parsers.po_content_parser("test.po", _PO_SNIPPET)
292 self.assertTrue(any("Carol" in str(h) for h in holders))
293
294 def test_po_ignores_msgid_lines(self):
295 holders, _ = parsers.po_content_parser("test.po", _PO_SNIPPET)
296 all_text = " ".join(str(h) for h in holders)
297 self.assertNotIn("hello", all_text)
298
299 def test_python_extracts_copyright_from_comment(self):
300 holders, _ = parsers.python_content_parser("test.py", _PY_SNIPPET)
301 self.assertTrue(any("Alice" in str(h) for h in holders))
302
303 def test_python_falls_back_on_invalid_syntax(self):
304 holders, _ = parsers.python_content_parser("bad.py", b"\xff\xfe garbage ~~~")
305 self.assertIsInstance(holders, list)
306
307 def test_python_invalid_escape_emits_no_syntaxwarning(self):
308 # Foreign source (e.g. ruff fixtures) may contain invalid escape
309 # sequences such as f"\{x}". Tokenizing it to extract comments must not
310 # leak a SyntaxWarning to the user's stderr.
311 data = b'# Copyright 2024 Alice <[email protected]>\nx = f"\\{foo}\\{bar:\\}"\n'
312 with warnings.catch_warnings(record=True) as caught:
313 warnings.simplefilter("always")
314 parsers.python_content_parser("frag.py", data)
315 leaked = [w for w in caught if issubclass(w.category, SyntaxWarning)]
316 self.assertFalse(leaked, "tokenizing foreign source leaked a SyntaxWarning")
317
318
319 class TestLookupContentParser(unittest.TestCase):
320 """lookup_content_parser routes MIME types to content parsers."""
321
322 def _lookup(self, ext: str) -> parsers.ContentParserFunc:
323 return parsers.lookup_content_parser(xdg.Mime.get_type(f"dummy{ext}"))
324
325 def test_python_uses_python_content_parser(self):
326 self.assertIs(self._lookup(".py"), parsers.python_content_parser)
327
328 def test_html_uses_html_content_parser(self):
329 self.assertIs(self._lookup(".html"), parsers.html_content_parser)
330
331 def test_po_uses_po_content_parser(self):
332 self.assertIs(self._lookup(".po"), parsers.po_content_parser)
333
334 def test_gz_uses_cmd_content_parser_factory_result(self):
335 parser = self._lookup(".gz")
336 self.assertIs(parser, parsers.cmd_content_parser_factory("zcat"))
337
338 def test_tar_uses_generic_content_parser(self):
339 self.assertIs(self._lookup(".tar"), parsers.generic_content_parser)
340
341 def test_unknown_extension_falls_back_to_generic(self):
342 self.assertIs(self._lookup(".xyzzy_unknown"), parsers.generic_content_parser)
343
344
345 class TestUnifiedParserRegistry(unittest.TestCase):
346 """One registry of Parser objects; the path/bytes lookups are views over it."""
347
348 def test_registry_holds_parser_objects(self):
349 self.assertTrue(parsers.KNOWN_PARSERS)
350 self.assertTrue(
351 all(isinstance(p, parsers.Parser) for p in parsers.KNOWN_PARSERS.values())
352 )
353
354 def test_lookup_parser_pairs_both_entry_points(self):
355 p = parsers.lookup_parser(xdg.Mime.get_type("dummy.gz"))
356 self.assertIs(p.from_path, parsers.cmd_parser_factory("zcat"))
357 self.assertIs(p.from_bytes, parsers.cmd_content_parser_factory("zcat"))
358
359 def test_lookups_are_views_over_lookup_parser(self):
360 xt = xdg.Mime.get_type("dummy.py")
361 p = parsers.lookup_parser(xt)
362 self.assertIs(parsers.lookup_mimetypes(xt), p.from_path)
363 self.assertIs(parsers.lookup_content_parser(xt), p.from_bytes)
364
365 def test_unknown_falls_back_to_generic_parser_object(self):
366 p = parsers.lookup_parser(xdg.Mime.get_type("dummy.xyzzy_unknown"))
367 self.assertIs(p.from_path, parsers.generic_parser)
368 self.assertIs(p.from_bytes, parsers.generic_content_parser)
369
370
371 class TestParseContentBytes(unittest.TestCase):
372 """parse_content_bytes integration: dispatch and result shape."""
373
374 def test_text_mode_uses_generic_regardless_of_extension(self):
375 opts = _make_options(text=True)
376 data = b"# Copyright 2024 Grace <[email protected]>\n"
377 holders, _ = parsers.parse_content_bytes("script.py", data, opts)
378 self.assertTrue(any("Grace" in str(h) for h in holders))
379
380 def test_python_extension_finds_copyright(self):
381 opts = _make_options(text=False)
382 data = b"# Copyright 2024 Henry <[email protected]>\n"
383 holders, _ = parsers.parse_content_bytes("script.py", data, opts)
384 self.assertTrue(any("Henry" in str(h) for h in holders))
385
386 def test_magic_detection_shebang_for_extensionless_file(self):
387 opts = _make_options(text=False)
388 data = b"#!/usr/bin/python3\n# Copyright 2024 Iris <[email protected]>\n"
389 holders, _ = parsers.parse_content_bytes("Makefile", data, opts)
390 self.assertTrue(any("Iris" in str(h) for h in holders))
391
392 def test_returns_list_and_iterable_for_empty_bytes(self):
393 opts = _make_options(text=False)
394 holders, licenses = parsers.parse_content_bytes("empty.txt", b"", opts)
395 self.assertIsInstance(holders, list)
396 for lic in licenses:
397 self.assertIsInstance(lic, str)
398
399 def test_binary_content_is_skipped(self):
400 opts = _make_options(text=False)
401 data = b"\x7fELF\x00\x00Copyright 2024 Ghost <[email protected]>\x00"
402 holders, _ = parsers.parse_content_bytes("blob.o", data, opts)
403 self.assertEqual(holders, [])
404
405 def test_binary_skip_not_applied_in_text_mode(self):
406 # --text forces text handling; honour it even for binary bytes.
407 opts = _make_options(text=True)
408 data = b"\x00 Copyright 2024 Ghost <[email protected]>\x00"
409 holders, _ = parsers.parse_content_bytes("blob.o", data, opts)
410 self.assertTrue(any("Ghost" in str(h) for h in holders))
411
412 def test_text_with_unknown_mime_still_scanned(self):
413 opts = _make_options(text=False)
414 data = b"Copyright 2024 Henry <[email protected]>\n"
415 holders, _ = parsers.parse_content_bytes("notes.xyz", data, opts)
416 self.assertTrue(any("Henry" in str(h) for h in holders))
417
418 def test_utf16_bom_text_not_skipped(self):
419 # UTF-16 text legitimately contains NUL bytes; the BOM exempts it.
420 opts = _make_options(text=False)
421 data = "Copyright 2024 Ivy <[email protected]>".encode("utf-16")
422 holders, _ = parsers.parse_content_bytes("blob.o", data, opts)
423 self.assertTrue(any("Ivy" in str(h) for h in holders))
424
425
426 if __name__ == "__main__":
427 unittest.main()