blob: 66f426515ac0b37df6a0d75bb463f9cda45453a6 [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):
68 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):
72 print "__str__:", args
73 return "AllTests"
74
75 def __repr__(self, *args):
76 print "__repr__:", args
77 return "AllTests"
78
Neil Schemenauer3a313e32004-07-19 16:29:17 +000079 def __int__(self, *args):
80 print "__int__:", args
81 return 1
82
83 def __float__(self, *args):
84 print "__float__:", args
85 return 1.0
86
87 def __long__(self, *args):
88 print "__long__:", args
89 return 1L
90
91 def __oct__(self, *args):
92 print "__oct__:", args
93 return '01'
94
95 def __hex__(self, *args):
96 print "__hex__:", args
97 return '0x1'
98
Thomas Wouters1d75a792000-08-17 22:37:32 +000099 def __cmp__(self, *args):
100 print "__cmp__:", args
101 return 0
102
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000103 def __eq__(self, *args):
104 print "__eq__:", args
105 return True
106
107 def __ne__(self, *args):
108 print "__ne__:", args
109 return False
110
111 def __lt__(self, *args):
112 print "__lt__:", args
113 return False
114
115 def __le__(self, *args):
116 print "__le__:", args
117 return True
118
119 def __gt__(self, *args):
120 print "__gt__:", args
121 return False
122
123 def __ge__(self, *args):
124 print "__ge__:", args
125 return True
126
Barry Warsaw07d8d642001-08-20 20:29:07 +0000127 def __del__(self, *args):
128 print "__del__:", args
129
Tim Peters01705212001-12-11 19:28:47 +0000130# Synthesize AllTests methods from the names in testmeths.
131
132method_template = """\
133def __%(method)s__(self, *args):
134 print "__%(method)s__:", args
135"""
136
Thomas Wouters4cdada92006-04-15 09:19:16 +0000137d = {}
Thomas Wouters1d75a792000-08-17 22:37:32 +0000138for method in testmeths:
Thomas Wouters4cdada92006-04-15 09:19:16 +0000139 exec method_template % locals() in d
140for k in d:
141 setattr(AllTests, k, d[k])
142del d, k
Tim Peters01705212001-12-11 19:28:47 +0000143del method, method_template
Thomas Wouters1d75a792000-08-17 22:37:32 +0000144
145# this also tests __init__ of course.
146testme = AllTests()
147
148# Binary operations
149
150testme + 1
1511 + testme
152
153testme - 1
1541 - testme
155
156testme * 1
1571 * testme
158
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000159testme / 1
1601 / testme
Thomas Wouters1d75a792000-08-17 22:37:32 +0000161
162testme % 1
1631 % testme
164
165divmod(testme,1)
166divmod(1, testme)
167
168testme ** 1
1691 ** testme
170
171testme >> 1
1721 >> testme
173
174testme << 1
1751 << testme
176
177testme & 1
1781 & testme
179
180testme | 1
1811 | testme
182
183testme ^ 1
1841 ^ testme
185
186
187# List/dict operations
188
1891 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.
223 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)
233long(testme)
234float(testme)
235oct(testme)
236hex(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000237
238# And the rest...
239
240hash(testme)
241repr(testme)
242str(testme)
243
244testme == 1
245testme < 1
246testme > 1
247testme <> 1
248testme != 1
2491 == testme
2501 < testme
2511 > testme
2521 <> testme
2531 != testme
254
255# This test has to be last (duh.)
256
257del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000258if sys.platform[:4] == 'java':
259 import java
260 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000261
262# Interfering tests
263
264class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000265 def __getattr__(self, *args):
266 print "__getattr__:", args
267 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000268
Fred Drake004d5e62000-10-23 17:22:08 +0000269 def __setattr__(self, *args):
270 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000271
Fred Drake004d5e62000-10-23 17:22:08 +0000272 def __delattr__(self, *args):
273 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000274
275testme = ExtraTests()
276testme.spam
277testme.eggs = "spam, spam, spam and ham"
278del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000279
280
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000281# return values of some method are type-checked
282class BadTypeClass:
283 def __int__(self):
284 return None
285 __float__ = __int__
286 __long__ = __int__
287 __str__ = __int__
288 __repr__ = __int__
289 __oct__ = __int__
290 __hex__ = __int__
291
292def check_exc(stmt, exception):
293 """Raise TestFailed if executing 'stmt' does not raise 'exception'
294 """
295 try:
296 exec stmt
297 except exception:
298 pass
299 else:
300 raise TestFailed, "%s should raise %s" % (stmt, exception)
301
302check_exc("int(BadTypeClass())", TypeError)
303check_exc("float(BadTypeClass())", TypeError)
304check_exc("long(BadTypeClass())", TypeError)
305check_exc("str(BadTypeClass())", TypeError)
306check_exc("repr(BadTypeClass())", TypeError)
307check_exc("oct(BadTypeClass())", TypeError)
308check_exc("hex(BadTypeClass())", TypeError)
309
310# mixing up ints and longs is okay
311class IntLongMixClass:
312 def __int__(self):
313 return 0L
314
315 def __long__(self):
316 return 0
317
318try:
319 int(IntLongMixClass())
320except TypeError:
321 raise TestFailed, "TypeError should not be raised"
322
323try:
324 long(IntLongMixClass())
325except TypeError:
326 raise TestFailed, "TypeError should not be raised"
327
328
Guido van Rossum23120242001-01-18 23:47:15 +0000329# Test correct errors from hash() on objects with comparisons but no __hash__
330
331class C0:
332 pass
333
334hash(C0()) # This should work; the next two should raise TypeError
335
336class C1:
337 def __cmp__(self, other): return 0
338
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000339check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000340
341class C2:
342 def __eq__(self, other): return 1
343
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000344check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000345
346# Test for SF bug 532646
347
348class A:
349 pass
350A.__call__ = A()
351a = A()
352try:
353 a() # This should not segfault
354except RuntimeError:
355 pass
356else:
357 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000358
359
360# Tests for exceptions raised in instance_getattr2().
361
362def booh(self):
363 raise AttributeError, "booh"
364
365class A:
366 a = property(booh)
367try:
368 A().a # Raised AttributeError: A instance has no attribute 'a'
369except AttributeError, x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000370 if str(x) != "booh":
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000371 print "attribute error for A().a got masked:", str(x)
372
373class E:
374 __eq__ = property(booh)
375E() == E() # In debug mode, caused a C-level assert() to fail
376
377class I:
378 __init__ = property(booh)
379try:
380 I() # In debug mode, printed XXX undetected error and raises AttributeError
381except AttributeError, x:
382 pass
383else:
384 print "attribute error for I.__init__ got masked"
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000385
386
387# Test comparison and hash of methods
388class A:
389 def __init__(self, x):
390 self.x = x
391 def f(self):
392 pass
393 def g(self):
394 pass
395 def __eq__(self, other):
396 return self.x == other.x
397 def __hash__(self):
398 return self.x
399class B(A):
400 pass
401
402a1 = A(1)
403a2 = A(2)
404assert a1.f == a1.f
405assert a1.f != a2.f
406assert a1.f != a1.g
407assert a1.f == A(1).f
408assert hash(a1.f) == hash(a1.f)
409assert hash(a1.f) == hash(A(1).f)
410
411assert A.f != a1.f
412assert A.f != A.g
413assert B.f == A.f
414assert hash(B.f) == hash(A.f)
415
416# the following triggers a SystemError in 2.4
417a = A(hash(A.f.im_func)^(-1))
418hash(a.f)