blob: b8b4cab96d3e66fef8447da0ee79d05b1d5913b2 [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 Wouters1d75a792000-08-17 22:37:32 +0000118for method in testmeths:
Tim Peters01705212001-12-11 19:28:47 +0000119 exec method_template % locals() in AllTests.__dict__
120
121del method, method_template
Thomas Wouters1d75a792000-08-17 22:37:32 +0000122
123# this also tests __init__ of course.
124testme = AllTests()
125
126# Binary operations
127
128testme + 1
1291 + testme
130
131testme - 1
1321 - testme
133
134testme * 1
1351 * testme
136
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000137testme / 1
1381 / testme
Thomas Wouters1d75a792000-08-17 22:37:32 +0000139
140testme % 1
1411 % testme
142
143divmod(testme,1)
144divmod(1, testme)
145
146testme ** 1
1471 ** 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
164
165# List/dict operations
166
1671 in testme
168
169testme[1]
170testme[1] = 1
171del testme[1]
172
173testme[:42]
174testme[:42] = "The Answer"
175del testme[:42]
176
177testme[2:1024:10]
178testme[2:1024:10] = "A lot"
179del testme[2:1024:10]
180
181testme[:42, ..., :24:, 24, 100]
182testme[:42, ..., :24:, 24, 100] = "Strange"
183del testme[:42, ..., :24:, 24, 100]
184
185
186# Now remove the slice hooks to see if converting normal slices to slice
187# object works.
188
189del AllTests.__getslice__
190del AllTests.__setslice__
191del AllTests.__delslice__
192
Barry Warsaw07d8d642001-08-20 20:29:07 +0000193import sys
194if sys.platform[:4] != 'java':
195 testme[:42]
196 testme[:42] = "The Answer"
197 del testme[:42]
198else:
199 # This works under Jython, but the actual slice values are
200 # different.
201 print "__getitem__: (slice(0, 42, None),)"
202 print "__setitem__: (slice(0, 42, None), 'The Answer')"
203 print "__delitem__: (slice(0, 42, None),)"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000204
205# Unary operations
206
207-testme
208+testme
209abs(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000210int(testme)
211long(testme)
212float(testme)
213oct(testme)
214hex(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000215
216# And the rest...
217
218hash(testme)
219repr(testme)
220str(testme)
221
222testme == 1
223testme < 1
224testme > 1
225testme <> 1
226testme != 1
2271 == testme
2281 < testme
2291 > testme
2301 <> testme
2311 != testme
232
233# This test has to be last (duh.)
234
235del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000236if sys.platform[:4] == 'java':
237 import java
238 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000239
240# Interfering tests
241
242class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000243 def __getattr__(self, *args):
244 print "__getattr__:", args
245 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000246
Fred Drake004d5e62000-10-23 17:22:08 +0000247 def __setattr__(self, *args):
248 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000249
Fred Drake004d5e62000-10-23 17:22:08 +0000250 def __delattr__(self, *args):
251 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000252
253testme = ExtraTests()
254testme.spam
255testme.eggs = "spam, spam, spam and ham"
256del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000257
258
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000259# return values of some method are type-checked
260class BadTypeClass:
261 def __int__(self):
262 return None
263 __float__ = __int__
264 __long__ = __int__
265 __str__ = __int__
266 __repr__ = __int__
267 __oct__ = __int__
268 __hex__ = __int__
269
270def check_exc(stmt, exception):
271 """Raise TestFailed if executing 'stmt' does not raise 'exception'
272 """
273 try:
274 exec stmt
275 except exception:
276 pass
277 else:
278 raise TestFailed, "%s should raise %s" % (stmt, exception)
279
280check_exc("int(BadTypeClass())", TypeError)
281check_exc("float(BadTypeClass())", TypeError)
282check_exc("long(BadTypeClass())", TypeError)
283check_exc("str(BadTypeClass())", TypeError)
284check_exc("repr(BadTypeClass())", TypeError)
285check_exc("oct(BadTypeClass())", TypeError)
286check_exc("hex(BadTypeClass())", TypeError)
287
288# mixing up ints and longs is okay
289class IntLongMixClass:
290 def __int__(self):
291 return 0L
292
293 def __long__(self):
294 return 0
295
296try:
297 int(IntLongMixClass())
298except TypeError:
299 raise TestFailed, "TypeError should not be raised"
300
301try:
302 long(IntLongMixClass())
303except TypeError:
304 raise TestFailed, "TypeError should not be raised"
305
306
Guido van Rossum23120242001-01-18 23:47:15 +0000307# Test correct errors from hash() on objects with comparisons but no __hash__
308
309class C0:
310 pass
311
312hash(C0()) # This should work; the next two should raise TypeError
313
314class C1:
315 def __cmp__(self, other): return 0
316
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000317check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000318
319class C2:
320 def __eq__(self, other): return 1
321
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000322check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000323
324# Test for SF bug 532646
325
326class A:
327 pass
328A.__call__ = A()
329a = A()
330try:
331 a() # This should not segfault
332except RuntimeError:
333 pass
334else:
335 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000336
337
338# Tests for exceptions raised in instance_getattr2().
339
340def booh(self):
341 raise AttributeError, "booh"
342
343class A:
344 a = property(booh)
345try:
346 A().a # Raised AttributeError: A instance has no attribute 'a'
347except AttributeError, x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000348 if str(x) != "booh":
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000349 print "attribute error for A().a got masked:", str(x)
350
351class E:
352 __eq__ = property(booh)
353E() == E() # In debug mode, caused a C-level assert() to fail
354
355class I:
356 __init__ = property(booh)
357try:
358 I() # In debug mode, printed XXX undetected error and raises AttributeError
359except AttributeError, x:
360 pass
361else:
362 print "attribute error for I.__init__ got masked"