blob: d872357ce0c093f029a9211379336e7ec52dae2b [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
52# "coerce",
53# "hash",
54# "str",
55# "repr",
Neil Schemenauer3a313e32004-07-19 16:29:17 +000056# "int",
57# "long",
58# "float",
59# "oct",
60# "hex",
Thomas Wouters1d75a792000-08-17 22:37:32 +000061
62# These are separate because they can influence the test of other methods.
63# "getattr",
64# "setattr",
65# "delattr",
66
67class AllTests:
68 def __coerce__(self, *args):
69 print "__coerce__:", args
Fred Drake004d5e62000-10-23 17:22:08 +000070 return (self,) + args
Thomas Wouters1d75a792000-08-17 22:37:32 +000071
72 def __hash__(self, *args):
73 print "__hash__:", args
Trent Mickd68d0a62000-10-04 17:50:59 +000074 return hash(id(self))
Thomas Wouters1d75a792000-08-17 22:37:32 +000075
76 def __str__(self, *args):
77 print "__str__:", args
78 return "AllTests"
79
80 def __repr__(self, *args):
81 print "__repr__:", args
82 return "AllTests"
83
Neil Schemenauer3a313e32004-07-19 16:29:17 +000084 def __int__(self, *args):
85 print "__int__:", args
86 return 1
87
88 def __float__(self, *args):
89 print "__float__:", args
90 return 1.0
91
92 def __long__(self, *args):
93 print "__long__:", args
94 return 1L
95
96 def __oct__(self, *args):
97 print "__oct__:", args
98 return '01'
99
100 def __hex__(self, *args):
101 print "__hex__:", args
102 return '0x1'
103
Thomas Wouters1d75a792000-08-17 22:37:32 +0000104 def __cmp__(self, *args):
105 print "__cmp__:", args
106 return 0
107
Barry Warsaw07d8d642001-08-20 20:29:07 +0000108 def __del__(self, *args):
109 print "__del__:", args
110
Tim Peters01705212001-12-11 19:28:47 +0000111# Synthesize AllTests methods from the names in testmeths.
112
113method_template = """\
114def __%(method)s__(self, *args):
115 print "__%(method)s__:", args
116"""
117
Thomas Wouters4cdada92006-04-15 09:19:16 +0000118d = {}
Thomas Wouters1d75a792000-08-17 22:37:32 +0000119for method in testmeths:
Thomas Wouters4cdada92006-04-15 09:19:16 +0000120 exec method_template % locals() in d
121for k in d:
122 setattr(AllTests, k, d[k])
123del d, k
Tim Peters01705212001-12-11 19:28:47 +0000124del method, method_template
Thomas Wouters1d75a792000-08-17 22:37:32 +0000125
126# this also tests __init__ of course.
127testme = AllTests()
128
129# Binary operations
130
131testme + 1
1321 + testme
133
134testme - 1
1351 - testme
136
137testme * 1
1381 * testme
139
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000140testme / 1
1411 / testme
Thomas Wouters1d75a792000-08-17 22:37:32 +0000142
143testme % 1
1441 % testme
145
146divmod(testme,1)
147divmod(1, testme)
148
149testme ** 1
1501 ** testme
151
152testme >> 1
1531 >> testme
154
155testme << 1
1561 << testme
157
158testme & 1
1591 & testme
160
161testme | 1
1621 | testme
163
164testme ^ 1
1651 ^ testme
166
167
168# List/dict operations
169
1701 in testme
171
172testme[1]
173testme[1] = 1
174del testme[1]
175
176testme[:42]
177testme[:42] = "The Answer"
178del testme[:42]
179
180testme[2:1024:10]
181testme[2:1024:10] = "A lot"
182del testme[2:1024:10]
183
184testme[:42, ..., :24:, 24, 100]
185testme[:42, ..., :24:, 24, 100] = "Strange"
186del testme[:42, ..., :24:, 24, 100]
187
188
189# Now remove the slice hooks to see if converting normal slices to slice
190# object works.
191
192del AllTests.__getslice__
193del AllTests.__setslice__
194del AllTests.__delslice__
195
Barry Warsaw07d8d642001-08-20 20:29:07 +0000196import sys
197if sys.platform[:4] != 'java':
198 testme[:42]
199 testme[:42] = "The Answer"
200 del testme[:42]
201else:
202 # This works under Jython, but the actual slice values are
203 # different.
204 print "__getitem__: (slice(0, 42, None),)"
205 print "__setitem__: (slice(0, 42, None), 'The Answer')"
206 print "__delitem__: (slice(0, 42, None),)"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000207
208# Unary operations
209
210-testme
211+testme
212abs(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000213int(testme)
214long(testme)
215float(testme)
216oct(testme)
217hex(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000218
219# And the rest...
220
221hash(testme)
222repr(testme)
223str(testme)
224
225testme == 1
226testme < 1
227testme > 1
228testme <> 1
229testme != 1
2301 == testme
2311 < testme
2321 > testme
2331 <> testme
2341 != testme
235
236# This test has to be last (duh.)
237
238del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000239if sys.platform[:4] == 'java':
240 import java
241 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000242
243# Interfering tests
244
245class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000246 def __getattr__(self, *args):
247 print "__getattr__:", args
248 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000249
Fred Drake004d5e62000-10-23 17:22:08 +0000250 def __setattr__(self, *args):
251 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000252
Fred Drake004d5e62000-10-23 17:22:08 +0000253 def __delattr__(self, *args):
254 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000255
256testme = ExtraTests()
257testme.spam
258testme.eggs = "spam, spam, spam and ham"
259del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000260
261
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000262# return values of some method are type-checked
263class BadTypeClass:
264 def __int__(self):
265 return None
266 __float__ = __int__
267 __long__ = __int__
268 __str__ = __int__
269 __repr__ = __int__
270 __oct__ = __int__
271 __hex__ = __int__
272
273def check_exc(stmt, exception):
274 """Raise TestFailed if executing 'stmt' does not raise 'exception'
275 """
276 try:
277 exec stmt
278 except exception:
279 pass
280 else:
281 raise TestFailed, "%s should raise %s" % (stmt, exception)
282
283check_exc("int(BadTypeClass())", TypeError)
284check_exc("float(BadTypeClass())", TypeError)
285check_exc("long(BadTypeClass())", TypeError)
286check_exc("str(BadTypeClass())", TypeError)
287check_exc("repr(BadTypeClass())", TypeError)
288check_exc("oct(BadTypeClass())", TypeError)
289check_exc("hex(BadTypeClass())", TypeError)
290
291# mixing up ints and longs is okay
292class IntLongMixClass:
293 def __int__(self):
294 return 0L
295
296 def __long__(self):
297 return 0
298
299try:
300 int(IntLongMixClass())
301except TypeError:
302 raise TestFailed, "TypeError should not be raised"
303
304try:
305 long(IntLongMixClass())
306except TypeError:
307 raise TestFailed, "TypeError should not be raised"
308
309
Guido van Rossum23120242001-01-18 23:47:15 +0000310# Test correct errors from hash() on objects with comparisons but no __hash__
311
312class C0:
313 pass
314
315hash(C0()) # This should work; the next two should raise TypeError
316
317class C1:
318 def __cmp__(self, other): return 0
319
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000320check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000321
322class C2:
323 def __eq__(self, other): return 1
324
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000325check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000326
327# Test for SF bug 532646
328
329class A:
330 pass
331A.__call__ = A()
332a = A()
333try:
334 a() # This should not segfault
335except RuntimeError:
336 pass
337else:
338 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000339
340
341# Tests for exceptions raised in instance_getattr2().
342
343def booh(self):
344 raise AttributeError, "booh"
345
346class A:
347 a = property(booh)
348try:
349 A().a # Raised AttributeError: A instance has no attribute 'a'
350except AttributeError, x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000351 if str(x) != "booh":
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000352 print "attribute error for A().a got masked:", str(x)
353
354class E:
355 __eq__ = property(booh)
356E() == E() # In debug mode, caused a C-level assert() to fail
357
358class I:
359 __init__ = property(booh)
360try:
361 I() # In debug mode, printed XXX undetected error and raises AttributeError
362except AttributeError, x:
363 pass
364else:
365 print "attribute error for I.__init__ got masked"
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000366
367
368# Test comparison and hash of methods
369class A:
370 def __init__(self, x):
371 self.x = x
372 def f(self):
373 pass
374 def g(self):
375 pass
376 def __eq__(self, other):
377 return self.x == other.x
378 def __hash__(self):
379 return self.x
380class B(A):
381 pass
382
383a1 = A(1)
384a2 = A(2)
385assert a1.f == a1.f
386assert a1.f != a2.f
387assert a1.f != a1.g
388assert a1.f == A(1).f
389assert hash(a1.f) == hash(a1.f)
390assert hash(a1.f) == hash(A(1).f)
391
392assert A.f != a1.f
393assert A.f != A.g
394assert B.f == A.f
395assert hash(B.f) == hash(A.f)
396
397# the following triggers a SystemError in 2.4
398a = A(hash(A.f.im_func)^(-1))
399hash(a.f)