Debian Codegraph @

py/tests/test_constraint.py

raw
1 # --------------------------------------------------------------------------------------
2 # Copyright (c) 2014-2024,, Nucleic Development Team.
3 #
4 # Distributed under the terms of the Modified BSD License.
5 #
6 # The full license is in the file LICENSE, distributed with this software.
7 # --------------------------------------------------------------------------------------
8 import gc
9 import re
10
11 import pytest
12
13 from kiwisolver import Constraint, Variable, strength
14
15
16 @pytest.mark.parametrize("op", ("==", "<=", ">="))
17 def test_constraint_creation(op) -> None:
18 """Test constraints creation and methods."""
19 v = Variable("foo")
20 c = Constraint(v + 1, op)
21
22 assert c.strength() == strength.required and c.op() == op
23 e = c.expression()
24 t = e.terms()
25 assert (
26 e.constant() == 1
27 and len(t) == 1
28 and t[0].variable() is v
29 and t[0].coefficient() == 1
30 )
31
32 constraint_format = r"1 \* foo \+ 1 %s 0 | strength = 1.001e\+[0]+9" % op
33 assert re.match(constraint_format, str(c))
34
35 for s in ("weak", "medium", "strong", "required"):
36 # Not an exact literal...
37 c = Constraint(v + 1, op, s) # type: ignore
38 assert c.strength() == getattr(strength, s)
39
40 # Ensure we test garbage collection.
41 del c
42 gc.collect()
43
44
45 def test_constraint_creation2() -> None:
46 """Test for errors in Constraints creation."""
47 v = Variable("foo")
48
49 with pytest.raises(TypeError) as excinfo:
50 Constraint(1, "==") # type: ignore
51 assert "Expression" in excinfo.exconly()
52
53 with pytest.raises(TypeError) as excinfo:
54 Constraint(v + 1, 1) # type: ignore
55 assert "str" in excinfo.exconly()
56
57 with pytest.raises(ValueError) as excinfo2:
58 Constraint(v + 1, "!=") # type: ignore
59 assert "relational operator" in excinfo2.exconly()
60
61
62 @pytest.mark.parametrize("op", ("==", "<=", ">="))
63 def test_constraint_repr(op) -> None:
64 """Test the repr method of a constraint object."""
65 v = Variable("foo")
66 c = Constraint(v + 1, op)
67
68 assert op in repr(c)
69
70
71 def test_constraint_or_operator() -> None:
72 """Test modifying a constraint strength using the | operator."""
73 v = Variable("foo")
74 c = Constraint(v + 1, "==")
75
76 for s in ("weak", "medium", "strong", "required", strength.create(1, 1, 0)):
77 c2 = c | s # type: ignore
78 if isinstance(s, str):
79 assert c2.strength() == getattr(strength, s)
80 else:
81 assert c2.strength() == s
82
83 with pytest.raises(ValueError):
84 c | "unknown" # type: ignore