Debian Codegraph @

tests/cmdoptions_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 cmdoptions CLI flags."""
18
19 import dataclasses
20 import tempfile
21 import typing
22 import unittest
23 from pathlib import Path
24
25 from decopy import cmdoptions
26 from decopy.common.core_types import Options
27
28 # The Options-owned defaults the CLI must reuse rather than re-declare.
29 _SHARED_DEFAULT_FIELDS = (
30 "spdx",
31 "explain",
32 "since",
33 "expand_archives",
34 "max_archive_depth",
35 "max_archive_member_size",
36 "use_gitignore",
37 "fill_licenses",
38 "list_license_files",
39 )
40
41
42 def _option_default(name):
43 field = next(f for f in dataclasses.fields(Options) if f.name == name)
44 return field.default
45
46
47 class FillLicensesOptionTest(unittest.TestCase):
48 """Tests for the --fill-licenses / --no-fill-licenses option."""
49
50 _BASE: typing.ClassVar[list[str]] = ["--no-progress", "--root", "."]
51
52 def test_defaults_to_true(self):
53 opts = cmdoptions.process_options(self._BASE)
54 self.assertTrue(opts.fill_licenses)
55
56 def test_no_flag_disables(self):
57 opts = cmdoptions.process_options([*self._BASE, "--no-fill-licenses"])
58 self.assertFalse(opts.fill_licenses)
59
60 def test_flag_enables(self):
61 opts = cmdoptions.process_options([*self._BASE, "--fill-licenses"])
62 self.assertTrue(opts.fill_licenses)
63
64 def test_last_flag_wins(self):
65 opts = cmdoptions.process_options(
66 [*self._BASE, "--fill-licenses", "--no-fill-licenses"]
67 )
68 self.assertFalse(opts.fill_licenses)
69
70 def test_field_is_bool(self):
71 opts = cmdoptions.process_options(self._BASE)
72 self.assertIsInstance(opts, Options)
73 self.assertIs(type(opts.fill_licenses), bool)
74
75
76 class ListLicenseFilesOptionTest(unittest.TestCase):
77 """Tests for the --list-license-files / --no-list-license-files option."""
78
79 _BASE: typing.ClassVar[list[str]] = ["--no-progress", "--root", "."]
80
81 def test_defaults_to_false(self):
82 opts = cmdoptions.process_options(self._BASE)
83 self.assertFalse(opts.list_license_files)
84
85 def test_flag_enables(self):
86 opts = cmdoptions.process_options([*self._BASE, "--list-license-files"])
87 self.assertTrue(opts.list_license_files)
88
89 def test_no_flag_disables(self):
90 opts = cmdoptions.process_options(
91 [*self._BASE, "--list-license-files", "--no-list-license-files"]
92 )
93 self.assertFalse(opts.list_license_files)
94
95
96 class TestProcessOptionsDefaults(unittest.TestCase):
97 """The CLI defaults come from the Options dataclass (single source)."""
98
99 def test_defaults_match_options_dataclass(self):
100 with tempfile.TemporaryDirectory() as tmp:
101 options = cmdoptions.process_options(["--no-progress", "--root", tmp])
102 for name in _SHARED_DEFAULT_FIELDS:
103 self.assertEqual(
104 getattr(options, name),
105 _option_default(name),
106 f"{name}: CLI default diverged from Options default",
107 )
108
109
110 class TestProcessOptionsAssembly(unittest.TestCase):
111 """Characterisation snapshot: a representative argv -> Options field values.
112
113 Pins the parse/assemble behaviour so the process_options decomposition
114 cannot change any produced value.
115 """
116
117 def test_flag_matrix_produces_expected_options(self):
118 with tempfile.TemporaryDirectory() as tmp:
119 options = cmdoptions.process_options(
120 [
121 "--no-progress",
122 "--spdx",
123 "--no-glob",
124 "--group-by",
125 "copyright",
126 "--mode",
127 "partial",
128 "--jobs",
129 "4",
130 "--since",
131 "HEAD~1",
132 "--max-archive-depth",
133 "3",
134 "--no-fill-licenses",
135 "--copyright-file",
136 "debian/copyright",
137 "--output",
138 "-",
139 "--root",
140 tmp,
141 ]
142 )
143
144 self.assertEqual(options.mode, "partial")
145 self.assertEqual(options.group_by, "copyright")
146 self.assertEqual(options.jobs, 4)
147 self.assertEqual(options.since, "HEAD~1")
148 self.assertEqual(options.max_archive_depth, 3)
149 self.assertEqual(options.copyright_file, "debian/copyright")
150 self.assertTrue(options.spdx)
151 self.assertFalse(options.glob)
152 self.assertFalse(options.progress)
153 self.assertFalse(options.fill_licenses)
154 # "-" is the stdout sentinel, normalised to the empty string.
155 self.assertEqual(options.output, "")
156 # root is absolutised.
157 self.assertEqual(options.root, str(Path(tmp).absolute()))
158 # The four exclude regexes are compiled onto the result.
159 for name in (
160 "exclude_fullname_res",
161 "exclude_special_re",
162 "exclude_file_re",
163 "exclude_directory_re",
164 ):
165 self.assertIsNotNone(getattr(options, name))
166
167 def test_changed_shorthand_sets_mode(self):
168 with tempfile.TemporaryDirectory() as tmp:
169 options = cmdoptions.process_options(
170 ["--no-progress", "--changed", "--root", tmp]
171 )
172 self.assertEqual(options.mode, "changed")
173
174 def test_files_are_relative_to_root(self):
175 with tempfile.TemporaryDirectory() as tmp:
176 (Path(tmp) / "a.c").write_text("", encoding="utf-8")
177 options = cmdoptions.process_options(
178 ["--no-progress", "--root", tmp, str(Path(tmp) / "a.c")]
179 )
180 self.assertEqual(options.files, ["a.c"])
181
182 def test_every_required_option_field_is_produced(self):
183 """A required Options field with no CLI wiring would fail construction.
184
185 Guards the namespace->Options assembly: a new required field on Options
186 without a matching argument makes process_options raise.
187 """
188 with tempfile.TemporaryDirectory() as tmp:
189 options = cmdoptions.process_options(["--no-progress", "--root", tmp])
190 required = [
191 f.name
192 for f in dataclasses.fields(Options)
193 if f.default is dataclasses.MISSING
194 and f.default_factory is dataclasses.MISSING
195 ]
196 for name in required:
197 self.assertTrue(hasattr(options, name))
198
199
200 if __name__ == "__main__":
201 unittest.main()
202
203
204 class ExcludeOptionTest(unittest.TestCase):
205 """-X/--exclude collects every pattern given, in order."""
206
207 @staticmethod
208 def _patterns(args: list[str]) -> list[str]:
209 with tempfile.TemporaryDirectory() as tmp:
210 options = cmdoptions.process_options(
211 ["--no-progress", "--root", tmp, *args]
212 )
213 return [pattern.pattern for pattern in options.exclude_fullname_res]
214
215 def test_repeated_exclude_keeps_every_pattern(self):
216 self.assertEqual(
217 self._patterns(["-X", "^build/", "-X", "^po/"]), ["^build/", "^po/"]
218 )
219
220 def test_single_exclude_is_one_pattern(self):
221 self.assertEqual(self._patterns(["-X", "^build/"]), ["^build/"])
222
223 def test_no_exclude_is_empty(self):
224 self.assertEqual(self._patterns([]), [])