Debian Codegraph @

tests/license_expr_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 the licence-expression module (AST, parsers, renderers).
18
19 Cover the public surface: the AST node types, the SPDX and DEP-5 parsers, the
20 DEP-5 and SPDX renderers with their injected leaf converters, license_atoms and
21 map_leaves.
22 """
23
24 import unittest
25
26 from decopy.licensing.license_expr import (
27 And,
28 License,
29 Or,
30 UnconvertibleError,
31 With,
32 license_atoms,
33 map_leaves,
34 parse_dep5_expression,
35 parse_spdx_expression,
36 render_dep5_expression,
37 render_spdx_expression,
38 )
39
40
41 class TestRenderDep5Expression(unittest.TestCase):
42 """render_dep5_expression() with the default identity converters."""
43
44 def test_single_license(self):
45 self.assertEqual(render_dep5_expression(License("MIT")), "MIT")
46
47 def test_or_join(self):
48 tree = Or((License("A"), License("B")))
49 self.assertEqual(render_dep5_expression(tree), "A or B")
50
51 def test_and_join(self):
52 tree = And((License("A"), License("B")))
53 self.assertEqual(render_dep5_expression(tree), "A and B")
54
55 def test_or_operand_of_and_gets_comma(self):
56 # DEP-5 sec 7.2: an `or` grouped under an `and` is set off with a comma.
57 tree = And((Or((License("A"), License("B"))), License("C")))
58 self.assertEqual(render_dep5_expression(tree), "A or B, and C")
59
60 def test_with_uses_identity_label_by_default(self):
61 # The default identity convert_exception keeps the label verbatim, so a
62 # DEP-5-sourced With node round-trips without an SPDX lookup.
63 tree = With(License("GPL-2+"), "OpenSSL")
64 self.assertEqual(render_dep5_expression(tree), "GPL-2+ with OpenSSL exception")
65
66
67 class TestRenderDep5InjectedConverters(unittest.TestCase):
68 """The injected convert_id / convert_exception hooks."""
69
70 def test_convert_id_applied_to_leaves(self):
71 tree = Or((License("x"), License("y")))
72 self.assertEqual(render_dep5_expression(tree, convert_id=str.upper), "X or Y")
73
74 def test_unknown_exception_raises(self):
75 # convert_exception returning None (an unknown exception) is unrenderable.
76 tree = With(License("GPL-2+"), "Nope")
77 with self.assertRaises(UnconvertibleError):
78 render_dep5_expression(tree, convert_exception=lambda _e: None)
79
80
81 class TestParseSpdxExpression(unittest.TestCase):
82 """parse_spdx_expression() lives here now; precedence sanity checks."""
83
84 def test_and_binds_tighter_than_or(self):
85 self.assertEqual(
86 parse_spdx_expression("A OR B AND C"),
87 Or((License("A"), And((License("B"), License("C"))))),
88 )
89
90 def test_malformed_raises(self):
91 with self.assertRaises(ValueError):
92 parse_spdx_expression("(A OR B")
93
94
95 class TestParseDep5Expression(unittest.TestCase):
96 """parse_dep5_expression(): DEP-5 short-name expression -> AST."""
97
98 def test_or(self):
99 self.assertEqual(
100 parse_dep5_expression("A or B"), Or((License("A"), License("B")))
101 )
102
103 def test_and(self):
104 self.assertEqual(
105 parse_dep5_expression("A and B"), And((License("A"), License("B")))
106 )
107
108 def test_and_binds_tighter_than_or(self):
109 self.assertEqual(
110 parse_dep5_expression("A or B and C"),
111 Or((License("A"), And((License("B"), License("C"))))),
112 )
113
114 def test_comma_overrides_precedence(self):
115 # The one documented comma case: ", and" loosens the `and` below `or`.
116 self.assertEqual(
117 parse_dep5_expression("A or B, and C"),
118 And((Or((License("A"), License("B"))), License("C"))),
119 )
120
121 def test_spec_complex_example(self):
122 self.assertEqual(
123 parse_dep5_expression("GPL-2+ or Artistic-2.0, and BSD-3-clause"),
124 And(
125 (
126 Or((License("GPL-2+"), License("Artistic-2.0"))),
127 License("BSD-3-clause"),
128 )
129 ),
130 )
131
132 def test_lenient_comma_or_left_fold(self):
133 # Undocumented `, or` plus a second comma; the reader must still parse it.
134 self.assertEqual(
135 parse_dep5_expression("B or C, and D, or A"),
136 Or(
137 (
138 And((Or((License("B"), License("C"))), License("D"))),
139 License("A"),
140 )
141 ),
142 )
143
144 def test_with_exception(self):
145 self.assertEqual(
146 parse_dep5_expression("GPL-2+ with OpenSSL exception"),
147 With(License("GPL-2+"), "OpenSSL"),
148 )
149
150 def test_name_containing_operator_substring_not_split(self):
151 # "Sandia" contains "and"; "Borceux" contains "or" -- neither is split,
152 # because tokenisation is on whitespace/commas, not substrings.
153 self.assertEqual(
154 parse_dep5_expression("Sandia and Borceux"),
155 And((License("Sandia"), License("Borceux"))),
156 )
157
158 def test_empty_raises(self):
159 with self.assertRaises(ValueError):
160 parse_dep5_expression("")
161 with self.assertRaises(ValueError):
162 parse_dep5_expression(" ")
163
164
165 class TestDep5RoundTrip(unittest.TestCase):
166 """render_dep5_expression(parse_dep5_expression(s)) == s, documented subset."""
167
168 def test_round_trip(self):
169 for s in (
170 "A or B",
171 "A and B",
172 "A or B and C",
173 "A or B, and C",
174 "GPL-2+ or Artistic-2.0, and BSD-3-clause",
175 "GPL-2+ with OpenSSL exception",
176 ):
177 with self.subTest(expr=s):
178 self.assertEqual(render_dep5_expression(parse_dep5_expression(s)), s)
179
180
181 class TestLicenseAtoms(unittest.TestCase):
182 """license_atoms(): leaf names in order, de-duplicated."""
183
184 def test_flat_or(self):
185 self.assertEqual(license_atoms(parse_dep5_expression("A or B")), ["A", "B"])
186
187 def test_nested(self):
188 self.assertEqual(
189 license_atoms(parse_dep5_expression("A or B, and C")), ["A", "B", "C"]
190 )
191
192 def test_with_contributes_full_string(self):
193 self.assertEqual(
194 license_atoms(With(License("GPL-2+"), "OpenSSL")),
195 ["GPL-2+ with OpenSSL exception"],
196 )
197
198 def test_dedup_preserves_order(self):
199 self.assertEqual(
200 license_atoms(parse_dep5_expression("A or A or B")), ["A", "B"]
201 )
202
203
204 class TestRenderSpdxExpression(unittest.TestCase):
205 """render_spdx_expression(): AST -> unambiguous parenthesised SPDX."""
206
207 def test_single(self):
208 self.assertEqual(render_spdx_expression(License("MIT")), "MIT")
209
210 def test_flat_and_or(self):
211 self.assertEqual(
212 render_spdx_expression(And((License("A"), License("B")))), "A AND B"
213 )
214 self.assertEqual(
215 render_spdx_expression(Or((License("A"), License("B")))), "A OR B"
216 )
217
218 def test_with(self):
219 self.assertEqual(
220 render_spdx_expression(With(License("GPL-2+"), "Classpath-exception-2.0")),
221 "GPL-2+ WITH Classpath-exception-2.0",
222 )
223
224 def test_convert_name_applied(self):
225 tree = Or((License("a"), License("b")))
226 self.assertEqual(render_spdx_expression(tree, convert_name=str.upper), "A OR B")
227
228 def test_convert_exception_applied(self):
229 # The exception id is converted by convert_exception (default identity).
230 self.assertEqual(
231 render_spdx_expression(
232 With(License("a"), "x"),
233 convert_name=str.upper,
234 convert_exception=str.upper,
235 ),
236 "A WITH X",
237 )
238
239 def test_compound_operands_parenthesised(self):
240 # A tree DEP-5 cannot hold without losing meaning, rendered as SPDX.
241 tree = Or((License("A"), And((Or((License("B"), License("C"))), License("D")))))
242 self.assertEqual(render_spdx_expression(tree), "A OR ((B OR C) AND D)")
243
244 def test_two_independent_clauses(self):
245 # An or of two independent and-over-or clauses is inexpressible in DEP-5.
246 tree = Or(
247 (
248 And((Or((License("A"), License("B"))), License("C"))),
249 And((Or((License("D"), License("E"))), License("F"))),
250 )
251 )
252 self.assertEqual(
253 render_spdx_expression(tree),
254 "((A OR B) AND C) OR ((D OR E) AND F)",
255 )
256
257
258 class TestMapLeaves(unittest.TestCase):
259 """map_leaves(): rebuild an AST with converted leaf names/exceptions."""
260
261 def test_identity_default(self):
262 tree = And((Or((License("A"), License("B"))), License("C")))
263 self.assertEqual(map_leaves(tree), tree)
264
265 def test_converts_license_and_with_leaves(self):
266 tree = Or((License("a"), With(License("b"), "x")))
267 self.assertEqual(
268 map_leaves(tree, convert_id=str.upper, convert_exception=str.upper),
269 Or((License("A"), With(License("B"), "X"))),
270 )
271
272
273 class TestSpdxRoundTrip(unittest.TestCase):
274 """SPDX is unambiguous: parse(render(ast)) == ast for the fallback trees."""
275
276 def test_round_trip(self):
277 trees = (
278 Or((License("A"), And((Or((License("B"), License("C"))), License("D"))))),
279 Or(
280 (
281 And((Or((License("A"), License("B"))), License("C"))),
282 And((Or((License("D"), License("E"))), License("F"))),
283 )
284 ),
285 )
286 for tree in trees:
287 with self.subTest(tree=tree):
288 self.assertEqual(
289 parse_spdx_expression(render_spdx_expression(tree)), tree
290 )
291
292
293 if __name__ == "__main__":
294 unittest.main()