blob: 795acd911bdfebc01c4730d89b7881b65ec39aac [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
Thomas Wouters1d75a792000-08-17 22:37:32 +0000247testme != 1
2481 == testme
2491 < testme
2501 > testme
Thomas Wouters1d75a792000-08-17 22:37:32 +00002511 != testme
252
253# This test has to be last (duh.)
254
255del testme
Barry Warsaw07d8d642001-08-20 20:29:07 +0000256if sys.platform[:4] == 'java':
257 import java
258 java.lang.System.gc()
Thomas Wouters1d75a792000-08-17 22:37:32 +0000259
260# Interfering tests
261
262class ExtraTests:
Fred Drake004d5e62000-10-23 17:22:08 +0000263 def __getattr__(self, *args):
264 print "__getattr__:", args
265 return "SomeVal"
Thomas Wouters1d75a792000-08-17 22:37:32 +0000266
Fred Drake004d5e62000-10-23 17:22:08 +0000267 def __setattr__(self, *args):
268 print "__setattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000269
Fred Drake004d5e62000-10-23 17:22:08 +0000270 def __delattr__(self, *args):
271 print "__delattr__:", args
Thomas Wouters1d75a792000-08-17 22:37:32 +0000272
273testme = ExtraTests()
274testme.spam
275testme.eggs = "spam, spam, spam and ham"
276del testme.cardinal
Guido van Rossum23120242001-01-18 23:47:15 +0000277
278
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000279# return values of some method are type-checked
280class BadTypeClass:
281 def __int__(self):
282 return None
283 __float__ = __int__
284 __long__ = __int__
285 __str__ = __int__
286 __repr__ = __int__
287 __oct__ = __int__
288 __hex__ = __int__
289
290def check_exc(stmt, exception):
291 """Raise TestFailed if executing 'stmt' does not raise 'exception'
292 """
293 try:
294 exec stmt
295 except exception:
296 pass
297 else:
298 raise TestFailed, "%s should raise %s" % (stmt, exception)
299
300check_exc("int(BadTypeClass())", TypeError)
301check_exc("float(BadTypeClass())", TypeError)
302check_exc("long(BadTypeClass())", TypeError)
303check_exc("str(BadTypeClass())", TypeError)
304check_exc("repr(BadTypeClass())", TypeError)
305check_exc("oct(BadTypeClass())", TypeError)
306check_exc("hex(BadTypeClass())", TypeError)
307
308# mixing up ints and longs is okay
309class IntLongMixClass:
310 def __int__(self):
311 return 0L
312
313 def __long__(self):
314 return 0
315
316try:
317 int(IntLongMixClass())
318except TypeError:
319 raise TestFailed, "TypeError should not be raised"
320
321try:
322 long(IntLongMixClass())
323except TypeError:
324 raise TestFailed, "TypeError should not be raised"
325
326
Guido van Rossum23120242001-01-18 23:47:15 +0000327# Test correct errors from hash() on objects with comparisons but no __hash__
328
329class C0:
330 pass
331
332hash(C0()) # This should work; the next two should raise TypeError
333
334class C1:
335 def __cmp__(self, other): return 0
336
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000337check_exc("hash(C1())", TypeError)
Guido van Rossum23120242001-01-18 23:47:15 +0000338
339class C2:
340 def __eq__(self, other): return 1
341
Neil Schemenauer3a313e32004-07-19 16:29:17 +0000342check_exc("hash(C2())", TypeError)
Guido van Rossum16b93b32002-06-13 21:32:51 +0000343
344# Test for SF bug 532646
345
346class A:
347 pass
348A.__call__ = A()
349a = A()
350try:
351 a() # This should not segfault
352except RuntimeError:
353 pass
354else:
355 raise TestFailed, "how could this not have overflowed the stack?"
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000356
357
358# Tests for exceptions raised in instance_getattr2().
359
360def booh(self):
361 raise AttributeError, "booh"
362
363class A:
364 a = property(booh)
365try:
366 A().a # Raised AttributeError: A instance has no attribute 'a'
367except AttributeError, x:
Michael W. Hudsonabb103b2005-05-04 11:59:38 +0000368 if str(x) != "booh":
Guido van Rossum2c9590f2002-10-29 19:08:29 +0000369 print "attribute error for A().a got masked:", str(x)
370
371class E:
372 __eq__ = property(booh)
373E() == E() # In debug mode, caused a C-level assert() to fail
374
375class I:
376 __init__ = property(booh)
377try:
378 I() # In debug mode, printed XXX undetected error and raises AttributeError
379except AttributeError, x:
380 pass
381else:
382 print "attribute error for I.__init__ got masked"
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000383
384
385# Test comparison and hash of methods
386class A:
387 def __init__(self, x):
388 self.x = x
389 def f(self):
390 pass
391 def g(self):
392 pass
393 def __eq__(self, other):
394 return self.x == other.x
395 def __hash__(self):
396 return self.x
397class B(A):
398 pass
399
400a1 = A(1)
401a2 = A(2)
402assert a1.f == a1.f
403assert a1.f != a2.f
404assert a1.f != a1.g
405assert a1.f == A(1).f
406assert hash(a1.f) == hash(a1.f)
407assert hash(a1.f) == hash(A(1).f)
408
409assert A.f != a1.f
410assert A.f != A.g
411assert B.f == A.f
412assert hash(B.f) == hash(A.f)
413
414# the following triggers a SystemError in 2.4
415a = A(hash(A.f.im_func)^(-1))
416hash(a.f)