blob: a0b3300c84d78b9151b8a3147d84b39a7e051b36 [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
Barry Warsaw07d8d642001-08-20 20:29:07 +0000103 def __del__(self, *args):
104 print "__del__:", args
105
Tim Peters01705212001-12-11 19:28:47 +0000106# Synthesize AllTests methods from the names in testmeths.
107
108method_template = """\
109def __%(method)s__(self, *args):
110 print "__%(method)s__:", args
111"""
112
Thomas Wouters4cdada92006-04-15 09:19:16 +0000113d = {}
Thomas Wouters1d75a792000-08-17 22:37:32 +0000114for method in testmeths:
Thomas Wouters4cdada92006-04-15 09:19:16 +0000115 exec method_template % locals() in d
116for k in d:
117 setattr(AllTests, k, d[k])
118del d, k
Tim Peters01705212001-12-11 19:28:47 +0000119del method, method_template
Thomas Wouters1d75a792000-08-17 22:37:32 +0000120
121# this also tests __init__ of course.
122testme = AllTests()
123
124# Binary operations
125
126testme + 1
1271 + testme
128
129testme - 1
1301 - testme
131
132testme * 1
1331 * testme
134
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000135testme / 1
1361 / testme
Thomas Wouters1d75a792000-08-17 22:37:32 +0000137
138testme % 1
1391 % testme
140
141divmod(testme,1)
142divmod(1, testme)
143
144testme ** 1
1451 ** testme
146
147testme >> 1
1481 >> testme
149
150testme << 1
1511 << testme
152
153testme & 1
1541 & testme
155
156testme | 1
1571 | testme
158
159testme ^ 1
1601 ^ testme
161
162
163# List/dict operations
164
1651 in testme
166
167testme[1]
168testme[1] = 1
169del testme[1]
170
171testme[:42]
172testme[:42] = "The Answer"
173del testme[:42]
174
175testme[2:1024:10]
176testme[2:1024:10] = "A lot"
177del testme[2:1024:10]
178
179testme[:42, ..., :24:, 24, 100]
180testme[:42, ..., :24:, 24, 100] = "Strange"
181del testme[:42, ..., :24:, 24, 100]
182
183
184# Now remove the slice hooks to see if converting normal slices to slice
185# object works.
186
187del AllTests.__getslice__
188del AllTests.__setslice__
189del AllTests.__delslice__
190
Barry Warsaw07d8d642001-08-20 20:29:07 +0000191import sys
192if sys.platform[:4] != 'java':
193 testme[:42]
194 testme[:42] = "The Answer"
195 del testme[:42]
196else:
197 # This works under Jython, but the actual slice values are
198 # different.
199 print "__getitem__: (slice(0, 42, None),)"
200 print "__setitem__: (slice(0, 42, None), 'The Answer')"
201 print "__delitem__: (slice(0, 42, None),)"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000202
203# Unary operations
204
205-testme
206+testme
207abs(testme)
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000208int(testme)
209long(testme)
210float(testme)
211oct(testme)
212hex(testme)
Thomas Wouters1d75a792000-08-17 22:37:32 +0000213
214# And the rest...
215
216hash(testme)
217repr(testme)
218str(testme)
219
220testme == 1
221testme < 1
222testme > 1
223testme <> 1
224testme != 1
2251 == testme
2261 < testme
2271 > testme
2281 <> testme
2291 != testme
230
231# This test has to be last (duh.)
232
233del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000234if sys.platform[:4] == 'java':
235 import java
236 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000237
238# Interfering tests
239
240class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000241 def __getattr__(self, *args):
242 print "__getattr__:", args
243 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000244
Fred Drake004d5e62000-10-23 17:22:08 +0000245 def __setattr__(self, *args):
246 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000247
Fred Drake004d5e62000-10-23 17:22:08 +0000248 def __delattr__(self, *args):
249 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000250
251testme = ExtraTests()
252testme.spam
253testme.eggs = "spam, spam, spam and ham"
254del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000255
256
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000257# return values of some method are type-checked
258class BadTypeClass:
259 def __int__(self):
260 return None
261 __float__ = __int__
262 __long__ = __int__
263 __str__ = __int__
264 __repr__ = __int__
265 __oct__ = __int__
266 __hex__ = __int__
267
268def check_exc(stmt, exception):
269 """Raise TestFailed if executing 'stmt' does not raise 'exception'
270 """
271 try:
272 exec stmt
273 except exception:
274 pass
275 else:
276 raise TestFailed, "%s should raise %s" % (stmt, exception)
277
278check_exc("int(BadTypeClass())", TypeError)
279check_exc("float(BadTypeClass())", TypeError)
280check_exc("long(BadTypeClass())", TypeError)
281check_exc("str(BadTypeClass())", TypeError)
282check_exc("repr(BadTypeClass())", TypeError)
283check_exc("oct(BadTypeClass())", TypeError)
284check_exc("hex(BadTypeClass())", TypeError)
285
286# mixing up ints and longs is okay
287class IntLongMixClass:
288 def __int__(self):
289 return 0L
290
291 def __long__(self):
292 return 0
293
294try:
295 int(IntLongMixClass())
296except TypeError:
297 raise TestFailed, "TypeError should not be raised"
298
299try:
300 long(IntLongMixClass())
301except TypeError:
302 raise TestFailed, "TypeError should not be raised"
303
304
Guido van Rossum23120242001-01-18 23:47:15 +0000305# Test correct errors from hash() on objects with comparisons but no __hash__
306
307class C0:
308 pass
309
310hash(C0()) # This should work; the next two should raise TypeError
311
312class C1:
313 def __cmp__(self, other): return 0
314
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000315check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000316
317class C2:
318 def __eq__(self, other): return 1
319
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000320check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000321
322# Test for SF bug 532646
323
324class A:
325 pass
326A.__call__ = A()
327a = A()
328try:
329 a() # This should not segfault
330except RuntimeError:
331 pass
332else:
333 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000334
335
336# Tests for exceptions raised in instance_getattr2().
337
338def booh(self):
339 raise AttributeError, "booh"
340
341class A:
342 a = property(booh)
343try:
344 A().a # Raised AttributeError: A instance has no attribute 'a'
345except AttributeError, x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000346 if str(x) != "booh":
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000347 print "attribute error for A().a got masked:", str(x)
348
349class E:
350 __eq__ = property(booh)
351E() == E() # In debug mode, caused a C-level assert() to fail
352
353class I:
354 __init__ = property(booh)
355try:
356 I() # In debug mode, printed XXX undetected error and raises AttributeError
357except AttributeError, x:
358 pass
359else:
360 print "attribute error for I.__init__ got masked"
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000361
362
363# Test comparison and hash of methods
364class A:
365 def __init__(self, x):
366 self.x = x
367 def f(self):
368 pass
369 def g(self):
370 pass
371 def __eq__(self, other):
372 return self.x == other.x
373 def __hash__(self):
374 return self.x
375class B(A):
376 pass
377
378a1 = A(1)
379a2 = A(2)
380assert a1.f == a1.f
381assert a1.f != a2.f
382assert a1.f != a1.g
383assert a1.f == A(1).f
384assert hash(a1.f) == hash(a1.f)
385assert hash(a1.f) == hash(A(1).f)
386
387assert A.f != a1.f
388assert A.f != A.g
389assert B.f == A.f
390assert hash(B.f) == hash(A.f)
391
392# the following triggers a SystemError in 2.4
393a = A(hash(A.f.im_func)^(-1))
394hash(a.f)