Debian Codegraph @

Lib/test/test_richcmp.py

raw
1 # Tests for rich comparisons
2
3 import unittest
4 from test import support
5
6 import operator
7
8 class Number:
9
10 def __init__(self, x):
11 self.x = x
12
13 def __lt__(self, other):
14 return self.x < other
15
16 def __le__(self, other):
17 return self.x <= other
18
19 def __eq__(self, other):
20 return self.x == other
21
22 def __ne__(self, other):
23 return self.x != other
24
25 def __gt__(self, other):
26 return self.x > other
27
28 def __ge__(self, other):
29 return self.x >= other
30
31 def __repr__(self):
32 return "Number(%r)" % (self.x, )
33
34 class Vector:
35
36 def __init__(self, data):
37 self.data = data
38
39 def __len__(self):
40 return len(self.data)
41
42 def __getitem__(self, i):
43 return self.data[i]
44
45 def __setitem__(self, i, v):
46 self.data[i] = v
47
48 __hash__ = None # Vectors cannot be hashed
49
50 def __bool__(self):
51 raise TypeError("Vectors cannot be used in Boolean contexts")
52
53 def __repr__(self):
54 return "Vector(%r)" % (self.data, )
55
56 def __lt__(self, other):
57 return Vector([a < b for a, b in zip(self.data, self.__cast(other))])
58
59 def __le__(self, other):
60 return Vector([a <= b for a, b in zip(self.data, self.__cast(other))])
61
62 def __eq__(self, other):
63 return Vector([a == b for a, b in zip(self.data, self.__cast(other))])
64
65 def __ne__(self, other):
66 return Vector([a != b for a, b in zip(self.data, self.__cast(other))])
67
68 def __gt__(self, other):
69 return Vector([a > b for a, b in zip(self.data, self.__cast(other))])
70
71 def __ge__(self, other):
72 return Vector([a >= b for a, b in zip(self.data, self.__cast(other))])
73
74 def __cast(self, other):
75 if isinstance(other, Vector):
76 other = other.data
77 if len(self.data) != len(other):
78 raise ValueError("Cannot compare vectors of different length")
79 return other
80
81 opmap = {
82 "lt": (lambda a,b: a< b, operator.lt, operator.__lt__),
83 "le": (lambda a,b: a<=b, operator.le, operator.__le__),
84 "eq": (lambda a,b: a==b, operator.eq, operator.__eq__),
85 "ne": (lambda a,b: a!=b, operator.ne, operator.__ne__),
86 "gt": (lambda a,b: a> b, operator.gt, operator.__gt__),
87 "ge": (lambda a,b: a>=b, operator.ge, operator.__ge__)
88 }
89
90 class VectorTest(unittest.TestCase):
91
92 def checkfail(self, error, opname, *args):
93 for op in opmap[opname]:
94 self.assertRaises(error, op, *args)
95
96 def checkequal(self, opname, a, b, expres):
97 for op in opmap[opname]:
98 realres = op(a, b)
99 # can't use assertEqual(realres, expres) here
100 self.assertEqual(len(realres), len(expres))
101 for i in range(len(realres)):
102 # results are bool, so we can use "is" here
103 self.assertTrue(realres[i] is expres[i])
104
105 def test_mixed(self):
106 # check that comparisons involving Vector objects
107 # which return rich results (i.e. Vectors with itemwise
108 # comparison results) work
109 a = Vector(range(2))
110 b = Vector(range(3))
111 # all comparisons should fail for different length
112 for opname in opmap:
113 self.checkfail(ValueError, opname, a, b)
114
115 a = list(range(5))
116 b = 5 * [2]
117 # try mixed arguments (but not (a, b) as that won't return a bool vector)
118 args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
119 for (a, b) in args:
120 self.checkequal("lt", a, b, [True, True, False, False, False])
121 self.checkequal("le", a, b, [True, True, True, False, False])
122 self.checkequal("eq", a, b, [False, False, True, False, False])
123 self.checkequal("ne", a, b, [True, True, False, True, True ])
124 self.checkequal("gt", a, b, [False, False, False, True, True ])
125 self.checkequal("ge", a, b, [False, False, True, True, True ])
126
127 for ops in opmap.values():
128 for op in ops:
129 # calls __bool__, which should fail
130 self.assertRaises(TypeError, bool, op(a, b))
131
132 class NumberTest(unittest.TestCase):
133
134 def test_basic(self):
135 # Check that comparisons involving Number objects
136 # give the same results give as comparing the
137 # corresponding ints
138 for a in range(3):
139 for b in range(3):
140 for typea in (int, Number):
141 for typeb in (int, Number):
142 if typea==typeb==int:
143 continue # the combination int, int is useless
144 ta = typea(a)
145 tb = typeb(b)
146 for ops in opmap.values():
147 for op in ops:
148 realoutcome = op(a, b)
149 testoutcome = op(ta, tb)
150 self.assertEqual(realoutcome, testoutcome)
151
152 def checkvalue(self, opname, a, b, expres):
153 for typea in (int, Number):
154 for typeb in (int, Number):
155 ta = typea(a)
156 tb = typeb(b)
157 for op in opmap[opname]:
158 realres = op(ta, tb)
159 realres = getattr(realres, "x", realres)
160 self.assertTrue(realres is expres)
161
162 def test_values(self):
163 # check all operators and all comparison results
164 self.checkvalue("lt", 0, 0, False)
165 self.checkvalue("le", 0, 0, True )
166 self.checkvalue("eq", 0, 0, True )
167 self.checkvalue("ne", 0, 0, False)
168 self.checkvalue("gt", 0, 0, False)
169 self.checkvalue("ge", 0, 0, True )
170
171 self.checkvalue("lt", 0, 1, True )
172 self.checkvalue("le", 0, 1, True )
173 self.checkvalue("eq", 0, 1, False)
174 self.checkvalue("ne", 0, 1, True )
175 self.checkvalue("gt", 0, 1, False)
176 self.checkvalue("ge", 0, 1, False)
177
178 self.checkvalue("lt", 1, 0, False)
179 self.checkvalue("le", 1, 0, False)
180 self.checkvalue("eq", 1, 0, False)
181 self.checkvalue("ne", 1, 0, True )
182 self.checkvalue("gt", 1, 0, True )
183 self.checkvalue("ge", 1, 0, True )
184
185 class MiscTest(unittest.TestCase):
186
187 def test_misbehavin(self):
188 class Misb:
189 def __lt__(self_, other): return 0
190 def __gt__(self_, other): return 0
191 def __eq__(self_, other): return 0
192 def __le__(self_, other): self.fail("This shouldn't happen")
193 def __ge__(self_, other): self.fail("This shouldn't happen")
194 def __ne__(self_, other): self.fail("This shouldn't happen")
195 a = Misb()
196 b = Misb()
197 self.assertEqual(a<b, 0)
198 self.assertEqual(a==b, 0)
199 self.assertEqual(a>b, 0)
200
201 def test_not(self):
202 # Check that exceptions in __bool__ are properly
203 # propagated by the not operator
204 import operator
205 class Exc(Exception):
206 pass
207 class Bad:
208 def __bool__(self):
209 raise Exc
210
211 def do(bad):
212 not bad
213
214 for func in (do, operator.not_):
215 self.assertRaises(Exc, func, Bad())
216
217 @support.no_tracing
218 @support.infinite_recursion(25)
219 def test_recursion(self):
220 # Check that comparison for recursive objects fails gracefully
221 from collections import UserList
222 a = UserList()
223 b = UserList()
224 a.append(b)
225 b.append(a)
226 self.assertRaises(RecursionError, operator.eq, a, b)
227 self.assertRaises(RecursionError, operator.ne, a, b)
228 self.assertRaises(RecursionError, operator.lt, a, b)
229 self.assertRaises(RecursionError, operator.le, a, b)
230 self.assertRaises(RecursionError, operator.gt, a, b)
231 self.assertRaises(RecursionError, operator.ge, a, b)
232
233 b.append(17)
234 # Even recursive lists of different lengths are different,
235 # but they cannot be ordered
236 self.assertTrue(not (a == b))
237 self.assertTrue(a != b)
238 self.assertRaises(RecursionError, operator.lt, a, b)
239 self.assertRaises(RecursionError, operator.le, a, b)
240 self.assertRaises(RecursionError, operator.gt, a, b)
241 self.assertRaises(RecursionError, operator.ge, a, b)
242 a.append(17)
243 self.assertRaises(RecursionError, operator.eq, a, b)
244 self.assertRaises(RecursionError, operator.ne, a, b)
245 a.insert(0, 11)
246 b.insert(0, 12)
247 self.assertTrue(not (a == b))
248 self.assertTrue(a != b)
249 self.assertTrue(a < b)
250
251 def test_exception_message(self):
252 class Spam:
253 pass
254
255 tests = [
256 (lambda: 42 < None, r"'<' .* of 'int' and 'NoneType'"),
257 (lambda: None < 42, r"'<' .* of 'NoneType' and 'int'"),
258 (lambda: 42 > None, r"'>' .* of 'int' and 'NoneType'"),
259 (lambda: "foo" < None, r"'<' .* of 'str' and 'NoneType'"),
260 (lambda: "foo" >= 666, r"'>=' .* of 'str' and 'int'"),
261 (lambda: 42 <= None, r"'<=' .* of 'int' and 'NoneType'"),
262 (lambda: 42 >= None, r"'>=' .* of 'int' and 'NoneType'"),
263 (lambda: 42 < [], r"'<' .* of 'int' and 'list'"),
264 (lambda: () > [], r"'>' .* of 'tuple' and 'list'"),
265 (lambda: None >= None, r"'>=' .* of 'NoneType' and 'NoneType'"),
266 (lambda: Spam() < 42, r"'<' .* of 'Spam' and 'int'"),
267 (lambda: 42 < Spam(), r"'<' .* of 'int' and 'Spam'"),
268 (lambda: Spam() <= Spam(), r"'<=' .* of 'Spam' and 'Spam'"),
269 ]
270 for i, test in enumerate(tests):
271 with self.subTest(test=i):
272 with self.assertRaisesRegex(TypeError, test[1]):
273 test[0]()
274
275
276 class DictTest(unittest.TestCase):
277
278 def test_dicts(self):
279 # Verify that __eq__ and __ne__ work for dicts even if the keys and
280 # values don't support anything other than __eq__ and __ne__ (and
281 # __hash__). Complex numbers are a fine example of that.
282 import random
283 imag1a = {}
284 for i in range(50):
285 imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
286 items = list(imag1a.items())
287 random.shuffle(items)
288 imag1b = {}
289 for k, v in items:
290 imag1b[k] = v
291 imag2 = imag1b.copy()
292 imag2[k] = v + 1.0
293 self.assertEqual(imag1a, imag1a)
294 self.assertEqual(imag1a, imag1b)
295 self.assertEqual(imag2, imag2)
296 self.assertTrue(imag1a != imag2)
297 for opname in ("lt", "le", "gt", "ge"):
298 for op in opmap[opname]:
299 self.assertRaises(TypeError, op, imag1a, imag2)
300
301 class ListTest(unittest.TestCase):
302
303 def test_coverage(self):
304 # exercise all comparisons for lists
305 x = [42]
306 self.assertIs(x<x, False)
307 self.assertIs(x<=x, True)
308 self.assertIs(x==x, True)
309 self.assertIs(x!=x, False)
310 self.assertIs(x>x, False)
311 self.assertIs(x>=x, True)
312 y = [42, 42]
313 self.assertIs(x<y, True)
314 self.assertIs(x<=y, True)
315 self.assertIs(x==y, False)
316 self.assertIs(x!=y, True)
317 self.assertIs(x>y, False)
318 self.assertIs(x>=y, False)
319
320 def test_badentry(self):
321 # make sure that exceptions for item comparison are properly
322 # propagated in list comparisons
323 class Exc(Exception):
324 pass
325 class Bad:
326 def __eq__(self, other):
327 raise Exc
328
329 x = [Bad()]
330 y = [Bad()]
331
332 for op in opmap["eq"]:
333 self.assertRaises(Exc, op, x, y)
334
335 def test_goodentry(self):
336 # This test exercises the final call to PyObject_RichCompare()
337 # in Objects/listobject.c::list_richcompare()
338 class Good:
339 def __lt__(self, other):
340 return True
341
342 x = [Good()]
343 y = [Good()]
344
345 for op in opmap["lt"]:
346 self.assertIs(op(x, y), True)
347
348
349 if __name__ == "__main__":
350 unittest.main()