blob: 003b4a51e6a92153dd639498b83c227b7328f405 [file] [log] [blame]
Thomas Wouters1d75a792000-08-17 22:37:32 +00001"Test the functionality of Python classes implementing operators."
2
Barry Warsaw408b6d32002-07-30 23:27:12 +00003from test.test_support import TestFailed
Thomas Wouters1d75a792000-08-17 22:37:32 +00004
5testmeths = [
6
7# Binary operations
8 "add",
9 "radd",
10 "sub",
11 "rsub",
12 "mul",
13 "rmul",
Neal Norwitzbcc0db82006-03-24 08:14:36 +000014 "truediv",
15 "rtruediv",
Thomas Wouters1d75a792000-08-17 22:37:32 +000016 "mod",
17 "rmod",
18 "divmod",
19 "rdivmod",
20 "pow",
21 "rpow",
22 "rshift",
23 "rrshift",
24 "lshift",
25 "rlshift",
26 "and",
27 "rand",
28 "or",
29 "ror",
30 "xor",
31 "rxor",
32
33# List/dict operations
34 "contains",
35 "getitem",
36 "getslice",
37 "setitem",
38 "setslice",
39 "delitem",
40 "delslice",
41
42# Unary operations
43 "neg",
44 "pos",
45 "abs",
Thomas Wouters1d75a792000-08-17 22:37:32 +000046
47# generic operations
48 "init",
Thomas Wouters1d75a792000-08-17 22:37:32 +000049 ]
50
51# These need to return something other than None
Thomas Wouters1d75a792000-08-17 22:37:32 +000052# "hash",
53# "str",
54# "repr",
Neil Schemenauer3a313e32004-07-19 16:29:17 +000055# "int",
56# "long",
57# "float",
58# "oct",
59# "hex",
Thomas Wouters1d75a792000-08-17 22:37:32 +000060
61# These are separate because they can influence the test of other methods.
62# "getattr",
63# "setattr",
64# "delattr",
65
66class AllTests:
Thomas Wouters1d75a792000-08-17 22:37:32 +000067 def __hash__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000068 print("__hash__:", args)
Trent Mickd68d0a62000-10-04 17:50:59 +000069 return hash(id(self))
Thomas Wouters1d75a792000-08-17 22:37:32 +000070
71 def __str__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000072 print("__str__:", args)
Thomas Wouters1d75a792000-08-17 22:37:32 +000073 return "AllTests"
74
75 def __repr__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000076 print("__repr__:", args)
Thomas Wouters1d75a792000-08-17 22:37:32 +000077 return "AllTests"
78
Neil Schemenauer3a313e32004-07-19 16:29:17 +000079 def __int__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000080 print("__int__:", args)
Neil Schemenauer3a313e32004-07-19 16:29:17 +000081 return 1
82
Guido van Rossumcd16bf62007-06-13 18:07:49 +000083 def __index__(self, *args):
84 print("__index__:", args)
85 return 1
86
Neil Schemenauer3a313e32004-07-19 16:29:17 +000087 def __float__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000088 print("__float__:", args)
Neil Schemenauer3a313e32004-07-19 16:29:17 +000089 return 1.0
90
Thomas Wouters1d75a792000-08-17 22:37:32 +000091 def __cmp__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000092 print("__cmp__:", args)
Thomas Wouters1d75a792000-08-17 22:37:32 +000093 return 0
94
Guido van Rossum47b9ff62006-08-24 00:41:19 +000095 def __eq__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000096 print("__eq__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +000097 return True
98
99 def __ne__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000100 print("__ne__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000101 return False
102
103 def __lt__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print("__lt__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000105 return False
106
107 def __le__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print("__le__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000109 return True
110
111 def __gt__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print("__gt__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000113 return False
114
115 def __ge__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000116 print("__ge__:", args)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000117 return True
118
Barry Warsaw07d8d642001-08-20 20:29:07 +0000119 def __del__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 print("__del__:", args)
Barry Warsaw07d8d642001-08-20 20:29:07 +0000121
Tim Peters01705212001-12-11 19:28:47 +0000122# Synthesize AllTests methods from the names in testmeths.
123
124method_template = """\
125def __%(method)s__(self, *args):
Georg Brandl88fc6642007-02-09 21:28:07 +0000126 print("__%(method)s__:", args)
Tim Peters01705212001-12-11 19:28:47 +0000127"""
128
Thomas Wouters4cdada92006-04-15 09:19:16 +0000129d = {}
Thomas Wouters1d75a792000-08-17 22:37:32 +0000130for method in testmeths:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000131 exec(method_template % locals(), d)
Thomas Wouters4cdada92006-04-15 09:19:16 +0000132for k in d:
133 setattr(AllTests, k, d[k])
134del d, k
Tim Peters01705212001-12-11 19:28:47 +0000135del method, method_template
Thomas Wouters1d75a792000-08-17 22:37:32 +0000136
137# this also tests __init__ of course.
138testme = AllTests()
139
140# Binary operations
141
142testme + 1
1431 + testme
144
145testme - 1
1461 - testme
147
148testme * 1
1491 * testme
150
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000151testme / 1
1521 / testme
Thomas Wouters1d75a792000-08-17 22:37:32 +0000153
154testme % 1
1551 % testme
156
157divmod(testme,1)
158divmod(1, testme)
159
160testme ** 1
1611 ** testme
162
163testme >> 1
1641 >> testme
165
166testme << 1
1671 << testme
168
169testme & 1
1701 & testme
171
172testme | 1
1731 | testme
174
175testme ^ 1
1761 ^ testme
177
178
179# List/dict operations
180
Thomas Wouters89f507f2006-12-13 04:49:30 +0000181class Empty: pass
182
183try:
184 1 in Empty()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000185 print('failed, should have raised TypeError')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186except TypeError:
187 pass
188
Thomas Wouters1d75a792000-08-17 22:37:32 +00001891 in testme
190
191testme[1]
192testme[1] = 1
193del testme[1]
194
195testme[:42]
196testme[:42] = "The Answer"
197del testme[:42]
198
199testme[2:1024:10]
200testme[2:1024:10] = "A lot"
201del testme[2:1024:10]
202
203testme[:42, ..., :24:, 24, 100]
204testme[:42, ..., :24:, 24, 100] = "Strange"
205del testme[:42, ..., :24:, 24, 100]
206
207
208# Now remove the slice hooks to see if converting normal slices to slice
209# object works.
210
211del AllTests.__getslice__
212del AllTests.__setslice__
213del AllTests.__delslice__
214
Barry Warsaw07d8d642001-08-20 20:29:07 +0000215import sys
216if sys.platform[:4] != 'java':
217 testme[:42]
218 testme[:42] = "The Answer"
219 del testme[:42]
220else:
221 # This works under Jython, but the actual slice values are
222 # different.
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print("__getitem__: (slice(0, 42, None),)")
224 print("__setitem__: (slice(0, 42, None), 'The Answer')")
225 print("__delitem__: (slice(0, 42, None),)")
Thomas Wouters1d75a792000-08-17 22:37:32 +0000226
227# Unary operations
228
229-testme
230+testme
231abs(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000232int(testme)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000233int(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000234float(testme)
235oct(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000236
237# And the rest...
238
239hash(testme)
240repr(testme)
241str(testme)
242
243testme == 1
244testme < 1
245testme > 1
Thomas Wouters1d75a792000-08-17 22:37:32 +0000246testme != 1
2471 == testme
2481 < testme
2491 > testme
Thomas Wouters1d75a792000-08-17 22:37:32 +00002501 != testme
251
252# This test has to be last (duh.)
253
254del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000255if sys.platform[:4] == 'java':
256 import java
257 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000258
259# Interfering tests
260
261class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000262 def __getattr__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000263 print("__getattr__:", args)
Fred Drake004d5e62000-10-23 17:22:08 +0000264 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000265
Fred Drake004d5e62000-10-23 17:22:08 +0000266 def __setattr__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000267 print("__setattr__:", args)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000268
Fred Drake004d5e62000-10-23 17:22:08 +0000269 def __delattr__(self, *args):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000270 print("__delattr__:", args)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000271
272testme = ExtraTests()
273testme.spam
274testme.eggs = "spam, spam, spam and ham"
275del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000276
277
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000278# return values of some method are type-checked
279class BadTypeClass:
280 def __int__(self):
281 return None
282 __float__ = __int__
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000283 __str__ = __int__
284 __repr__ = __int__
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000285
286def check_exc(stmt, exception):
287 """Raise TestFailed if executing 'stmt' does not raise 'exception'
288 """
289 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000290 exec(stmt)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000291 except exception:
292 pass
293 else:
294 raise TestFailed, "%s should raise %s" % (stmt, exception)
295
296check_exc("int(BadTypeClass())", TypeError)
297check_exc("float(BadTypeClass())", TypeError)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000298check_exc("str(BadTypeClass())", TypeError)
299check_exc("repr(BadTypeClass())", TypeError)
300check_exc("oct(BadTypeClass())", TypeError)
301check_exc("hex(BadTypeClass())", TypeError)
302
Guido van Rossum23120242001-01-18 23:47:15 +0000303# Test correct errors from hash() on objects with comparisons but no __hash__
304
305class C0:
306 pass
307
308hash(C0()) # This should work; the next two should raise TypeError
309
310class C1:
311 def __cmp__(self, other): return 0
312
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000313check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000314
315class C2:
316 def __eq__(self, other): return 1
317
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000318check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000319
320# Test for SF bug 532646
321
322class A:
323 pass
324A.__call__ = A()
325a = A()
326try:
327 a() # This should not segfault
328except RuntimeError:
329 pass
330else:
331 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000332
333
334# Tests for exceptions raised in instance_getattr2().
335
336def booh(self):
337 raise AttributeError, "booh"
338
339class A:
340 a = property(booh)
341try:
342 A().a # Raised AttributeError: A instance has no attribute 'a'
Guido van Rossumb940e112007-01-10 16:19:56 +0000343except AttributeError as x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000344 if str(x) != "booh":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000345 print("attribute error for A().a got masked:", str(x))
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000346
347class E:
348 __eq__ = property(booh)
349E() == E() # In debug mode, caused a C-level assert() to fail
350
351class I:
352 __init__ = property(booh)
353try:
354 I() # In debug mode, printed XXX undetected error and raises AttributeError
Guido van Rossumb940e112007-01-10 16:19:56 +0000355except AttributeError as x:
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000356 pass
357else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000358 print("attribute error for I.__init__ got masked")
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000359
360
361# Test comparison and hash of methods
362class A:
363 def __init__(self, x):
364 self.x = x
365 def f(self):
366 pass
367 def g(self):
368 pass
369 def __eq__(self, other):
370 return self.x == other.x
371 def __hash__(self):
372 return self.x
373class B(A):
374 pass
375
376a1 = A(1)
377a2 = A(2)
378assert a1.f == a1.f
379assert a1.f != a2.f
380assert a1.f != a1.g
381assert a1.f == A(1).f
382assert hash(a1.f) == hash(a1.f)
383assert hash(a1.f) == hash(A(1).f)
384
385assert A.f != a1.f
386assert A.f != A.g
387assert B.f == A.f
388assert hash(B.f) == hash(A.f)
389
390# the following triggers a SystemError in 2.4
391a = A(hash(A.f.im_func)^(-1))
392hash(a.f)