blob: d925c7585c75d66cc36ba39f7127da151d4c51bb [file] [log] [blame]
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001# Test enhancements related to descriptors and new-style classes
Tim Peters6d6c1a32001-08-02 04:15:00 +00002
Neal Norwitz1a997502003-01-13 20:13:12 +00003from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
Tim Peters6d6c1a32001-08-02 04:15:00 +00004from copy import deepcopy
Tim Peters4d9b4662002-04-16 01:59:17 +00005import warnings
6
7warnings.filterwarnings("ignore",
8 r'complex divmod\(\), // and % are deprecated$',
Guido van Rossum155a34d2002-06-03 19:45:32 +00009 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Guido van Rossum875eeaa2001-10-11 18:33:53 +000011def veris(a, b):
12 if a is not b:
13 raise TestFailed, "%r is %r" % (a, b)
14
Tim Peters6d6c1a32001-08-02 04:15:00 +000015def testunop(a, res, expr="len(a)", meth="__len__"):
16 if verbose: print "checking", expr
17 dict = {'a': a}
Guido van Rossum45704552001-10-08 16:35:45 +000018 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000019 t = type(a)
20 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000021 while meth not in t.__dict__:
22 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000023 vereq(m, t.__dict__[meth])
24 vereq(m(a), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000025 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000026 vereq(bm(), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000027
28def testbinop(a, b, res, expr="a+b", meth="__add__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b}
Tim Peters3caca232001-12-06 06:23:26 +000031
32 # XXX Hack so this passes before 2.3 when -Qnew is specified.
33 if meth == "__div__" and 1/2 == 0.5:
34 meth = "__truediv__"
35
Guido van Rossum45704552001-10-08 16:35:45 +000036 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000037 t = type(a)
38 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000039 while meth not in t.__dict__:
40 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000041 vereq(m, t.__dict__[meth])
42 vereq(m(a, b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000043 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000044 vereq(bm(b), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000045
46def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
47 if verbose: print "checking", expr
48 dict = {'a': a, 'b': b, 'c': c}
Guido van Rossum45704552001-10-08 16:35:45 +000049 vereq(eval(expr, dict), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000050 t = type(a)
51 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000052 while meth not in t.__dict__:
53 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000054 vereq(m, t.__dict__[meth])
55 vereq(m(a, b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000056 bm = getattr(a, meth)
Guido van Rossum45704552001-10-08 16:35:45 +000057 vereq(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000058
59def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b}
62 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000063 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000064 t = type(a)
65 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000066 while meth not in t.__dict__:
67 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000068 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000069 dict['a'] = deepcopy(a)
70 m(dict['a'], b)
Guido van Rossum45704552001-10-08 16:35:45 +000071 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000072 dict['a'] = deepcopy(a)
73 bm = getattr(dict['a'], meth)
74 bm(b)
Guido van Rossum45704552001-10-08 16:35:45 +000075 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000076
77def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
78 if verbose: print "checking", stmt
79 dict = {'a': deepcopy(a), 'b': b, 'c': c}
80 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000081 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000082 t = type(a)
83 m = getattr(t, meth)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000084 while meth not in t.__dict__:
85 t = t.__bases__[0]
Guido van Rossum45704552001-10-08 16:35:45 +000086 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 dict['a'] = deepcopy(a)
88 m(dict['a'], b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000089 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000090 dict['a'] = deepcopy(a)
91 bm = getattr(dict['a'], meth)
92 bm(b, c)
Guido van Rossum45704552001-10-08 16:35:45 +000093 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +000094
95def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
96 if verbose: print "checking", stmt
97 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
98 exec stmt in dict
Guido van Rossum45704552001-10-08 16:35:45 +000099 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 t = type(a)
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000101 while meth not in t.__dict__:
102 t = t.__bases__[0]
Tim Peters6d6c1a32001-08-02 04:15:00 +0000103 m = getattr(t, meth)
Guido van Rossum45704552001-10-08 16:35:45 +0000104 vereq(m, t.__dict__[meth])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 dict['a'] = deepcopy(a)
106 m(dict['a'], b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000107 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108 dict['a'] = deepcopy(a)
109 bm = getattr(dict['a'], meth)
110 bm(b, c, d)
Guido van Rossum45704552001-10-08 16:35:45 +0000111 vereq(dict['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000112
Tim Peters2f93e282001-10-04 05:27:00 +0000113def class_docstrings():
114 class Classic:
115 "A classic docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000116 vereq(Classic.__doc__, "A classic docstring.")
117 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000118
119 class Classic2:
120 pass
121 verify(Classic2.__doc__ is None)
122
Tim Peters4fb1fe82001-10-04 05:48:13 +0000123 class NewStatic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000124 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000125 vereq(NewStatic.__doc__, "Another docstring.")
126 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000127
Tim Peters4fb1fe82001-10-04 05:48:13 +0000128 class NewStatic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000129 pass
130 verify(NewStatic2.__doc__ is None)
131
Tim Peters4fb1fe82001-10-04 05:48:13 +0000132 class NewDynamic(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000133 "Another docstring."
Guido van Rossum45704552001-10-08 16:35:45 +0000134 vereq(NewDynamic.__doc__, "Another docstring.")
135 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
Tim Peters2f93e282001-10-04 05:27:00 +0000136
Tim Peters4fb1fe82001-10-04 05:48:13 +0000137 class NewDynamic2(object):
Tim Peters2f93e282001-10-04 05:27:00 +0000138 pass
139 verify(NewDynamic2.__doc__ is None)
140
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141def lists():
142 if verbose: print "Testing list operations..."
143 testbinop([1], [2], [1,2], "a+b", "__add__")
144 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
145 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
148 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
150 testunop([1,2,3], 3, "len(a)", "__len__")
151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
155
156def dicts():
157 if verbose: print "Testing dict operations..."
158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
162 d = {1:2,3:4}
163 l1 = []
164 for i in d.keys(): l1.append(i)
165 l = []
166 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000167 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 l = []
169 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000170 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 l = []
Tim Petersa427a2b2001-10-29 22:25:45 +0000172 for i in dict.__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000173 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 d = {1:2, 3:4}
175 testunop(d, 2, "len(a)", "__len__")
Guido van Rossum45704552001-10-08 16:35:45 +0000176 vereq(eval(repr(d), {}), d)
177 vereq(eval(d.__repr__(), {}), d)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
179
Tim Peters25786c02001-09-02 08:22:48 +0000180def dict_constructor():
181 if verbose:
Tim Petersa427a2b2001-10-29 22:25:45 +0000182 print "Testing dict constructor ..."
183 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000184 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000185 d = dict({})
Guido van Rossum45704552001-10-08 16:35:45 +0000186 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000187 d = dict({1: 2, 'a': 'b'})
Guido van Rossum45704552001-10-08 16:35:45 +0000188 vereq(d, {1: 2, 'a': 'b'})
Tim Petersa427a2b2001-10-29 22:25:45 +0000189 vereq(d, dict(d.items()))
Just van Rossuma797d812002-11-23 09:45:04 +0000190 vereq(d, dict(d.iteritems()))
191 d = dict({'one':1, 'two':2})
192 vereq(d, dict(one=1, two=2))
193 vereq(d, dict(**d))
194 vereq(d, dict({"one": 1}, two=2))
195 vereq(d, dict([("two", 2)], one=1))
196 vereq(d, dict([("one", 100), ("two", 200)], **d))
197 verify(d is not dict(**d))
Tim Peters25786c02001-09-02 08:22:48 +0000198 for badarg in 0, 0L, 0j, "0", [0], (0,):
199 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000200 dict(badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000201 except TypeError:
202 pass
Tim Peters1fc240e2001-10-26 05:06:50 +0000203 except ValueError:
204 if badarg == "0":
205 # It's a sequence, and its elements are also sequences (gotta
206 # love strings <wink>), but they aren't of length 2, so this
207 # one seemed better as a ValueError than a TypeError.
208 pass
209 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000210 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000211 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000212 raise TestFailed("no TypeError from dict(%r)" % badarg)
Tim Peters25786c02001-09-02 08:22:48 +0000213
214 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000215 dict({}, {})
Tim Peters25786c02001-09-02 08:22:48 +0000216 except TypeError:
217 pass
218 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000219 raise TestFailed("no TypeError from dict({}, {})")
Tim Peters25786c02001-09-02 08:22:48 +0000220
221 class Mapping:
Tim Peters1fc240e2001-10-26 05:06:50 +0000222 # Lacks a .keys() method; will be added later.
Tim Peters25786c02001-09-02 08:22:48 +0000223 dict = {1:2, 3:4, 'a':1j}
224
Tim Peters25786c02001-09-02 08:22:48 +0000225 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000226 dict(Mapping())
Tim Peters25786c02001-09-02 08:22:48 +0000227 except TypeError:
228 pass
229 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000230 raise TestFailed("no TypeError from dict(incomplete mapping)")
Tim Peters25786c02001-09-02 08:22:48 +0000231
232 Mapping.keys = lambda self: self.dict.keys()
Tim Peters1fc240e2001-10-26 05:06:50 +0000233 Mapping.__getitem__ = lambda self, i: self.dict[i]
Just van Rossuma797d812002-11-23 09:45:04 +0000234 d = dict(Mapping())
Guido van Rossum45704552001-10-08 16:35:45 +0000235 vereq(d, Mapping.dict)
Tim Peters25786c02001-09-02 08:22:48 +0000236
Tim Peters1fc240e2001-10-26 05:06:50 +0000237 # Init from sequence of iterable objects, each producing a 2-sequence.
238 class AddressBookEntry:
239 def __init__(self, first, last):
240 self.first = first
241 self.last = last
242 def __iter__(self):
243 return iter([self.first, self.last])
244
Tim Petersa427a2b2001-10-29 22:25:45 +0000245 d = dict([AddressBookEntry('Tim', 'Warsaw'),
Tim Petersfe677e22001-10-30 05:41:07 +0000246 AddressBookEntry('Barry', 'Peters'),
247 AddressBookEntry('Tim', 'Peters'),
248 AddressBookEntry('Barry', 'Warsaw')])
Tim Peters1fc240e2001-10-26 05:06:50 +0000249 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
250
Tim Petersa427a2b2001-10-29 22:25:45 +0000251 d = dict(zip(range(4), range(1, 5)))
252 vereq(d, dict([(i, i+1) for i in range(4)]))
Tim Peters1fc240e2001-10-26 05:06:50 +0000253
254 # Bad sequence lengths.
Tim Peters9fda73c2001-10-26 20:57:38 +0000255 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
Tim Peters1fc240e2001-10-26 05:06:50 +0000256 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000257 dict(bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000258 except ValueError:
259 pass
260 else:
Tim Petersa427a2b2001-10-29 22:25:45 +0000261 raise TestFailed("no ValueError from dict(%r)" % bad)
Tim Peters1fc240e2001-10-26 05:06:50 +0000262
Tim Peters5d2b77c2001-09-03 05:47:38 +0000263def test_dir():
264 if verbose:
265 print "Testing dir() ..."
266 junk = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000267 vereq(dir(), ['junk'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000268 del junk
269
270 # Just make sure these don't blow up!
271 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
272 dir(arg)
273
Tim Peters37a309d2001-09-04 01:20:04 +0000274 # Try classic classes.
Tim Peters5d2b77c2001-09-03 05:47:38 +0000275 class C:
276 Cdata = 1
277 def Cmethod(self): pass
278
279 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
Guido van Rossum45704552001-10-08 16:35:45 +0000280 vereq(dir(C), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000281 verify('im_self' in dir(C.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000282
283 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
Guido van Rossum45704552001-10-08 16:35:45 +0000284 vereq(dir(c), cstuff)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000285
286 c.cdata = 2
287 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000288 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000289 verify('im_self' in dir(c.Cmethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000290
291 class A(C):
292 Adata = 1
293 def Amethod(self): pass
Tim Peters5d2b77c2001-09-03 05:47:38 +0000294
Tim Peters37a309d2001-09-04 01:20:04 +0000295 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000296 vereq(dir(A), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000297 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000298 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000299 vereq(dir(a), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000300 verify('im_self' in dir(a.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000301 a.adata = 42
302 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000303 vereq(dir(a), astuff + ['adata', 'amethod'])
Tim Peters37a309d2001-09-04 01:20:04 +0000304
305 # The same, but with new-style classes. Since these have object as a
306 # base class, a lot more gets sucked in.
307 def interesting(strings):
308 return [s for s in strings if not s.startswith('_')]
309
Tim Peters5d2b77c2001-09-03 05:47:38 +0000310 class C(object):
311 Cdata = 1
312 def Cmethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000313
314 cstuff = ['Cdata', 'Cmethod']
Guido van Rossum45704552001-10-08 16:35:45 +0000315 vereq(interesting(dir(C)), cstuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000316
317 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000318 vereq(interesting(dir(c)), cstuff)
Tim Peters305b5852001-09-17 02:38:46 +0000319 verify('im_self' in dir(C.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000320
321 c.cdata = 2
322 c.cmethod = lambda self: 0
Guido van Rossum45704552001-10-08 16:35:45 +0000323 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000324 verify('im_self' in dir(c.Cmethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000325
Tim Peters5d2b77c2001-09-03 05:47:38 +0000326 class A(C):
327 Adata = 1
328 def Amethod(self): pass
Tim Peters37a309d2001-09-04 01:20:04 +0000329
330 astuff = ['Adata', 'Amethod'] + cstuff
Guido van Rossum45704552001-10-08 16:35:45 +0000331 vereq(interesting(dir(A)), astuff)
Tim Peters305b5852001-09-17 02:38:46 +0000332 verify('im_self' in dir(A.Amethod))
Tim Peters37a309d2001-09-04 01:20:04 +0000333 a = A()
Guido van Rossum45704552001-10-08 16:35:45 +0000334 vereq(interesting(dir(a)), astuff)
Tim Peters37a309d2001-09-04 01:20:04 +0000335 a.adata = 42
336 a.amethod = lambda self: 3
Guido van Rossum45704552001-10-08 16:35:45 +0000337 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
Tim Peters305b5852001-09-17 02:38:46 +0000338 verify('im_self' in dir(a.Amethod))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000339
Tim Peterscaaff8d2001-09-10 23:12:14 +0000340 # Try a module subclass.
341 import sys
342 class M(type(sys)):
343 pass
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000344 minstance = M("m")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000345 minstance.b = 2
346 minstance.a = 1
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000347 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
348 vereq(names, ['a', 'b'])
Tim Peterscaaff8d2001-09-10 23:12:14 +0000349
350 class M2(M):
351 def getdict(self):
352 return "Not a dict!"
353 __dict__ = property(getdict)
354
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000355 m2instance = M2("m2")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000356 m2instance.b = 2
357 m2instance.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +0000358 vereq(m2instance.__dict__, "Not a dict!")
Tim Peterscaaff8d2001-09-10 23:12:14 +0000359 try:
360 dir(m2instance)
361 except TypeError:
362 pass
363
Tim Peters9e6a3992001-10-30 05:45:26 +0000364 # Two essentially featureless objects, just inheriting stuff from
365 # object.
366 vereq(dir(None), dir(Ellipsis))
367
Guido van Rossum44022412002-05-13 18:29:46 +0000368 # Nasty test case for proxied objects
369 class Wrapper(object):
370 def __init__(self, obj):
371 self.__obj = obj
372 def __repr__(self):
373 return "Wrapper(%s)" % repr(self.__obj)
374 def __getitem__(self, key):
375 return Wrapper(self.__obj[key])
376 def __len__(self):
377 return len(self.__obj)
378 def __getattr__(self, name):
379 return Wrapper(getattr(self.__obj, name))
380
381 class C(object):
382 def __getclass(self):
383 return Wrapper(type(self))
384 __class__ = property(__getclass)
385
386 dir(C()) # This used to segfault
387
Tim Peters6d6c1a32001-08-02 04:15:00 +0000388binops = {
389 'add': '+',
390 'sub': '-',
391 'mul': '*',
392 'div': '/',
393 'mod': '%',
394 'divmod': 'divmod',
395 'pow': '**',
396 'lshift': '<<',
397 'rshift': '>>',
398 'and': '&',
399 'xor': '^',
400 'or': '|',
401 'cmp': 'cmp',
402 'lt': '<',
403 'le': '<=',
404 'eq': '==',
405 'ne': '!=',
406 'gt': '>',
407 'ge': '>=',
408 }
409
410for name, expr in binops.items():
411 if expr.islower():
412 expr = expr + "(a, b)"
413 else:
414 expr = 'a %s b' % expr
415 binops[name] = expr
416
417unops = {
418 'pos': '+',
419 'neg': '-',
420 'abs': 'abs',
421 'invert': '~',
422 'int': 'int',
423 'long': 'long',
424 'float': 'float',
425 'oct': 'oct',
426 'hex': 'hex',
427 }
428
429for name, expr in unops.items():
430 if expr.islower():
431 expr = expr + "(a)"
432 else:
433 expr = '%s a' % expr
434 unops[name] = expr
435
436def numops(a, b, skip=[]):
437 dict = {'a': a, 'b': b}
438 for name, expr in binops.items():
439 if name not in skip:
440 name = "__%s__" % name
441 if hasattr(a, name):
442 res = eval(expr, dict)
443 testbinop(a, b, res, expr, name)
444 for name, expr in unops.items():
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000445 if name not in skip:
446 name = "__%s__" % name
447 if hasattr(a, name):
448 res = eval(expr, dict)
449 testunop(a, res, expr, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450
451def ints():
452 if verbose: print "Testing int operations..."
453 numops(100, 3)
Guido van Rossum15d529a2002-03-11 00:07:13 +0000454 # The following crashes in Python 2.2
455 vereq((1).__nonzero__(), 1)
456 vereq((0).__nonzero__(), 0)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000457 # This returns 'NotImplemented' in Python 2.2
458 class C(int):
459 def __add__(self, other):
460 return NotImplemented
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000461 vereq(C(5L), 5)
Guido van Rossumc9e9e402002-03-11 13:21:25 +0000462 try:
463 C() + ""
464 except TypeError:
465 pass
466 else:
Neal Norwitz1af5e352002-03-11 14:44:12 +0000467 raise TestFailed, "NotImplemented should have caused TypeError"
Neal Norwitzde8b94c2003-02-10 02:12:43 +0000468 import sys
469 try:
470 C(sys.maxint+1)
471 except OverflowError:
472 pass
473 else:
474 raise TestFailed, "should have raised OverflowError"
Tim Peters6d6c1a32001-08-02 04:15:00 +0000475
476def longs():
477 if verbose: print "Testing long operations..."
478 numops(100L, 3L)
479
480def floats():
481 if verbose: print "Testing float operations..."
482 numops(100.0, 3.0)
483
484def complexes():
485 if verbose: print "Testing complex operations..."
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +0000486 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000487 class Number(complex):
488 __slots__ = ['prec']
Tim Peters3f996e72001-09-13 19:18:27 +0000489 def __new__(cls, *args, **kwds):
490 result = complex.__new__(cls, *args)
491 result.prec = kwds.get('prec', 12)
492 return result
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 def __repr__(self):
494 prec = self.prec
495 if self.imag == 0.0:
496 return "%.*g" % (prec, self.real)
497 if self.real == 0.0:
498 return "%.*gj" % (prec, self.imag)
499 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
500 __str__ = __repr__
Tim Peters3f996e72001-09-13 19:18:27 +0000501
Tim Peters6d6c1a32001-08-02 04:15:00 +0000502 a = Number(3.14, prec=6)
Guido van Rossum45704552001-10-08 16:35:45 +0000503 vereq(`a`, "3.14")
504 vereq(a.prec, 6)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000505
Tim Peters3f996e72001-09-13 19:18:27 +0000506 a = Number(a, prec=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000507 vereq(`a`, "3.1")
508 vereq(a.prec, 2)
Tim Peters3f996e72001-09-13 19:18:27 +0000509
510 a = Number(234.5)
Guido van Rossum45704552001-10-08 16:35:45 +0000511 vereq(`a`, "234.5")
512 vereq(a.prec, 12)
Tim Peters3f996e72001-09-13 19:18:27 +0000513
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514def spamlists():
515 if verbose: print "Testing spamlist operations..."
516 import copy, xxsubtype as spam
517 def spamlist(l, memo=None):
518 import xxsubtype as spam
519 return spam.spamlist(l)
520 # This is an ugly hack:
521 copy._deepcopy_dispatch[spam.spamlist] = spamlist
522
523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
528 "a[b:c]", "__getslice__")
529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
530 "a+=b", "__iadd__")
531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
538 # Test subclassing
539 class C(spam.spamlist):
540 def foo(self): return 1
541 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000542 vereq(a, [])
543 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000544 a.append(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000545 vereq(a, [100])
546 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 a.setstate(42)
Guido van Rossum45704552001-10-08 16:35:45 +0000548 vereq(a.getstate(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000549
550def spamdicts():
551 if verbose: print "Testing spamdict operations..."
552 import copy, xxsubtype as spam
553 def spamdict(d, memo=None):
554 import xxsubtype as spam
555 sd = spam.spamdict()
556 for k, v in d.items(): sd[k] = v
557 return sd
558 # This is an ugly hack:
559 copy._deepcopy_dispatch[spam.spamdict] = spamdict
560
561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
565 d = spamdict({1:2,3:4})
566 l1 = []
567 for i in d.keys(): l1.append(i)
568 l = []
569 for i in iter(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000570 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000571 l = []
572 for i in d.__iter__(): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000573 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574 l = []
575 for i in type(spamdict({})).__iter__(d): l.append(i)
Guido van Rossum45704552001-10-08 16:35:45 +0000576 vereq(l, l1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577 straightd = {1:2, 3:4}
578 spamd = spamdict(straightd)
579 testunop(spamd, 2, "len(a)", "__len__")
580 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
582 "a[b]=c", "__setitem__")
583 # Test subclassing
584 class C(spam.spamdict):
585 def foo(self): return 1
586 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000587 vereq(a.items(), [])
588 vereq(a.foo(), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 a['foo'] = 'bar'
Guido van Rossum45704552001-10-08 16:35:45 +0000590 vereq(a.items(), [('foo', 'bar')])
591 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592 a.setstate(100)
Guido van Rossum45704552001-10-08 16:35:45 +0000593 vereq(a.getstate(), 100)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
595def pydicts():
596 if verbose: print "Testing Python subclass of dict..."
Tim Petersa427a2b2001-10-29 22:25:45 +0000597 verify(issubclass(dict, dict))
598 verify(isinstance({}, dict))
599 d = dict()
Guido van Rossum45704552001-10-08 16:35:45 +0000600 vereq(d, {})
Tim Petersa427a2b2001-10-29 22:25:45 +0000601 verify(d.__class__ is dict)
602 verify(isinstance(d, dict))
603 class C(dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604 state = -1
605 def __init__(self, *a, **kw):
606 if a:
Guido van Rossum90c45142001-11-24 21:07:01 +0000607 vereq(len(a), 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000608 self.state = a[0]
609 if kw:
610 for k, v in kw.items(): self[v] = k
611 def __getitem__(self, key):
612 return self.get(key, 0)
613 def __setitem__(self, key, value):
Guido van Rossum90c45142001-11-24 21:07:01 +0000614 verify(isinstance(key, type(0)))
Tim Petersa427a2b2001-10-29 22:25:45 +0000615 dict.__setitem__(self, key, value)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616 def setstate(self, state):
617 self.state = state
618 def getstate(self):
619 return self.state
Tim Petersa427a2b2001-10-29 22:25:45 +0000620 verify(issubclass(C, dict))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 a1 = C(12)
Guido van Rossum45704552001-10-08 16:35:45 +0000622 vereq(a1.state, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 a2 = C(foo=1, bar=2)
Guido van Rossum45704552001-10-08 16:35:45 +0000624 vereq(a2[1] == 'foo' and a2[2], 'bar')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000626 vereq(a.state, -1)
627 vereq(a.getstate(), -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 a.setstate(0)
Guido van Rossum45704552001-10-08 16:35:45 +0000629 vereq(a.state, 0)
630 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000632 vereq(a.state, 10)
633 vereq(a.getstate(), 10)
634 vereq(a[42], 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 a[42] = 24
Guido van Rossum45704552001-10-08 16:35:45 +0000636 vereq(a[42], 24)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637 if verbose: print "pydict stress test ..."
638 N = 50
639 for i in range(N):
640 a[i] = C()
641 for j in range(N):
642 a[i][j] = i*j
643 for i in range(N):
644 for j in range(N):
Guido van Rossum45704552001-10-08 16:35:45 +0000645 vereq(a[i][j], i*j)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646
647def pylists():
648 if verbose: print "Testing Python subclass of list..."
649 class C(list):
650 def __getitem__(self, i):
651 return list.__getitem__(self, i) + 100
652 def __getslice__(self, i, j):
653 return (i, j)
654 a = C()
655 a.extend([0,1,2])
Guido van Rossum45704552001-10-08 16:35:45 +0000656 vereq(a[0], 100)
657 vereq(a[1], 101)
658 vereq(a[2], 102)
659 vereq(a[100:200], (100,200))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660
661def metaclass():
662 if verbose: print "Testing __metaclass__..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 class C:
664 __metaclass__ = type
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000672 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000674 vereq(a.getstate(), 10)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 class D:
676 class __metaclass__(type):
677 def myself(cls): return cls
Guido van Rossum45704552001-10-08 16:35:45 +0000678 vereq(D.myself(), D)
Guido van Rossum309b5662001-08-17 11:43:17 +0000679 d = D()
680 verify(d.__class__ is D)
681 class M1(type):
682 def __new__(cls, name, bases, dict):
683 dict['__spam__'] = 1
684 return type.__new__(cls, name, bases, dict)
685 class C:
686 __metaclass__ = M1
Guido van Rossum45704552001-10-08 16:35:45 +0000687 vereq(C.__spam__, 1)
Guido van Rossum309b5662001-08-17 11:43:17 +0000688 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000689 vereq(c.__spam__, 1)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000690
Guido van Rossum309b5662001-08-17 11:43:17 +0000691 class _instance(object):
692 pass
693 class M2(object):
694 def __new__(cls, name, bases, dict):
695 self = object.__new__(cls)
696 self.name = name
697 self.bases = bases
698 self.dict = dict
699 return self
700 __new__ = staticmethod(__new__)
701 def __call__(self):
702 it = _instance()
Guido van Rossum7e1ff692001-08-17 11:55:58 +0000703 # Early binding of methods
704 for key in self.dict:
705 if key.startswith("__"):
706 continue
707 setattr(it, key, self.dict[key].__get__(it, self))
Guido van Rossum309b5662001-08-17 11:43:17 +0000708 return it
709 class C:
710 __metaclass__ = M2
711 def spam(self):
712 return 42
Guido van Rossum45704552001-10-08 16:35:45 +0000713 vereq(C.name, 'C')
714 vereq(C.bases, ())
Guido van Rossum309b5662001-08-17 11:43:17 +0000715 verify('spam' in C.dict)
716 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000717 vereq(c.spam(), 42)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
Guido van Rossum91ee7982001-08-30 20:52:40 +0000719 # More metaclass examples
720
721 class autosuper(type):
722 # Automatically add __super to the class
723 # This trick only works for dynamic classes
Guido van Rossum91ee7982001-08-30 20:52:40 +0000724 def __new__(metaclass, name, bases, dict):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000725 cls = super(autosuper, metaclass).__new__(metaclass,
726 name, bases, dict)
Guido van Rossumbfa47b02001-08-31 04:35:14 +0000727 # Name mangling for __super removes leading underscores
Guido van Rossum91ee7982001-08-30 20:52:40 +0000728 while name[:1] == "_":
729 name = name[1:]
Guido van Rossum91ee7982001-08-30 20:52:40 +0000730 if name:
731 name = "_%s__super" % name
732 else:
733 name = "__super"
734 setattr(cls, name, super(cls))
735 return cls
736 class A:
737 __metaclass__ = autosuper
738 def meth(self):
739 return "A"
740 class B(A):
741 def meth(self):
742 return "B" + self.__super.meth()
743 class C(A):
744 def meth(self):
745 return "C" + self.__super.meth()
746 class D(C, B):
747 def meth(self):
748 return "D" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000749 vereq(D().meth(), "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000750 class E(B, C):
751 def meth(self):
752 return "E" + self.__super.meth()
Guido van Rossum45704552001-10-08 16:35:45 +0000753 vereq(E().meth(), "EBCA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000754
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000755 class autoproperty(type):
756 # Automatically create property attributes when methods
Guido van Rossum91ee7982001-08-30 20:52:40 +0000757 # named _get_x and/or _set_x are found
758 def __new__(metaclass, name, bases, dict):
759 hits = {}
760 for key, val in dict.iteritems():
761 if key.startswith("_get_"):
762 key = key[5:]
763 get, set = hits.get(key, (None, None))
764 get = val
765 hits[key] = get, set
766 elif key.startswith("_set_"):
767 key = key[5:]
768 get, set = hits.get(key, (None, None))
769 set = val
770 hits[key] = get, set
771 for key, (get, set) in hits.iteritems():
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000772 dict[key] = property(get, set)
773 return super(autoproperty, metaclass).__new__(metaclass,
Guido van Rossum91ee7982001-08-30 20:52:40 +0000774 name, bases, dict)
775 class A:
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000776 __metaclass__ = autoproperty
Guido van Rossum91ee7982001-08-30 20:52:40 +0000777 def _get_x(self):
778 return -self.__x
779 def _set_x(self, x):
780 self.__x = -x
781 a = A()
782 verify(not hasattr(a, "x"))
783 a.x = 12
Guido van Rossum45704552001-10-08 16:35:45 +0000784 vereq(a.x, 12)
785 vereq(a._A__x, -12)
Guido van Rossum91ee7982001-08-30 20:52:40 +0000786
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000787 class multimetaclass(autoproperty, autosuper):
Guido van Rossum91ee7982001-08-30 20:52:40 +0000788 # Merge of multiple cooperating metaclasses
789 pass
790 class A:
791 __metaclass__ = multimetaclass
792 def _get_x(self):
793 return "A"
794 class B(A):
795 def _get_x(self):
796 return "B" + self.__super._get_x()
797 class C(A):
798 def _get_x(self):
799 return "C" + self.__super._get_x()
800 class D(C, B):
801 def _get_x(self):
802 return "D" + self.__super._get_x()
Guido van Rossum45704552001-10-08 16:35:45 +0000803 vereq(D().x, "DCBA")
Guido van Rossum91ee7982001-08-30 20:52:40 +0000804
Guido van Rossumf76de622001-10-18 15:49:21 +0000805 # Make sure type(x) doesn't call x.__class__.__init__
806 class T(type):
807 counter = 0
808 def __init__(self, *args):
809 T.counter += 1
810 class C:
811 __metaclass__ = T
812 vereq(T.counter, 1)
813 a = C()
814 vereq(type(a), C)
815 vereq(T.counter, 1)
816
Guido van Rossum29d26062001-12-11 04:37:34 +0000817 class C(object): pass
818 c = C()
819 try: c()
820 except TypeError: pass
Neal Norwitzb1295da2002-04-01 18:59:20 +0000821 else: raise TestFailed, "calling object w/o call method should raise TypeError"
Guido van Rossum29d26062001-12-11 04:37:34 +0000822
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823def pymods():
824 if verbose: print "Testing Python subclass of module..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 log = []
Guido van Rossumd3077402001-08-12 05:24:18 +0000826 import sys
827 MT = type(sys)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 class MM(MT):
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000829 def __init__(self, name):
830 MT.__init__(self, name)
Guido van Rossum867a8d22001-09-21 19:29:08 +0000831 def __getattribute__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 log.append(("getattr", name))
Guido van Rossum867a8d22001-09-21 19:29:08 +0000833 return MT.__getattribute__(self, name)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 def __setattr__(self, name, value):
835 log.append(("setattr", name, value))
836 MT.__setattr__(self, name, value)
837 def __delattr__(self, name):
838 log.append(("delattr", name))
839 MT.__delattr__(self, name)
Guido van Rossum1bdd9b02002-06-04 06:10:37 +0000840 a = MM("a")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 a.foo = 12
842 x = a.foo
843 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +0000844 vereq(log, [("setattr", "foo", 12),
845 ("getattr", "foo"),
846 ("delattr", "foo")])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847
848def multi():
849 if verbose: print "Testing multiple inheritance..."
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 class C(object):
851 def __init__(self):
852 self.__state = 0
853 def getstate(self):
854 return self.__state
855 def setstate(self, state):
856 self.__state = state
857 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +0000858 vereq(a.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859 a.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000860 vereq(a.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000861 class D(dict, C):
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862 def __init__(self):
863 type({}).__init__(self)
864 C.__init__(self)
865 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +0000866 vereq(d.keys(), [])
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867 d["hello"] = "world"
Guido van Rossum45704552001-10-08 16:35:45 +0000868 vereq(d.items(), [("hello", "world")])
869 vereq(d["hello"], "world")
870 vereq(d.getstate(), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871 d.setstate(10)
Guido van Rossum45704552001-10-08 16:35:45 +0000872 vereq(d.getstate(), 10)
Tim Petersa427a2b2001-10-29 22:25:45 +0000873 vereq(D.__mro__, (D, dict, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874
Guido van Rossume45763a2001-08-10 21:28:46 +0000875 # SF bug #442833
876 class Node(object):
877 def __int__(self):
878 return int(self.foo())
879 def foo(self):
880 return "23"
881 class Frag(Node, list):
882 def foo(self):
883 return "42"
Guido van Rossum45704552001-10-08 16:35:45 +0000884 vereq(Node().__int__(), 23)
885 vereq(int(Node()), 23)
886 vereq(Frag().__int__(), 42)
887 vereq(int(Frag()), 42)
Guido van Rossume45763a2001-08-10 21:28:46 +0000888
Tim Petersa91e9642001-11-14 23:32:33 +0000889 # MI mixing classic and new-style classes.
Tim Peters144b98d2001-11-14 23:56:45 +0000890
891 class A:
892 x = 1
893
894 class B(A):
895 pass
896
897 class C(A):
898 x = 2
899
900 class D(B, C):
901 pass
902 vereq(D.x, 1)
903
904 # Classic MRO is preserved for a classic base class.
905 class E(D, object):
906 pass
907 vereq(E.__mro__, (E, D, B, A, C, object))
908 vereq(E.x, 1)
909
910 # But with a mix of classic bases, their MROs are combined using
911 # new-style MRO.
912 class F(B, C, object):
913 pass
914 vereq(F.__mro__, (F, B, C, A, object))
915 vereq(F.x, 2)
916
917 # Try something else.
Tim Petersa91e9642001-11-14 23:32:33 +0000918 class C:
919 def cmethod(self):
920 return "C a"
921 def all_method(self):
922 return "C b"
923
924 class M1(C, object):
925 def m1method(self):
926 return "M1 a"
927 def all_method(self):
928 return "M1 b"
929
930 vereq(M1.__mro__, (M1, C, object))
931 m = M1()
932 vereq(m.cmethod(), "C a")
933 vereq(m.m1method(), "M1 a")
934 vereq(m.all_method(), "M1 b")
935
936 class D(C):
937 def dmethod(self):
938 return "D a"
939 def all_method(self):
940 return "D b"
941
Guido van Rossum9a818922002-11-14 19:50:14 +0000942 class M2(D, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000943 def m2method(self):
944 return "M2 a"
945 def all_method(self):
946 return "M2 b"
947
Guido van Rossum9a818922002-11-14 19:50:14 +0000948 vereq(M2.__mro__, (M2, D, C, object))
Tim Petersa91e9642001-11-14 23:32:33 +0000949 m = M2()
950 vereq(m.cmethod(), "C a")
951 vereq(m.dmethod(), "D a")
952 vereq(m.m2method(), "M2 a")
953 vereq(m.all_method(), "M2 b")
954
Guido van Rossum9a818922002-11-14 19:50:14 +0000955 class M3(M1, M2, object):
Tim Petersa91e9642001-11-14 23:32:33 +0000956 def m3method(self):
957 return "M3 a"
958 def all_method(self):
959 return "M3 b"
Guido van Rossum9a818922002-11-14 19:50:14 +0000960 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
Tim Peters144b98d2001-11-14 23:56:45 +0000961 m = M3()
962 vereq(m.cmethod(), "C a")
963 vereq(m.dmethod(), "D a")
964 vereq(m.m1method(), "M1 a")
965 vereq(m.m2method(), "M2 a")
966 vereq(m.m3method(), "M3 a")
967 vereq(m.all_method(), "M3 b")
Tim Petersa91e9642001-11-14 23:32:33 +0000968
Guido van Rossume54616c2001-12-14 04:19:56 +0000969 class Classic:
970 pass
971 try:
972 class New(Classic):
973 __metaclass__ = type
974 except TypeError:
975 pass
976 else:
977 raise TestFailed, "new class with only classic bases - shouldn't be"
978
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979def diamond():
980 if verbose: print "Testing multiple inheritance special cases..."
981 class A(object):
982 def spam(self): return "A"
Guido van Rossum45704552001-10-08 16:35:45 +0000983 vereq(A().spam(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984 class B(A):
985 def boo(self): return "B"
986 def spam(self): return "B"
Guido van Rossum45704552001-10-08 16:35:45 +0000987 vereq(B().spam(), "B")
988 vereq(B().boo(), "B")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 class C(A):
990 def boo(self): return "C"
Guido van Rossum45704552001-10-08 16:35:45 +0000991 vereq(C().spam(), "A")
992 vereq(C().boo(), "C")
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 class D(B, C): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000994 vereq(D().spam(), "B")
995 vereq(D().boo(), "B")
996 vereq(D.__mro__, (D, B, C, A, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 class E(C, B): pass
Guido van Rossum45704552001-10-08 16:35:45 +0000998 vereq(E().spam(), "B")
999 vereq(E().boo(), "C")
1000 vereq(E.__mro__, (E, C, B, A, object))
Guido van Rossum9a818922002-11-14 19:50:14 +00001001 # MRO order disagreement
1002 try:
1003 class F(D, E): pass
1004 except TypeError:
1005 pass
1006 else:
1007 raise TestFailed, "expected MRO order disagreement (F)"
1008 try:
1009 class G(E, D): pass
1010 except TypeError:
1011 pass
1012 else:
1013 raise TestFailed, "expected MRO order disagreement (G)"
1014
1015
1016# see thread python-dev/2002-October/029035.html
1017def ex5():
1018 if verbose: print "Testing ex5 from C3 switch discussion..."
1019 class A(object): pass
1020 class B(object): pass
1021 class C(object): pass
1022 class X(A): pass
1023 class Y(A): pass
1024 class Z(X,B,Y,C): pass
1025 vereq(Z.__mro__, (Z, X, B, Y, A, C, object))
1026
1027# see "A Monotonic Superclass Linearization for Dylan",
1028# by Kim Barrett et al. (OOPSLA 1996)
1029def monotonicity():
1030 if verbose: print "Testing MRO monotonicity..."
1031 class Boat(object): pass
1032 class DayBoat(Boat): pass
1033 class WheelBoat(Boat): pass
1034 class EngineLess(DayBoat): pass
1035 class SmallMultihull(DayBoat): pass
1036 class PedalWheelBoat(EngineLess,WheelBoat): pass
1037 class SmallCatamaran(SmallMultihull): pass
1038 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
1039
1040 vereq(PedalWheelBoat.__mro__,
1041 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1042 object))
1043 vereq(SmallCatamaran.__mro__,
1044 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1045
1046 vereq(Pedalo.__mro__,
1047 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1048 SmallMultihull, DayBoat, WheelBoat, Boat, object))
1049
1050# see "A Monotonic Superclass Linearization for Dylan",
1051# by Kim Barrett et al. (OOPSLA 1996)
1052def consistency_with_epg():
1053 if verbose: print "Testing consistentcy with EPG..."
1054 class Pane(object): pass
1055 class ScrollingMixin(object): pass
1056 class EditingMixin(object): pass
1057 class ScrollablePane(Pane,ScrollingMixin): pass
1058 class EditablePane(Pane,EditingMixin): pass
1059 class EditableScrollablePane(ScrollablePane,EditablePane): pass
1060
1061 vereq(EditableScrollablePane.__mro__,
1062 (EditableScrollablePane, ScrollablePane, EditablePane,
1063 Pane, ScrollingMixin, EditingMixin, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064
Raymond Hettinger83245b52003-03-12 04:25:42 +00001065mro_err_msg = """Cannot create class.The superclasses have conflicting
1066inheritance trees which leave the method resolution order (MRO)
1067undefined for bases """
1068
Guido van Rossumd32047f2002-11-25 21:38:52 +00001069def mro_disagreement():
1070 if verbose: print "Testing error messages for MRO disagreement..."
1071 def raises(exc, expected, callable, *args):
1072 try:
1073 callable(*args)
1074 except exc, msg:
Guido van Rossuma01fa262002-11-27 04:00:59 +00001075 if not str(msg).startswith(expected):
Guido van Rossumd32047f2002-11-25 21:38:52 +00001076 raise TestFailed, "Message %r, expected %r" % (str(msg),
1077 expected)
1078 else:
1079 raise TestFailed, "Expected %s" % exc
1080 class A(object): pass
1081 class B(A): pass
1082 class C(object): pass
1083 # Test some very simple errors
1084 raises(TypeError, "duplicate base class A",
1085 type, "X", (A, A), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001086 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001087 type, "X", (A, B), {})
Raymond Hettinger83245b52003-03-12 04:25:42 +00001088 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001089 type, "X", (A, C, B), {})
1090 # Test a slightly more complex error
1091 class GridLayout(object): pass
1092 class HorizontalGrid(GridLayout): pass
1093 class VerticalGrid(GridLayout): pass
1094 class HVGrid(HorizontalGrid, VerticalGrid): pass
1095 class VHGrid(VerticalGrid, HorizontalGrid): pass
Raymond Hettinger83245b52003-03-12 04:25:42 +00001096 raises(TypeError, mro_err_msg,
Guido van Rossumd32047f2002-11-25 21:38:52 +00001097 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1098
Guido van Rossum37202612001-08-09 19:45:21 +00001099def objects():
1100 if verbose: print "Testing object class..."
1101 a = object()
Guido van Rossum45704552001-10-08 16:35:45 +00001102 vereq(a.__class__, object)
1103 vereq(type(a), object)
Guido van Rossum37202612001-08-09 19:45:21 +00001104 b = object()
1105 verify(a is not b)
1106 verify(not hasattr(a, "foo"))
1107 try:
1108 a.foo = 12
Guido van Rossum6d946272001-08-10 19:42:38 +00001109 except (AttributeError, TypeError):
Guido van Rossum37202612001-08-09 19:45:21 +00001110 pass
1111 else:
1112 verify(0, "object() should not allow setting a foo attribute")
1113 verify(not hasattr(object(), "__dict__"))
1114
1115 class Cdict(object):
1116 pass
1117 x = Cdict()
Guido van Rossum45704552001-10-08 16:35:45 +00001118 vereq(x.__dict__, {})
Guido van Rossum37202612001-08-09 19:45:21 +00001119 x.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001120 vereq(x.foo, 1)
1121 vereq(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +00001122
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123def slots():
1124 if verbose: print "Testing __slots__..."
1125 class C0(object):
1126 __slots__ = []
1127 x = C0()
1128 verify(not hasattr(x, "__dict__"))
1129 verify(not hasattr(x, "foo"))
1130
1131 class C1(object):
1132 __slots__ = ['a']
1133 x = C1()
1134 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001135 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001136 x.a = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001137 vereq(x.a, 1)
Guido van Rossum6b705992001-12-04 16:23:42 +00001138 x.a = None
1139 veris(x.a, None)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 del x.a
Guido van Rossum6b705992001-12-04 16:23:42 +00001141 verify(not hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142
1143 class C3(object):
1144 __slots__ = ['a', 'b', 'c']
1145 x = C3()
1146 verify(not hasattr(x, "__dict__"))
Guido van Rossum6b705992001-12-04 16:23:42 +00001147 verify(not hasattr(x, 'a'))
1148 verify(not hasattr(x, 'b'))
1149 verify(not hasattr(x, 'c'))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 x.a = 1
1151 x.b = 2
1152 x.c = 3
Guido van Rossum45704552001-10-08 16:35:45 +00001153 vereq(x.a, 1)
1154 vereq(x.b, 2)
1155 vereq(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001157 class C4(object):
1158 """Validate name mangling"""
1159 __slots__ = ['__a']
1160 def __init__(self, value):
1161 self.__a = value
1162 def get(self):
1163 return self.__a
1164 x = C4(5)
1165 verify(not hasattr(x, '__dict__'))
1166 verify(not hasattr(x, '__a'))
1167 vereq(x.get(), 5)
1168 try:
1169 x.__a = 6
1170 except AttributeError:
1171 pass
1172 else:
1173 raise TestFailed, "Double underscored names not mangled"
1174
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001175 # Make sure slot names are proper identifiers
1176 try:
1177 class C(object):
1178 __slots__ = [None]
1179 except TypeError:
1180 pass
1181 else:
1182 raise TestFailed, "[None] slots not caught"
1183 try:
1184 class C(object):
1185 __slots__ = ["foo bar"]
1186 except TypeError:
1187 pass
1188 else:
1189 raise TestFailed, "['foo bar'] slots not caught"
1190 try:
1191 class C(object):
1192 __slots__ = ["foo\0bar"]
1193 except TypeError:
1194 pass
1195 else:
1196 raise TestFailed, "['foo\\0bar'] slots not caught"
1197 try:
1198 class C(object):
1199 __slots__ = ["1"]
1200 except TypeError:
1201 pass
1202 else:
1203 raise TestFailed, "['1'] slots not caught"
1204 try:
1205 class C(object):
1206 __slots__ = [""]
1207 except TypeError:
1208 pass
1209 else:
1210 raise TestFailed, "[''] slots not caught"
1211 class C(object):
1212 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1213
Guido van Rossum33bab012001-12-05 22:45:48 +00001214 # Test leaks
1215 class Counted(object):
1216 counter = 0 # counts the number of instances alive
1217 def __init__(self):
1218 Counted.counter += 1
1219 def __del__(self):
1220 Counted.counter -= 1
1221 class C(object):
1222 __slots__ = ['a', 'b', 'c']
1223 x = C()
1224 x.a = Counted()
1225 x.b = Counted()
1226 x.c = Counted()
1227 vereq(Counted.counter, 3)
1228 del x
1229 vereq(Counted.counter, 0)
1230 class D(C):
1231 pass
1232 x = D()
1233 x.a = Counted()
1234 x.z = Counted()
1235 vereq(Counted.counter, 2)
1236 del x
1237 vereq(Counted.counter, 0)
1238 class E(D):
1239 __slots__ = ['e']
1240 x = E()
1241 x.a = Counted()
1242 x.z = Counted()
1243 x.e = Counted()
1244 vereq(Counted.counter, 3)
1245 del x
1246 vereq(Counted.counter, 0)
1247
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001248 # Test cyclical leaks [SF bug 519621]
1249 class F(object):
1250 __slots__ = ['a', 'b']
1251 log = []
1252 s = F()
1253 s.a = [Counted(), s]
1254 vereq(Counted.counter, 1)
1255 s = None
1256 import gc
1257 gc.collect()
1258 vereq(Counted.counter, 0)
1259
Raymond Hettingerab5dae32002-06-24 13:08:16 +00001260 # Test lookup leaks [SF bug 572567]
1261 import sys,gc
1262 class G(object):
1263 def __cmp__(self, other):
1264 return 0
1265 g = G()
1266 orig_objects = len(gc.get_objects())
1267 for i in xrange(10):
1268 g==g
1269 new_objects = len(gc.get_objects())
1270 vereq(orig_objects, new_objects)
1271
Guido van Rossum8b056da2002-08-13 18:26:26 +00001272def slotspecials():
1273 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
1274
1275 class D(object):
1276 __slots__ = ["__dict__"]
1277 a = D()
1278 verify(hasattr(a, "__dict__"))
1279 verify(not hasattr(a, "__weakref__"))
1280 a.foo = 42
1281 vereq(a.__dict__, {"foo": 42})
1282
1283 class W(object):
1284 __slots__ = ["__weakref__"]
1285 a = W()
1286 verify(hasattr(a, "__weakref__"))
1287 verify(not hasattr(a, "__dict__"))
1288 try:
1289 a.foo = 42
1290 except AttributeError:
1291 pass
1292 else:
1293 raise TestFailed, "shouldn't be allowed to set a.foo"
1294
1295 class C1(W, D):
1296 __slots__ = []
1297 a = C1()
1298 verify(hasattr(a, "__dict__"))
1299 verify(hasattr(a, "__weakref__"))
1300 a.foo = 42
1301 vereq(a.__dict__, {"foo": 42})
1302
1303 class C2(D, W):
1304 __slots__ = []
1305 a = C2()
1306 verify(hasattr(a, "__dict__"))
1307 verify(hasattr(a, "__weakref__"))
1308 a.foo = 42
1309 vereq(a.__dict__, {"foo": 42})
1310
Guido van Rossum9a818922002-11-14 19:50:14 +00001311# MRO order disagreement
1312#
1313# class C3(C1, C2):
1314# __slots__ = []
1315#
1316# class C4(C2, C1):
1317# __slots__ = []
Guido van Rossum8b056da2002-08-13 18:26:26 +00001318
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319def dynamics():
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001320 if verbose: print "Testing class attribute propagation..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 class D(object):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001323 class E(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 pass
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001325 class F(D):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 pass
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 D.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001328 vereq(D.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 # Test that dynamic attributes are inherited
Guido van Rossum45704552001-10-08 16:35:45 +00001330 vereq(E.foo, 1)
1331 vereq(F.foo, 1)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001332 # Test dynamic instances
1333 class C(object):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001334 pass
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001335 a = C()
Guido van Rossumd3077402001-08-12 05:24:18 +00001336 verify(not hasattr(a, "foobar"))
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001337 C.foobar = 2
Guido van Rossum45704552001-10-08 16:35:45 +00001338 vereq(a.foobar, 2)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001339 C.method = lambda self: 42
Guido van Rossum45704552001-10-08 16:35:45 +00001340 vereq(a.method(), 42)
Guido van Rossum9d4fe422001-08-12 03:38:18 +00001341 C.__repr__ = lambda self: "C()"
Guido van Rossum45704552001-10-08 16:35:45 +00001342 vereq(repr(a), "C()")
Guido van Rossumd3077402001-08-12 05:24:18 +00001343 C.__int__ = lambda self: 100
Guido van Rossum45704552001-10-08 16:35:45 +00001344 vereq(int(a), 100)
1345 vereq(a.foobar, 2)
Guido van Rossumd3077402001-08-12 05:24:18 +00001346 verify(not hasattr(a, "spam"))
1347 def mygetattr(self, name):
1348 if name == "spam":
1349 return "spam"
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001350 raise AttributeError
1351 C.__getattr__ = mygetattr
Guido van Rossum45704552001-10-08 16:35:45 +00001352 vereq(a.spam, "spam")
Guido van Rossumd3077402001-08-12 05:24:18 +00001353 a.new = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001354 vereq(a.new, 12)
Guido van Rossumd3077402001-08-12 05:24:18 +00001355 def mysetattr(self, name, value):
1356 if name == "spam":
1357 raise AttributeError
1358 return object.__setattr__(self, name, value)
1359 C.__setattr__ = mysetattr
1360 try:
1361 a.spam = "not spam"
1362 except AttributeError:
1363 pass
1364 else:
1365 verify(0, "expected AttributeError")
Guido van Rossum45704552001-10-08 16:35:45 +00001366 vereq(a.spam, "spam")
Guido van Rossum80e36752001-08-14 20:00:33 +00001367 class D(C):
1368 pass
1369 d = D()
1370 d.foo = 1
Guido van Rossum45704552001-10-08 16:35:45 +00001371 vereq(d.foo, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372
Guido van Rossum7e35d572001-09-15 03:14:32 +00001373 # Test handling of int*seq and seq*int
1374 class I(int):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001375 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001376 vereq("a"*I(2), "aa")
1377 vereq(I(2)*"a", "aa")
1378 vereq(2*I(3), 6)
1379 vereq(I(3)*2, 6)
1380 vereq(I(3)*I(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001381
1382 # Test handling of long*seq and seq*long
1383 class L(long):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001384 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001385 vereq("a"*L(2L), "aa")
1386 vereq(L(2L)*"a", "aa")
1387 vereq(2*L(3), 6)
1388 vereq(L(3)*2, 6)
1389 vereq(L(3)*L(2), 6)
Guido van Rossum7e35d572001-09-15 03:14:32 +00001390
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001391 # Test comparison of classes with dynamic metaclasses
1392 class dynamicmetaclass(type):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001393 pass
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00001394 class someclass:
1395 __metaclass__ = dynamicmetaclass
1396 verify(someclass != object)
1397
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398def errors():
1399 if verbose: print "Testing errors..."
1400
1401 try:
Tim Petersa427a2b2001-10-29 22:25:45 +00001402 class C(list, dict):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403 pass
1404 except TypeError:
1405 pass
1406 else:
1407 verify(0, "inheritance from both list and dict should be illegal")
1408
1409 try:
1410 class C(object, None):
1411 pass
1412 except TypeError:
1413 pass
1414 else:
1415 verify(0, "inheritance from non-type should be illegal")
1416 class Classic:
1417 pass
1418
1419 try:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001420 class C(type(len)):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 pass
1422 except TypeError:
1423 pass
1424 else:
Guido van Rossum8aea0cc2001-08-29 15:48:43 +00001425 verify(0, "inheritance from CFunction should be illegal")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426
1427 try:
1428 class C(object):
1429 __slots__ = 1
1430 except TypeError:
1431 pass
1432 else:
1433 verify(0, "__slots__ = 1 should be illegal")
1434
1435 try:
1436 class C(object):
1437 __slots__ = [1]
1438 except TypeError:
1439 pass
1440 else:
1441 verify(0, "__slots__ = [1] should be illegal")
1442
1443def classmethods():
1444 if verbose: print "Testing class methods..."
1445 class C(object):
1446 def foo(*a): return a
1447 goo = classmethod(foo)
1448 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001449 vereq(C.goo(1), (C, 1))
1450 vereq(c.goo(1), (C, 1))
1451 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452 class D(C):
1453 pass
1454 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001455 vereq(D.goo(1), (D, 1))
1456 vereq(d.goo(1), (D, 1))
1457 vereq(d.foo(1), (d, 1))
1458 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum7e305482002-03-18 03:09:06 +00001459 # Test for a specific crash (SF bug 528132)
1460 def f(cls, arg): return (cls, arg)
1461 ff = classmethod(f)
1462 vereq(ff.__get__(0, int)(42), (int, 42))
1463 vereq(ff.__get__(0)(42), (int, 42))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464
Guido van Rossum155db9a2002-04-02 17:53:47 +00001465 # Test super() with classmethods (SF bug 535444)
1466 veris(C.goo.im_self, C)
1467 veris(D.goo.im_self, D)
1468 veris(super(D,D).goo.im_self, D)
1469 veris(super(D,d).goo.im_self, D)
1470 vereq(super(D,D).goo(), (D,))
1471 vereq(super(D,d).goo(), (D,))
1472
Fred Drakef841aa62002-03-28 15:49:54 +00001473def classmethods_in_c():
1474 if verbose: print "Testing C-based class methods..."
1475 import xxsubtype as spam
1476 a = (1, 2, 3)
1477 d = {'abc': 123}
1478 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001479 veris(x, spam.spamlist)
1480 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001481 vereq(d, d1)
1482 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
Tim Petersbca1cbc2002-12-09 22:56:13 +00001483 veris(x, spam.spamlist)
1484 vereq(a, a1)
Fred Drakef841aa62002-03-28 15:49:54 +00001485 vereq(d, d1)
1486
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487def staticmethods():
1488 if verbose: print "Testing static methods..."
1489 class C(object):
1490 def foo(*a): return a
1491 goo = staticmethod(foo)
1492 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001493 vereq(C.goo(1), (1,))
1494 vereq(c.goo(1), (1,))
1495 vereq(c.foo(1), (c, 1,))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 class D(C):
1497 pass
1498 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001499 vereq(D.goo(1), (1,))
1500 vereq(d.goo(1), (1,))
1501 vereq(d.foo(1), (d, 1))
1502 vereq(D.foo(d, 1), (d, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503
Fred Drakef841aa62002-03-28 15:49:54 +00001504def staticmethods_in_c():
1505 if verbose: print "Testing C-based static methods..."
1506 import xxsubtype as spam
1507 a = (1, 2, 3)
1508 d = {"abc": 123}
1509 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1510 veris(x, None)
1511 vereq(a, a1)
1512 vereq(d, d1)
1513 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1514 veris(x, None)
1515 vereq(a, a1)
1516 vereq(d, d1)
1517
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518def classic():
1519 if verbose: print "Testing classic classes..."
1520 class C:
1521 def foo(*a): return a
1522 goo = classmethod(foo)
1523 c = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001524 vereq(C.goo(1), (C, 1))
1525 vereq(c.goo(1), (C, 1))
1526 vereq(c.foo(1), (c, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 class D(C):
1528 pass
1529 d = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001530 vereq(D.goo(1), (D, 1))
1531 vereq(d.goo(1), (D, 1))
1532 vereq(d.foo(1), (d, 1))
1533 vereq(D.foo(d, 1), (d, 1))
Guido van Rossum93018762001-08-17 13:40:47 +00001534 class E: # *not* subclassing from C
1535 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001536 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001537 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001538
1539def compattr():
1540 if verbose: print "Testing computed attributes..."
1541 class C(object):
1542 class computed_attribute(object):
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001543 def __init__(self, get, set=None, delete=None):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 self.__get = get
1545 self.__set = set
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001546 self.__delete = delete
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 def __get__(self, obj, type=None):
1548 return self.__get(obj)
1549 def __set__(self, obj, value):
1550 return self.__set(obj, value)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001551 def __delete__(self, obj):
1552 return self.__delete(obj)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 def __init__(self):
1554 self.__x = 0
1555 def __get_x(self):
1556 x = self.__x
1557 self.__x = x+1
1558 return x
1559 def __set_x(self, x):
1560 self.__x = x
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001561 def __delete_x(self):
1562 del self.__x
1563 x = computed_attribute(__get_x, __set_x, __delete_x)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001565 vereq(a.x, 0)
1566 vereq(a.x, 1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 a.x = 10
Guido van Rossum45704552001-10-08 16:35:45 +00001568 vereq(a.x, 10)
1569 vereq(a.x, 11)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001570 del a.x
1571 vereq(hasattr(a, 'x'), 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572
1573def newslot():
1574 if verbose: print "Testing __new__ slot override..."
1575 class C(list):
1576 def __new__(cls):
1577 self = list.__new__(cls)
1578 self.foo = 1
1579 return self
1580 def __init__(self):
1581 self.foo = self.foo + 2
1582 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001583 vereq(a.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584 verify(a.__class__ is C)
1585 class D(C):
1586 pass
1587 b = D()
Guido van Rossum45704552001-10-08 16:35:45 +00001588 vereq(b.foo, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 verify(b.__class__ is D)
1590
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591def altmro():
1592 if verbose: print "Testing mro() and overriding it..."
1593 class A(object):
1594 def f(self): return "A"
1595 class B(A):
1596 pass
1597 class C(A):
1598 def f(self): return "C"
1599 class D(B, C):
1600 pass
Guido van Rossum45704552001-10-08 16:35:45 +00001601 vereq(D.mro(), [D, B, C, A, object])
1602 vereq(D.__mro__, (D, B, C, A, object))
1603 vereq(D().f(), "C")
Guido van Rossum9a818922002-11-14 19:50:14 +00001604
Guido van Rossumd3077402001-08-12 05:24:18 +00001605 class PerverseMetaType(type):
1606 def mro(cls):
1607 L = type.mro(cls)
1608 L.reverse()
1609 return L
Guido van Rossum9a818922002-11-14 19:50:14 +00001610 class X(D,B,C,A):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 __metaclass__ = PerverseMetaType
Guido van Rossum45704552001-10-08 16:35:45 +00001612 vereq(X.__mro__, (object, A, C, B, D, X))
1613 vereq(X().f(), "A")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001614
1615def overloading():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001616 if verbose: print "Testing operator overloading..."
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617
1618 class B(object):
1619 "Intermediate class because object doesn't have a __setattr__"
1620
1621 class C(B):
1622
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001623 def __getattr__(self, name):
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624 if name == "foo":
1625 return ("getattr", name)
1626 else:
Guido van Rossum19c1cd52001-09-21 21:24:49 +00001627 raise AttributeError
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 def __setattr__(self, name, value):
1629 if name == "foo":
1630 self.setattr = (name, value)
1631 else:
1632 return B.__setattr__(self, name, value)
1633 def __delattr__(self, name):
1634 if name == "foo":
1635 self.delattr = name
1636 else:
1637 return B.__delattr__(self, name)
1638
1639 def __getitem__(self, key):
1640 return ("getitem", key)
1641 def __setitem__(self, key, value):
1642 self.setitem = (key, value)
1643 def __delitem__(self, key):
1644 self.delitem = key
1645
1646 def __getslice__(self, i, j):
1647 return ("getslice", i, j)
1648 def __setslice__(self, i, j, value):
1649 self.setslice = (i, j, value)
1650 def __delslice__(self, i, j):
1651 self.delslice = (i, j)
1652
1653 a = C()
Guido van Rossum45704552001-10-08 16:35:45 +00001654 vereq(a.foo, ("getattr", "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 a.foo = 12
Guido van Rossum45704552001-10-08 16:35:45 +00001656 vereq(a.setattr, ("foo", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 del a.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001658 vereq(a.delattr, "foo")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659
Guido van Rossum45704552001-10-08 16:35:45 +00001660 vereq(a[12], ("getitem", 12))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661 a[12] = 21
Guido van Rossum45704552001-10-08 16:35:45 +00001662 vereq(a.setitem, (12, 21))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 del a[12]
Guido van Rossum45704552001-10-08 16:35:45 +00001664 vereq(a.delitem, 12)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665
Guido van Rossum45704552001-10-08 16:35:45 +00001666 vereq(a[0:10], ("getslice", 0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 a[0:10] = "foo"
Guido van Rossum45704552001-10-08 16:35:45 +00001668 vereq(a.setslice, (0, 10, "foo"))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 del a[0:10]
Guido van Rossum45704552001-10-08 16:35:45 +00001670 vereq(a.delslice, (0, 10))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001672def methods():
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001673 if verbose: print "Testing methods..."
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001674 class C(object):
1675 def __init__(self, x):
1676 self.x = x
1677 def foo(self):
1678 return self.x
1679 c1 = C(1)
Guido van Rossum45704552001-10-08 16:35:45 +00001680 vereq(c1.foo(), 1)
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001681 class D(C):
1682 boo = C.foo
1683 goo = c1.foo
1684 d2 = D(2)
Guido van Rossum45704552001-10-08 16:35:45 +00001685 vereq(d2.foo(), 2)
1686 vereq(d2.boo(), 2)
1687 vereq(d2.goo(), 1)
Guido van Rossum93018762001-08-17 13:40:47 +00001688 class E(object):
1689 foo = C.foo
Guido van Rossum45704552001-10-08 16:35:45 +00001690 vereq(E().foo, C.foo) # i.e., unbound
Guido van Rossum84a79a82001-08-17 13:58:31 +00001691 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Guido van Rossumb5a136b2001-08-15 17:51:17 +00001692
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001693def specials():
1694 # Test operators like __hash__ for which a built-in default exists
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001695 if verbose: print "Testing special operators..."
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001696 # Test the default behavior for static classes
1697 class C(object):
1698 def __getitem__(self, i):
1699 if 0 <= i < 10: return i
1700 raise IndexError
1701 c1 = C()
1702 c2 = C()
1703 verify(not not c1)
Guido van Rossum45704552001-10-08 16:35:45 +00001704 vereq(hash(c1), id(c1))
1705 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1706 vereq(c1, c1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001707 verify(c1 != c2)
1708 verify(not c1 != c1)
1709 verify(not c1 == c2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001710 # Note that the module name appears in str/repr, and that varies
1711 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001712 verify(str(c1).find('C object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001713 vereq(str(c1), repr(c1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001714 verify(-1 not in c1)
1715 for i in range(10):
1716 verify(i in c1)
1717 verify(10 not in c1)
1718 # Test the default behavior for dynamic classes
1719 class D(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001720 def __getitem__(self, i):
1721 if 0 <= i < 10: return i
1722 raise IndexError
1723 d1 = D()
1724 d2 = D()
1725 verify(not not d1)
Guido van Rossum45704552001-10-08 16:35:45 +00001726 vereq(hash(d1), id(d1))
1727 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1728 vereq(d1, d1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001729 verify(d1 != d2)
1730 verify(not d1 != d1)
1731 verify(not d1 == d2)
Tim Peters4d2dded2001-08-16 19:50:51 +00001732 # Note that the module name appears in str/repr, and that varies
1733 # depending on whether this test is run standalone or from a framework.
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001734 verify(str(d1).find('D object at ') >= 0)
Guido van Rossum45704552001-10-08 16:35:45 +00001735 vereq(str(d1), repr(d1))
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001736 verify(-1 not in d1)
1737 for i in range(10):
1738 verify(i in d1)
1739 verify(10 not in d1)
1740 # Test overridden behavior for static classes
1741 class Proxy(object):
1742 def __init__(self, x):
1743 self.x = x
1744 def __nonzero__(self):
1745 return not not self.x
1746 def __hash__(self):
1747 return hash(self.x)
1748 def __eq__(self, other):
1749 return self.x == other
1750 def __ne__(self, other):
1751 return self.x != other
1752 def __cmp__(self, other):
1753 return cmp(self.x, other.x)
1754 def __str__(self):
1755 return "Proxy:%s" % self.x
1756 def __repr__(self):
1757 return "Proxy(%r)" % self.x
1758 def __contains__(self, value):
1759 return value in self.x
1760 p0 = Proxy(0)
1761 p1 = Proxy(1)
1762 p_1 = Proxy(-1)
1763 verify(not p0)
1764 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001765 vereq(hash(p0), hash(0))
1766 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001767 verify(p0 != p1)
1768 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001769 vereq(not p0, p1)
1770 vereq(cmp(p0, p1), -1)
1771 vereq(cmp(p0, p0), 0)
1772 vereq(cmp(p0, p_1), 1)
1773 vereq(str(p0), "Proxy:0")
1774 vereq(repr(p0), "Proxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001775 p10 = Proxy(range(10))
1776 verify(-1 not in p10)
1777 for i in range(10):
1778 verify(i in p10)
1779 verify(10 not in p10)
1780 # Test overridden behavior for dynamic classes
1781 class DProxy(object):
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001782 def __init__(self, x):
1783 self.x = x
1784 def __nonzero__(self):
1785 return not not self.x
1786 def __hash__(self):
1787 return hash(self.x)
1788 def __eq__(self, other):
1789 return self.x == other
1790 def __ne__(self, other):
1791 return self.x != other
1792 def __cmp__(self, other):
1793 return cmp(self.x, other.x)
1794 def __str__(self):
1795 return "DProxy:%s" % self.x
1796 def __repr__(self):
1797 return "DProxy(%r)" % self.x
1798 def __contains__(self, value):
1799 return value in self.x
1800 p0 = DProxy(0)
1801 p1 = DProxy(1)
1802 p_1 = DProxy(-1)
1803 verify(not p0)
1804 verify(not not p1)
Guido van Rossum45704552001-10-08 16:35:45 +00001805 vereq(hash(p0), hash(0))
1806 vereq(p0, p0)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001807 verify(p0 != p1)
1808 verify(not p0 != p0)
Guido van Rossum45704552001-10-08 16:35:45 +00001809 vereq(not p0, p1)
1810 vereq(cmp(p0, p1), -1)
1811 vereq(cmp(p0, p0), 0)
1812 vereq(cmp(p0, p_1), 1)
1813 vereq(str(p0), "DProxy:0")
1814 vereq(repr(p0), "DProxy(0)")
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001815 p10 = DProxy(range(10))
1816 verify(-1 not in p10)
1817 for i in range(10):
1818 verify(i in p10)
1819 verify(10 not in p10)
Guido van Rossum843daa82001-09-18 20:04:26 +00001820 # Safety test for __cmp__
1821 def unsafecmp(a, b):
1822 try:
1823 a.__class__.__cmp__(a, b)
1824 except TypeError:
1825 pass
1826 else:
1827 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1828 a.__class__, a, b)
1829 unsafecmp(u"123", "123")
1830 unsafecmp("123", u"123")
1831 unsafecmp(1, 1.0)
1832 unsafecmp(1.0, 1)
1833 unsafecmp(1, 1L)
1834 unsafecmp(1L, 1)
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00001835
Neal Norwitz1a997502003-01-13 20:13:12 +00001836 class Letter(str):
1837 def __new__(cls, letter):
1838 if letter == 'EPS':
1839 return str.__new__(cls)
1840 return str.__new__(cls, letter)
1841 def __str__(self):
1842 if not self:
1843 return 'EPS'
Tim Petersf2715e02003-02-19 02:35:07 +00001844 return self
Neal Norwitz1a997502003-01-13 20:13:12 +00001845
1846 # sys.stdout needs to be the original to trigger the recursion bug
1847 import sys
1848 test_stdout = sys.stdout
1849 sys.stdout = get_original_stdout()
1850 try:
1851 # nothing should actually be printed, this should raise an exception
1852 print Letter('w')
1853 except RuntimeError:
1854 pass
1855 else:
1856 raise TestFailed, "expected a RuntimeError for print recursion"
1857 sys.stdout = test_stdout
1858
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001859def weakrefs():
1860 if verbose: print "Testing weak references..."
1861 import weakref
1862 class C(object):
1863 pass
1864 c = C()
1865 r = weakref.ref(c)
1866 verify(r() is c)
1867 del c
1868 verify(r() is None)
1869 del r
1870 class NoWeak(object):
1871 __slots__ = ['foo']
1872 no = NoWeak()
1873 try:
1874 weakref.ref(no)
1875 except TypeError, msg:
Fred Drake4bf018b2001-10-22 21:45:25 +00001876 verify(str(msg).find("weak reference") >= 0)
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00001877 else:
1878 verify(0, "weakref.ref(no) should be illegal")
1879 class Weak(object):
1880 __slots__ = ['foo', '__weakref__']
1881 yes = Weak()
1882 r = weakref.ref(yes)
1883 verify(r() is yes)
1884 del yes
1885 verify(r() is None)
1886 del r
1887
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00001888def properties():
1889 if verbose: print "Testing property..."
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001890 class C(object):
1891 def getx(self):
1892 return self.__x
1893 def setx(self, value):
1894 self.__x = value
1895 def delx(self):
1896 del self.__x
Tim Peters66c1a522001-09-24 21:17:50 +00001897 x = property(getx, setx, delx, doc="I'm the x property.")
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001898 a = C()
1899 verify(not hasattr(a, "x"))
1900 a.x = 42
Guido van Rossum45704552001-10-08 16:35:45 +00001901 vereq(a._C__x, 42)
1902 vereq(a.x, 42)
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001903 del a.x
1904 verify(not hasattr(a, "x"))
1905 verify(not hasattr(a, "_C__x"))
1906 C.x.__set__(a, 100)
Guido van Rossum45704552001-10-08 16:35:45 +00001907 vereq(C.x.__get__(a), 100)
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00001908 C.x.__delete__(a)
1909 verify(not hasattr(a, "x"))
Guido van Rossum76f0cb82001-08-24 15:24:24 +00001910
Tim Peters66c1a522001-09-24 21:17:50 +00001911 raw = C.__dict__['x']
1912 verify(isinstance(raw, property))
1913
1914 attrs = dir(raw)
1915 verify("__doc__" in attrs)
1916 verify("fget" in attrs)
1917 verify("fset" in attrs)
1918 verify("fdel" in attrs)
1919
Guido van Rossum45704552001-10-08 16:35:45 +00001920 vereq(raw.__doc__, "I'm the x property.")
Tim Peters66c1a522001-09-24 21:17:50 +00001921 verify(raw.fget is C.__dict__['getx'])
1922 verify(raw.fset is C.__dict__['setx'])
1923 verify(raw.fdel is C.__dict__['delx'])
1924
1925 for attr in "__doc__", "fget", "fset", "fdel":
1926 try:
1927 setattr(raw, attr, 42)
1928 except TypeError, msg:
1929 if str(msg).find('readonly') < 0:
1930 raise TestFailed("when setting readonly attr %r on a "
1931 "property, got unexpected TypeError "
1932 "msg %r" % (attr, str(msg)))
1933 else:
1934 raise TestFailed("expected TypeError from trying to set "
1935 "readonly %r attr on a property" % attr)
1936
Neal Norwitz673cd822002-10-18 16:33:13 +00001937 class D(object):
1938 __getitem__ = property(lambda s: 1/0)
1939
1940 d = D()
1941 try:
1942 for i in d:
1943 str(i)
1944 except ZeroDivisionError:
1945 pass
1946 else:
1947 raise TestFailed, "expected ZeroDivisionError from bad property"
1948
Guido van Rossumc4a18802001-08-24 16:55:27 +00001949def supers():
Guido van Rossum9881fc12001-08-24 17:07:20 +00001950 if verbose: print "Testing super..."
Guido van Rossumc4a18802001-08-24 16:55:27 +00001951
1952 class A(object):
1953 def meth(self, a):
1954 return "A(%r)" % a
1955
Guido van Rossum45704552001-10-08 16:35:45 +00001956 vereq(A().meth(1), "A(1)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001957
1958 class B(A):
1959 def __init__(self):
1960 self.__super = super(B, self)
1961 def meth(self, a):
1962 return "B(%r)" % a + self.__super.meth(a)
1963
Guido van Rossum45704552001-10-08 16:35:45 +00001964 vereq(B().meth(2), "B(2)A(2)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001965
1966 class C(A):
Guido van Rossumc4a18802001-08-24 16:55:27 +00001967 def meth(self, a):
1968 return "C(%r)" % a + self.__super.meth(a)
1969 C._C__super = super(C)
1970
Guido van Rossum45704552001-10-08 16:35:45 +00001971 vereq(C().meth(3), "C(3)A(3)")
Guido van Rossumc4a18802001-08-24 16:55:27 +00001972
1973 class D(C, B):
1974 def meth(self, a):
1975 return "D(%r)" % a + super(D, self).meth(a)
1976
Guido van Rossum5b443c62001-12-03 15:38:28 +00001977 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1978
1979 # Test for subclassing super
1980
1981 class mysuper(super):
1982 def __init__(self, *args):
1983 return super(mysuper, self).__init__(*args)
1984
1985 class E(D):
1986 def meth(self, a):
1987 return "E(%r)" % a + mysuper(E, self).meth(a)
1988
1989 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1990
1991 class F(E):
1992 def meth(self, a):
1993 s = self.__super
1994 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1995 F._F__super = mysuper(F)
1996
1997 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1998
1999 # Make sure certain errors are raised
2000
2001 try:
2002 super(D, 42)
2003 except TypeError:
2004 pass
2005 else:
2006 raise TestFailed, "shouldn't allow super(D, 42)"
2007
2008 try:
2009 super(D, C())
2010 except TypeError:
2011 pass
2012 else:
2013 raise TestFailed, "shouldn't allow super(D, C())"
2014
2015 try:
2016 super(D).__get__(12)
2017 except TypeError:
2018 pass
2019 else:
2020 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2021
2022 try:
2023 super(D).__get__(C())
2024 except TypeError:
2025 pass
2026 else:
2027 raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossumc4a18802001-08-24 16:55:27 +00002028
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002029def inherits():
2030 if verbose: print "Testing inheritance from basic types..."
2031
2032 class hexint(int):
2033 def __repr__(self):
2034 return hex(self)
2035 def __add__(self, other):
2036 return hexint(int.__add__(self, other))
2037 # (Note that overriding __radd__ doesn't work,
2038 # because the int type gets first dibs.)
Guido van Rossum45704552001-10-08 16:35:45 +00002039 vereq(repr(hexint(7) + 9), "0x10")
2040 vereq(repr(hexint(1000) + 7), "0x3ef")
Tim Peters64b5ce32001-09-10 20:52:51 +00002041 a = hexint(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002042 vereq(a, 12345)
2043 vereq(int(a), 12345)
Tim Peters64b5ce32001-09-10 20:52:51 +00002044 verify(int(a).__class__ is int)
Guido van Rossum45704552001-10-08 16:35:45 +00002045 vereq(hash(a), hash(12345))
Tim Peters73a1dfe2001-09-11 21:44:14 +00002046 verify((+a).__class__ is int)
2047 verify((a >> 0).__class__ is int)
2048 verify((a << 0).__class__ is int)
2049 verify((hexint(0) << 12).__class__ is int)
2050 verify((hexint(0) >> 12).__class__ is int)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002051
2052 class octlong(long):
2053 __slots__ = []
2054 def __str__(self):
2055 s = oct(self)
2056 if s[-1] == 'L':
2057 s = s[:-1]
2058 return s
2059 def __add__(self, other):
2060 return self.__class__(super(octlong, self).__add__(other))
2061 __radd__ = __add__
Guido van Rossum45704552001-10-08 16:35:45 +00002062 vereq(str(octlong(3) + 5), "010")
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002063 # (Note that overriding __radd__ here only seems to work
2064 # because the example uses a short int left argument.)
Guido van Rossum45704552001-10-08 16:35:45 +00002065 vereq(str(5 + octlong(3000)), "05675")
Tim Peters64b5ce32001-09-10 20:52:51 +00002066 a = octlong(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002067 vereq(a, 12345L)
2068 vereq(long(a), 12345L)
2069 vereq(hash(a), hash(12345L))
Tim Peters64b5ce32001-09-10 20:52:51 +00002070 verify(long(a).__class__ is long)
Tim Peters69c2de32001-09-11 22:31:33 +00002071 verify((+a).__class__ is long)
2072 verify((-a).__class__ is long)
2073 verify((-octlong(0)).__class__ is long)
2074 verify((a >> 0).__class__ is long)
2075 verify((a << 0).__class__ is long)
2076 verify((a - 0).__class__ is long)
2077 verify((a * 1).__class__ is long)
2078 verify((a ** 1).__class__ is long)
2079 verify((a // 1).__class__ is long)
2080 verify((1 * a).__class__ is long)
2081 verify((a | 0).__class__ is long)
2082 verify((a ^ 0).__class__ is long)
2083 verify((a & -1L).__class__ is long)
2084 verify((octlong(0) << 12).__class__ is long)
2085 verify((octlong(0) >> 12).__class__ is long)
2086 verify(abs(octlong(0)).__class__ is long)
2087
2088 # Because octlong overrides __add__, we can't check the absence of +0
2089 # optimizations using octlong.
2090 class longclone(long):
2091 pass
2092 a = longclone(1)
2093 verify((a + 0).__class__ is long)
2094 verify((0 + a).__class__ is long)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002095
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002096 # Check that negative clones don't segfault
2097 a = longclone(-1)
2098 vereq(a.__dict__, {})
Tim Peters5329cdb2002-03-02 04:18:04 +00002099 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
Guido van Rossum2eb0b872002-03-01 22:24:49 +00002100
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002101 class precfloat(float):
2102 __slots__ = ['prec']
2103 def __init__(self, value=0.0, prec=12):
2104 self.prec = int(prec)
2105 float.__init__(value)
2106 def __repr__(self):
2107 return "%.*g" % (self.prec, self)
Guido van Rossum45704552001-10-08 16:35:45 +00002108 vereq(repr(precfloat(1.1)), "1.1")
Tim Peters64b5ce32001-09-10 20:52:51 +00002109 a = precfloat(12345)
Guido van Rossum45704552001-10-08 16:35:45 +00002110 vereq(a, 12345.0)
2111 vereq(float(a), 12345.0)
Tim Peters7a50f252001-09-10 21:28:20 +00002112 verify(float(a).__class__ is float)
Guido van Rossum45704552001-10-08 16:35:45 +00002113 vereq(hash(a), hash(12345.0))
Tim Peters0280cf72001-09-11 21:53:35 +00002114 verify((+a).__class__ is float)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002115
Tim Peters2400fa42001-09-12 19:12:49 +00002116 class madcomplex(complex):
2117 def __repr__(self):
2118 return "%.17gj%+.17g" % (self.imag, self.real)
2119 a = madcomplex(-3, 4)
Guido van Rossum45704552001-10-08 16:35:45 +00002120 vereq(repr(a), "4j-3")
Tim Peters2400fa42001-09-12 19:12:49 +00002121 base = complex(-3, 4)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002122 veris(base.__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002123 vereq(a, base)
2124 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002125 veris(complex(a).__class__, complex)
Tim Peters2400fa42001-09-12 19:12:49 +00002126 a = madcomplex(a) # just trying another form of the constructor
Guido van Rossum45704552001-10-08 16:35:45 +00002127 vereq(repr(a), "4j-3")
2128 vereq(a, base)
2129 vereq(complex(a), base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002130 veris(complex(a).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002131 vereq(hash(a), hash(base))
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002132 veris((+a).__class__, complex)
2133 veris((a + 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002134 vereq(a + 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002135 veris((a - 0).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002136 vereq(a - 0, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002137 veris((a * 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002138 vereq(a * 1, base)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002139 veris((a / 1).__class__, complex)
Guido van Rossum45704552001-10-08 16:35:45 +00002140 vereq(a / 1, base)
Tim Peters2400fa42001-09-12 19:12:49 +00002141
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002142 class madtuple(tuple):
2143 _rev = None
2144 def rev(self):
2145 if self._rev is not None:
2146 return self._rev
2147 L = list(self)
2148 L.reverse()
2149 self._rev = self.__class__(L)
2150 return self._rev
2151 a = madtuple((1,2,3,4,5,6,7,8,9,0))
Guido van Rossum45704552001-10-08 16:35:45 +00002152 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2153 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2154 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002155 for i in range(512):
2156 t = madtuple(range(i))
2157 u = t.rev()
2158 v = u.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002159 vereq(v, t)
Tim Peters64b5ce32001-09-10 20:52:51 +00002160 a = madtuple((1,2,3,4,5))
Guido van Rossum45704552001-10-08 16:35:45 +00002161 vereq(tuple(a), (1,2,3,4,5))
Tim Peters4c3a0a32001-09-10 23:37:46 +00002162 verify(tuple(a).__class__ is tuple)
Guido van Rossum45704552001-10-08 16:35:45 +00002163 vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters7b07a412001-09-11 19:48:03 +00002164 verify(a[:].__class__ is tuple)
2165 verify((a * 1).__class__ is tuple)
2166 verify((a * 0).__class__ is tuple)
2167 verify((a + ()).__class__ is tuple)
Tim Peters64b5ce32001-09-10 20:52:51 +00002168 a = madtuple(())
Guido van Rossum45704552001-10-08 16:35:45 +00002169 vereq(tuple(a), ())
Guido van Rossum779ce4a2001-09-11 14:02:22 +00002170 verify(tuple(a).__class__ is tuple)
Tim Peters7b07a412001-09-11 19:48:03 +00002171 verify((a + a).__class__ is tuple)
2172 verify((a * 0).__class__ is tuple)
2173 verify((a * 1).__class__ is tuple)
2174 verify((a * 2).__class__ is tuple)
2175 verify(a[:].__class__ is tuple)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002176
2177 class madstring(str):
2178 _rev = None
2179 def rev(self):
2180 if self._rev is not None:
2181 return self._rev
2182 L = list(self)
2183 L.reverse()
2184 self._rev = self.__class__("".join(L))
2185 return self._rev
2186 s = madstring("abcdefghijklmnopqrstuvwxyz")
Guido van Rossum45704552001-10-08 16:35:45 +00002187 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2188 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2189 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002190 for i in range(256):
2191 s = madstring("".join(map(chr, range(i))))
2192 t = s.rev()
2193 u = t.rev()
Guido van Rossum45704552001-10-08 16:35:45 +00002194 vereq(u, s)
Tim Peters64b5ce32001-09-10 20:52:51 +00002195 s = madstring("12345")
Guido van Rossum45704552001-10-08 16:35:45 +00002196 vereq(str(s), "12345")
Tim Peters5a49ade2001-09-11 01:41:59 +00002197 verify(str(s).__class__ is str)
Guido van Rossumcaa9f432001-08-30 20:06:08 +00002198
Tim Peters8fa5dd02001-09-12 02:18:30 +00002199 base = "\x00" * 5
2200 s = madstring(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002201 vereq(s, base)
2202 vereq(str(s), base)
Tim Petersc636f562001-09-11 01:52:02 +00002203 verify(str(s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002204 vereq(hash(s), hash(base))
2205 vereq({s: 1}[base], 1)
2206 vereq({base: 1}[s], 1)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002207 verify((s + "").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002208 vereq(s + "", base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002209 verify(("" + s).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002210 vereq("" + s, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002211 verify((s * 0).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002212 vereq(s * 0, "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002213 verify((s * 1).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002214 vereq(s * 1, base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002215 verify((s * 2).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002216 vereq(s * 2, base + base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002217 verify(s[:].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002218 vereq(s[:], base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002219 verify(s[0:0].__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002220 vereq(s[0:0], "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002221 verify(s.strip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002222 vereq(s.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002223 verify(s.lstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002224 vereq(s.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002225 verify(s.rstrip().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002226 vereq(s.rstrip(), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002227 identitytab = ''.join([chr(i) for i in range(256)])
2228 verify(s.translate(identitytab).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002229 vereq(s.translate(identitytab), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002230 verify(s.translate(identitytab, "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002231 vereq(s.translate(identitytab, "x"), base)
2232 vereq(s.translate(identitytab, "\x00"), "")
Tim Peters8fa5dd02001-09-12 02:18:30 +00002233 verify(s.replace("x", "x").__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002234 vereq(s.replace("x", "x"), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002235 verify(s.ljust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002236 vereq(s.ljust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002237 verify(s.rjust(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002238 vereq(s.rjust(len(s)), base)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002239 verify(s.center(len(s)).__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002240 vereq(s.center(len(s)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002241 verify(s.lower().__class__ is str)
Guido van Rossum45704552001-10-08 16:35:45 +00002242 vereq(s.lower(), base)
Tim Petersc636f562001-09-11 01:52:02 +00002243
Tim Peters111f6092001-09-12 07:54:51 +00002244 s = madstring("x y")
Guido van Rossum45704552001-10-08 16:35:45 +00002245 vereq(s, "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002246 verify(intern(s).__class__ is str)
2247 verify(intern(s) is intern("x y"))
Guido van Rossum45704552001-10-08 16:35:45 +00002248 vereq(intern(s), "x y")
Tim Peters111f6092001-09-12 07:54:51 +00002249
2250 i = intern("y x")
2251 s = madstring("y x")
Guido van Rossum45704552001-10-08 16:35:45 +00002252 vereq(s, i)
Tim Peters111f6092001-09-12 07:54:51 +00002253 verify(intern(s).__class__ is str)
2254 verify(intern(s) is i)
2255
2256 s = madstring(i)
2257 verify(intern(s).__class__ is str)
2258 verify(intern(s) is i)
2259
Guido van Rossum91ee7982001-08-30 20:52:40 +00002260 class madunicode(unicode):
2261 _rev = None
2262 def rev(self):
2263 if self._rev is not None:
2264 return self._rev
2265 L = list(self)
2266 L.reverse()
2267 self._rev = self.__class__(u"".join(L))
2268 return self._rev
2269 u = madunicode("ABCDEF")
Guido van Rossum45704552001-10-08 16:35:45 +00002270 vereq(u, u"ABCDEF")
2271 vereq(u.rev(), madunicode(u"FEDCBA"))
2272 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
Tim Peters7a29bd52001-09-12 03:03:31 +00002273 base = u"12345"
2274 u = madunicode(base)
Guido van Rossum45704552001-10-08 16:35:45 +00002275 vereq(unicode(u), base)
Tim Peters78e0fc72001-09-11 03:07:38 +00002276 verify(unicode(u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002277 vereq(hash(u), hash(base))
2278 vereq({u: 1}[base], 1)
2279 vereq({base: 1}[u], 1)
Tim Peters7a29bd52001-09-12 03:03:31 +00002280 verify(u.strip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002281 vereq(u.strip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002282 verify(u.lstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002283 vereq(u.lstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002284 verify(u.rstrip().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002285 vereq(u.rstrip(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002286 verify(u.replace(u"x", u"x").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002287 vereq(u.replace(u"x", u"x"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002288 verify(u.replace(u"xy", u"xy").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002289 vereq(u.replace(u"xy", u"xy"), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002290 verify(u.center(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002291 vereq(u.center(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002292 verify(u.ljust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002293 vereq(u.ljust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002294 verify(u.rjust(len(u)).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002295 vereq(u.rjust(len(u)), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002296 verify(u.lower().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002297 vereq(u.lower(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002298 verify(u.upper().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002299 vereq(u.upper(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002300 verify(u.capitalize().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002301 vereq(u.capitalize(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002302 verify(u.title().__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002303 vereq(u.title(), base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002304 verify((u + u"").__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002305 vereq(u + u"", base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002306 verify((u"" + u).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002307 vereq(u"" + u, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002308 verify((u * 0).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002309 vereq(u * 0, u"")
Tim Peters7a29bd52001-09-12 03:03:31 +00002310 verify((u * 1).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002311 vereq(u * 1, base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002312 verify((u * 2).__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002313 vereq(u * 2, base + base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002314 verify(u[:].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002315 vereq(u[:], base)
Tim Peters7a29bd52001-09-12 03:03:31 +00002316 verify(u[0:0].__class__ is unicode)
Guido van Rossum45704552001-10-08 16:35:45 +00002317 vereq(u[0:0], u"")
Guido van Rossum91ee7982001-08-30 20:52:40 +00002318
Guido van Rossum12b22ff2001-10-09 20:36:44 +00002319 class sublist(list):
2320 pass
2321 a = sublist(range(5))
2322 vereq(a, range(5))
2323 a.append("hello")
2324 vereq(a, range(5) + ["hello"])
2325 a[5] = 5
2326 vereq(a, range(6))
2327 a.extend(range(6, 20))
2328 vereq(a, range(20))
2329 a[-5:] = []
2330 vereq(a, range(15))
2331 del a[10:15]
2332 vereq(len(a), 10)
2333 vereq(a, range(10))
2334 vereq(list(a), range(10))
2335 vereq(a[0], 0)
2336 vereq(a[9], 9)
2337 vereq(a[-10], 0)
2338 vereq(a[-1], 9)
2339 vereq(a[:5], range(5))
2340
Tim Peters59c9a642001-09-13 05:38:56 +00002341 class CountedInput(file):
2342 """Counts lines read by self.readline().
2343
2344 self.lineno is the 0-based ordinal of the last line read, up to
2345 a maximum of one greater than the number of lines in the file.
2346
2347 self.ateof is true if and only if the final "" line has been read,
2348 at which point self.lineno stops incrementing, and further calls
2349 to readline() continue to return "".
2350 """
2351
2352 lineno = 0
2353 ateof = 0
2354 def readline(self):
2355 if self.ateof:
2356 return ""
2357 s = file.readline(self)
2358 # Next line works too.
2359 # s = super(CountedInput, self).readline()
2360 self.lineno += 1
2361 if s == "":
2362 self.ateof = 1
2363 return s
2364
Tim Peters561f8992001-09-13 19:36:36 +00002365 f = file(name=TESTFN, mode='w')
Tim Peters59c9a642001-09-13 05:38:56 +00002366 lines = ['a\n', 'b\n', 'c\n']
2367 try:
2368 f.writelines(lines)
2369 f.close()
2370 f = CountedInput(TESTFN)
2371 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2372 got = f.readline()
Guido van Rossum45704552001-10-08 16:35:45 +00002373 vereq(expected, got)
2374 vereq(f.lineno, i)
2375 vereq(f.ateof, (i > len(lines)))
Tim Peters59c9a642001-09-13 05:38:56 +00002376 f.close()
2377 finally:
2378 try:
2379 f.close()
2380 except:
2381 pass
2382 try:
2383 import os
2384 os.unlink(TESTFN)
2385 except:
2386 pass
2387
Tim Peters808b94e2001-09-13 19:33:07 +00002388def keywords():
2389 if verbose:
2390 print "Testing keyword args to basic type constructors ..."
Guido van Rossum45704552001-10-08 16:35:45 +00002391 vereq(int(x=1), 1)
2392 vereq(float(x=2), 2.0)
2393 vereq(long(x=3), 3L)
2394 vereq(complex(imag=42, real=666), complex(666, 42))
2395 vereq(str(object=500), '500')
2396 vereq(unicode(string='abc', errors='strict'), u'abc')
2397 vereq(tuple(sequence=range(3)), (0, 1, 2))
2398 vereq(list(sequence=(0, 1, 2)), range(3))
Just van Rossuma797d812002-11-23 09:45:04 +00002399 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
Tim Peters808b94e2001-09-13 19:33:07 +00002400
2401 for constructor in (int, float, long, complex, str, unicode,
Just van Rossuma797d812002-11-23 09:45:04 +00002402 tuple, list, file):
Tim Peters808b94e2001-09-13 19:33:07 +00002403 try:
2404 constructor(bogus_keyword_arg=1)
2405 except TypeError:
2406 pass
2407 else:
2408 raise TestFailed("expected TypeError from bogus keyword "
2409 "argument to %r" % constructor)
Tim Peters561f8992001-09-13 19:36:36 +00002410
Tim Peters8fa45672001-09-13 21:01:29 +00002411def restricted():
Guido van Rossum4f374182003-01-06 16:03:43 +00002412 # XXX This test is disabled because rexec is not deemed safe
2413 return
Tim Peters8fa45672001-09-13 21:01:29 +00002414 import rexec
2415 if verbose:
2416 print "Testing interaction with restricted execution ..."
2417
2418 sandbox = rexec.RExec()
2419
2420 code1 = """f = open(%r, 'w')""" % TESTFN
2421 code2 = """f = file(%r, 'w')""" % TESTFN
2422 code3 = """\
2423f = open(%r)
2424t = type(f) # a sneaky way to get the file() constructor
2425f.close()
2426f = t(%r, 'w') # rexec can't catch this by itself
2427""" % (TESTFN, TESTFN)
2428
2429 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2430 f.close()
2431
2432 try:
2433 for code in code1, code2, code3:
2434 try:
2435 sandbox.r_exec(code)
2436 except IOError, msg:
2437 if str(msg).find("restricted") >= 0:
2438 outcome = "OK"
2439 else:
2440 outcome = "got an exception, but not an expected one"
2441 else:
2442 outcome = "expected a restricted-execution exception"
2443
2444 if outcome != "OK":
2445 raise TestFailed("%s, in %r" % (outcome, code))
2446
2447 finally:
2448 try:
2449 import os
2450 os.unlink(TESTFN)
2451 except:
2452 pass
2453
Tim Peters0ab085c2001-09-14 00:25:33 +00002454def str_subclass_as_dict_key():
2455 if verbose:
2456 print "Testing a str subclass used as dict key .."
2457
2458 class cistr(str):
2459 """Sublcass of str that computes __eq__ case-insensitively.
2460
2461 Also computes a hash code of the string in canonical form.
2462 """
2463
2464 def __init__(self, value):
2465 self.canonical = value.lower()
2466 self.hashcode = hash(self.canonical)
2467
2468 def __eq__(self, other):
2469 if not isinstance(other, cistr):
2470 other = cistr(other)
2471 return self.canonical == other.canonical
2472
2473 def __hash__(self):
2474 return self.hashcode
2475
Guido van Rossum45704552001-10-08 16:35:45 +00002476 vereq(cistr('ABC'), 'abc')
2477 vereq('aBc', cistr('ABC'))
2478 vereq(str(cistr('ABC')), 'ABC')
Tim Peters0ab085c2001-09-14 00:25:33 +00002479
2480 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
Guido van Rossum45704552001-10-08 16:35:45 +00002481 vereq(d[cistr('one')], 1)
2482 vereq(d[cistr('tWo')], 2)
2483 vereq(d[cistr('THrEE')], 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002484 verify(cistr('ONe') in d)
Guido van Rossum45704552001-10-08 16:35:45 +00002485 vereq(d.get(cistr('thrEE')), 3)
Tim Peters0ab085c2001-09-14 00:25:33 +00002486
Guido van Rossumab3b0342001-09-18 20:38:53 +00002487def classic_comparisons():
2488 if verbose: print "Testing classic comparisons..."
Guido van Rossum0639f592001-09-18 21:06:04 +00002489 class classic:
2490 pass
2491 for base in (classic, int, object):
Guido van Rossumab3b0342001-09-18 20:38:53 +00002492 if verbose: print " (base = %s)" % base
2493 class C(base):
2494 def __init__(self, value):
2495 self.value = int(value)
2496 def __cmp__(self, other):
2497 if isinstance(other, C):
2498 return cmp(self.value, other.value)
2499 if isinstance(other, int) or isinstance(other, long):
2500 return cmp(self.value, other)
2501 return NotImplemented
2502 c1 = C(1)
2503 c2 = C(2)
2504 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002505 vereq(c1, 1)
Guido van Rossumab3b0342001-09-18 20:38:53 +00002506 c = {1: c1, 2: c2, 3: c3}
2507 for x in 1, 2, 3:
2508 for y in 1, 2, 3:
2509 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2510 for op in "<", "<=", "==", "!=", ">", ">=":
2511 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2512 "x=%d, y=%d" % (x, y))
2513 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2514 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2515
Guido van Rossum0639f592001-09-18 21:06:04 +00002516def rich_comparisons():
2517 if verbose:
2518 print "Testing rich comparisons..."
Guido van Rossum22056422001-09-24 17:52:04 +00002519 class Z(complex):
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002520 pass
Guido van Rossum22056422001-09-24 17:52:04 +00002521 z = Z(1)
Guido van Rossum45704552001-10-08 16:35:45 +00002522 vereq(z, 1+0j)
2523 vereq(1+0j, z)
Guido van Rossum22056422001-09-24 17:52:04 +00002524 class ZZ(complex):
2525 def __eq__(self, other):
2526 try:
2527 return abs(self - other) <= 1e-6
2528 except:
2529 return NotImplemented
2530 zz = ZZ(1.0000003)
Guido van Rossum45704552001-10-08 16:35:45 +00002531 vereq(zz, 1+0j)
2532 vereq(1+0j, zz)
Tim Peters66c1a522001-09-24 21:17:50 +00002533
Guido van Rossum0639f592001-09-18 21:06:04 +00002534 class classic:
2535 pass
2536 for base in (classic, int, object, list):
2537 if verbose: print " (base = %s)" % base
2538 class C(base):
2539 def __init__(self, value):
2540 self.value = int(value)
2541 def __cmp__(self, other):
2542 raise TestFailed, "shouldn't call __cmp__"
2543 def __eq__(self, other):
2544 if isinstance(other, C):
2545 return self.value == other.value
2546 if isinstance(other, int) or isinstance(other, long):
2547 return self.value == other
2548 return NotImplemented
2549 def __ne__(self, other):
2550 if isinstance(other, C):
2551 return self.value != other.value
2552 if isinstance(other, int) or isinstance(other, long):
2553 return self.value != other
2554 return NotImplemented
2555 def __lt__(self, other):
2556 if isinstance(other, C):
2557 return self.value < other.value
2558 if isinstance(other, int) or isinstance(other, long):
2559 return self.value < other
2560 return NotImplemented
2561 def __le__(self, other):
2562 if isinstance(other, C):
2563 return self.value <= other.value
2564 if isinstance(other, int) or isinstance(other, long):
2565 return self.value <= other
2566 return NotImplemented
2567 def __gt__(self, other):
2568 if isinstance(other, C):
2569 return self.value > other.value
2570 if isinstance(other, int) or isinstance(other, long):
2571 return self.value > other
2572 return NotImplemented
2573 def __ge__(self, other):
2574 if isinstance(other, C):
2575 return self.value >= other.value
2576 if isinstance(other, int) or isinstance(other, long):
2577 return self.value >= other
2578 return NotImplemented
2579 c1 = C(1)
2580 c2 = C(2)
2581 c3 = C(3)
Guido van Rossum45704552001-10-08 16:35:45 +00002582 vereq(c1, 1)
Guido van Rossum0639f592001-09-18 21:06:04 +00002583 c = {1: c1, 2: c2, 3: c3}
2584 for x in 1, 2, 3:
2585 for y in 1, 2, 3:
2586 for op in "<", "<=", "==", "!=", ">", ">=":
2587 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2588 "x=%d, y=%d" % (x, y))
2589 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2590 "x=%d, y=%d" % (x, y))
2591 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2592 "x=%d, y=%d" % (x, y))
2593
Guido van Rossum1952e382001-09-19 01:25:16 +00002594def coercions():
2595 if verbose: print "Testing coercions..."
2596 class I(int): pass
2597 coerce(I(0), 0)
2598 coerce(0, I(0))
2599 class L(long): pass
2600 coerce(L(0), 0)
2601 coerce(L(0), 0L)
2602 coerce(0, L(0))
2603 coerce(0L, L(0))
2604 class F(float): pass
2605 coerce(F(0), 0)
2606 coerce(F(0), 0L)
2607 coerce(F(0), 0.)
2608 coerce(0, F(0))
2609 coerce(0L, F(0))
2610 coerce(0., F(0))
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002611 class C(complex): pass
Guido van Rossum1952e382001-09-19 01:25:16 +00002612 coerce(C(0), 0)
2613 coerce(C(0), 0L)
2614 coerce(C(0), 0.)
2615 coerce(C(0), 0j)
2616 coerce(0, C(0))
2617 coerce(0L, C(0))
2618 coerce(0., C(0))
2619 coerce(0j, C(0))
2620
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002621def descrdoc():
2622 if verbose: print "Testing descriptor doc strings..."
2623 def check(descr, what):
Guido van Rossum45704552001-10-08 16:35:45 +00002624 vereq(descr.__doc__, what)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002625 check(file.closed, "True if the file is closed") # getset descriptor
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00002626 check(file.name, "file name") # member descriptor
2627
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002628def setclass():
2629 if verbose: print "Testing __class__ assignment..."
2630 class C(object): pass
2631 class D(object): pass
2632 class E(object): pass
2633 class F(D, E): pass
2634 for cls in C, D, E, F:
2635 for cls2 in C, D, E, F:
2636 x = cls()
2637 x.__class__ = cls2
2638 verify(x.__class__ is cls2)
2639 x.__class__ = cls
2640 verify(x.__class__ is cls)
2641 def cant(x, C):
2642 try:
2643 x.__class__ = C
2644 except TypeError:
2645 pass
2646 else:
2647 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
Guido van Rossumb6b89422002-04-15 01:03:30 +00002648 try:
2649 delattr(x, "__class__")
2650 except TypeError:
2651 pass
2652 else:
2653 raise TestFailed, "shouldn't allow del %r.__class__" % x
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002654 cant(C(), list)
2655 cant(list(), C)
2656 cant(C(), 1)
2657 cant(C(), object)
2658 cant(object(), list)
2659 cant(list(), object)
Guido van Rossum40af8892002-08-10 05:42:07 +00002660 class Int(int): __slots__ = []
2661 cant(2, Int)
2662 cant(Int(), int)
2663 cant(True, int)
2664 cant(2, bool)
Neal Norwitz78ce6b12002-12-24 15:26:42 +00002665 o = object()
2666 cant(o, type(1))
2667 cant(o, type(None))
2668 del o
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002669
Guido van Rossum6661be32001-10-26 04:26:12 +00002670def setdict():
2671 if verbose: print "Testing __dict__ assignment..."
2672 class C(object): pass
2673 a = C()
2674 a.__dict__ = {'b': 1}
2675 vereq(a.b, 1)
2676 def cant(x, dict):
2677 try:
2678 x.__dict__ = dict
2679 except TypeError:
2680 pass
2681 else:
2682 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2683 cant(a, None)
2684 cant(a, [])
2685 cant(a, 1)
Guido van Rossumd331cb52001-12-05 19:46:42 +00002686 del a.__dict__ # Deleting __dict__ is allowed
Guido van Rossum6661be32001-10-26 04:26:12 +00002687 # Classes don't allow __dict__ assignment
2688 cant(C, {})
2689
Guido van Rossum3926a632001-09-25 16:25:58 +00002690def pickles():
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002691 if verbose:
2692 print "Testing pickling and copying new-style classes and objects..."
Guido van Rossum3926a632001-09-25 16:25:58 +00002693 import pickle, cPickle
2694
2695 def sorteditems(d):
2696 L = d.items()
2697 L.sort()
2698 return L
2699
2700 global C
2701 class C(object):
2702 def __init__(self, a, b):
2703 super(C, self).__init__()
2704 self.a = a
2705 self.b = b
2706 def __repr__(self):
2707 return "C(%r, %r)" % (self.a, self.b)
2708
2709 global C1
2710 class C1(list):
2711 def __new__(cls, a, b):
2712 return super(C1, cls).__new__(cls)
Guido van Rossumf6318592003-02-07 14:59:13 +00002713 def __getnewargs__(self):
2714 return (self.a, self.b)
Guido van Rossum3926a632001-09-25 16:25:58 +00002715 def __init__(self, a, b):
2716 self.a = a
2717 self.b = b
2718 def __repr__(self):
2719 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2720
2721 global C2
2722 class C2(int):
2723 def __new__(cls, a, b, val=0):
2724 return super(C2, cls).__new__(cls, val)
Guido van Rossumf6318592003-02-07 14:59:13 +00002725 def __getnewargs__(self):
2726 return (self.a, self.b, int(self))
Guido van Rossum3926a632001-09-25 16:25:58 +00002727 def __init__(self, a, b, val=0):
2728 self.a = a
2729 self.b = b
2730 def __repr__(self):
2731 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2732
Guido van Rossum90c45142001-11-24 21:07:01 +00002733 global C3
2734 class C3(object):
2735 def __init__(self, foo):
2736 self.foo = foo
2737 def __getstate__(self):
2738 return self.foo
2739 def __setstate__(self, foo):
2740 self.foo = foo
2741
2742 global C4classic, C4
2743 class C4classic: # classic
2744 pass
2745 class C4(C4classic, object): # mixed inheritance
2746 pass
2747
Guido van Rossum3926a632001-09-25 16:25:58 +00002748 for p in pickle, cPickle:
2749 for bin in 0, 1:
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002750 if verbose:
2751 print p.__name__, ["text", "binary"][bin]
Guido van Rossum3926a632001-09-25 16:25:58 +00002752
2753 for cls in C, C1, C2:
2754 s = p.dumps(cls, bin)
2755 cls2 = p.loads(s)
2756 verify(cls2 is cls)
2757
2758 a = C1(1, 2); a.append(42); a.append(24)
2759 b = C2("hello", "world", 42)
2760 s = p.dumps((a, b), bin)
2761 x, y = p.loads(s)
Guido van Rossum90c45142001-11-24 21:07:01 +00002762 vereq(x.__class__, a.__class__)
2763 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2764 vereq(y.__class__, b.__class__)
2765 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2766 vereq(`x`, `a`)
2767 vereq(`y`, `b`)
Guido van Rossum3926a632001-09-25 16:25:58 +00002768 if verbose:
2769 print "a = x =", a
2770 print "b = y =", b
Guido van Rossum90c45142001-11-24 21:07:01 +00002771 # Test for __getstate__ and __setstate__ on new style class
2772 u = C3(42)
2773 s = p.dumps(u, bin)
2774 v = p.loads(s)
2775 veris(u.__class__, v.__class__)
2776 vereq(u.foo, v.foo)
2777 # Test for picklability of hybrid class
2778 u = C4()
2779 u.foo = 42
2780 s = p.dumps(u, bin)
2781 v = p.loads(s)
2782 veris(u.__class__, v.__class__)
2783 vereq(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002784
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002785 # Testing copy.deepcopy()
2786 if verbose:
2787 print "deepcopy"
2788 import copy
2789 for cls in C, C1, C2:
2790 cls2 = copy.deepcopy(cls)
2791 verify(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002792
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002793 a = C1(1, 2); a.append(42); a.append(24)
2794 b = C2("hello", "world", 42)
2795 x, y = copy.deepcopy((a, b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002796 vereq(x.__class__, a.__class__)
2797 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2798 vereq(y.__class__, b.__class__)
2799 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2800 vereq(`x`, `a`)
2801 vereq(`y`, `b`)
Guido van Rossumfe1fd0e2001-10-02 19:58:32 +00002802 if verbose:
2803 print "a = x =", a
2804 print "b = y =", b
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002805
Guido van Rossum8c842552002-03-14 23:05:54 +00002806def pickleslots():
2807 if verbose: print "Testing pickling of classes with __slots__ ..."
2808 import pickle, cPickle
2809 # Pickling of classes with __slots__ but without __getstate__ should fail
2810 global B, C, D, E
2811 class B(object):
2812 pass
2813 for base in [object, B]:
2814 class C(base):
2815 __slots__ = ['a']
2816 class D(C):
2817 pass
2818 try:
2819 pickle.dumps(C())
2820 except TypeError:
2821 pass
2822 else:
2823 raise TestFailed, "should fail: pickle C instance - %s" % base
2824 try:
2825 cPickle.dumps(C())
2826 except TypeError:
2827 pass
2828 else:
2829 raise TestFailed, "should fail: cPickle C instance - %s" % base
2830 try:
2831 pickle.dumps(C())
2832 except TypeError:
2833 pass
2834 else:
2835 raise TestFailed, "should fail: pickle D instance - %s" % base
2836 try:
2837 cPickle.dumps(D())
2838 except TypeError:
2839 pass
2840 else:
2841 raise TestFailed, "should fail: cPickle D instance - %s" % base
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002842 # Give C a nice generic __getstate__ and __setstate__
Guido van Rossum8c842552002-03-14 23:05:54 +00002843 class C(base):
2844 __slots__ = ['a']
2845 def __getstate__(self):
2846 try:
2847 d = self.__dict__.copy()
2848 except AttributeError:
2849 d = {}
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002850 for cls in self.__class__.__mro__:
2851 for sn in cls.__dict__.get('__slots__', ()):
2852 try:
2853 d[sn] = getattr(self, sn)
2854 except AttributeError:
2855 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00002856 return d
2857 def __setstate__(self, d):
2858 for k, v in d.items():
2859 setattr(self, k, v)
2860 class D(C):
2861 pass
2862 # Now it should work
2863 x = C()
2864 y = pickle.loads(pickle.dumps(x))
2865 vereq(hasattr(y, 'a'), 0)
2866 y = cPickle.loads(cPickle.dumps(x))
2867 vereq(hasattr(y, 'a'), 0)
2868 x.a = 42
2869 y = pickle.loads(pickle.dumps(x))
2870 vereq(y.a, 42)
2871 y = cPickle.loads(cPickle.dumps(x))
2872 vereq(y.a, 42)
2873 x = D()
2874 x.a = 42
2875 x.b = 100
2876 y = pickle.loads(pickle.dumps(x))
2877 vereq(y.a + y.b, 142)
2878 y = cPickle.loads(cPickle.dumps(x))
2879 vereq(y.a + y.b, 142)
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002880 # A subclass that adds a slot should also work
Guido van Rossum8c842552002-03-14 23:05:54 +00002881 class E(C):
2882 __slots__ = ['b']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00002883 x = E()
2884 x.a = 42
2885 x.b = "foo"
2886 y = pickle.loads(pickle.dumps(x))
2887 vereq(y.a, x.a)
2888 vereq(y.b, x.b)
2889 y = cPickle.loads(cPickle.dumps(x))
2890 vereq(y.a, x.a)
2891 vereq(y.b, x.b)
Guido van Rossum8c842552002-03-14 23:05:54 +00002892
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002893def copies():
2894 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2895 import copy
2896 class C(object):
2897 pass
2898
2899 a = C()
2900 a.foo = 12
2901 b = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002902 vereq(b.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002903
2904 a.bar = [1,2,3]
2905 c = copy.copy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002906 vereq(c.bar, a.bar)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002907 verify(c.bar is a.bar)
2908
2909 d = copy.deepcopy(a)
Guido van Rossum45704552001-10-08 16:35:45 +00002910 vereq(d.__dict__, a.__dict__)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002911 a.bar.append(4)
Guido van Rossum45704552001-10-08 16:35:45 +00002912 vereq(d.bar, [1,2,3])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002913
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002914def binopoverride():
2915 if verbose: print "Testing overrides of binary operations..."
2916 class I(int):
2917 def __repr__(self):
2918 return "I(%r)" % int(self)
2919 def __add__(self, other):
2920 return I(int(self) + int(other))
2921 __radd__ = __add__
2922 def __pow__(self, other, mod=None):
2923 if mod is None:
2924 return I(pow(int(self), int(other)))
2925 else:
2926 return I(pow(int(self), int(other), int(mod)))
2927 def __rpow__(self, other, mod=None):
2928 if mod is None:
2929 return I(pow(int(other), int(self), mod))
2930 else:
2931 return I(pow(int(other), int(self), int(mod)))
Tim Peters2f93e282001-10-04 05:27:00 +00002932
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002933 vereq(`I(1) + I(2)`, "I(3)")
2934 vereq(`I(1) + 2`, "I(3)")
2935 vereq(`1 + I(2)`, "I(3)")
2936 vereq(`I(2) ** I(3)`, "I(8)")
2937 vereq(`2 ** I(3)`, "I(8)")
2938 vereq(`I(2) ** 3`, "I(8)")
2939 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2940 class S(str):
2941 def __eq__(self, other):
2942 return self.lower() == other.lower()
2943
Guido van Rossum875eeaa2001-10-11 18:33:53 +00002944def subclasspropagation():
2945 if verbose: print "Testing propagation of slot functions to subclasses..."
2946 class A(object):
2947 pass
2948 class B(A):
2949 pass
2950 class C(A):
2951 pass
2952 class D(B, C):
2953 pass
2954 d = D()
2955 vereq(hash(d), id(d))
2956 A.__hash__ = lambda self: 42
2957 vereq(hash(d), 42)
2958 C.__hash__ = lambda self: 314
2959 vereq(hash(d), 314)
2960 B.__hash__ = lambda self: 144
2961 vereq(hash(d), 144)
2962 D.__hash__ = lambda self: 100
2963 vereq(hash(d), 100)
2964 del D.__hash__
2965 vereq(hash(d), 144)
2966 del B.__hash__
2967 vereq(hash(d), 314)
2968 del C.__hash__
2969 vereq(hash(d), 42)
2970 del A.__hash__
2971 vereq(hash(d), id(d))
2972 d.foo = 42
2973 d.bar = 42
2974 vereq(d.foo, 42)
2975 vereq(d.bar, 42)
2976 def __getattribute__(self, name):
2977 if name == "foo":
2978 return 24
2979 return object.__getattribute__(self, name)
2980 A.__getattribute__ = __getattribute__
2981 vereq(d.foo, 24)
2982 vereq(d.bar, 42)
2983 def __getattr__(self, name):
2984 if name in ("spam", "foo", "bar"):
2985 return "hello"
2986 raise AttributeError, name
2987 B.__getattr__ = __getattr__
2988 vereq(d.spam, "hello")
2989 vereq(d.foo, 24)
2990 vereq(d.bar, 42)
2991 del A.__getattribute__
2992 vereq(d.foo, 42)
2993 del d.foo
2994 vereq(d.foo, "hello")
2995 vereq(d.bar, 42)
2996 del B.__getattr__
2997 try:
2998 d.foo
2999 except AttributeError:
3000 pass
3001 else:
3002 raise TestFailed, "d.foo should be undefined now"
Tim Petersfc57ccb2001-10-12 02:38:24 +00003003
Guido van Rossume7f3e242002-06-14 02:35:45 +00003004 # Test a nasty bug in recurse_down_subclasses()
3005 import gc
3006 class A(object):
3007 pass
3008 class B(A):
3009 pass
3010 del B
3011 gc.collect()
3012 A.__setitem__ = lambda *a: None # crash
3013
Tim Petersfc57ccb2001-10-12 02:38:24 +00003014def buffer_inherit():
3015 import binascii
3016 # SF bug [#470040] ParseTuple t# vs subclasses.
3017 if verbose:
3018 print "Testing that buffer interface is inherited ..."
3019
3020 class MyStr(str):
3021 pass
3022 base = 'abc'
3023 m = MyStr(base)
3024 # b2a_hex uses the buffer interface to get its argument's value, via
3025 # PyArg_ParseTuple 't#' code.
3026 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3027
3028 # It's not clear that unicode will continue to support the character
3029 # buffer interface, and this test will fail if that's taken away.
3030 class MyUni(unicode):
3031 pass
3032 base = u'abc'
3033 m = MyUni(base)
3034 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3035
3036 class MyInt(int):
3037 pass
3038 m = MyInt(42)
3039 try:
3040 binascii.b2a_hex(m)
3041 raise TestFailed('subclass of int should not have a buffer interface')
3042 except TypeError:
3043 pass
Tim Peters0ab085c2001-09-14 00:25:33 +00003044
Tim Petersc9933152001-10-16 20:18:24 +00003045def str_of_str_subclass():
3046 import binascii
3047 import cStringIO
3048
3049 if verbose:
3050 print "Testing __str__ defined in subclass of str ..."
3051
3052 class octetstring(str):
3053 def __str__(self):
3054 return binascii.b2a_hex(self)
3055 def __repr__(self):
3056 return self + " repr"
3057
3058 o = octetstring('A')
3059 vereq(type(o), octetstring)
3060 vereq(type(str(o)), str)
3061 vereq(type(repr(o)), str)
3062 vereq(ord(o), 0x41)
3063 vereq(str(o), '41')
3064 vereq(repr(o), 'A repr')
3065 vereq(o.__str__(), '41')
3066 vereq(o.__repr__(), 'A repr')
3067
3068 capture = cStringIO.StringIO()
3069 # Calling str() or not exercises different internal paths.
3070 print >> capture, o
3071 print >> capture, str(o)
3072 vereq(capture.getvalue(), '41\n41\n')
3073 capture.close()
3074
Guido van Rossumc8e56452001-10-22 00:43:43 +00003075def kwdargs():
3076 if verbose: print "Testing keyword arguments to __init__, __call__..."
3077 def f(a): return a
3078 vereq(f.__call__(a=42), 42)
3079 a = []
3080 list.__init__(a, sequence=[0, 1, 2])
Tim Peters1fc240e2001-10-26 05:06:50 +00003081 vereq(a, [0, 1, 2])
Guido van Rossumc8e56452001-10-22 00:43:43 +00003082
Guido van Rossumed87ad82001-10-30 02:33:02 +00003083def delhook():
3084 if verbose: print "Testing __del__ hook..."
3085 log = []
3086 class C(object):
3087 def __del__(self):
3088 log.append(1)
3089 c = C()
3090 vereq(log, [])
3091 del c
3092 vereq(log, [1])
3093
Guido van Rossum29d26062001-12-11 04:37:34 +00003094 class D(object): pass
3095 d = D()
3096 try: del d[0]
3097 except TypeError: pass
3098 else: raise TestFailed, "invalid del() didn't raise TypeError"
3099
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003100def hashinherit():
3101 if verbose: print "Testing hash of mutable subclasses..."
3102
3103 class mydict(dict):
3104 pass
3105 d = mydict()
3106 try:
3107 hash(d)
3108 except TypeError:
3109 pass
3110 else:
3111 raise TestFailed, "hash() of dict subclass should fail"
3112
3113 class mylist(list):
3114 pass
3115 d = mylist()
3116 try:
3117 hash(d)
3118 except TypeError:
3119 pass
3120 else:
3121 raise TestFailed, "hash() of list subclass should fail"
3122
Guido van Rossum29d26062001-12-11 04:37:34 +00003123def strops():
3124 try: 'a' + 5
3125 except TypeError: pass
3126 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3127
3128 try: ''.split('')
3129 except ValueError: pass
3130 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3131
3132 try: ''.join([0])
3133 except TypeError: pass
3134 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3135
3136 try: ''.rindex('5')
3137 except ValueError: pass
3138 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3139
Guido van Rossum29d26062001-12-11 04:37:34 +00003140 try: '%(n)s' % None
3141 except TypeError: pass
3142 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3143
3144 try: '%(n' % {}
3145 except ValueError: pass
3146 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3147
3148 try: '%*s' % ('abc')
3149 except TypeError: pass
3150 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3151
3152 try: '%*.*s' % ('abc', 5)
3153 except TypeError: pass
3154 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3155
3156 try: '%s' % (1, 2)
3157 except TypeError: pass
3158 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3159
3160 try: '%' % None
3161 except ValueError: pass
3162 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3163
3164 vereq('534253'.isdigit(), 1)
3165 vereq('534253x'.isdigit(), 0)
3166 vereq('%c' % 5, '\x05')
3167 vereq('%c' % '5', '5')
3168
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003169def deepcopyrecursive():
3170 if verbose: print "Testing deepcopy of recursive objects..."
3171 class Node:
3172 pass
3173 a = Node()
3174 b = Node()
3175 a.b = b
3176 b.a = a
3177 z = deepcopy(a) # This blew up before
Guido van Rossum29d26062001-12-11 04:37:34 +00003178
Guido van Rossumd7035672002-03-12 20:43:31 +00003179def modules():
3180 if verbose: print "Testing uninitialized module objects..."
3181 from types import ModuleType as M
3182 m = M.__new__(M)
3183 str(m)
3184 vereq(hasattr(m, "__name__"), 0)
3185 vereq(hasattr(m, "__file__"), 0)
3186 vereq(hasattr(m, "foo"), 0)
3187 vereq(m.__dict__, None)
3188 m.foo = 1
3189 vereq(m.__dict__, {"foo": 1})
Guido van Rossum29d26062001-12-11 04:37:34 +00003190
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003191def dictproxyiterkeys():
3192 class C(object):
3193 def meth(self):
3194 pass
3195 if verbose: print "Testing dict-proxy iterkeys..."
3196 keys = [ key for key in C.__dict__.iterkeys() ]
3197 keys.sort()
3198 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3199
3200def dictproxyitervalues():
3201 class C(object):
3202 def meth(self):
3203 pass
3204 if verbose: print "Testing dict-proxy itervalues..."
3205 values = [ values for values in C.__dict__.itervalues() ]
3206 vereq(len(values), 5)
3207
3208def dictproxyiteritems():
3209 class C(object):
3210 def meth(self):
3211 pass
3212 if verbose: print "Testing dict-proxy iteritems..."
3213 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3214 keys.sort()
3215 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3216
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003217def funnynew():
3218 if verbose: print "Testing __new__ returning something unexpected..."
3219 class C(object):
3220 def __new__(cls, arg):
3221 if isinstance(arg, str): return [1, 2, 3]
3222 elif isinstance(arg, int): return object.__new__(D)
3223 else: return object.__new__(cls)
3224 class D(C):
3225 def __init__(self, arg):
3226 self.foo = arg
3227 vereq(C("1"), [1, 2, 3])
3228 vereq(D("1"), [1, 2, 3])
3229 d = D(None)
3230 veris(d.foo, None)
3231 d = C(1)
3232 vereq(isinstance(d, D), True)
3233 vereq(d.foo, 1)
3234 d = D(1)
3235 vereq(isinstance(d, D), True)
3236 vereq(d.foo, 1)
3237
Guido van Rossume8fc6402002-04-16 16:44:51 +00003238def imulbug():
3239 # SF bug 544647
3240 if verbose: print "Testing for __imul__ problems..."
3241 class C(object):
3242 def __imul__(self, other):
3243 return (self, other)
3244 x = C()
3245 y = x
3246 y *= 1.0
3247 vereq(y, (x, 1.0))
3248 y = x
3249 y *= 2
3250 vereq(y, (x, 2))
3251 y = x
3252 y *= 3L
3253 vereq(y, (x, 3L))
3254 y = x
3255 y *= 1L<<100
3256 vereq(y, (x, 1L<<100))
3257 y = x
3258 y *= None
3259 vereq(y, (x, None))
3260 y = x
3261 y *= "foo"
3262 vereq(y, (x, "foo"))
3263
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003264def docdescriptor():
3265 # SF bug 542984
3266 if verbose: print "Testing __doc__ descriptor..."
3267 class DocDescr(object):
3268 def __get__(self, object, otype):
3269 if object:
3270 object = object.__class__.__name__ + ' instance'
3271 if otype:
3272 otype = otype.__name__
3273 return 'object=%s; type=%s' % (object, otype)
3274 class OldClass:
3275 __doc__ = DocDescr()
3276 class NewClass(object):
3277 __doc__ = DocDescr()
3278 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3279 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3280 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3281 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3282
Tim Petersafb2c802002-04-18 18:06:20 +00003283def string_exceptions():
3284 if verbose:
3285 print "Testing string exceptions ..."
3286
3287 # Ensure builtin strings work OK as exceptions.
3288 astring = "An exception string."
3289 try:
3290 raise astring
3291 except astring:
3292 pass
3293 else:
3294 raise TestFailed, "builtin string not usable as exception"
3295
3296 # Ensure string subclass instances do not.
3297 class MyStr(str):
3298 pass
3299
3300 newstring = MyStr("oops -- shouldn't work")
3301 try:
3302 raise newstring
3303 except TypeError:
3304 pass
3305 except:
3306 raise TestFailed, "string subclass allowed as exception"
3307
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003308def copy_setstate():
3309 if verbose:
3310 print "Testing that copy.*copy() correctly uses __setstate__..."
3311 import copy
3312 class C(object):
3313 def __init__(self, foo=None):
3314 self.foo = foo
3315 self.__foo = foo
3316 def setfoo(self, foo=None):
3317 self.foo = foo
3318 def getfoo(self):
3319 return self.__foo
3320 def __getstate__(self):
3321 return [self.foo]
3322 def __setstate__(self, lst):
3323 assert len(lst) == 1
3324 self.__foo = self.foo = lst[0]
3325 a = C(42)
3326 a.setfoo(24)
3327 vereq(a.foo, 24)
3328 vereq(a.getfoo(), 42)
3329 b = copy.copy(a)
3330 vereq(b.foo, 24)
3331 vereq(b.getfoo(), 24)
3332 b = copy.deepcopy(a)
3333 vereq(b.foo, 24)
3334 vereq(b.getfoo(), 24)
3335
Guido van Rossum09638c12002-06-13 19:17:46 +00003336def slices():
3337 if verbose:
3338 print "Testing cases with slices and overridden __getitem__ ..."
3339 # Strings
3340 vereq("hello"[:4], "hell")
3341 vereq("hello"[slice(4)], "hell")
3342 vereq(str.__getitem__("hello", slice(4)), "hell")
3343 class S(str):
3344 def __getitem__(self, x):
3345 return str.__getitem__(self, x)
3346 vereq(S("hello")[:4], "hell")
3347 vereq(S("hello")[slice(4)], "hell")
3348 vereq(S("hello").__getitem__(slice(4)), "hell")
3349 # Tuples
3350 vereq((1,2,3)[:2], (1,2))
3351 vereq((1,2,3)[slice(2)], (1,2))
3352 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3353 class T(tuple):
3354 def __getitem__(self, x):
3355 return tuple.__getitem__(self, x)
3356 vereq(T((1,2,3))[:2], (1,2))
3357 vereq(T((1,2,3))[slice(2)], (1,2))
3358 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3359 # Lists
3360 vereq([1,2,3][:2], [1,2])
3361 vereq([1,2,3][slice(2)], [1,2])
3362 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3363 class L(list):
3364 def __getitem__(self, x):
3365 return list.__getitem__(self, x)
3366 vereq(L([1,2,3])[:2], [1,2])
3367 vereq(L([1,2,3])[slice(2)], [1,2])
3368 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3369 # Now do lists and __setitem__
3370 a = L([1,2,3])
3371 a[slice(1, 3)] = [3,2]
3372 vereq(a, [1,3,2])
3373 a[slice(0, 2, 1)] = [3,1]
3374 vereq(a, [3,1,2])
3375 a.__setitem__(slice(1, 3), [2,1])
3376 vereq(a, [3,2,1])
3377 a.__setitem__(slice(0, 2, 1), [2,3])
3378 vereq(a, [2,3,1])
3379
Tim Peters2484aae2002-07-11 06:56:07 +00003380def subtype_resurrection():
3381 if verbose:
Tim Peters45228ca2002-07-11 07:09:42 +00003382 print "Testing resurrection of new-style instance..."
Tim Peters2484aae2002-07-11 06:56:07 +00003383
3384 class C(object):
3385 container = []
3386
3387 def __del__(self):
3388 # resurrect the instance
3389 C.container.append(self)
3390
3391 c = C()
3392 c.attr = 42
Tim Peters14cb1e12002-07-11 18:26:21 +00003393 # The most interesting thing here is whether this blows up, due to flawed
Tim Peters45228ca2002-07-11 07:09:42 +00003394 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
Tim Peters2484aae2002-07-11 06:56:07 +00003395 del c
Tim Peters14cb1e12002-07-11 18:26:21 +00003396
3397 # If that didn't blow up, it's also interesting to see whether clearing
3398 # the last container slot works: that will attempt to delete c again,
3399 # which will cause c to get appended back to the container again "during"
3400 # the del.
3401 del C.container[-1]
3402 vereq(len(C.container), 1)
Tim Peters2484aae2002-07-11 06:56:07 +00003403 vereq(C.container[-1].attr, 42)
Guido van Rossum09638c12002-06-13 19:17:46 +00003404
Tim Peters14cb1e12002-07-11 18:26:21 +00003405 # Make c mortal again, so that the test framework with -l doesn't report
3406 # it as a leak.
3407 del C.__del__
3408
Guido van Rossum2d702462002-08-06 21:28:28 +00003409def slottrash():
3410 # Deallocating deeply nested slotted trash caused stack overflows
3411 if verbose:
3412 print "Testing slot trash..."
3413 class trash(object):
3414 __slots__ = ['x']
3415 def __init__(self, x):
3416 self.x = x
3417 o = None
3418 for i in xrange(50000):
3419 o = trash(o)
3420 del o
3421
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003422def slotmultipleinheritance():
3423 # SF bug 575229, multiple inheritance w/ slots dumps core
3424 class A(object):
3425 __slots__=()
3426 class B(object):
3427 pass
3428 class C(A,B) :
3429 __slots__=()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003430 vereq(C.__basicsize__, B.__basicsize__)
3431 verify(hasattr(C, '__dict__'))
3432 verify(hasattr(C, '__weakref__'))
3433 C().x = 2
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003434
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003435def testrmul():
3436 # SF patch 592646
3437 if verbose:
3438 print "Testing correct invocation of __rmul__..."
3439 class C(object):
3440 def __mul__(self, other):
3441 return "mul"
3442 def __rmul__(self, other):
3443 return "rmul"
3444 a = C()
3445 vereq(a*2, "mul")
3446 vereq(a*2.2, "mul")
3447 vereq(2*a, "rmul")
3448 vereq(2.2*a, "rmul")
3449
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003450def testipow():
3451 # [SF bug 620179]
3452 if verbose:
3453 print "Testing correct invocation of __ipow__..."
3454 class C(object):
3455 def __ipow__(self, other):
3456 pass
3457 a = C()
3458 a **= 2
3459
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003460def do_this_first():
3461 if verbose:
3462 print "Testing SF bug 551412 ..."
3463 # This dumps core when SF bug 551412 isn't fixed --
3464 # but only when test_descr.py is run separately.
3465 # (That can't be helped -- as soon as PyType_Ready()
3466 # is called for PyLong_Type, the bug is gone.)
3467 class UserLong(object):
3468 def __pow__(self, *args):
3469 pass
3470 try:
3471 pow(0L, UserLong(), 0L)
3472 except:
3473 pass
3474
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003475 if verbose:
3476 print "Testing SF bug 570483..."
3477 # Another segfault only when run early
3478 # (before PyType_Ready(tuple) is called)
3479 type.mro(tuple)
3480
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003481def test_mutable_bases():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003482 if verbose:
3483 print "Testing mutable bases..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003484 # stuff that should work:
3485 class C(object):
3486 pass
3487 class C2(object):
3488 def __getattribute__(self, attr):
3489 if attr == 'a':
3490 return 2
3491 else:
Tim Peters6578dc92002-12-24 18:31:27 +00003492 return super(C2, self).__getattribute__(attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003493 def meth(self):
3494 return 1
3495 class D(C):
3496 pass
3497 class E(D):
3498 pass
3499 d = D()
3500 e = E()
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003501 D.__bases__ = (C,)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003502 D.__bases__ = (C2,)
3503 vereq(d.meth(), 1)
3504 vereq(e.meth(), 1)
3505 vereq(d.a, 2)
3506 vereq(e.a, 2)
3507 vereq(C2.__subclasses__(), [D])
3508
3509 # stuff that shouldn't:
3510 class L(list):
3511 pass
3512
3513 try:
3514 L.__bases__ = (dict,)
3515 except TypeError:
3516 pass
3517 else:
3518 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3519
3520 try:
3521 list.__bases__ = (dict,)
3522 except TypeError:
3523 pass
3524 else:
3525 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3526
3527 try:
3528 del D.__bases__
3529 except TypeError:
3530 pass
3531 else:
3532 raise TestFailed, "shouldn't be able to delete .__bases__"
3533
3534 try:
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003535 D.__bases__ = ()
3536 except TypeError, msg:
3537 if str(msg) == "a new-style class can't have only classic bases":
3538 raise TestFailed, "wrong error message for .__bases__ = ()"
3539 else:
3540 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3541
3542 try:
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003543 D.__bases__ = (D,)
3544 except TypeError:
3545 pass
3546 else:
3547 # actually, we'll have crashed by here...
3548 raise TestFailed, "shouldn't be able to create inheritance cycles"
3549
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +00003550 try:
3551 D.__bases__ = (E,)
3552 except TypeError:
3553 pass
3554 else:
3555 raise TestFailed, "shouldn't be able to create inheritance cycles"
3556
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003557 # let's throw a classic class into the mix:
3558 class Classic:
3559 def meth2(self):
3560 return 3
3561
3562 D.__bases__ = (C, Classic)
3563
3564 vereq(d.meth2(), 3)
3565 vereq(e.meth2(), 3)
3566 try:
3567 d.a
3568 except AttributeError:
3569 pass
3570 else:
3571 raise TestFailed, "attribute should have vanished"
3572
3573 try:
3574 D.__bases__ = (Classic,)
3575 except TypeError:
3576 pass
3577 else:
3578 raise TestFailed, "new-style class must have a new-style base"
3579
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003580def test_mutable_bases_with_failing_mro():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003581 if verbose:
3582 print "Testing mutable bases with failing mro..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003583 class WorkOnce(type):
3584 def __new__(self, name, bases, ns):
3585 self.flag = 0
3586 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3587 def mro(self):
3588 if self.flag > 0:
3589 raise RuntimeError, "bozo"
3590 else:
3591 self.flag += 1
3592 return type.mro(self)
3593
3594 class WorkAlways(type):
3595 def mro(self):
3596 # this is here to make sure that .mro()s aren't called
3597 # with an exception set (which was possible at one point).
3598 # An error message will be printed in a debug build.
3599 # What's a good way to test for this?
3600 return type.mro(self)
3601
3602 class C(object):
3603 pass
3604
3605 class C2(object):
3606 pass
3607
3608 class D(C):
3609 pass
3610
3611 class E(D):
3612 pass
3613
3614 class F(D):
3615 __metaclass__ = WorkOnce
3616
3617 class G(D):
3618 __metaclass__ = WorkAlways
3619
3620 # Immediate subclasses have their mro's adjusted in alphabetical
3621 # order, so E's will get adjusted before adjusting F's fails. We
3622 # check here that E's gets restored.
Tim Peters6578dc92002-12-24 18:31:27 +00003623
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003624 E_mro_before = E.__mro__
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003625 D_mro_before = D.__mro__
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003626
3627 try:
3628 D.__bases__ = (C2,)
3629 except RuntimeError:
3630 vereq(E.__mro__, E_mro_before)
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +00003631 vereq(D.__mro__, D_mro_before)
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003632 else:
3633 raise TestFailed, "exception not propagated"
3634
3635def test_mutable_bases_catch_mro_conflict():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003636 if verbose:
3637 print "Testing mutable bases catch mro conflict..."
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003638 class A(object):
3639 pass
3640
3641 class B(object):
3642 pass
3643
3644 class C(A, B):
3645 pass
3646
3647 class D(A, B):
3648 pass
3649
3650 class E(C, D):
3651 pass
3652
3653 try:
3654 C.__bases__ = (B, A)
3655 except TypeError:
3656 pass
3657 else:
3658 raise TestFailed, "didn't catch MRO conflict"
Tim Peters6578dc92002-12-24 18:31:27 +00003659
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003660def mutable_names():
Guido van Rossum2720b0d2003-01-06 21:26:44 +00003661 if verbose:
3662 print "Testing mutable names..."
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003663 class C(object):
3664 pass
3665
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003666 # C.__module__ could be 'test_descr' or '__main__'
3667 mod = C.__module__
Tim Peters6578dc92002-12-24 18:31:27 +00003668
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +00003669 C.__name__ = 'D'
3670 vereq((C.__module__, C.__name__), (mod, 'D'))
3671
3672 C.__name__ = 'D.E'
3673 vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters6578dc92002-12-24 18:31:27 +00003674
Guido van Rossum613f24f2003-01-06 23:00:59 +00003675def subclass_right_op():
3676 if verbose:
3677 print "Testing correct dispatch of subclass overloading __r<op>__..."
3678
3679 # This code tests various cases where right-dispatch of a subclass
3680 # should be preferred over left-dispatch of a base class.
3681
3682 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3683
3684 class B(int):
Guido van Rossumf389c772003-02-27 20:04:19 +00003685 def __floordiv__(self, other):
3686 return "B.__floordiv__"
3687 def __rfloordiv__(self, other):
3688 return "B.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003689
Guido van Rossumf389c772003-02-27 20:04:19 +00003690 vereq(B(1) // 1, "B.__floordiv__")
3691 vereq(1 // B(1), "B.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003692
3693 # Case 2: subclass of object; this is just the baseline for case 3
3694
3695 class C(object):
Guido van Rossumf389c772003-02-27 20:04:19 +00003696 def __floordiv__(self, other):
3697 return "C.__floordiv__"
3698 def __rfloordiv__(self, other):
3699 return "C.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003700
Guido van Rossumf389c772003-02-27 20:04:19 +00003701 vereq(C() // 1, "C.__floordiv__")
3702 vereq(1 // C(), "C.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003703
3704 # Case 3: subclass of new-style class; here it gets interesting
3705
3706 class D(C):
Guido van Rossumf389c772003-02-27 20:04:19 +00003707 def __floordiv__(self, other):
3708 return "D.__floordiv__"
3709 def __rfloordiv__(self, other):
3710 return "D.__rfloordiv__"
Guido van Rossum613f24f2003-01-06 23:00:59 +00003711
Guido van Rossumf389c772003-02-27 20:04:19 +00003712 vereq(D() // C(), "D.__floordiv__")
3713 vereq(C() // D(), "D.__rfloordiv__")
Guido van Rossum613f24f2003-01-06 23:00:59 +00003714
3715 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3716
3717 class E(C):
3718 pass
3719
Guido van Rossumf389c772003-02-27 20:04:19 +00003720 vereq(E.__rfloordiv__, C.__rfloordiv__)
Guido van Rossum613f24f2003-01-06 23:00:59 +00003721
Guido van Rossumf389c772003-02-27 20:04:19 +00003722 vereq(E() // 1, "C.__floordiv__")
3723 vereq(1 // E(), "C.__rfloordiv__")
3724 vereq(E() // C(), "C.__floordiv__")
3725 vereq(C() // E(), "C.__floordiv__") # This one would fail
Guido van Rossum613f24f2003-01-06 23:00:59 +00003726
Guido van Rossum373c7412003-01-07 13:41:37 +00003727def dict_type_with_metaclass():
3728 if verbose:
3729 print "Testing type of __dict__ when __metaclass__ set..."
3730
3731 class B(object):
3732 pass
3733 class M(type):
3734 pass
3735 class C:
3736 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3737 __metaclass__ = M
3738 veris(type(C.__dict__), type(B.__dict__))
3739
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003740def meth_class_get():
3741 # Full coverage of descrobject.c::classmethod_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003742 if verbose:
3743 print "Testing __get__ method of METH_CLASS C methods..."
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003744 # Baseline
3745 arg = [1, 2, 3]
3746 res = {1: None, 2: None, 3: None}
3747 vereq(dict.fromkeys(arg), res)
3748 vereq({}.fromkeys(arg), res)
3749 # Now get the descriptor
3750 descr = dict.__dict__["fromkeys"]
3751 # More baseline using the descriptor directly
3752 vereq(descr.__get__(None, dict)(arg), res)
3753 vereq(descr.__get__({})(arg), res)
3754 # Now check various error cases
3755 try:
3756 descr.__get__(None, None)
3757 except TypeError:
3758 pass
3759 else:
3760 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3761 try:
3762 descr.__get__(42)
3763 except TypeError:
3764 pass
3765 else:
3766 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3767 try:
3768 descr.__get__(None, 42)
3769 except TypeError:
3770 pass
3771 else:
3772 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3773 try:
3774 descr.__get__(None, int)
3775 except TypeError:
3776 pass
3777 else:
3778 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3779
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003780def isinst_isclass():
3781 if verbose:
3782 print "Testing proxy isinstance() and isclass()..."
3783 class Proxy(object):
3784 def __init__(self, obj):
3785 self.__obj = obj
3786 def __getattribute__(self, name):
3787 if name.startswith("_Proxy__"):
3788 return object.__getattribute__(self, name)
3789 else:
3790 return getattr(self.__obj, name)
3791 # Test with a classic class
3792 class C:
3793 pass
3794 a = C()
3795 pa = Proxy(a)
3796 verify(isinstance(a, C)) # Baseline
3797 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003798 # Test with a classic subclass
3799 class D(C):
3800 pass
3801 a = D()
3802 pa = Proxy(a)
3803 verify(isinstance(a, C)) # Baseline
3804 verify(isinstance(pa, C)) # Test
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003805 # Test with a new-style class
3806 class C(object):
3807 pass
3808 a = C()
3809 pa = Proxy(a)
3810 verify(isinstance(a, C)) # Baseline
3811 verify(isinstance(pa, C)) # Test
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003812 # Test with a new-style subclass
3813 class D(C):
3814 pass
3815 a = D()
3816 pa = Proxy(a)
3817 verify(isinstance(a, C)) # Baseline
3818 verify(isinstance(pa, C)) # Test
3819
3820def proxysuper():
3821 if verbose:
3822 print "Testing super() for a proxy object..."
3823 class Proxy(object):
3824 def __init__(self, obj):
3825 self.__obj = obj
3826 def __getattribute__(self, name):
3827 if name.startswith("_Proxy__"):
3828 return object.__getattribute__(self, name)
3829 else:
3830 return getattr(self.__obj, name)
3831
3832 class B(object):
3833 def f(self):
3834 return "B.f"
3835
3836 class C(B):
3837 def f(self):
3838 return super(C, self).f() + "->C.f"
3839
3840 obj = C()
3841 p = Proxy(obj)
3842 vereq(C.__dict__["f"](p), "B.f->C.f")
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003843
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003844
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003845def test_main():
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003846 do_this_first()
Tim Peters2f93e282001-10-04 05:27:00 +00003847 class_docstrings()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848 lists()
3849 dicts()
Tim Peters25786c02001-09-02 08:22:48 +00003850 dict_constructor()
Tim Peters5d2b77c2001-09-03 05:47:38 +00003851 test_dir()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852 ints()
3853 longs()
3854 floats()
3855 complexes()
3856 spamlists()
3857 spamdicts()
3858 pydicts()
3859 pylists()
3860 metaclass()
3861 pymods()
3862 multi()
Guido van Rossumd32047f2002-11-25 21:38:52 +00003863 mro_disagreement()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 diamond()
Guido van Rossum9a818922002-11-14 19:50:14 +00003865 ex5()
3866 monotonicity()
3867 consistency_with_epg()
Guido van Rossum37202612001-08-09 19:45:21 +00003868 objects()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869 slots()
Guido van Rossum8b056da2002-08-13 18:26:26 +00003870 slotspecials()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871 dynamics()
3872 errors()
3873 classmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003874 classmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875 staticmethods()
Fred Drakef841aa62002-03-28 15:49:54 +00003876 staticmethods_in_c()
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877 classic()
3878 compattr()
3879 newslot()
3880 altmro()
3881 overloading()
Guido van Rossumb5a136b2001-08-15 17:51:17 +00003882 methods()
Guido van Rossuma4ff6ab2001-08-15 23:57:59 +00003883 specials()
Guido van Rossum65d5d7f2001-08-17 21:27:53 +00003884 weakrefs()
Guido van Rossum8bce4ac2001-09-06 21:56:42 +00003885 properties()
Guido van Rossumc4a18802001-08-24 16:55:27 +00003886 supers()
Guido van Rossumcaa9f432001-08-30 20:06:08 +00003887 inherits()
Tim Peters808b94e2001-09-13 19:33:07 +00003888 keywords()
Tim Peters8fa45672001-09-13 21:01:29 +00003889 restricted()
Tim Peters0ab085c2001-09-14 00:25:33 +00003890 str_subclass_as_dict_key()
Guido van Rossumab3b0342001-09-18 20:38:53 +00003891 classic_comparisons()
Guido van Rossum0639f592001-09-18 21:06:04 +00003892 rich_comparisons()
Guido van Rossum1952e382001-09-19 01:25:16 +00003893 coercions()
Guido van Rossum8b9cc7e2001-09-20 21:49:53 +00003894 descrdoc()
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003895 setclass()
Guido van Rossum6661be32001-10-26 04:26:12 +00003896 setdict()
Guido van Rossum3926a632001-09-25 16:25:58 +00003897 pickles()
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003898 copies()
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003899 binopoverride()
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003900 subclasspropagation()
Tim Petersfc57ccb2001-10-12 02:38:24 +00003901 buffer_inherit()
Tim Petersc9933152001-10-16 20:18:24 +00003902 str_of_str_subclass()
Guido van Rossumc8e56452001-10-22 00:43:43 +00003903 kwdargs()
Guido van Rossumed87ad82001-10-30 02:33:02 +00003904 delhook()
Guido van Rossumdbb53d92001-12-03 16:32:18 +00003905 hashinherit()
Guido van Rossum29d26062001-12-11 04:37:34 +00003906 strops()
Guido van Rossum2764a3a2001-12-28 21:39:03 +00003907 deepcopyrecursive()
Guido van Rossumd7035672002-03-12 20:43:31 +00003908 modules()
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003909 dictproxyiterkeys()
3910 dictproxyitervalues()
3911 dictproxyiteritems()
Guido van Rossum8c842552002-03-14 23:05:54 +00003912 pickleslots()
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00003913 funnynew()
Guido van Rossume8fc6402002-04-16 16:44:51 +00003914 imulbug()
Guido van Rossumd99b3e72002-04-18 00:27:33 +00003915 docdescriptor()
Tim Petersafb2c802002-04-18 18:06:20 +00003916 string_exceptions()
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00003917 copy_setstate()
Guido van Rossum09638c12002-06-13 19:17:46 +00003918 slices()
Tim Peters2484aae2002-07-11 06:56:07 +00003919 subtype_resurrection()
Guido van Rossum2d702462002-08-06 21:28:28 +00003920 slottrash()
Neal Norwitzf9dd0f12002-08-13 17:16:49 +00003921 slotmultipleinheritance()
Guido van Rossum0f5f0b82002-08-09 16:11:37 +00003922 testrmul()
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003923 testipow()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003924 test_mutable_bases()
3925 test_mutable_bases_with_failing_mro()
3926 test_mutable_bases_catch_mro_conflict()
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003927 mutable_names()
Guido van Rossum613f24f2003-01-06 23:00:59 +00003928 subclass_right_op()
Guido van Rossum373c7412003-01-07 13:41:37 +00003929 dict_type_with_metaclass()
Guido van Rossumb6e5a0c2003-02-11 18:44:42 +00003930 meth_class_get()
Guido van Rossum03bc7d32003-02-12 03:32:58 +00003931 isinst_isclass()
Guido van Rossuma89d10e2003-02-12 03:58:38 +00003932 proxysuper()
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003933
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003934 if verbose: print "All OK"
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935
Guido van Rossuma56b42b2001-09-20 21:39:07 +00003936if __name__ == "__main__":
3937 test_main()