blob: a564f73985ad0efb26b7c9cb4bfcfb62f5bb47da [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",
14 "div",
15 "rdiv",
16 "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
Tim Peters01705212001-12-11 19:28:47 +0000137if 1/2 == 0:
138 testme / 1
139 1 / testme
140else:
141 # True division is in effect, so "/" doesn't map to __div__ etc; but
142 # the canned expected-output file requires that __div__ etc get called.
143 testme.__coerce__(1)
144 testme.__div__(1)
145 testme.__coerce__(1)
146 testme.__rdiv__(1)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000147
148testme % 1
1491 % testme
150
151divmod(testme,1)
152divmod(1, testme)
153
154testme ** 1
1551 ** testme
156
157testme >> 1
1581 >> testme
159
160testme << 1
1611 << testme
162
163testme & 1
1641 & testme
165
166testme | 1
1671 | testme
168
169testme ^ 1
1701 ^ testme
171
172
173# List/dict operations
174
1751 in testme
176
177testme[1]
178testme[1] = 1
179del testme[1]
180
181testme[:42]
182testme[:42] = "The Answer"
183del testme[:42]
184
185testme[2:1024:10]
186testme[2:1024:10] = "A lot"
187del testme[2:1024:10]
188
189testme[:42, ..., :24:, 24, 100]
190testme[:42, ..., :24:, 24, 100] = "Strange"
191del testme[:42, ..., :24:, 24, 100]
192
193
194# Now remove the slice hooks to see if converting normal slices to slice
195# object works.
196
197del AllTests.__getslice__
198del AllTests.__setslice__
199del AllTests.__delslice__
200
Barry Warsaw07d8d642001-08-20 20:29:07 +0000201import sys
202if sys.platform[:4] != 'java':
203 testme[:42]
204 testme[:42] = "The Answer"
205 del testme[:42]
206else:
207 # This works under Jython, but the actual slice values are
208 # different.
209 print "__getitem__: (slice(0, 42, None),)"
210 print "__setitem__: (slice(0, 42, None), 'The Answer')"
211 print "__delitem__: (slice(0, 42, None),)"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000212
213# Unary operations
214
215-testme
216+testme
217abs(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000218int(testme)
219long(testme)
220float(testme)
221oct(testme)
222hex(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000223
224# And the rest...
225
226hash(testme)
227repr(testme)
228str(testme)
229
230testme == 1
231testme < 1
232testme > 1
233testme <> 1
234testme != 1
2351 == testme
2361 < testme
2371 > testme
2381 <> testme
2391 != testme
240
241# This test has to be last (duh.)
242
243del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000244if sys.platform[:4] == 'java':
245 import java
246 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000247
248# Interfering tests
249
250class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000251 def __getattr__(self, *args):
252 print "__getattr__:", args
253 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000254
Fred Drake004d5e62000-10-23 17:22:08 +0000255 def __setattr__(self, *args):
256 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000257
Fred Drake004d5e62000-10-23 17:22:08 +0000258 def __delattr__(self, *args):
259 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000260
261testme = ExtraTests()
262testme.spam
263testme.eggs = "spam, spam, spam and ham"
264del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000265
266
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000267# return values of some method are type-checked
268class BadTypeClass:
269 def __int__(self):
270 return None
271 __float__ = __int__
272 __long__ = __int__
273 __str__ = __int__
274 __repr__ = __int__
275 __oct__ = __int__
276 __hex__ = __int__
277
278def check_exc(stmt, exception):
279 """Raise TestFailed if executing 'stmt' does not raise 'exception'
280 """
281 try:
282 exec stmt
283 except exception:
284 pass
285 else:
286 raise TestFailed, "%s should raise %s" % (stmt, exception)
287
288check_exc("int(BadTypeClass())", TypeError)
289check_exc("float(BadTypeClass())", TypeError)
290check_exc("long(BadTypeClass())", TypeError)
291check_exc("str(BadTypeClass())", TypeError)
292check_exc("repr(BadTypeClass())", TypeError)
293check_exc("oct(BadTypeClass())", TypeError)
294check_exc("hex(BadTypeClass())", TypeError)
295
296# mixing up ints and longs is okay
297class IntLongMixClass:
298 def __int__(self):
299 return 0L
300
301 def __long__(self):
302 return 0
303
304try:
305 int(IntLongMixClass())
306except TypeError:
307 raise TestFailed, "TypeError should not be raised"
308
309try:
310 long(IntLongMixClass())
311except TypeError:
312 raise TestFailed, "TypeError should not be raised"
313
314
Guido van Rossum23120242001-01-18 23:47:15 +0000315# Test correct errors from hash() on objects with comparisons but no __hash__
316
317class C0:
318 pass
319
320hash(C0()) # This should work; the next two should raise TypeError
321
322class C1:
323 def __cmp__(self, other): return 0
324
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000325check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000326
327class C2:
328 def __eq__(self, other): return 1
329
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000330check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000331
332# Test for SF bug 532646
333
334class A:
335 pass
336A.__call__ = A()
337a = A()
338try:
339 a() # This should not segfault
340except RuntimeError:
341 pass
342else:
343 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000344
345
346# Tests for exceptions raised in instance_getattr2().
347
348def booh(self):
349 raise AttributeError, "booh"
350
351class A:
352 a = property(booh)
353try:
354 A().a # Raised AttributeError: A instance has no attribute 'a'
355except AttributeError, x:
356 if str(x) is not "booh":
357 print "attribute error for A().a got masked:", str(x)
358
359class E:
360 __eq__ = property(booh)
361E() == E() # In debug mode, caused a C-level assert() to fail
362
363class I:
364 __init__ = property(booh)
365try:
366 I() # In debug mode, printed XXX undetected error and raises AttributeError
367except AttributeError, x:
368 pass
369else:
370 print "attribute error for I.__init__ got masked"