1 | n/a | import builtins |
---|
2 | n/a | import copyreg |
---|
3 | n/a | import gc |
---|
4 | n/a | import itertools |
---|
5 | n/a | import math |
---|
6 | n/a | import pickle |
---|
7 | n/a | import sys |
---|
8 | n/a | import types |
---|
9 | n/a | import unittest |
---|
10 | n/a | import warnings |
---|
11 | n/a | import weakref |
---|
12 | n/a | |
---|
13 | n/a | from copy import deepcopy |
---|
14 | n/a | from test import support |
---|
15 | n/a | |
---|
16 | n/a | |
---|
17 | n/a | class OperatorsTest(unittest.TestCase): |
---|
18 | n/a | |
---|
19 | n/a | def __init__(self, *args, **kwargs): |
---|
20 | n/a | unittest.TestCase.__init__(self, *args, **kwargs) |
---|
21 | n/a | self.binops = { |
---|
22 | n/a | 'add': '+', |
---|
23 | n/a | 'sub': '-', |
---|
24 | n/a | 'mul': '*', |
---|
25 | n/a | 'matmul': '@', |
---|
26 | n/a | 'truediv': '/', |
---|
27 | n/a | 'floordiv': '//', |
---|
28 | n/a | 'divmod': 'divmod', |
---|
29 | n/a | 'pow': '**', |
---|
30 | n/a | 'lshift': '<<', |
---|
31 | n/a | 'rshift': '>>', |
---|
32 | n/a | 'and': '&', |
---|
33 | n/a | 'xor': '^', |
---|
34 | n/a | 'or': '|', |
---|
35 | n/a | 'cmp': 'cmp', |
---|
36 | n/a | 'lt': '<', |
---|
37 | n/a | 'le': '<=', |
---|
38 | n/a | 'eq': '==', |
---|
39 | n/a | 'ne': '!=', |
---|
40 | n/a | 'gt': '>', |
---|
41 | n/a | 'ge': '>=', |
---|
42 | n/a | } |
---|
43 | n/a | |
---|
44 | n/a | for name, expr in list(self.binops.items()): |
---|
45 | n/a | if expr.islower(): |
---|
46 | n/a | expr = expr + "(a, b)" |
---|
47 | n/a | else: |
---|
48 | n/a | expr = 'a %s b' % expr |
---|
49 | n/a | self.binops[name] = expr |
---|
50 | n/a | |
---|
51 | n/a | self.unops = { |
---|
52 | n/a | 'pos': '+', |
---|
53 | n/a | 'neg': '-', |
---|
54 | n/a | 'abs': 'abs', |
---|
55 | n/a | 'invert': '~', |
---|
56 | n/a | 'int': 'int', |
---|
57 | n/a | 'float': 'float', |
---|
58 | n/a | } |
---|
59 | n/a | |
---|
60 | n/a | for name, expr in list(self.unops.items()): |
---|
61 | n/a | if expr.islower(): |
---|
62 | n/a | expr = expr + "(a)" |
---|
63 | n/a | else: |
---|
64 | n/a | expr = '%s a' % expr |
---|
65 | n/a | self.unops[name] = expr |
---|
66 | n/a | |
---|
67 | n/a | def unop_test(self, a, res, expr="len(a)", meth="__len__"): |
---|
68 | n/a | d = {'a': a} |
---|
69 | n/a | self.assertEqual(eval(expr, d), res) |
---|
70 | n/a | t = type(a) |
---|
71 | n/a | m = getattr(t, meth) |
---|
72 | n/a | |
---|
73 | n/a | # Find method in parent class |
---|
74 | n/a | while meth not in t.__dict__: |
---|
75 | n/a | t = t.__bases__[0] |
---|
76 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
77 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
78 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
79 | n/a | self.assertEqual(m(a), res) |
---|
80 | n/a | bm = getattr(a, meth) |
---|
81 | n/a | self.assertEqual(bm(), res) |
---|
82 | n/a | |
---|
83 | n/a | def binop_test(self, a, b, res, expr="a+b", meth="__add__"): |
---|
84 | n/a | d = {'a': a, 'b': b} |
---|
85 | n/a | |
---|
86 | n/a | self.assertEqual(eval(expr, d), res) |
---|
87 | n/a | t = type(a) |
---|
88 | n/a | m = getattr(t, meth) |
---|
89 | n/a | while meth not in t.__dict__: |
---|
90 | n/a | t = t.__bases__[0] |
---|
91 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
92 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
93 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
94 | n/a | self.assertEqual(m(a, b), res) |
---|
95 | n/a | bm = getattr(a, meth) |
---|
96 | n/a | self.assertEqual(bm(b), res) |
---|
97 | n/a | |
---|
98 | n/a | def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"): |
---|
99 | n/a | d = {'a': a, 'b': b, 'c': c} |
---|
100 | n/a | self.assertEqual(eval(expr, d), res) |
---|
101 | n/a | t = type(a) |
---|
102 | n/a | m = getattr(t, meth) |
---|
103 | n/a | while meth not in t.__dict__: |
---|
104 | n/a | t = t.__bases__[0] |
---|
105 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
106 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
107 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
108 | n/a | self.assertEqual(m(a, slice(b, c)), res) |
---|
109 | n/a | bm = getattr(a, meth) |
---|
110 | n/a | self.assertEqual(bm(slice(b, c)), res) |
---|
111 | n/a | |
---|
112 | n/a | def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"): |
---|
113 | n/a | d = {'a': deepcopy(a), 'b': b} |
---|
114 | n/a | exec(stmt, d) |
---|
115 | n/a | self.assertEqual(d['a'], res) |
---|
116 | n/a | t = type(a) |
---|
117 | n/a | m = getattr(t, meth) |
---|
118 | n/a | while meth not in t.__dict__: |
---|
119 | n/a | t = t.__bases__[0] |
---|
120 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
121 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
122 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
123 | n/a | d['a'] = deepcopy(a) |
---|
124 | n/a | m(d['a'], b) |
---|
125 | n/a | self.assertEqual(d['a'], res) |
---|
126 | n/a | d['a'] = deepcopy(a) |
---|
127 | n/a | bm = getattr(d['a'], meth) |
---|
128 | n/a | bm(b) |
---|
129 | n/a | self.assertEqual(d['a'], res) |
---|
130 | n/a | |
---|
131 | n/a | def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"): |
---|
132 | n/a | d = {'a': deepcopy(a), 'b': b, 'c': c} |
---|
133 | n/a | exec(stmt, d) |
---|
134 | n/a | self.assertEqual(d['a'], res) |
---|
135 | n/a | t = type(a) |
---|
136 | n/a | m = getattr(t, meth) |
---|
137 | n/a | while meth not in t.__dict__: |
---|
138 | n/a | t = t.__bases__[0] |
---|
139 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
140 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
141 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
142 | n/a | d['a'] = deepcopy(a) |
---|
143 | n/a | m(d['a'], b, c) |
---|
144 | n/a | self.assertEqual(d['a'], res) |
---|
145 | n/a | d['a'] = deepcopy(a) |
---|
146 | n/a | bm = getattr(d['a'], meth) |
---|
147 | n/a | bm(b, c) |
---|
148 | n/a | self.assertEqual(d['a'], res) |
---|
149 | n/a | |
---|
150 | n/a | def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"): |
---|
151 | n/a | dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} |
---|
152 | n/a | exec(stmt, dictionary) |
---|
153 | n/a | self.assertEqual(dictionary['a'], res) |
---|
154 | n/a | t = type(a) |
---|
155 | n/a | while meth not in t.__dict__: |
---|
156 | n/a | t = t.__bases__[0] |
---|
157 | n/a | m = getattr(t, meth) |
---|
158 | n/a | # in some implementations (e.g. PyPy), 'm' can be a regular unbound |
---|
159 | n/a | # method object; the getattr() below obtains its underlying function. |
---|
160 | n/a | self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) |
---|
161 | n/a | dictionary['a'] = deepcopy(a) |
---|
162 | n/a | m(dictionary['a'], slice(b, c), d) |
---|
163 | n/a | self.assertEqual(dictionary['a'], res) |
---|
164 | n/a | dictionary['a'] = deepcopy(a) |
---|
165 | n/a | bm = getattr(dictionary['a'], meth) |
---|
166 | n/a | bm(slice(b, c), d) |
---|
167 | n/a | self.assertEqual(dictionary['a'], res) |
---|
168 | n/a | |
---|
169 | n/a | def test_lists(self): |
---|
170 | n/a | # Testing list operations... |
---|
171 | n/a | # Asserts are within individual test methods |
---|
172 | n/a | self.binop_test([1], [2], [1,2], "a+b", "__add__") |
---|
173 | n/a | self.binop_test([1,2,3], 2, 1, "b in a", "__contains__") |
---|
174 | n/a | self.binop_test([1,2,3], 4, 0, "b in a", "__contains__") |
---|
175 | n/a | self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__") |
---|
176 | n/a | self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__") |
---|
177 | n/a | self.setop_test([1], [2], [1,2], "a+=b", "__iadd__") |
---|
178 | n/a | self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__") |
---|
179 | n/a | self.unop_test([1,2,3], 3, "len(a)", "__len__") |
---|
180 | n/a | self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__") |
---|
181 | n/a | self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__") |
---|
182 | n/a | self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__") |
---|
183 | n/a | self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", |
---|
184 | n/a | "__setitem__") |
---|
185 | n/a | |
---|
186 | n/a | def test_dicts(self): |
---|
187 | n/a | # Testing dict operations... |
---|
188 | n/a | self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__") |
---|
189 | n/a | self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__") |
---|
190 | n/a | self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__") |
---|
191 | n/a | |
---|
192 | n/a | d = {1:2, 3:4} |
---|
193 | n/a | l1 = [] |
---|
194 | n/a | for i in list(d.keys()): |
---|
195 | n/a | l1.append(i) |
---|
196 | n/a | l = [] |
---|
197 | n/a | for i in iter(d): |
---|
198 | n/a | l.append(i) |
---|
199 | n/a | self.assertEqual(l, l1) |
---|
200 | n/a | l = [] |
---|
201 | n/a | for i in d.__iter__(): |
---|
202 | n/a | l.append(i) |
---|
203 | n/a | self.assertEqual(l, l1) |
---|
204 | n/a | l = [] |
---|
205 | n/a | for i in dict.__iter__(d): |
---|
206 | n/a | l.append(i) |
---|
207 | n/a | self.assertEqual(l, l1) |
---|
208 | n/a | d = {1:2, 3:4} |
---|
209 | n/a | self.unop_test(d, 2, "len(a)", "__len__") |
---|
210 | n/a | self.assertEqual(eval(repr(d), {}), d) |
---|
211 | n/a | self.assertEqual(eval(d.__repr__(), {}), d) |
---|
212 | n/a | self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", |
---|
213 | n/a | "__setitem__") |
---|
214 | n/a | |
---|
215 | n/a | # Tests for unary and binary operators |
---|
216 | n/a | def number_operators(self, a, b, skip=[]): |
---|
217 | n/a | dict = {'a': a, 'b': b} |
---|
218 | n/a | |
---|
219 | n/a | for name, expr in self.binops.items(): |
---|
220 | n/a | if name not in skip: |
---|
221 | n/a | name = "__%s__" % name |
---|
222 | n/a | if hasattr(a, name): |
---|
223 | n/a | res = eval(expr, dict) |
---|
224 | n/a | self.binop_test(a, b, res, expr, name) |
---|
225 | n/a | |
---|
226 | n/a | for name, expr in list(self.unops.items()): |
---|
227 | n/a | if name not in skip: |
---|
228 | n/a | name = "__%s__" % name |
---|
229 | n/a | if hasattr(a, name): |
---|
230 | n/a | res = eval(expr, dict) |
---|
231 | n/a | self.unop_test(a, res, expr, name) |
---|
232 | n/a | |
---|
233 | n/a | def test_ints(self): |
---|
234 | n/a | # Testing int operations... |
---|
235 | n/a | self.number_operators(100, 3) |
---|
236 | n/a | # The following crashes in Python 2.2 |
---|
237 | n/a | self.assertEqual((1).__bool__(), 1) |
---|
238 | n/a | self.assertEqual((0).__bool__(), 0) |
---|
239 | n/a | # This returns 'NotImplemented' in Python 2.2 |
---|
240 | n/a | class C(int): |
---|
241 | n/a | def __add__(self, other): |
---|
242 | n/a | return NotImplemented |
---|
243 | n/a | self.assertEqual(C(5), 5) |
---|
244 | n/a | try: |
---|
245 | n/a | C() + "" |
---|
246 | n/a | except TypeError: |
---|
247 | n/a | pass |
---|
248 | n/a | else: |
---|
249 | n/a | self.fail("NotImplemented should have caused TypeError") |
---|
250 | n/a | |
---|
251 | n/a | def test_floats(self): |
---|
252 | n/a | # Testing float operations... |
---|
253 | n/a | self.number_operators(100.0, 3.0) |
---|
254 | n/a | |
---|
255 | n/a | def test_complexes(self): |
---|
256 | n/a | # Testing complex operations... |
---|
257 | n/a | self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', |
---|
258 | n/a | 'int', 'float', |
---|
259 | n/a | 'floordiv', 'divmod', 'mod']) |
---|
260 | n/a | |
---|
261 | n/a | class Number(complex): |
---|
262 | n/a | __slots__ = ['prec'] |
---|
263 | n/a | def __new__(cls, *args, **kwds): |
---|
264 | n/a | result = complex.__new__(cls, *args) |
---|
265 | n/a | result.prec = kwds.get('prec', 12) |
---|
266 | n/a | return result |
---|
267 | n/a | def __repr__(self): |
---|
268 | n/a | prec = self.prec |
---|
269 | n/a | if self.imag == 0.0: |
---|
270 | n/a | return "%.*g" % (prec, self.real) |
---|
271 | n/a | if self.real == 0.0: |
---|
272 | n/a | return "%.*gj" % (prec, self.imag) |
---|
273 | n/a | return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) |
---|
274 | n/a | __str__ = __repr__ |
---|
275 | n/a | |
---|
276 | n/a | a = Number(3.14, prec=6) |
---|
277 | n/a | self.assertEqual(repr(a), "3.14") |
---|
278 | n/a | self.assertEqual(a.prec, 6) |
---|
279 | n/a | |
---|
280 | n/a | a = Number(a, prec=2) |
---|
281 | n/a | self.assertEqual(repr(a), "3.1") |
---|
282 | n/a | self.assertEqual(a.prec, 2) |
---|
283 | n/a | |
---|
284 | n/a | a = Number(234.5) |
---|
285 | n/a | self.assertEqual(repr(a), "234.5") |
---|
286 | n/a | self.assertEqual(a.prec, 12) |
---|
287 | n/a | |
---|
288 | n/a | def test_explicit_reverse_methods(self): |
---|
289 | n/a | # see issue 9930 |
---|
290 | n/a | self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0)) |
---|
291 | n/a | self.assertEqual(float.__rsub__(3.0, 1), -2.0) |
---|
292 | n/a | |
---|
293 | n/a | @support.impl_detail("the module 'xxsubtype' is internal") |
---|
294 | n/a | def test_spam_lists(self): |
---|
295 | n/a | # Testing spamlist operations... |
---|
296 | n/a | import copy, xxsubtype as spam |
---|
297 | n/a | |
---|
298 | n/a | def spamlist(l, memo=None): |
---|
299 | n/a | import xxsubtype as spam |
---|
300 | n/a | return spam.spamlist(l) |
---|
301 | n/a | |
---|
302 | n/a | # This is an ugly hack: |
---|
303 | n/a | copy._deepcopy_dispatch[spam.spamlist] = spamlist |
---|
304 | n/a | |
---|
305 | n/a | self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", |
---|
306 | n/a | "__add__") |
---|
307 | n/a | self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") |
---|
308 | n/a | self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") |
---|
309 | n/a | self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") |
---|
310 | n/a | self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]", |
---|
311 | n/a | "__getitem__") |
---|
312 | n/a | self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b", |
---|
313 | n/a | "__iadd__") |
---|
314 | n/a | self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", |
---|
315 | n/a | "__imul__") |
---|
316 | n/a | self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__") |
---|
317 | n/a | self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", |
---|
318 | n/a | "__mul__") |
---|
319 | n/a | self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", |
---|
320 | n/a | "__rmul__") |
---|
321 | n/a | self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", |
---|
322 | n/a | "__setitem__") |
---|
323 | n/a | self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), |
---|
324 | n/a | spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__") |
---|
325 | n/a | # Test subclassing |
---|
326 | n/a | class C(spam.spamlist): |
---|
327 | n/a | def foo(self): return 1 |
---|
328 | n/a | a = C() |
---|
329 | n/a | self.assertEqual(a, []) |
---|
330 | n/a | self.assertEqual(a.foo(), 1) |
---|
331 | n/a | a.append(100) |
---|
332 | n/a | self.assertEqual(a, [100]) |
---|
333 | n/a | self.assertEqual(a.getstate(), 0) |
---|
334 | n/a | a.setstate(42) |
---|
335 | n/a | self.assertEqual(a.getstate(), 42) |
---|
336 | n/a | |
---|
337 | n/a | @support.impl_detail("the module 'xxsubtype' is internal") |
---|
338 | n/a | def test_spam_dicts(self): |
---|
339 | n/a | # Testing spamdict operations... |
---|
340 | n/a | import copy, xxsubtype as spam |
---|
341 | n/a | def spamdict(d, memo=None): |
---|
342 | n/a | import xxsubtype as spam |
---|
343 | n/a | sd = spam.spamdict() |
---|
344 | n/a | for k, v in list(d.items()): |
---|
345 | n/a | sd[k] = v |
---|
346 | n/a | return sd |
---|
347 | n/a | # This is an ugly hack: |
---|
348 | n/a | copy._deepcopy_dispatch[spam.spamdict] = spamdict |
---|
349 | n/a | |
---|
350 | n/a | self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") |
---|
351 | n/a | self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") |
---|
352 | n/a | self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") |
---|
353 | n/a | d = spamdict({1:2,3:4}) |
---|
354 | n/a | l1 = [] |
---|
355 | n/a | for i in list(d.keys()): |
---|
356 | n/a | l1.append(i) |
---|
357 | n/a | l = [] |
---|
358 | n/a | for i in iter(d): |
---|
359 | n/a | l.append(i) |
---|
360 | n/a | self.assertEqual(l, l1) |
---|
361 | n/a | l = [] |
---|
362 | n/a | for i in d.__iter__(): |
---|
363 | n/a | l.append(i) |
---|
364 | n/a | self.assertEqual(l, l1) |
---|
365 | n/a | l = [] |
---|
366 | n/a | for i in type(spamdict({})).__iter__(d): |
---|
367 | n/a | l.append(i) |
---|
368 | n/a | self.assertEqual(l, l1) |
---|
369 | n/a | straightd = {1:2, 3:4} |
---|
370 | n/a | spamd = spamdict(straightd) |
---|
371 | n/a | self.unop_test(spamd, 2, "len(a)", "__len__") |
---|
372 | n/a | self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__") |
---|
373 | n/a | self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), |
---|
374 | n/a | "a[b]=c", "__setitem__") |
---|
375 | n/a | # Test subclassing |
---|
376 | n/a | class C(spam.spamdict): |
---|
377 | n/a | def foo(self): return 1 |
---|
378 | n/a | a = C() |
---|
379 | n/a | self.assertEqual(list(a.items()), []) |
---|
380 | n/a | self.assertEqual(a.foo(), 1) |
---|
381 | n/a | a['foo'] = 'bar' |
---|
382 | n/a | self.assertEqual(list(a.items()), [('foo', 'bar')]) |
---|
383 | n/a | self.assertEqual(a.getstate(), 0) |
---|
384 | n/a | a.setstate(100) |
---|
385 | n/a | self.assertEqual(a.getstate(), 100) |
---|
386 | n/a | |
---|
387 | n/a | class ClassPropertiesAndMethods(unittest.TestCase): |
---|
388 | n/a | |
---|
389 | n/a | def assertHasAttr(self, obj, name): |
---|
390 | n/a | self.assertTrue(hasattr(obj, name), |
---|
391 | n/a | '%r has no attribute %r' % (obj, name)) |
---|
392 | n/a | |
---|
393 | n/a | def assertNotHasAttr(self, obj, name): |
---|
394 | n/a | self.assertFalse(hasattr(obj, name), |
---|
395 | n/a | '%r has unexpected attribute %r' % (obj, name)) |
---|
396 | n/a | |
---|
397 | n/a | def test_python_dicts(self): |
---|
398 | n/a | # Testing Python subclass of dict... |
---|
399 | n/a | self.assertTrue(issubclass(dict, dict)) |
---|
400 | n/a | self.assertIsInstance({}, dict) |
---|
401 | n/a | d = dict() |
---|
402 | n/a | self.assertEqual(d, {}) |
---|
403 | n/a | self.assertIs(d.__class__, dict) |
---|
404 | n/a | self.assertIsInstance(d, dict) |
---|
405 | n/a | class C(dict): |
---|
406 | n/a | state = -1 |
---|
407 | n/a | def __init__(self_local, *a, **kw): |
---|
408 | n/a | if a: |
---|
409 | n/a | self.assertEqual(len(a), 1) |
---|
410 | n/a | self_local.state = a[0] |
---|
411 | n/a | if kw: |
---|
412 | n/a | for k, v in list(kw.items()): |
---|
413 | n/a | self_local[v] = k |
---|
414 | n/a | def __getitem__(self, key): |
---|
415 | n/a | return self.get(key, 0) |
---|
416 | n/a | def __setitem__(self_local, key, value): |
---|
417 | n/a | self.assertIsInstance(key, type(0)) |
---|
418 | n/a | dict.__setitem__(self_local, key, value) |
---|
419 | n/a | def setstate(self, state): |
---|
420 | n/a | self.state = state |
---|
421 | n/a | def getstate(self): |
---|
422 | n/a | return self.state |
---|
423 | n/a | self.assertTrue(issubclass(C, dict)) |
---|
424 | n/a | a1 = C(12) |
---|
425 | n/a | self.assertEqual(a1.state, 12) |
---|
426 | n/a | a2 = C(foo=1, bar=2) |
---|
427 | n/a | self.assertEqual(a2[1] == 'foo' and a2[2], 'bar') |
---|
428 | n/a | a = C() |
---|
429 | n/a | self.assertEqual(a.state, -1) |
---|
430 | n/a | self.assertEqual(a.getstate(), -1) |
---|
431 | n/a | a.setstate(0) |
---|
432 | n/a | self.assertEqual(a.state, 0) |
---|
433 | n/a | self.assertEqual(a.getstate(), 0) |
---|
434 | n/a | a.setstate(10) |
---|
435 | n/a | self.assertEqual(a.state, 10) |
---|
436 | n/a | self.assertEqual(a.getstate(), 10) |
---|
437 | n/a | self.assertEqual(a[42], 0) |
---|
438 | n/a | a[42] = 24 |
---|
439 | n/a | self.assertEqual(a[42], 24) |
---|
440 | n/a | N = 50 |
---|
441 | n/a | for i in range(N): |
---|
442 | n/a | a[i] = C() |
---|
443 | n/a | for j in range(N): |
---|
444 | n/a | a[i][j] = i*j |
---|
445 | n/a | for i in range(N): |
---|
446 | n/a | for j in range(N): |
---|
447 | n/a | self.assertEqual(a[i][j], i*j) |
---|
448 | n/a | |
---|
449 | n/a | def test_python_lists(self): |
---|
450 | n/a | # Testing Python subclass of list... |
---|
451 | n/a | class C(list): |
---|
452 | n/a | def __getitem__(self, i): |
---|
453 | n/a | if isinstance(i, slice): |
---|
454 | n/a | return i.start, i.stop |
---|
455 | n/a | return list.__getitem__(self, i) + 100 |
---|
456 | n/a | a = C() |
---|
457 | n/a | a.extend([0,1,2]) |
---|
458 | n/a | self.assertEqual(a[0], 100) |
---|
459 | n/a | self.assertEqual(a[1], 101) |
---|
460 | n/a | self.assertEqual(a[2], 102) |
---|
461 | n/a | self.assertEqual(a[100:200], (100,200)) |
---|
462 | n/a | |
---|
463 | n/a | def test_metaclass(self): |
---|
464 | n/a | # Testing metaclasses... |
---|
465 | n/a | class C(metaclass=type): |
---|
466 | n/a | def __init__(self): |
---|
467 | n/a | self.__state = 0 |
---|
468 | n/a | def getstate(self): |
---|
469 | n/a | return self.__state |
---|
470 | n/a | def setstate(self, state): |
---|
471 | n/a | self.__state = state |
---|
472 | n/a | a = C() |
---|
473 | n/a | self.assertEqual(a.getstate(), 0) |
---|
474 | n/a | a.setstate(10) |
---|
475 | n/a | self.assertEqual(a.getstate(), 10) |
---|
476 | n/a | class _metaclass(type): |
---|
477 | n/a | def myself(cls): return cls |
---|
478 | n/a | class D(metaclass=_metaclass): |
---|
479 | n/a | pass |
---|
480 | n/a | self.assertEqual(D.myself(), D) |
---|
481 | n/a | d = D() |
---|
482 | n/a | self.assertEqual(d.__class__, D) |
---|
483 | n/a | class M1(type): |
---|
484 | n/a | def __new__(cls, name, bases, dict): |
---|
485 | n/a | dict['__spam__'] = 1 |
---|
486 | n/a | return type.__new__(cls, name, bases, dict) |
---|
487 | n/a | class C(metaclass=M1): |
---|
488 | n/a | pass |
---|
489 | n/a | self.assertEqual(C.__spam__, 1) |
---|
490 | n/a | c = C() |
---|
491 | n/a | self.assertEqual(c.__spam__, 1) |
---|
492 | n/a | |
---|
493 | n/a | class _instance(object): |
---|
494 | n/a | pass |
---|
495 | n/a | class M2(object): |
---|
496 | n/a | @staticmethod |
---|
497 | n/a | def __new__(cls, name, bases, dict): |
---|
498 | n/a | self = object.__new__(cls) |
---|
499 | n/a | self.name = name |
---|
500 | n/a | self.bases = bases |
---|
501 | n/a | self.dict = dict |
---|
502 | n/a | return self |
---|
503 | n/a | def __call__(self): |
---|
504 | n/a | it = _instance() |
---|
505 | n/a | # Early binding of methods |
---|
506 | n/a | for key in self.dict: |
---|
507 | n/a | if key.startswith("__"): |
---|
508 | n/a | continue |
---|
509 | n/a | setattr(it, key, self.dict[key].__get__(it, self)) |
---|
510 | n/a | return it |
---|
511 | n/a | class C(metaclass=M2): |
---|
512 | n/a | def spam(self): |
---|
513 | n/a | return 42 |
---|
514 | n/a | self.assertEqual(C.name, 'C') |
---|
515 | n/a | self.assertEqual(C.bases, ()) |
---|
516 | n/a | self.assertIn('spam', C.dict) |
---|
517 | n/a | c = C() |
---|
518 | n/a | self.assertEqual(c.spam(), 42) |
---|
519 | n/a | |
---|
520 | n/a | # More metaclass examples |
---|
521 | n/a | |
---|
522 | n/a | class autosuper(type): |
---|
523 | n/a | # Automatically add __super to the class |
---|
524 | n/a | # This trick only works for dynamic classes |
---|
525 | n/a | def __new__(metaclass, name, bases, dict): |
---|
526 | n/a | cls = super(autosuper, metaclass).__new__(metaclass, |
---|
527 | n/a | name, bases, dict) |
---|
528 | n/a | # Name mangling for __super removes leading underscores |
---|
529 | n/a | while name[:1] == "_": |
---|
530 | n/a | name = name[1:] |
---|
531 | n/a | if name: |
---|
532 | n/a | name = "_%s__super" % name |
---|
533 | n/a | else: |
---|
534 | n/a | name = "__super" |
---|
535 | n/a | setattr(cls, name, super(cls)) |
---|
536 | n/a | return cls |
---|
537 | n/a | class A(metaclass=autosuper): |
---|
538 | n/a | def meth(self): |
---|
539 | n/a | return "A" |
---|
540 | n/a | class B(A): |
---|
541 | n/a | def meth(self): |
---|
542 | n/a | return "B" + self.__super.meth() |
---|
543 | n/a | class C(A): |
---|
544 | n/a | def meth(self): |
---|
545 | n/a | return "C" + self.__super.meth() |
---|
546 | n/a | class D(C, B): |
---|
547 | n/a | def meth(self): |
---|
548 | n/a | return "D" + self.__super.meth() |
---|
549 | n/a | self.assertEqual(D().meth(), "DCBA") |
---|
550 | n/a | class E(B, C): |
---|
551 | n/a | def meth(self): |
---|
552 | n/a | return "E" + self.__super.meth() |
---|
553 | n/a | self.assertEqual(E().meth(), "EBCA") |
---|
554 | n/a | |
---|
555 | n/a | class autoproperty(type): |
---|
556 | n/a | # Automatically create property attributes when methods |
---|
557 | n/a | # named _get_x and/or _set_x are found |
---|
558 | n/a | def __new__(metaclass, name, bases, dict): |
---|
559 | n/a | hits = {} |
---|
560 | n/a | for key, val in dict.items(): |
---|
561 | n/a | if key.startswith("_get_"): |
---|
562 | n/a | key = key[5:] |
---|
563 | n/a | get, set = hits.get(key, (None, None)) |
---|
564 | n/a | get = val |
---|
565 | n/a | hits[key] = get, set |
---|
566 | n/a | elif key.startswith("_set_"): |
---|
567 | n/a | key = key[5:] |
---|
568 | n/a | get, set = hits.get(key, (None, None)) |
---|
569 | n/a | set = val |
---|
570 | n/a | hits[key] = get, set |
---|
571 | n/a | for key, (get, set) in hits.items(): |
---|
572 | n/a | dict[key] = property(get, set) |
---|
573 | n/a | return super(autoproperty, metaclass).__new__(metaclass, |
---|
574 | n/a | name, bases, dict) |
---|
575 | n/a | class A(metaclass=autoproperty): |
---|
576 | n/a | def _get_x(self): |
---|
577 | n/a | return -self.__x |
---|
578 | n/a | def _set_x(self, x): |
---|
579 | n/a | self.__x = -x |
---|
580 | n/a | a = A() |
---|
581 | n/a | self.assertNotHasAttr(a, "x") |
---|
582 | n/a | a.x = 12 |
---|
583 | n/a | self.assertEqual(a.x, 12) |
---|
584 | n/a | self.assertEqual(a._A__x, -12) |
---|
585 | n/a | |
---|
586 | n/a | class multimetaclass(autoproperty, autosuper): |
---|
587 | n/a | # Merge of multiple cooperating metaclasses |
---|
588 | n/a | pass |
---|
589 | n/a | class A(metaclass=multimetaclass): |
---|
590 | n/a | def _get_x(self): |
---|
591 | n/a | return "A" |
---|
592 | n/a | class B(A): |
---|
593 | n/a | def _get_x(self): |
---|
594 | n/a | return "B" + self.__super._get_x() |
---|
595 | n/a | class C(A): |
---|
596 | n/a | def _get_x(self): |
---|
597 | n/a | return "C" + self.__super._get_x() |
---|
598 | n/a | class D(C, B): |
---|
599 | n/a | def _get_x(self): |
---|
600 | n/a | return "D" + self.__super._get_x() |
---|
601 | n/a | self.assertEqual(D().x, "DCBA") |
---|
602 | n/a | |
---|
603 | n/a | # Make sure type(x) doesn't call x.__class__.__init__ |
---|
604 | n/a | class T(type): |
---|
605 | n/a | counter = 0 |
---|
606 | n/a | def __init__(self, *args): |
---|
607 | n/a | T.counter += 1 |
---|
608 | n/a | class C(metaclass=T): |
---|
609 | n/a | pass |
---|
610 | n/a | self.assertEqual(T.counter, 1) |
---|
611 | n/a | a = C() |
---|
612 | n/a | self.assertEqual(type(a), C) |
---|
613 | n/a | self.assertEqual(T.counter, 1) |
---|
614 | n/a | |
---|
615 | n/a | class C(object): pass |
---|
616 | n/a | c = C() |
---|
617 | n/a | try: c() |
---|
618 | n/a | except TypeError: pass |
---|
619 | n/a | else: self.fail("calling object w/o call method should raise " |
---|
620 | n/a | "TypeError") |
---|
621 | n/a | |
---|
622 | n/a | # Testing code to find most derived baseclass |
---|
623 | n/a | class A(type): |
---|
624 | n/a | def __new__(*args, **kwargs): |
---|
625 | n/a | return type.__new__(*args, **kwargs) |
---|
626 | n/a | |
---|
627 | n/a | class B(object): |
---|
628 | n/a | pass |
---|
629 | n/a | |
---|
630 | n/a | class C(object, metaclass=A): |
---|
631 | n/a | pass |
---|
632 | n/a | |
---|
633 | n/a | # The most derived metaclass of D is A rather than type. |
---|
634 | n/a | class D(B, C): |
---|
635 | n/a | pass |
---|
636 | n/a | self.assertIs(A, type(D)) |
---|
637 | n/a | |
---|
638 | n/a | # issue1294232: correct metaclass calculation |
---|
639 | n/a | new_calls = [] # to check the order of __new__ calls |
---|
640 | n/a | class AMeta(type): |
---|
641 | n/a | @staticmethod |
---|
642 | n/a | def __new__(mcls, name, bases, ns): |
---|
643 | n/a | new_calls.append('AMeta') |
---|
644 | n/a | return super().__new__(mcls, name, bases, ns) |
---|
645 | n/a | @classmethod |
---|
646 | n/a | def __prepare__(mcls, name, bases): |
---|
647 | n/a | return {} |
---|
648 | n/a | |
---|
649 | n/a | class BMeta(AMeta): |
---|
650 | n/a | @staticmethod |
---|
651 | n/a | def __new__(mcls, name, bases, ns): |
---|
652 | n/a | new_calls.append('BMeta') |
---|
653 | n/a | return super().__new__(mcls, name, bases, ns) |
---|
654 | n/a | @classmethod |
---|
655 | n/a | def __prepare__(mcls, name, bases): |
---|
656 | n/a | ns = super().__prepare__(name, bases) |
---|
657 | n/a | ns['BMeta_was_here'] = True |
---|
658 | n/a | return ns |
---|
659 | n/a | |
---|
660 | n/a | class A(metaclass=AMeta): |
---|
661 | n/a | pass |
---|
662 | n/a | self.assertEqual(['AMeta'], new_calls) |
---|
663 | n/a | new_calls.clear() |
---|
664 | n/a | |
---|
665 | n/a | class B(metaclass=BMeta): |
---|
666 | n/a | pass |
---|
667 | n/a | # BMeta.__new__ calls AMeta.__new__ with super: |
---|
668 | n/a | self.assertEqual(['BMeta', 'AMeta'], new_calls) |
---|
669 | n/a | new_calls.clear() |
---|
670 | n/a | |
---|
671 | n/a | class C(A, B): |
---|
672 | n/a | pass |
---|
673 | n/a | # The most derived metaclass is BMeta: |
---|
674 | n/a | self.assertEqual(['BMeta', 'AMeta'], new_calls) |
---|
675 | n/a | new_calls.clear() |
---|
676 | n/a | # BMeta.__prepare__ should've been called: |
---|
677 | n/a | self.assertIn('BMeta_was_here', C.__dict__) |
---|
678 | n/a | |
---|
679 | n/a | # The order of the bases shouldn't matter: |
---|
680 | n/a | class C2(B, A): |
---|
681 | n/a | pass |
---|
682 | n/a | self.assertEqual(['BMeta', 'AMeta'], new_calls) |
---|
683 | n/a | new_calls.clear() |
---|
684 | n/a | self.assertIn('BMeta_was_here', C2.__dict__) |
---|
685 | n/a | |
---|
686 | n/a | # Check correct metaclass calculation when a metaclass is declared: |
---|
687 | n/a | class D(C, metaclass=type): |
---|
688 | n/a | pass |
---|
689 | n/a | self.assertEqual(['BMeta', 'AMeta'], new_calls) |
---|
690 | n/a | new_calls.clear() |
---|
691 | n/a | self.assertIn('BMeta_was_here', D.__dict__) |
---|
692 | n/a | |
---|
693 | n/a | class E(C, metaclass=AMeta): |
---|
694 | n/a | pass |
---|
695 | n/a | self.assertEqual(['BMeta', 'AMeta'], new_calls) |
---|
696 | n/a | new_calls.clear() |
---|
697 | n/a | self.assertIn('BMeta_was_here', E.__dict__) |
---|
698 | n/a | |
---|
699 | n/a | # Special case: the given metaclass isn't a class, |
---|
700 | n/a | # so there is no metaclass calculation. |
---|
701 | n/a | marker = object() |
---|
702 | n/a | def func(*args, **kwargs): |
---|
703 | n/a | return marker |
---|
704 | n/a | class X(metaclass=func): |
---|
705 | n/a | pass |
---|
706 | n/a | class Y(object, metaclass=func): |
---|
707 | n/a | pass |
---|
708 | n/a | class Z(D, metaclass=func): |
---|
709 | n/a | pass |
---|
710 | n/a | self.assertIs(marker, X) |
---|
711 | n/a | self.assertIs(marker, Y) |
---|
712 | n/a | self.assertIs(marker, Z) |
---|
713 | n/a | |
---|
714 | n/a | # The given metaclass is a class, |
---|
715 | n/a | # but not a descendant of type. |
---|
716 | n/a | prepare_calls = [] # to track __prepare__ calls |
---|
717 | n/a | class ANotMeta: |
---|
718 | n/a | def __new__(mcls, *args, **kwargs): |
---|
719 | n/a | new_calls.append('ANotMeta') |
---|
720 | n/a | return super().__new__(mcls) |
---|
721 | n/a | @classmethod |
---|
722 | n/a | def __prepare__(mcls, name, bases): |
---|
723 | n/a | prepare_calls.append('ANotMeta') |
---|
724 | n/a | return {} |
---|
725 | n/a | class BNotMeta(ANotMeta): |
---|
726 | n/a | def __new__(mcls, *args, **kwargs): |
---|
727 | n/a | new_calls.append('BNotMeta') |
---|
728 | n/a | return super().__new__(mcls) |
---|
729 | n/a | @classmethod |
---|
730 | n/a | def __prepare__(mcls, name, bases): |
---|
731 | n/a | prepare_calls.append('BNotMeta') |
---|
732 | n/a | return super().__prepare__(name, bases) |
---|
733 | n/a | |
---|
734 | n/a | class A(metaclass=ANotMeta): |
---|
735 | n/a | pass |
---|
736 | n/a | self.assertIs(ANotMeta, type(A)) |
---|
737 | n/a | self.assertEqual(['ANotMeta'], prepare_calls) |
---|
738 | n/a | prepare_calls.clear() |
---|
739 | n/a | self.assertEqual(['ANotMeta'], new_calls) |
---|
740 | n/a | new_calls.clear() |
---|
741 | n/a | |
---|
742 | n/a | class B(metaclass=BNotMeta): |
---|
743 | n/a | pass |
---|
744 | n/a | self.assertIs(BNotMeta, type(B)) |
---|
745 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
746 | n/a | prepare_calls.clear() |
---|
747 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
748 | n/a | new_calls.clear() |
---|
749 | n/a | |
---|
750 | n/a | class C(A, B): |
---|
751 | n/a | pass |
---|
752 | n/a | self.assertIs(BNotMeta, type(C)) |
---|
753 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
754 | n/a | new_calls.clear() |
---|
755 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
756 | n/a | prepare_calls.clear() |
---|
757 | n/a | |
---|
758 | n/a | class C2(B, A): |
---|
759 | n/a | pass |
---|
760 | n/a | self.assertIs(BNotMeta, type(C2)) |
---|
761 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
762 | n/a | new_calls.clear() |
---|
763 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
764 | n/a | prepare_calls.clear() |
---|
765 | n/a | |
---|
766 | n/a | # This is a TypeError, because of a metaclass conflict: |
---|
767 | n/a | # BNotMeta is neither a subclass, nor a superclass of type |
---|
768 | n/a | with self.assertRaises(TypeError): |
---|
769 | n/a | class D(C, metaclass=type): |
---|
770 | n/a | pass |
---|
771 | n/a | |
---|
772 | n/a | class E(C, metaclass=ANotMeta): |
---|
773 | n/a | pass |
---|
774 | n/a | self.assertIs(BNotMeta, type(E)) |
---|
775 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
776 | n/a | new_calls.clear() |
---|
777 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
778 | n/a | prepare_calls.clear() |
---|
779 | n/a | |
---|
780 | n/a | class F(object(), C): |
---|
781 | n/a | pass |
---|
782 | n/a | self.assertIs(BNotMeta, type(F)) |
---|
783 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
784 | n/a | new_calls.clear() |
---|
785 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
786 | n/a | prepare_calls.clear() |
---|
787 | n/a | |
---|
788 | n/a | class F2(C, object()): |
---|
789 | n/a | pass |
---|
790 | n/a | self.assertIs(BNotMeta, type(F2)) |
---|
791 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) |
---|
792 | n/a | new_calls.clear() |
---|
793 | n/a | self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) |
---|
794 | n/a | prepare_calls.clear() |
---|
795 | n/a | |
---|
796 | n/a | # TypeError: BNotMeta is neither a |
---|
797 | n/a | # subclass, nor a superclass of int |
---|
798 | n/a | with self.assertRaises(TypeError): |
---|
799 | n/a | class X(C, int()): |
---|
800 | n/a | pass |
---|
801 | n/a | with self.assertRaises(TypeError): |
---|
802 | n/a | class X(int(), C): |
---|
803 | n/a | pass |
---|
804 | n/a | |
---|
805 | n/a | def test_module_subclasses(self): |
---|
806 | n/a | # Testing Python subclass of module... |
---|
807 | n/a | log = [] |
---|
808 | n/a | MT = type(sys) |
---|
809 | n/a | class MM(MT): |
---|
810 | n/a | def __init__(self, name): |
---|
811 | n/a | MT.__init__(self, name) |
---|
812 | n/a | def __getattribute__(self, name): |
---|
813 | n/a | log.append(("getattr", name)) |
---|
814 | n/a | return MT.__getattribute__(self, name) |
---|
815 | n/a | def __setattr__(self, name, value): |
---|
816 | n/a | log.append(("setattr", name, value)) |
---|
817 | n/a | MT.__setattr__(self, name, value) |
---|
818 | n/a | def __delattr__(self, name): |
---|
819 | n/a | log.append(("delattr", name)) |
---|
820 | n/a | MT.__delattr__(self, name) |
---|
821 | n/a | a = MM("a") |
---|
822 | n/a | a.foo = 12 |
---|
823 | n/a | x = a.foo |
---|
824 | n/a | del a.foo |
---|
825 | n/a | self.assertEqual(log, [("setattr", "foo", 12), |
---|
826 | n/a | ("getattr", "foo"), |
---|
827 | n/a | ("delattr", "foo")]) |
---|
828 | n/a | |
---|
829 | n/a | # http://python.org/sf/1174712 |
---|
830 | n/a | try: |
---|
831 | n/a | class Module(types.ModuleType, str): |
---|
832 | n/a | pass |
---|
833 | n/a | except TypeError: |
---|
834 | n/a | pass |
---|
835 | n/a | else: |
---|
836 | n/a | self.fail("inheriting from ModuleType and str at the same time " |
---|
837 | n/a | "should fail") |
---|
838 | n/a | |
---|
839 | n/a | def test_multiple_inheritance(self): |
---|
840 | n/a | # Testing multiple inheritance... |
---|
841 | n/a | class C(object): |
---|
842 | n/a | def __init__(self): |
---|
843 | n/a | self.__state = 0 |
---|
844 | n/a | def getstate(self): |
---|
845 | n/a | return self.__state |
---|
846 | n/a | def setstate(self, state): |
---|
847 | n/a | self.__state = state |
---|
848 | n/a | a = C() |
---|
849 | n/a | self.assertEqual(a.getstate(), 0) |
---|
850 | n/a | a.setstate(10) |
---|
851 | n/a | self.assertEqual(a.getstate(), 10) |
---|
852 | n/a | class D(dict, C): |
---|
853 | n/a | def __init__(self): |
---|
854 | n/a | type({}).__init__(self) |
---|
855 | n/a | C.__init__(self) |
---|
856 | n/a | d = D() |
---|
857 | n/a | self.assertEqual(list(d.keys()), []) |
---|
858 | n/a | d["hello"] = "world" |
---|
859 | n/a | self.assertEqual(list(d.items()), [("hello", "world")]) |
---|
860 | n/a | self.assertEqual(d["hello"], "world") |
---|
861 | n/a | self.assertEqual(d.getstate(), 0) |
---|
862 | n/a | d.setstate(10) |
---|
863 | n/a | self.assertEqual(d.getstate(), 10) |
---|
864 | n/a | self.assertEqual(D.__mro__, (D, dict, C, object)) |
---|
865 | n/a | |
---|
866 | n/a | # SF bug #442833 |
---|
867 | n/a | class Node(object): |
---|
868 | n/a | def __int__(self): |
---|
869 | n/a | return int(self.foo()) |
---|
870 | n/a | def foo(self): |
---|
871 | n/a | return "23" |
---|
872 | n/a | class Frag(Node, list): |
---|
873 | n/a | def foo(self): |
---|
874 | n/a | return "42" |
---|
875 | n/a | self.assertEqual(Node().__int__(), 23) |
---|
876 | n/a | self.assertEqual(int(Node()), 23) |
---|
877 | n/a | self.assertEqual(Frag().__int__(), 42) |
---|
878 | n/a | self.assertEqual(int(Frag()), 42) |
---|
879 | n/a | |
---|
880 | n/a | def test_diamond_inheritance(self): |
---|
881 | n/a | # Testing multiple inheritance special cases... |
---|
882 | n/a | class A(object): |
---|
883 | n/a | def spam(self): return "A" |
---|
884 | n/a | self.assertEqual(A().spam(), "A") |
---|
885 | n/a | class B(A): |
---|
886 | n/a | def boo(self): return "B" |
---|
887 | n/a | def spam(self): return "B" |
---|
888 | n/a | self.assertEqual(B().spam(), "B") |
---|
889 | n/a | self.assertEqual(B().boo(), "B") |
---|
890 | n/a | class C(A): |
---|
891 | n/a | def boo(self): return "C" |
---|
892 | n/a | self.assertEqual(C().spam(), "A") |
---|
893 | n/a | self.assertEqual(C().boo(), "C") |
---|
894 | n/a | class D(B, C): pass |
---|
895 | n/a | self.assertEqual(D().spam(), "B") |
---|
896 | n/a | self.assertEqual(D().boo(), "B") |
---|
897 | n/a | self.assertEqual(D.__mro__, (D, B, C, A, object)) |
---|
898 | n/a | class E(C, B): pass |
---|
899 | n/a | self.assertEqual(E().spam(), "B") |
---|
900 | n/a | self.assertEqual(E().boo(), "C") |
---|
901 | n/a | self.assertEqual(E.__mro__, (E, C, B, A, object)) |
---|
902 | n/a | # MRO order disagreement |
---|
903 | n/a | try: |
---|
904 | n/a | class F(D, E): pass |
---|
905 | n/a | except TypeError: |
---|
906 | n/a | pass |
---|
907 | n/a | else: |
---|
908 | n/a | self.fail("expected MRO order disagreement (F)") |
---|
909 | n/a | try: |
---|
910 | n/a | class G(E, D): pass |
---|
911 | n/a | except TypeError: |
---|
912 | n/a | pass |
---|
913 | n/a | else: |
---|
914 | n/a | self.fail("expected MRO order disagreement (G)") |
---|
915 | n/a | |
---|
916 | n/a | # see thread python-dev/2002-October/029035.html |
---|
917 | n/a | def test_ex5_from_c3_switch(self): |
---|
918 | n/a | # Testing ex5 from C3 switch discussion... |
---|
919 | n/a | class A(object): pass |
---|
920 | n/a | class B(object): pass |
---|
921 | n/a | class C(object): pass |
---|
922 | n/a | class X(A): pass |
---|
923 | n/a | class Y(A): pass |
---|
924 | n/a | class Z(X,B,Y,C): pass |
---|
925 | n/a | self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object)) |
---|
926 | n/a | |
---|
927 | n/a | # see "A Monotonic Superclass Linearization for Dylan", |
---|
928 | n/a | # by Kim Barrett et al. (OOPSLA 1996) |
---|
929 | n/a | def test_monotonicity(self): |
---|
930 | n/a | # Testing MRO monotonicity... |
---|
931 | n/a | class Boat(object): pass |
---|
932 | n/a | class DayBoat(Boat): pass |
---|
933 | n/a | class WheelBoat(Boat): pass |
---|
934 | n/a | class EngineLess(DayBoat): pass |
---|
935 | n/a | class SmallMultihull(DayBoat): pass |
---|
936 | n/a | class PedalWheelBoat(EngineLess,WheelBoat): pass |
---|
937 | n/a | class SmallCatamaran(SmallMultihull): pass |
---|
938 | n/a | class Pedalo(PedalWheelBoat,SmallCatamaran): pass |
---|
939 | n/a | |
---|
940 | n/a | self.assertEqual(PedalWheelBoat.__mro__, |
---|
941 | n/a | (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object)) |
---|
942 | n/a | self.assertEqual(SmallCatamaran.__mro__, |
---|
943 | n/a | (SmallCatamaran, SmallMultihull, DayBoat, Boat, object)) |
---|
944 | n/a | self.assertEqual(Pedalo.__mro__, |
---|
945 | n/a | (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran, |
---|
946 | n/a | SmallMultihull, DayBoat, WheelBoat, Boat, object)) |
---|
947 | n/a | |
---|
948 | n/a | # see "A Monotonic Superclass Linearization for Dylan", |
---|
949 | n/a | # by Kim Barrett et al. (OOPSLA 1996) |
---|
950 | n/a | def test_consistency_with_epg(self): |
---|
951 | n/a | # Testing consistency with EPG... |
---|
952 | n/a | class Pane(object): pass |
---|
953 | n/a | class ScrollingMixin(object): pass |
---|
954 | n/a | class EditingMixin(object): pass |
---|
955 | n/a | class ScrollablePane(Pane,ScrollingMixin): pass |
---|
956 | n/a | class EditablePane(Pane,EditingMixin): pass |
---|
957 | n/a | class EditableScrollablePane(ScrollablePane,EditablePane): pass |
---|
958 | n/a | |
---|
959 | n/a | self.assertEqual(EditableScrollablePane.__mro__, |
---|
960 | n/a | (EditableScrollablePane, ScrollablePane, EditablePane, Pane, |
---|
961 | n/a | ScrollingMixin, EditingMixin, object)) |
---|
962 | n/a | |
---|
963 | n/a | def test_mro_disagreement(self): |
---|
964 | n/a | # Testing error messages for MRO disagreement... |
---|
965 | n/a | mro_err_msg = """Cannot create a consistent method resolution |
---|
966 | n/a | order (MRO) for bases """ |
---|
967 | n/a | |
---|
968 | n/a | def raises(exc, expected, callable, *args): |
---|
969 | n/a | try: |
---|
970 | n/a | callable(*args) |
---|
971 | n/a | except exc as msg: |
---|
972 | n/a | # the exact msg is generally considered an impl detail |
---|
973 | n/a | if support.check_impl_detail(): |
---|
974 | n/a | if not str(msg).startswith(expected): |
---|
975 | n/a | self.fail("Message %r, expected %r" % |
---|
976 | n/a | (str(msg), expected)) |
---|
977 | n/a | else: |
---|
978 | n/a | self.fail("Expected %s" % exc) |
---|
979 | n/a | |
---|
980 | n/a | class A(object): pass |
---|
981 | n/a | class B(A): pass |
---|
982 | n/a | class C(object): pass |
---|
983 | n/a | |
---|
984 | n/a | # Test some very simple errors |
---|
985 | n/a | raises(TypeError, "duplicate base class A", |
---|
986 | n/a | type, "X", (A, A), {}) |
---|
987 | n/a | raises(TypeError, mro_err_msg, |
---|
988 | n/a | type, "X", (A, B), {}) |
---|
989 | n/a | raises(TypeError, mro_err_msg, |
---|
990 | n/a | type, "X", (A, C, B), {}) |
---|
991 | n/a | # Test a slightly more complex error |
---|
992 | n/a | class GridLayout(object): pass |
---|
993 | n/a | class HorizontalGrid(GridLayout): pass |
---|
994 | n/a | class VerticalGrid(GridLayout): pass |
---|
995 | n/a | class HVGrid(HorizontalGrid, VerticalGrid): pass |
---|
996 | n/a | class VHGrid(VerticalGrid, HorizontalGrid): pass |
---|
997 | n/a | raises(TypeError, mro_err_msg, |
---|
998 | n/a | type, "ConfusedGrid", (HVGrid, VHGrid), {}) |
---|
999 | n/a | |
---|
1000 | n/a | def test_object_class(self): |
---|
1001 | n/a | # Testing object class... |
---|
1002 | n/a | a = object() |
---|
1003 | n/a | self.assertEqual(a.__class__, object) |
---|
1004 | n/a | self.assertEqual(type(a), object) |
---|
1005 | n/a | b = object() |
---|
1006 | n/a | self.assertNotEqual(a, b) |
---|
1007 | n/a | self.assertNotHasAttr(a, "foo") |
---|
1008 | n/a | try: |
---|
1009 | n/a | a.foo = 12 |
---|
1010 | n/a | except (AttributeError, TypeError): |
---|
1011 | n/a | pass |
---|
1012 | n/a | else: |
---|
1013 | n/a | self.fail("object() should not allow setting a foo attribute") |
---|
1014 | n/a | self.assertNotHasAttr(object(), "__dict__") |
---|
1015 | n/a | |
---|
1016 | n/a | class Cdict(object): |
---|
1017 | n/a | pass |
---|
1018 | n/a | x = Cdict() |
---|
1019 | n/a | self.assertEqual(x.__dict__, {}) |
---|
1020 | n/a | x.foo = 1 |
---|
1021 | n/a | self.assertEqual(x.foo, 1) |
---|
1022 | n/a | self.assertEqual(x.__dict__, {'foo': 1}) |
---|
1023 | n/a | |
---|
1024 | n/a | def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self): |
---|
1025 | n/a | class SubType(types.ModuleType): |
---|
1026 | n/a | a = 1 |
---|
1027 | n/a | |
---|
1028 | n/a | m = types.ModuleType("m") |
---|
1029 | n/a | self.assertTrue(m.__class__ is types.ModuleType) |
---|
1030 | n/a | self.assertFalse(hasattr(m, "a")) |
---|
1031 | n/a | |
---|
1032 | n/a | m.__class__ = SubType |
---|
1033 | n/a | self.assertTrue(m.__class__ is SubType) |
---|
1034 | n/a | self.assertTrue(hasattr(m, "a")) |
---|
1035 | n/a | |
---|
1036 | n/a | m.__class__ = types.ModuleType |
---|
1037 | n/a | self.assertTrue(m.__class__ is types.ModuleType) |
---|
1038 | n/a | self.assertFalse(hasattr(m, "a")) |
---|
1039 | n/a | |
---|
1040 | n/a | # Make sure that builtin immutable objects don't support __class__ |
---|
1041 | n/a | # assignment, because the object instances may be interned. |
---|
1042 | n/a | # We set __slots__ = () to ensure that the subclasses are |
---|
1043 | n/a | # memory-layout compatible, and thus otherwise reasonable candidates |
---|
1044 | n/a | # for __class__ assignment. |
---|
1045 | n/a | |
---|
1046 | n/a | # The following types have immutable instances, but are not |
---|
1047 | n/a | # subclassable and thus don't need to be checked: |
---|
1048 | n/a | # NoneType, bool |
---|
1049 | n/a | |
---|
1050 | n/a | class MyInt(int): |
---|
1051 | n/a | __slots__ = () |
---|
1052 | n/a | with self.assertRaises(TypeError): |
---|
1053 | n/a | (1).__class__ = MyInt |
---|
1054 | n/a | |
---|
1055 | n/a | class MyFloat(float): |
---|
1056 | n/a | __slots__ = () |
---|
1057 | n/a | with self.assertRaises(TypeError): |
---|
1058 | n/a | (1.0).__class__ = MyFloat |
---|
1059 | n/a | |
---|
1060 | n/a | class MyComplex(complex): |
---|
1061 | n/a | __slots__ = () |
---|
1062 | n/a | with self.assertRaises(TypeError): |
---|
1063 | n/a | (1 + 2j).__class__ = MyComplex |
---|
1064 | n/a | |
---|
1065 | n/a | class MyStr(str): |
---|
1066 | n/a | __slots__ = () |
---|
1067 | n/a | with self.assertRaises(TypeError): |
---|
1068 | n/a | "a".__class__ = MyStr |
---|
1069 | n/a | |
---|
1070 | n/a | class MyBytes(bytes): |
---|
1071 | n/a | __slots__ = () |
---|
1072 | n/a | with self.assertRaises(TypeError): |
---|
1073 | n/a | b"a".__class__ = MyBytes |
---|
1074 | n/a | |
---|
1075 | n/a | class MyTuple(tuple): |
---|
1076 | n/a | __slots__ = () |
---|
1077 | n/a | with self.assertRaises(TypeError): |
---|
1078 | n/a | ().__class__ = MyTuple |
---|
1079 | n/a | |
---|
1080 | n/a | class MyFrozenSet(frozenset): |
---|
1081 | n/a | __slots__ = () |
---|
1082 | n/a | with self.assertRaises(TypeError): |
---|
1083 | n/a | frozenset().__class__ = MyFrozenSet |
---|
1084 | n/a | |
---|
1085 | n/a | def test_slots(self): |
---|
1086 | n/a | # Testing __slots__... |
---|
1087 | n/a | class C0(object): |
---|
1088 | n/a | __slots__ = [] |
---|
1089 | n/a | x = C0() |
---|
1090 | n/a | self.assertNotHasAttr(x, "__dict__") |
---|
1091 | n/a | self.assertNotHasAttr(x, "foo") |
---|
1092 | n/a | |
---|
1093 | n/a | class C1(object): |
---|
1094 | n/a | __slots__ = ['a'] |
---|
1095 | n/a | x = C1() |
---|
1096 | n/a | self.assertNotHasAttr(x, "__dict__") |
---|
1097 | n/a | self.assertNotHasAttr(x, "a") |
---|
1098 | n/a | x.a = 1 |
---|
1099 | n/a | self.assertEqual(x.a, 1) |
---|
1100 | n/a | x.a = None |
---|
1101 | n/a | self.assertEqual(x.a, None) |
---|
1102 | n/a | del x.a |
---|
1103 | n/a | self.assertNotHasAttr(x, "a") |
---|
1104 | n/a | |
---|
1105 | n/a | class C3(object): |
---|
1106 | n/a | __slots__ = ['a', 'b', 'c'] |
---|
1107 | n/a | x = C3() |
---|
1108 | n/a | self.assertNotHasAttr(x, "__dict__") |
---|
1109 | n/a | self.assertNotHasAttr(x, 'a') |
---|
1110 | n/a | self.assertNotHasAttr(x, 'b') |
---|
1111 | n/a | self.assertNotHasAttr(x, 'c') |
---|
1112 | n/a | x.a = 1 |
---|
1113 | n/a | x.b = 2 |
---|
1114 | n/a | x.c = 3 |
---|
1115 | n/a | self.assertEqual(x.a, 1) |
---|
1116 | n/a | self.assertEqual(x.b, 2) |
---|
1117 | n/a | self.assertEqual(x.c, 3) |
---|
1118 | n/a | |
---|
1119 | n/a | class C4(object): |
---|
1120 | n/a | """Validate name mangling""" |
---|
1121 | n/a | __slots__ = ['__a'] |
---|
1122 | n/a | def __init__(self, value): |
---|
1123 | n/a | self.__a = value |
---|
1124 | n/a | def get(self): |
---|
1125 | n/a | return self.__a |
---|
1126 | n/a | x = C4(5) |
---|
1127 | n/a | self.assertNotHasAttr(x, '__dict__') |
---|
1128 | n/a | self.assertNotHasAttr(x, '__a') |
---|
1129 | n/a | self.assertEqual(x.get(), 5) |
---|
1130 | n/a | try: |
---|
1131 | n/a | x.__a = 6 |
---|
1132 | n/a | except AttributeError: |
---|
1133 | n/a | pass |
---|
1134 | n/a | else: |
---|
1135 | n/a | self.fail("Double underscored names not mangled") |
---|
1136 | n/a | |
---|
1137 | n/a | # Make sure slot names are proper identifiers |
---|
1138 | n/a | try: |
---|
1139 | n/a | class C(object): |
---|
1140 | n/a | __slots__ = [None] |
---|
1141 | n/a | except TypeError: |
---|
1142 | n/a | pass |
---|
1143 | n/a | else: |
---|
1144 | n/a | self.fail("[None] slots not caught") |
---|
1145 | n/a | try: |
---|
1146 | n/a | class C(object): |
---|
1147 | n/a | __slots__ = ["foo bar"] |
---|
1148 | n/a | except TypeError: |
---|
1149 | n/a | pass |
---|
1150 | n/a | else: |
---|
1151 | n/a | self.fail("['foo bar'] slots not caught") |
---|
1152 | n/a | try: |
---|
1153 | n/a | class C(object): |
---|
1154 | n/a | __slots__ = ["foo\0bar"] |
---|
1155 | n/a | except TypeError: |
---|
1156 | n/a | pass |
---|
1157 | n/a | else: |
---|
1158 | n/a | self.fail("['foo\\0bar'] slots not caught") |
---|
1159 | n/a | try: |
---|
1160 | n/a | class C(object): |
---|
1161 | n/a | __slots__ = ["1"] |
---|
1162 | n/a | except TypeError: |
---|
1163 | n/a | pass |
---|
1164 | n/a | else: |
---|
1165 | n/a | self.fail("['1'] slots not caught") |
---|
1166 | n/a | try: |
---|
1167 | n/a | class C(object): |
---|
1168 | n/a | __slots__ = [""] |
---|
1169 | n/a | except TypeError: |
---|
1170 | n/a | pass |
---|
1171 | n/a | else: |
---|
1172 | n/a | self.fail("[''] slots not caught") |
---|
1173 | n/a | class C(object): |
---|
1174 | n/a | __slots__ = ["a", "a_b", "_a", "A0123456789Z"] |
---|
1175 | n/a | # XXX(nnorwitz): was there supposed to be something tested |
---|
1176 | n/a | # from the class above? |
---|
1177 | n/a | |
---|
1178 | n/a | # Test a single string is not expanded as a sequence. |
---|
1179 | n/a | class C(object): |
---|
1180 | n/a | __slots__ = "abc" |
---|
1181 | n/a | c = C() |
---|
1182 | n/a | c.abc = 5 |
---|
1183 | n/a | self.assertEqual(c.abc, 5) |
---|
1184 | n/a | |
---|
1185 | n/a | # Test unicode slot names |
---|
1186 | n/a | # Test a single unicode string is not expanded as a sequence. |
---|
1187 | n/a | class C(object): |
---|
1188 | n/a | __slots__ = "abc" |
---|
1189 | n/a | c = C() |
---|
1190 | n/a | c.abc = 5 |
---|
1191 | n/a | self.assertEqual(c.abc, 5) |
---|
1192 | n/a | |
---|
1193 | n/a | # _unicode_to_string used to modify slots in certain circumstances |
---|
1194 | n/a | slots = ("foo", "bar") |
---|
1195 | n/a | class C(object): |
---|
1196 | n/a | __slots__ = slots |
---|
1197 | n/a | x = C() |
---|
1198 | n/a | x.foo = 5 |
---|
1199 | n/a | self.assertEqual(x.foo, 5) |
---|
1200 | n/a | self.assertIs(type(slots[0]), str) |
---|
1201 | n/a | # this used to leak references |
---|
1202 | n/a | try: |
---|
1203 | n/a | class C(object): |
---|
1204 | n/a | __slots__ = [chr(128)] |
---|
1205 | n/a | except (TypeError, UnicodeEncodeError): |
---|
1206 | n/a | pass |
---|
1207 | n/a | else: |
---|
1208 | n/a | self.fail("[chr(128)] slots not caught") |
---|
1209 | n/a | |
---|
1210 | n/a | # Test leaks |
---|
1211 | n/a | class Counted(object): |
---|
1212 | n/a | counter = 0 # counts the number of instances alive |
---|
1213 | n/a | def __init__(self): |
---|
1214 | n/a | Counted.counter += 1 |
---|
1215 | n/a | def __del__(self): |
---|
1216 | n/a | Counted.counter -= 1 |
---|
1217 | n/a | class C(object): |
---|
1218 | n/a | __slots__ = ['a', 'b', 'c'] |
---|
1219 | n/a | x = C() |
---|
1220 | n/a | x.a = Counted() |
---|
1221 | n/a | x.b = Counted() |
---|
1222 | n/a | x.c = Counted() |
---|
1223 | n/a | self.assertEqual(Counted.counter, 3) |
---|
1224 | n/a | del x |
---|
1225 | n/a | support.gc_collect() |
---|
1226 | n/a | self.assertEqual(Counted.counter, 0) |
---|
1227 | n/a | class D(C): |
---|
1228 | n/a | pass |
---|
1229 | n/a | x = D() |
---|
1230 | n/a | x.a = Counted() |
---|
1231 | n/a | x.z = Counted() |
---|
1232 | n/a | self.assertEqual(Counted.counter, 2) |
---|
1233 | n/a | del x |
---|
1234 | n/a | support.gc_collect() |
---|
1235 | n/a | self.assertEqual(Counted.counter, 0) |
---|
1236 | n/a | class E(D): |
---|
1237 | n/a | __slots__ = ['e'] |
---|
1238 | n/a | x = E() |
---|
1239 | n/a | x.a = Counted() |
---|
1240 | n/a | x.z = Counted() |
---|
1241 | n/a | x.e = Counted() |
---|
1242 | n/a | self.assertEqual(Counted.counter, 3) |
---|
1243 | n/a | del x |
---|
1244 | n/a | support.gc_collect() |
---|
1245 | n/a | self.assertEqual(Counted.counter, 0) |
---|
1246 | n/a | |
---|
1247 | n/a | # Test cyclical leaks [SF bug 519621] |
---|
1248 | n/a | class F(object): |
---|
1249 | n/a | __slots__ = ['a', 'b'] |
---|
1250 | n/a | s = F() |
---|
1251 | n/a | s.a = [Counted(), s] |
---|
1252 | n/a | self.assertEqual(Counted.counter, 1) |
---|
1253 | n/a | s = None |
---|
1254 | n/a | support.gc_collect() |
---|
1255 | n/a | self.assertEqual(Counted.counter, 0) |
---|
1256 | n/a | |
---|
1257 | n/a | # Test lookup leaks [SF bug 572567] |
---|
1258 | n/a | if hasattr(gc, 'get_objects'): |
---|
1259 | n/a | class G(object): |
---|
1260 | n/a | def __eq__(self, other): |
---|
1261 | n/a | return False |
---|
1262 | n/a | g = G() |
---|
1263 | n/a | orig_objects = len(gc.get_objects()) |
---|
1264 | n/a | for i in range(10): |
---|
1265 | n/a | g==g |
---|
1266 | n/a | new_objects = len(gc.get_objects()) |
---|
1267 | n/a | self.assertEqual(orig_objects, new_objects) |
---|
1268 | n/a | |
---|
1269 | n/a | class H(object): |
---|
1270 | n/a | __slots__ = ['a', 'b'] |
---|
1271 | n/a | def __init__(self): |
---|
1272 | n/a | self.a = 1 |
---|
1273 | n/a | self.b = 2 |
---|
1274 | n/a | def __del__(self_): |
---|
1275 | n/a | self.assertEqual(self_.a, 1) |
---|
1276 | n/a | self.assertEqual(self_.b, 2) |
---|
1277 | n/a | with support.captured_output('stderr') as s: |
---|
1278 | n/a | h = H() |
---|
1279 | n/a | del h |
---|
1280 | n/a | self.assertEqual(s.getvalue(), '') |
---|
1281 | n/a | |
---|
1282 | n/a | class X(object): |
---|
1283 | n/a | __slots__ = "a" |
---|
1284 | n/a | with self.assertRaises(AttributeError): |
---|
1285 | n/a | del X().a |
---|
1286 | n/a | |
---|
1287 | n/a | def test_slots_special(self): |
---|
1288 | n/a | # Testing __dict__ and __weakref__ in __slots__... |
---|
1289 | n/a | class D(object): |
---|
1290 | n/a | __slots__ = ["__dict__"] |
---|
1291 | n/a | a = D() |
---|
1292 | n/a | self.assertHasAttr(a, "__dict__") |
---|
1293 | n/a | self.assertNotHasAttr(a, "__weakref__") |
---|
1294 | n/a | a.foo = 42 |
---|
1295 | n/a | self.assertEqual(a.__dict__, {"foo": 42}) |
---|
1296 | n/a | |
---|
1297 | n/a | class W(object): |
---|
1298 | n/a | __slots__ = ["__weakref__"] |
---|
1299 | n/a | a = W() |
---|
1300 | n/a | self.assertHasAttr(a, "__weakref__") |
---|
1301 | n/a | self.assertNotHasAttr(a, "__dict__") |
---|
1302 | n/a | try: |
---|
1303 | n/a | a.foo = 42 |
---|
1304 | n/a | except AttributeError: |
---|
1305 | n/a | pass |
---|
1306 | n/a | else: |
---|
1307 | n/a | self.fail("shouldn't be allowed to set a.foo") |
---|
1308 | n/a | |
---|
1309 | n/a | class C1(W, D): |
---|
1310 | n/a | __slots__ = [] |
---|
1311 | n/a | a = C1() |
---|
1312 | n/a | self.assertHasAttr(a, "__dict__") |
---|
1313 | n/a | self.assertHasAttr(a, "__weakref__") |
---|
1314 | n/a | a.foo = 42 |
---|
1315 | n/a | self.assertEqual(a.__dict__, {"foo": 42}) |
---|
1316 | n/a | |
---|
1317 | n/a | class C2(D, W): |
---|
1318 | n/a | __slots__ = [] |
---|
1319 | n/a | a = C2() |
---|
1320 | n/a | self.assertHasAttr(a, "__dict__") |
---|
1321 | n/a | self.assertHasAttr(a, "__weakref__") |
---|
1322 | n/a | a.foo = 42 |
---|
1323 | n/a | self.assertEqual(a.__dict__, {"foo": 42}) |
---|
1324 | n/a | |
---|
1325 | n/a | def test_slots_descriptor(self): |
---|
1326 | n/a | # Issue2115: slot descriptors did not correctly check |
---|
1327 | n/a | # the type of the given object |
---|
1328 | n/a | import abc |
---|
1329 | n/a | class MyABC(metaclass=abc.ABCMeta): |
---|
1330 | n/a | __slots__ = "a" |
---|
1331 | n/a | |
---|
1332 | n/a | class Unrelated(object): |
---|
1333 | n/a | pass |
---|
1334 | n/a | MyABC.register(Unrelated) |
---|
1335 | n/a | |
---|
1336 | n/a | u = Unrelated() |
---|
1337 | n/a | self.assertIsInstance(u, MyABC) |
---|
1338 | n/a | |
---|
1339 | n/a | # This used to crash |
---|
1340 | n/a | self.assertRaises(TypeError, MyABC.a.__set__, u, 3) |
---|
1341 | n/a | |
---|
1342 | n/a | def test_dynamics(self): |
---|
1343 | n/a | # Testing class attribute propagation... |
---|
1344 | n/a | class D(object): |
---|
1345 | n/a | pass |
---|
1346 | n/a | class E(D): |
---|
1347 | n/a | pass |
---|
1348 | n/a | class F(D): |
---|
1349 | n/a | pass |
---|
1350 | n/a | D.foo = 1 |
---|
1351 | n/a | self.assertEqual(D.foo, 1) |
---|
1352 | n/a | # Test that dynamic attributes are inherited |
---|
1353 | n/a | self.assertEqual(E.foo, 1) |
---|
1354 | n/a | self.assertEqual(F.foo, 1) |
---|
1355 | n/a | # Test dynamic instances |
---|
1356 | n/a | class C(object): |
---|
1357 | n/a | pass |
---|
1358 | n/a | a = C() |
---|
1359 | n/a | self.assertNotHasAttr(a, "foobar") |
---|
1360 | n/a | C.foobar = 2 |
---|
1361 | n/a | self.assertEqual(a.foobar, 2) |
---|
1362 | n/a | C.method = lambda self: 42 |
---|
1363 | n/a | self.assertEqual(a.method(), 42) |
---|
1364 | n/a | C.__repr__ = lambda self: "C()" |
---|
1365 | n/a | self.assertEqual(repr(a), "C()") |
---|
1366 | n/a | C.__int__ = lambda self: 100 |
---|
1367 | n/a | self.assertEqual(int(a), 100) |
---|
1368 | n/a | self.assertEqual(a.foobar, 2) |
---|
1369 | n/a | self.assertNotHasAttr(a, "spam") |
---|
1370 | n/a | def mygetattr(self, name): |
---|
1371 | n/a | if name == "spam": |
---|
1372 | n/a | return "spam" |
---|
1373 | n/a | raise AttributeError |
---|
1374 | n/a | C.__getattr__ = mygetattr |
---|
1375 | n/a | self.assertEqual(a.spam, "spam") |
---|
1376 | n/a | a.new = 12 |
---|
1377 | n/a | self.assertEqual(a.new, 12) |
---|
1378 | n/a | def mysetattr(self, name, value): |
---|
1379 | n/a | if name == "spam": |
---|
1380 | n/a | raise AttributeError |
---|
1381 | n/a | return object.__setattr__(self, name, value) |
---|
1382 | n/a | C.__setattr__ = mysetattr |
---|
1383 | n/a | try: |
---|
1384 | n/a | a.spam = "not spam" |
---|
1385 | n/a | except AttributeError: |
---|
1386 | n/a | pass |
---|
1387 | n/a | else: |
---|
1388 | n/a | self.fail("expected AttributeError") |
---|
1389 | n/a | self.assertEqual(a.spam, "spam") |
---|
1390 | n/a | class D(C): |
---|
1391 | n/a | pass |
---|
1392 | n/a | d = D() |
---|
1393 | n/a | d.foo = 1 |
---|
1394 | n/a | self.assertEqual(d.foo, 1) |
---|
1395 | n/a | |
---|
1396 | n/a | # Test handling of int*seq and seq*int |
---|
1397 | n/a | class I(int): |
---|
1398 | n/a | pass |
---|
1399 | n/a | self.assertEqual("a"*I(2), "aa") |
---|
1400 | n/a | self.assertEqual(I(2)*"a", "aa") |
---|
1401 | n/a | self.assertEqual(2*I(3), 6) |
---|
1402 | n/a | self.assertEqual(I(3)*2, 6) |
---|
1403 | n/a | self.assertEqual(I(3)*I(2), 6) |
---|
1404 | n/a | |
---|
1405 | n/a | # Test comparison of classes with dynamic metaclasses |
---|
1406 | n/a | class dynamicmetaclass(type): |
---|
1407 | n/a | pass |
---|
1408 | n/a | class someclass(metaclass=dynamicmetaclass): |
---|
1409 | n/a | pass |
---|
1410 | n/a | self.assertNotEqual(someclass, object) |
---|
1411 | n/a | |
---|
1412 | n/a | def test_errors(self): |
---|
1413 | n/a | # Testing errors... |
---|
1414 | n/a | try: |
---|
1415 | n/a | class C(list, dict): |
---|
1416 | n/a | pass |
---|
1417 | n/a | except TypeError: |
---|
1418 | n/a | pass |
---|
1419 | n/a | else: |
---|
1420 | n/a | self.fail("inheritance from both list and dict should be illegal") |
---|
1421 | n/a | |
---|
1422 | n/a | try: |
---|
1423 | n/a | class C(object, None): |
---|
1424 | n/a | pass |
---|
1425 | n/a | except TypeError: |
---|
1426 | n/a | pass |
---|
1427 | n/a | else: |
---|
1428 | n/a | self.fail("inheritance from non-type should be illegal") |
---|
1429 | n/a | class Classic: |
---|
1430 | n/a | pass |
---|
1431 | n/a | |
---|
1432 | n/a | try: |
---|
1433 | n/a | class C(type(len)): |
---|
1434 | n/a | pass |
---|
1435 | n/a | except TypeError: |
---|
1436 | n/a | pass |
---|
1437 | n/a | else: |
---|
1438 | n/a | self.fail("inheritance from CFunction should be illegal") |
---|
1439 | n/a | |
---|
1440 | n/a | try: |
---|
1441 | n/a | class C(object): |
---|
1442 | n/a | __slots__ = 1 |
---|
1443 | n/a | except TypeError: |
---|
1444 | n/a | pass |
---|
1445 | n/a | else: |
---|
1446 | n/a | self.fail("__slots__ = 1 should be illegal") |
---|
1447 | n/a | |
---|
1448 | n/a | try: |
---|
1449 | n/a | class C(object): |
---|
1450 | n/a | __slots__ = [1] |
---|
1451 | n/a | except TypeError: |
---|
1452 | n/a | pass |
---|
1453 | n/a | else: |
---|
1454 | n/a | self.fail("__slots__ = [1] should be illegal") |
---|
1455 | n/a | |
---|
1456 | n/a | class M1(type): |
---|
1457 | n/a | pass |
---|
1458 | n/a | class M2(type): |
---|
1459 | n/a | pass |
---|
1460 | n/a | class A1(object, metaclass=M1): |
---|
1461 | n/a | pass |
---|
1462 | n/a | class A2(object, metaclass=M2): |
---|
1463 | n/a | pass |
---|
1464 | n/a | try: |
---|
1465 | n/a | class B(A1, A2): |
---|
1466 | n/a | pass |
---|
1467 | n/a | except TypeError: |
---|
1468 | n/a | pass |
---|
1469 | n/a | else: |
---|
1470 | n/a | self.fail("finding the most derived metaclass should have failed") |
---|
1471 | n/a | |
---|
1472 | n/a | def test_classmethods(self): |
---|
1473 | n/a | # Testing class methods... |
---|
1474 | n/a | class C(object): |
---|
1475 | n/a | def foo(*a): return a |
---|
1476 | n/a | goo = classmethod(foo) |
---|
1477 | n/a | c = C() |
---|
1478 | n/a | self.assertEqual(C.goo(1), (C, 1)) |
---|
1479 | n/a | self.assertEqual(c.goo(1), (C, 1)) |
---|
1480 | n/a | self.assertEqual(c.foo(1), (c, 1)) |
---|
1481 | n/a | class D(C): |
---|
1482 | n/a | pass |
---|
1483 | n/a | d = D() |
---|
1484 | n/a | self.assertEqual(D.goo(1), (D, 1)) |
---|
1485 | n/a | self.assertEqual(d.goo(1), (D, 1)) |
---|
1486 | n/a | self.assertEqual(d.foo(1), (d, 1)) |
---|
1487 | n/a | self.assertEqual(D.foo(d, 1), (d, 1)) |
---|
1488 | n/a | # Test for a specific crash (SF bug 528132) |
---|
1489 | n/a | def f(cls, arg): return (cls, arg) |
---|
1490 | n/a | ff = classmethod(f) |
---|
1491 | n/a | self.assertEqual(ff.__get__(0, int)(42), (int, 42)) |
---|
1492 | n/a | self.assertEqual(ff.__get__(0)(42), (int, 42)) |
---|
1493 | n/a | |
---|
1494 | n/a | # Test super() with classmethods (SF bug 535444) |
---|
1495 | n/a | self.assertEqual(C.goo.__self__, C) |
---|
1496 | n/a | self.assertEqual(D.goo.__self__, D) |
---|
1497 | n/a | self.assertEqual(super(D,D).goo.__self__, D) |
---|
1498 | n/a | self.assertEqual(super(D,d).goo.__self__, D) |
---|
1499 | n/a | self.assertEqual(super(D,D).goo(), (D,)) |
---|
1500 | n/a | self.assertEqual(super(D,d).goo(), (D,)) |
---|
1501 | n/a | |
---|
1502 | n/a | # Verify that a non-callable will raise |
---|
1503 | n/a | meth = classmethod(1).__get__(1) |
---|
1504 | n/a | self.assertRaises(TypeError, meth) |
---|
1505 | n/a | |
---|
1506 | n/a | # Verify that classmethod() doesn't allow keyword args |
---|
1507 | n/a | try: |
---|
1508 | n/a | classmethod(f, kw=1) |
---|
1509 | n/a | except TypeError: |
---|
1510 | n/a | pass |
---|
1511 | n/a | else: |
---|
1512 | n/a | self.fail("classmethod shouldn't accept keyword args") |
---|
1513 | n/a | |
---|
1514 | n/a | cm = classmethod(f) |
---|
1515 | n/a | self.assertEqual(cm.__dict__, {}) |
---|
1516 | n/a | cm.x = 42 |
---|
1517 | n/a | self.assertEqual(cm.x, 42) |
---|
1518 | n/a | self.assertEqual(cm.__dict__, {"x" : 42}) |
---|
1519 | n/a | del cm.x |
---|
1520 | n/a | self.assertNotHasAttr(cm, "x") |
---|
1521 | n/a | |
---|
1522 | n/a | @support.impl_detail("the module 'xxsubtype' is internal") |
---|
1523 | n/a | def test_classmethods_in_c(self): |
---|
1524 | n/a | # Testing C-based class methods... |
---|
1525 | n/a | import xxsubtype as spam |
---|
1526 | n/a | a = (1, 2, 3) |
---|
1527 | n/a | d = {'abc': 123} |
---|
1528 | n/a | x, a1, d1 = spam.spamlist.classmeth(*a, **d) |
---|
1529 | n/a | self.assertEqual(x, spam.spamlist) |
---|
1530 | n/a | self.assertEqual(a, a1) |
---|
1531 | n/a | self.assertEqual(d, d1) |
---|
1532 | n/a | x, a1, d1 = spam.spamlist().classmeth(*a, **d) |
---|
1533 | n/a | self.assertEqual(x, spam.spamlist) |
---|
1534 | n/a | self.assertEqual(a, a1) |
---|
1535 | n/a | self.assertEqual(d, d1) |
---|
1536 | n/a | spam_cm = spam.spamlist.__dict__['classmeth'] |
---|
1537 | n/a | x2, a2, d2 = spam_cm(spam.spamlist, *a, **d) |
---|
1538 | n/a | self.assertEqual(x2, spam.spamlist) |
---|
1539 | n/a | self.assertEqual(a2, a1) |
---|
1540 | n/a | self.assertEqual(d2, d1) |
---|
1541 | n/a | class SubSpam(spam.spamlist): pass |
---|
1542 | n/a | x2, a2, d2 = spam_cm(SubSpam, *a, **d) |
---|
1543 | n/a | self.assertEqual(x2, SubSpam) |
---|
1544 | n/a | self.assertEqual(a2, a1) |
---|
1545 | n/a | self.assertEqual(d2, d1) |
---|
1546 | n/a | with self.assertRaises(TypeError): |
---|
1547 | n/a | spam_cm() |
---|
1548 | n/a | with self.assertRaises(TypeError): |
---|
1549 | n/a | spam_cm(spam.spamlist()) |
---|
1550 | n/a | with self.assertRaises(TypeError): |
---|
1551 | n/a | spam_cm(list) |
---|
1552 | n/a | |
---|
1553 | n/a | def test_staticmethods(self): |
---|
1554 | n/a | # Testing static methods... |
---|
1555 | n/a | class C(object): |
---|
1556 | n/a | def foo(*a): return a |
---|
1557 | n/a | goo = staticmethod(foo) |
---|
1558 | n/a | c = C() |
---|
1559 | n/a | self.assertEqual(C.goo(1), (1,)) |
---|
1560 | n/a | self.assertEqual(c.goo(1), (1,)) |
---|
1561 | n/a | self.assertEqual(c.foo(1), (c, 1,)) |
---|
1562 | n/a | class D(C): |
---|
1563 | n/a | pass |
---|
1564 | n/a | d = D() |
---|
1565 | n/a | self.assertEqual(D.goo(1), (1,)) |
---|
1566 | n/a | self.assertEqual(d.goo(1), (1,)) |
---|
1567 | n/a | self.assertEqual(d.foo(1), (d, 1)) |
---|
1568 | n/a | self.assertEqual(D.foo(d, 1), (d, 1)) |
---|
1569 | n/a | sm = staticmethod(None) |
---|
1570 | n/a | self.assertEqual(sm.__dict__, {}) |
---|
1571 | n/a | sm.x = 42 |
---|
1572 | n/a | self.assertEqual(sm.x, 42) |
---|
1573 | n/a | self.assertEqual(sm.__dict__, {"x" : 42}) |
---|
1574 | n/a | del sm.x |
---|
1575 | n/a | self.assertNotHasAttr(sm, "x") |
---|
1576 | n/a | |
---|
1577 | n/a | @support.impl_detail("the module 'xxsubtype' is internal") |
---|
1578 | n/a | def test_staticmethods_in_c(self): |
---|
1579 | n/a | # Testing C-based static methods... |
---|
1580 | n/a | import xxsubtype as spam |
---|
1581 | n/a | a = (1, 2, 3) |
---|
1582 | n/a | d = {"abc": 123} |
---|
1583 | n/a | x, a1, d1 = spam.spamlist.staticmeth(*a, **d) |
---|
1584 | n/a | self.assertEqual(x, None) |
---|
1585 | n/a | self.assertEqual(a, a1) |
---|
1586 | n/a | self.assertEqual(d, d1) |
---|
1587 | n/a | x, a1, d2 = spam.spamlist().staticmeth(*a, **d) |
---|
1588 | n/a | self.assertEqual(x, None) |
---|
1589 | n/a | self.assertEqual(a, a1) |
---|
1590 | n/a | self.assertEqual(d, d1) |
---|
1591 | n/a | |
---|
1592 | n/a | def test_classic(self): |
---|
1593 | n/a | # Testing classic classes... |
---|
1594 | n/a | class C: |
---|
1595 | n/a | def foo(*a): return a |
---|
1596 | n/a | goo = classmethod(foo) |
---|
1597 | n/a | c = C() |
---|
1598 | n/a | self.assertEqual(C.goo(1), (C, 1)) |
---|
1599 | n/a | self.assertEqual(c.goo(1), (C, 1)) |
---|
1600 | n/a | self.assertEqual(c.foo(1), (c, 1)) |
---|
1601 | n/a | class D(C): |
---|
1602 | n/a | pass |
---|
1603 | n/a | d = D() |
---|
1604 | n/a | self.assertEqual(D.goo(1), (D, 1)) |
---|
1605 | n/a | self.assertEqual(d.goo(1), (D, 1)) |
---|
1606 | n/a | self.assertEqual(d.foo(1), (d, 1)) |
---|
1607 | n/a | self.assertEqual(D.foo(d, 1), (d, 1)) |
---|
1608 | n/a | class E: # *not* subclassing from C |
---|
1609 | n/a | foo = C.foo |
---|
1610 | n/a | self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound |
---|
1611 | n/a | self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method ")) |
---|
1612 | n/a | |
---|
1613 | n/a | def test_compattr(self): |
---|
1614 | n/a | # Testing computed attributes... |
---|
1615 | n/a | class C(object): |
---|
1616 | n/a | class computed_attribute(object): |
---|
1617 | n/a | def __init__(self, get, set=None, delete=None): |
---|
1618 | n/a | self.__get = get |
---|
1619 | n/a | self.__set = set |
---|
1620 | n/a | self.__delete = delete |
---|
1621 | n/a | def __get__(self, obj, type=None): |
---|
1622 | n/a | return self.__get(obj) |
---|
1623 | n/a | def __set__(self, obj, value): |
---|
1624 | n/a | return self.__set(obj, value) |
---|
1625 | n/a | def __delete__(self, obj): |
---|
1626 | n/a | return self.__delete(obj) |
---|
1627 | n/a | def __init__(self): |
---|
1628 | n/a | self.__x = 0 |
---|
1629 | n/a | def __get_x(self): |
---|
1630 | n/a | x = self.__x |
---|
1631 | n/a | self.__x = x+1 |
---|
1632 | n/a | return x |
---|
1633 | n/a | def __set_x(self, x): |
---|
1634 | n/a | self.__x = x |
---|
1635 | n/a | def __delete_x(self): |
---|
1636 | n/a | del self.__x |
---|
1637 | n/a | x = computed_attribute(__get_x, __set_x, __delete_x) |
---|
1638 | n/a | a = C() |
---|
1639 | n/a | self.assertEqual(a.x, 0) |
---|
1640 | n/a | self.assertEqual(a.x, 1) |
---|
1641 | n/a | a.x = 10 |
---|
1642 | n/a | self.assertEqual(a.x, 10) |
---|
1643 | n/a | self.assertEqual(a.x, 11) |
---|
1644 | n/a | del a.x |
---|
1645 | n/a | self.assertNotHasAttr(a, 'x') |
---|
1646 | n/a | |
---|
1647 | n/a | def test_newslots(self): |
---|
1648 | n/a | # Testing __new__ slot override... |
---|
1649 | n/a | class C(list): |
---|
1650 | n/a | def __new__(cls): |
---|
1651 | n/a | self = list.__new__(cls) |
---|
1652 | n/a | self.foo = 1 |
---|
1653 | n/a | return self |
---|
1654 | n/a | def __init__(self): |
---|
1655 | n/a | self.foo = self.foo + 2 |
---|
1656 | n/a | a = C() |
---|
1657 | n/a | self.assertEqual(a.foo, 3) |
---|
1658 | n/a | self.assertEqual(a.__class__, C) |
---|
1659 | n/a | class D(C): |
---|
1660 | n/a | pass |
---|
1661 | n/a | b = D() |
---|
1662 | n/a | self.assertEqual(b.foo, 3) |
---|
1663 | n/a | self.assertEqual(b.__class__, D) |
---|
1664 | n/a | |
---|
1665 | n/a | @unittest.expectedFailure |
---|
1666 | n/a | def test_bad_new(self): |
---|
1667 | n/a | self.assertRaises(TypeError, object.__new__) |
---|
1668 | n/a | self.assertRaises(TypeError, object.__new__, '') |
---|
1669 | n/a | self.assertRaises(TypeError, list.__new__, object) |
---|
1670 | n/a | self.assertRaises(TypeError, object.__new__, list) |
---|
1671 | n/a | class C(object): |
---|
1672 | n/a | __new__ = list.__new__ |
---|
1673 | n/a | self.assertRaises(TypeError, C) |
---|
1674 | n/a | class C(list): |
---|
1675 | n/a | __new__ = object.__new__ |
---|
1676 | n/a | self.assertRaises(TypeError, C) |
---|
1677 | n/a | |
---|
1678 | n/a | def test_object_new(self): |
---|
1679 | n/a | class A(object): |
---|
1680 | n/a | pass |
---|
1681 | n/a | object.__new__(A) |
---|
1682 | n/a | self.assertRaises(TypeError, object.__new__, A, 5) |
---|
1683 | n/a | object.__init__(A()) |
---|
1684 | n/a | self.assertRaises(TypeError, object.__init__, A(), 5) |
---|
1685 | n/a | |
---|
1686 | n/a | class A(object): |
---|
1687 | n/a | def __init__(self, foo): |
---|
1688 | n/a | self.foo = foo |
---|
1689 | n/a | object.__new__(A) |
---|
1690 | n/a | object.__new__(A, 5) |
---|
1691 | n/a | object.__init__(A(3)) |
---|
1692 | n/a | self.assertRaises(TypeError, object.__init__, A(3), 5) |
---|
1693 | n/a | |
---|
1694 | n/a | class A(object): |
---|
1695 | n/a | def __new__(cls, foo): |
---|
1696 | n/a | return object.__new__(cls) |
---|
1697 | n/a | object.__new__(A) |
---|
1698 | n/a | self.assertRaises(TypeError, object.__new__, A, 5) |
---|
1699 | n/a | object.__init__(A(3)) |
---|
1700 | n/a | object.__init__(A(3), 5) |
---|
1701 | n/a | |
---|
1702 | n/a | class A(object): |
---|
1703 | n/a | def __new__(cls, foo): |
---|
1704 | n/a | return object.__new__(cls) |
---|
1705 | n/a | def __init__(self, foo): |
---|
1706 | n/a | self.foo = foo |
---|
1707 | n/a | object.__new__(A) |
---|
1708 | n/a | self.assertRaises(TypeError, object.__new__, A, 5) |
---|
1709 | n/a | object.__init__(A(3)) |
---|
1710 | n/a | self.assertRaises(TypeError, object.__init__, A(3), 5) |
---|
1711 | n/a | |
---|
1712 | n/a | @unittest.expectedFailure |
---|
1713 | n/a | def test_restored_object_new(self): |
---|
1714 | n/a | class A(object): |
---|
1715 | n/a | def __new__(cls, *args, **kwargs): |
---|
1716 | n/a | raise AssertionError |
---|
1717 | n/a | self.assertRaises(AssertionError, A) |
---|
1718 | n/a | class B(A): |
---|
1719 | n/a | __new__ = object.__new__ |
---|
1720 | n/a | def __init__(self, foo): |
---|
1721 | n/a | self.foo = foo |
---|
1722 | n/a | with warnings.catch_warnings(): |
---|
1723 | n/a | warnings.simplefilter('error', DeprecationWarning) |
---|
1724 | n/a | b = B(3) |
---|
1725 | n/a | self.assertEqual(b.foo, 3) |
---|
1726 | n/a | self.assertEqual(b.__class__, B) |
---|
1727 | n/a | del B.__new__ |
---|
1728 | n/a | self.assertRaises(AssertionError, B) |
---|
1729 | n/a | del A.__new__ |
---|
1730 | n/a | with warnings.catch_warnings(): |
---|
1731 | n/a | warnings.simplefilter('error', DeprecationWarning) |
---|
1732 | n/a | b = B(3) |
---|
1733 | n/a | self.assertEqual(b.foo, 3) |
---|
1734 | n/a | self.assertEqual(b.__class__, B) |
---|
1735 | n/a | |
---|
1736 | n/a | def test_altmro(self): |
---|
1737 | n/a | # Testing mro() and overriding it... |
---|
1738 | n/a | class A(object): |
---|
1739 | n/a | def f(self): return "A" |
---|
1740 | n/a | class B(A): |
---|
1741 | n/a | pass |
---|
1742 | n/a | class C(A): |
---|
1743 | n/a | def f(self): return "C" |
---|
1744 | n/a | class D(B, C): |
---|
1745 | n/a | pass |
---|
1746 | n/a | self.assertEqual(D.mro(), [D, B, C, A, object]) |
---|
1747 | n/a | self.assertEqual(D.__mro__, (D, B, C, A, object)) |
---|
1748 | n/a | self.assertEqual(D().f(), "C") |
---|
1749 | n/a | |
---|
1750 | n/a | class PerverseMetaType(type): |
---|
1751 | n/a | def mro(cls): |
---|
1752 | n/a | L = type.mro(cls) |
---|
1753 | n/a | L.reverse() |
---|
1754 | n/a | return L |
---|
1755 | n/a | class X(D,B,C,A, metaclass=PerverseMetaType): |
---|
1756 | n/a | pass |
---|
1757 | n/a | self.assertEqual(X.__mro__, (object, A, C, B, D, X)) |
---|
1758 | n/a | self.assertEqual(X().f(), "A") |
---|
1759 | n/a | |
---|
1760 | n/a | try: |
---|
1761 | n/a | class _metaclass(type): |
---|
1762 | n/a | def mro(self): |
---|
1763 | n/a | return [self, dict, object] |
---|
1764 | n/a | class X(object, metaclass=_metaclass): |
---|
1765 | n/a | pass |
---|
1766 | n/a | # In CPython, the class creation above already raises |
---|
1767 | n/a | # TypeError, as a protection against the fact that |
---|
1768 | n/a | # instances of X would segfault it. In other Python |
---|
1769 | n/a | # implementations it would be ok to let the class X |
---|
1770 | n/a | # be created, but instead get a clean TypeError on the |
---|
1771 | n/a | # __setitem__ below. |
---|
1772 | n/a | x = object.__new__(X) |
---|
1773 | n/a | x[5] = 6 |
---|
1774 | n/a | except TypeError: |
---|
1775 | n/a | pass |
---|
1776 | n/a | else: |
---|
1777 | n/a | self.fail("devious mro() return not caught") |
---|
1778 | n/a | |
---|
1779 | n/a | try: |
---|
1780 | n/a | class _metaclass(type): |
---|
1781 | n/a | def mro(self): |
---|
1782 | n/a | return [1] |
---|
1783 | n/a | class X(object, metaclass=_metaclass): |
---|
1784 | n/a | pass |
---|
1785 | n/a | except TypeError: |
---|
1786 | n/a | pass |
---|
1787 | n/a | else: |
---|
1788 | n/a | self.fail("non-class mro() return not caught") |
---|
1789 | n/a | |
---|
1790 | n/a | try: |
---|
1791 | n/a | class _metaclass(type): |
---|
1792 | n/a | def mro(self): |
---|
1793 | n/a | return 1 |
---|
1794 | n/a | class X(object, metaclass=_metaclass): |
---|
1795 | n/a | pass |
---|
1796 | n/a | except TypeError: |
---|
1797 | n/a | pass |
---|
1798 | n/a | else: |
---|
1799 | n/a | self.fail("non-sequence mro() return not caught") |
---|
1800 | n/a | |
---|
1801 | n/a | def test_overloading(self): |
---|
1802 | n/a | # Testing operator overloading... |
---|
1803 | n/a | |
---|
1804 | n/a | class B(object): |
---|
1805 | n/a | "Intermediate class because object doesn't have a __setattr__" |
---|
1806 | n/a | |
---|
1807 | n/a | class C(B): |
---|
1808 | n/a | def __getattr__(self, name): |
---|
1809 | n/a | if name == "foo": |
---|
1810 | n/a | return ("getattr", name) |
---|
1811 | n/a | else: |
---|
1812 | n/a | raise AttributeError |
---|
1813 | n/a | def __setattr__(self, name, value): |
---|
1814 | n/a | if name == "foo": |
---|
1815 | n/a | self.setattr = (name, value) |
---|
1816 | n/a | else: |
---|
1817 | n/a | return B.__setattr__(self, name, value) |
---|
1818 | n/a | def __delattr__(self, name): |
---|
1819 | n/a | if name == "foo": |
---|
1820 | n/a | self.delattr = name |
---|
1821 | n/a | else: |
---|
1822 | n/a | return B.__delattr__(self, name) |
---|
1823 | n/a | |
---|
1824 | n/a | def __getitem__(self, key): |
---|
1825 | n/a | return ("getitem", key) |
---|
1826 | n/a | def __setitem__(self, key, value): |
---|
1827 | n/a | self.setitem = (key, value) |
---|
1828 | n/a | def __delitem__(self, key): |
---|
1829 | n/a | self.delitem = key |
---|
1830 | n/a | |
---|
1831 | n/a | a = C() |
---|
1832 | n/a | self.assertEqual(a.foo, ("getattr", "foo")) |
---|
1833 | n/a | a.foo = 12 |
---|
1834 | n/a | self.assertEqual(a.setattr, ("foo", 12)) |
---|
1835 | n/a | del a.foo |
---|
1836 | n/a | self.assertEqual(a.delattr, "foo") |
---|
1837 | n/a | |
---|
1838 | n/a | self.assertEqual(a[12], ("getitem", 12)) |
---|
1839 | n/a | a[12] = 21 |
---|
1840 | n/a | self.assertEqual(a.setitem, (12, 21)) |
---|
1841 | n/a | del a[12] |
---|
1842 | n/a | self.assertEqual(a.delitem, 12) |
---|
1843 | n/a | |
---|
1844 | n/a | self.assertEqual(a[0:10], ("getitem", slice(0, 10))) |
---|
1845 | n/a | a[0:10] = "foo" |
---|
1846 | n/a | self.assertEqual(a.setitem, (slice(0, 10), "foo")) |
---|
1847 | n/a | del a[0:10] |
---|
1848 | n/a | self.assertEqual(a.delitem, (slice(0, 10))) |
---|
1849 | n/a | |
---|
1850 | n/a | def test_methods(self): |
---|
1851 | n/a | # Testing methods... |
---|
1852 | n/a | class C(object): |
---|
1853 | n/a | def __init__(self, x): |
---|
1854 | n/a | self.x = x |
---|
1855 | n/a | def foo(self): |
---|
1856 | n/a | return self.x |
---|
1857 | n/a | c1 = C(1) |
---|
1858 | n/a | self.assertEqual(c1.foo(), 1) |
---|
1859 | n/a | class D(C): |
---|
1860 | n/a | boo = C.foo |
---|
1861 | n/a | goo = c1.foo |
---|
1862 | n/a | d2 = D(2) |
---|
1863 | n/a | self.assertEqual(d2.foo(), 2) |
---|
1864 | n/a | self.assertEqual(d2.boo(), 2) |
---|
1865 | n/a | self.assertEqual(d2.goo(), 1) |
---|
1866 | n/a | class E(object): |
---|
1867 | n/a | foo = C.foo |
---|
1868 | n/a | self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound |
---|
1869 | n/a | self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method ")) |
---|
1870 | n/a | |
---|
1871 | n/a | def test_special_method_lookup(self): |
---|
1872 | n/a | # The lookup of special methods bypasses __getattr__ and |
---|
1873 | n/a | # __getattribute__, but they still can be descriptors. |
---|
1874 | n/a | |
---|
1875 | n/a | def run_context(manager): |
---|
1876 | n/a | with manager: |
---|
1877 | n/a | pass |
---|
1878 | n/a | def iden(self): |
---|
1879 | n/a | return self |
---|
1880 | n/a | def hello(self): |
---|
1881 | n/a | return b"hello" |
---|
1882 | n/a | def empty_seq(self): |
---|
1883 | n/a | return [] |
---|
1884 | n/a | def zero(self): |
---|
1885 | n/a | return 0 |
---|
1886 | n/a | def complex_num(self): |
---|
1887 | n/a | return 1j |
---|
1888 | n/a | def stop(self): |
---|
1889 | n/a | raise StopIteration |
---|
1890 | n/a | def return_true(self, thing=None): |
---|
1891 | n/a | return True |
---|
1892 | n/a | def do_isinstance(obj): |
---|
1893 | n/a | return isinstance(int, obj) |
---|
1894 | n/a | def do_issubclass(obj): |
---|
1895 | n/a | return issubclass(int, obj) |
---|
1896 | n/a | def do_dict_missing(checker): |
---|
1897 | n/a | class DictSub(checker.__class__, dict): |
---|
1898 | n/a | pass |
---|
1899 | n/a | self.assertEqual(DictSub()["hi"], 4) |
---|
1900 | n/a | def some_number(self_, key): |
---|
1901 | n/a | self.assertEqual(key, "hi") |
---|
1902 | n/a | return 4 |
---|
1903 | n/a | def swallow(*args): pass |
---|
1904 | n/a | def format_impl(self, spec): |
---|
1905 | n/a | return "hello" |
---|
1906 | n/a | |
---|
1907 | n/a | # It would be nice to have every special method tested here, but I'm |
---|
1908 | n/a | # only listing the ones I can remember outside of typeobject.c, since it |
---|
1909 | n/a | # does it right. |
---|
1910 | n/a | specials = [ |
---|
1911 | n/a | ("__bytes__", bytes, hello, set(), {}), |
---|
1912 | n/a | ("__reversed__", reversed, empty_seq, set(), {}), |
---|
1913 | n/a | ("__length_hint__", list, zero, set(), |
---|
1914 | n/a | {"__iter__" : iden, "__next__" : stop}), |
---|
1915 | n/a | ("__sizeof__", sys.getsizeof, zero, set(), {}), |
---|
1916 | n/a | ("__instancecheck__", do_isinstance, return_true, set(), {}), |
---|
1917 | n/a | ("__missing__", do_dict_missing, some_number, |
---|
1918 | n/a | set(("__class__",)), {}), |
---|
1919 | n/a | ("__subclasscheck__", do_issubclass, return_true, |
---|
1920 | n/a | set(("__bases__",)), {}), |
---|
1921 | n/a | ("__enter__", run_context, iden, set(), {"__exit__" : swallow}), |
---|
1922 | n/a | ("__exit__", run_context, swallow, set(), {"__enter__" : iden}), |
---|
1923 | n/a | ("__complex__", complex, complex_num, set(), {}), |
---|
1924 | n/a | ("__format__", format, format_impl, set(), {}), |
---|
1925 | n/a | ("__floor__", math.floor, zero, set(), {}), |
---|
1926 | n/a | ("__trunc__", math.trunc, zero, set(), {}), |
---|
1927 | n/a | ("__trunc__", int, zero, set(), {}), |
---|
1928 | n/a | ("__ceil__", math.ceil, zero, set(), {}), |
---|
1929 | n/a | ("__dir__", dir, empty_seq, set(), {}), |
---|
1930 | n/a | ("__round__", round, zero, set(), {}), |
---|
1931 | n/a | ] |
---|
1932 | n/a | |
---|
1933 | n/a | class Checker(object): |
---|
1934 | n/a | def __getattr__(self, attr, test=self): |
---|
1935 | n/a | test.fail("__getattr__ called with {0}".format(attr)) |
---|
1936 | n/a | def __getattribute__(self, attr, test=self): |
---|
1937 | n/a | if attr not in ok: |
---|
1938 | n/a | test.fail("__getattribute__ called with {0}".format(attr)) |
---|
1939 | n/a | return object.__getattribute__(self, attr) |
---|
1940 | n/a | class SpecialDescr(object): |
---|
1941 | n/a | def __init__(self, impl): |
---|
1942 | n/a | self.impl = impl |
---|
1943 | n/a | def __get__(self, obj, owner): |
---|
1944 | n/a | record.append(1) |
---|
1945 | n/a | return self.impl.__get__(obj, owner) |
---|
1946 | n/a | class MyException(Exception): |
---|
1947 | n/a | pass |
---|
1948 | n/a | class ErrDescr(object): |
---|
1949 | n/a | def __get__(self, obj, owner): |
---|
1950 | n/a | raise MyException |
---|
1951 | n/a | |
---|
1952 | n/a | for name, runner, meth_impl, ok, env in specials: |
---|
1953 | n/a | class X(Checker): |
---|
1954 | n/a | pass |
---|
1955 | n/a | for attr, obj in env.items(): |
---|
1956 | n/a | setattr(X, attr, obj) |
---|
1957 | n/a | setattr(X, name, meth_impl) |
---|
1958 | n/a | runner(X()) |
---|
1959 | n/a | |
---|
1960 | n/a | record = [] |
---|
1961 | n/a | class X(Checker): |
---|
1962 | n/a | pass |
---|
1963 | n/a | for attr, obj in env.items(): |
---|
1964 | n/a | setattr(X, attr, obj) |
---|
1965 | n/a | setattr(X, name, SpecialDescr(meth_impl)) |
---|
1966 | n/a | runner(X()) |
---|
1967 | n/a | self.assertEqual(record, [1], name) |
---|
1968 | n/a | |
---|
1969 | n/a | class X(Checker): |
---|
1970 | n/a | pass |
---|
1971 | n/a | for attr, obj in env.items(): |
---|
1972 | n/a | setattr(X, attr, obj) |
---|
1973 | n/a | setattr(X, name, ErrDescr()) |
---|
1974 | n/a | self.assertRaises(MyException, runner, X()) |
---|
1975 | n/a | |
---|
1976 | n/a | def test_specials(self): |
---|
1977 | n/a | # Testing special operators... |
---|
1978 | n/a | # Test operators like __hash__ for which a built-in default exists |
---|
1979 | n/a | |
---|
1980 | n/a | # Test the default behavior for static classes |
---|
1981 | n/a | class C(object): |
---|
1982 | n/a | def __getitem__(self, i): |
---|
1983 | n/a | if 0 <= i < 10: return i |
---|
1984 | n/a | raise IndexError |
---|
1985 | n/a | c1 = C() |
---|
1986 | n/a | c2 = C() |
---|
1987 | n/a | self.assertFalse(not c1) |
---|
1988 | n/a | self.assertNotEqual(id(c1), id(c2)) |
---|
1989 | n/a | hash(c1) |
---|
1990 | n/a | hash(c2) |
---|
1991 | n/a | self.assertEqual(c1, c1) |
---|
1992 | n/a | self.assertTrue(c1 != c2) |
---|
1993 | n/a | self.assertFalse(c1 != c1) |
---|
1994 | n/a | self.assertFalse(c1 == c2) |
---|
1995 | n/a | # Note that the module name appears in str/repr, and that varies |
---|
1996 | n/a | # depending on whether this test is run standalone or from a framework. |
---|
1997 | n/a | self.assertGreaterEqual(str(c1).find('C object at '), 0) |
---|
1998 | n/a | self.assertEqual(str(c1), repr(c1)) |
---|
1999 | n/a | self.assertNotIn(-1, c1) |
---|
2000 | n/a | for i in range(10): |
---|
2001 | n/a | self.assertIn(i, c1) |
---|
2002 | n/a | self.assertNotIn(10, c1) |
---|
2003 | n/a | # Test the default behavior for dynamic classes |
---|
2004 | n/a | class D(object): |
---|
2005 | n/a | def __getitem__(self, i): |
---|
2006 | n/a | if 0 <= i < 10: return i |
---|
2007 | n/a | raise IndexError |
---|
2008 | n/a | d1 = D() |
---|
2009 | n/a | d2 = D() |
---|
2010 | n/a | self.assertFalse(not d1) |
---|
2011 | n/a | self.assertNotEqual(id(d1), id(d2)) |
---|
2012 | n/a | hash(d1) |
---|
2013 | n/a | hash(d2) |
---|
2014 | n/a | self.assertEqual(d1, d1) |
---|
2015 | n/a | self.assertNotEqual(d1, d2) |
---|
2016 | n/a | self.assertFalse(d1 != d1) |
---|
2017 | n/a | self.assertFalse(d1 == d2) |
---|
2018 | n/a | # Note that the module name appears in str/repr, and that varies |
---|
2019 | n/a | # depending on whether this test is run standalone or from a framework. |
---|
2020 | n/a | self.assertGreaterEqual(str(d1).find('D object at '), 0) |
---|
2021 | n/a | self.assertEqual(str(d1), repr(d1)) |
---|
2022 | n/a | self.assertNotIn(-1, d1) |
---|
2023 | n/a | for i in range(10): |
---|
2024 | n/a | self.assertIn(i, d1) |
---|
2025 | n/a | self.assertNotIn(10, d1) |
---|
2026 | n/a | # Test overridden behavior |
---|
2027 | n/a | class Proxy(object): |
---|
2028 | n/a | def __init__(self, x): |
---|
2029 | n/a | self.x = x |
---|
2030 | n/a | def __bool__(self): |
---|
2031 | n/a | return not not self.x |
---|
2032 | n/a | def __hash__(self): |
---|
2033 | n/a | return hash(self.x) |
---|
2034 | n/a | def __eq__(self, other): |
---|
2035 | n/a | return self.x == other |
---|
2036 | n/a | def __ne__(self, other): |
---|
2037 | n/a | return self.x != other |
---|
2038 | n/a | def __ge__(self, other): |
---|
2039 | n/a | return self.x >= other |
---|
2040 | n/a | def __gt__(self, other): |
---|
2041 | n/a | return self.x > other |
---|
2042 | n/a | def __le__(self, other): |
---|
2043 | n/a | return self.x <= other |
---|
2044 | n/a | def __lt__(self, other): |
---|
2045 | n/a | return self.x < other |
---|
2046 | n/a | def __str__(self): |
---|
2047 | n/a | return "Proxy:%s" % self.x |
---|
2048 | n/a | def __repr__(self): |
---|
2049 | n/a | return "Proxy(%r)" % self.x |
---|
2050 | n/a | def __contains__(self, value): |
---|
2051 | n/a | return value in self.x |
---|
2052 | n/a | p0 = Proxy(0) |
---|
2053 | n/a | p1 = Proxy(1) |
---|
2054 | n/a | p_1 = Proxy(-1) |
---|
2055 | n/a | self.assertFalse(p0) |
---|
2056 | n/a | self.assertFalse(not p1) |
---|
2057 | n/a | self.assertEqual(hash(p0), hash(0)) |
---|
2058 | n/a | self.assertEqual(p0, p0) |
---|
2059 | n/a | self.assertNotEqual(p0, p1) |
---|
2060 | n/a | self.assertFalse(p0 != p0) |
---|
2061 | n/a | self.assertEqual(not p0, p1) |
---|
2062 | n/a | self.assertTrue(p0 < p1) |
---|
2063 | n/a | self.assertTrue(p0 <= p1) |
---|
2064 | n/a | self.assertTrue(p1 > p0) |
---|
2065 | n/a | self.assertTrue(p1 >= p0) |
---|
2066 | n/a | self.assertEqual(str(p0), "Proxy:0") |
---|
2067 | n/a | self.assertEqual(repr(p0), "Proxy(0)") |
---|
2068 | n/a | p10 = Proxy(range(10)) |
---|
2069 | n/a | self.assertNotIn(-1, p10) |
---|
2070 | n/a | for i in range(10): |
---|
2071 | n/a | self.assertIn(i, p10) |
---|
2072 | n/a | self.assertNotIn(10, p10) |
---|
2073 | n/a | |
---|
2074 | n/a | def test_weakrefs(self): |
---|
2075 | n/a | # Testing weak references... |
---|
2076 | n/a | import weakref |
---|
2077 | n/a | class C(object): |
---|
2078 | n/a | pass |
---|
2079 | n/a | c = C() |
---|
2080 | n/a | r = weakref.ref(c) |
---|
2081 | n/a | self.assertEqual(r(), c) |
---|
2082 | n/a | del c |
---|
2083 | n/a | support.gc_collect() |
---|
2084 | n/a | self.assertEqual(r(), None) |
---|
2085 | n/a | del r |
---|
2086 | n/a | class NoWeak(object): |
---|
2087 | n/a | __slots__ = ['foo'] |
---|
2088 | n/a | no = NoWeak() |
---|
2089 | n/a | try: |
---|
2090 | n/a | weakref.ref(no) |
---|
2091 | n/a | except TypeError as msg: |
---|
2092 | n/a | self.assertIn("weak reference", str(msg)) |
---|
2093 | n/a | else: |
---|
2094 | n/a | self.fail("weakref.ref(no) should be illegal") |
---|
2095 | n/a | class Weak(object): |
---|
2096 | n/a | __slots__ = ['foo', '__weakref__'] |
---|
2097 | n/a | yes = Weak() |
---|
2098 | n/a | r = weakref.ref(yes) |
---|
2099 | n/a | self.assertEqual(r(), yes) |
---|
2100 | n/a | del yes |
---|
2101 | n/a | support.gc_collect() |
---|
2102 | n/a | self.assertEqual(r(), None) |
---|
2103 | n/a | del r |
---|
2104 | n/a | |
---|
2105 | n/a | def test_properties(self): |
---|
2106 | n/a | # Testing property... |
---|
2107 | n/a | class C(object): |
---|
2108 | n/a | def getx(self): |
---|
2109 | n/a | return self.__x |
---|
2110 | n/a | def setx(self, value): |
---|
2111 | n/a | self.__x = value |
---|
2112 | n/a | def delx(self): |
---|
2113 | n/a | del self.__x |
---|
2114 | n/a | x = property(getx, setx, delx, doc="I'm the x property.") |
---|
2115 | n/a | a = C() |
---|
2116 | n/a | self.assertNotHasAttr(a, "x") |
---|
2117 | n/a | a.x = 42 |
---|
2118 | n/a | self.assertEqual(a._C__x, 42) |
---|
2119 | n/a | self.assertEqual(a.x, 42) |
---|
2120 | n/a | del a.x |
---|
2121 | n/a | self.assertNotHasAttr(a, "x") |
---|
2122 | n/a | self.assertNotHasAttr(a, "_C__x") |
---|
2123 | n/a | C.x.__set__(a, 100) |
---|
2124 | n/a | self.assertEqual(C.x.__get__(a), 100) |
---|
2125 | n/a | C.x.__delete__(a) |
---|
2126 | n/a | self.assertNotHasAttr(a, "x") |
---|
2127 | n/a | |
---|
2128 | n/a | raw = C.__dict__['x'] |
---|
2129 | n/a | self.assertIsInstance(raw, property) |
---|
2130 | n/a | |
---|
2131 | n/a | attrs = dir(raw) |
---|
2132 | n/a | self.assertIn("__doc__", attrs) |
---|
2133 | n/a | self.assertIn("fget", attrs) |
---|
2134 | n/a | self.assertIn("fset", attrs) |
---|
2135 | n/a | self.assertIn("fdel", attrs) |
---|
2136 | n/a | |
---|
2137 | n/a | self.assertEqual(raw.__doc__, "I'm the x property.") |
---|
2138 | n/a | self.assertIs(raw.fget, C.__dict__['getx']) |
---|
2139 | n/a | self.assertIs(raw.fset, C.__dict__['setx']) |
---|
2140 | n/a | self.assertIs(raw.fdel, C.__dict__['delx']) |
---|
2141 | n/a | |
---|
2142 | n/a | for attr in "fget", "fset", "fdel": |
---|
2143 | n/a | try: |
---|
2144 | n/a | setattr(raw, attr, 42) |
---|
2145 | n/a | except AttributeError as msg: |
---|
2146 | n/a | if str(msg).find('readonly') < 0: |
---|
2147 | n/a | self.fail("when setting readonly attr %r on a property, " |
---|
2148 | n/a | "got unexpected AttributeError msg %r" % (attr, str(msg))) |
---|
2149 | n/a | else: |
---|
2150 | n/a | self.fail("expected AttributeError from trying to set readonly %r " |
---|
2151 | n/a | "attr on a property" % attr) |
---|
2152 | n/a | |
---|
2153 | n/a | raw.__doc__ = 42 |
---|
2154 | n/a | self.assertEqual(raw.__doc__, 42) |
---|
2155 | n/a | |
---|
2156 | n/a | class D(object): |
---|
2157 | n/a | __getitem__ = property(lambda s: 1/0) |
---|
2158 | n/a | |
---|
2159 | n/a | d = D() |
---|
2160 | n/a | try: |
---|
2161 | n/a | for i in d: |
---|
2162 | n/a | str(i) |
---|
2163 | n/a | except ZeroDivisionError: |
---|
2164 | n/a | pass |
---|
2165 | n/a | else: |
---|
2166 | n/a | self.fail("expected ZeroDivisionError from bad property") |
---|
2167 | n/a | |
---|
2168 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
2169 | n/a | "Docstrings are omitted with -O2 and above") |
---|
2170 | n/a | def test_properties_doc_attrib(self): |
---|
2171 | n/a | class E(object): |
---|
2172 | n/a | def getter(self): |
---|
2173 | n/a | "getter method" |
---|
2174 | n/a | return 0 |
---|
2175 | n/a | def setter(self_, value): |
---|
2176 | n/a | "setter method" |
---|
2177 | n/a | pass |
---|
2178 | n/a | prop = property(getter) |
---|
2179 | n/a | self.assertEqual(prop.__doc__, "getter method") |
---|
2180 | n/a | prop2 = property(fset=setter) |
---|
2181 | n/a | self.assertEqual(prop2.__doc__, None) |
---|
2182 | n/a | |
---|
2183 | n/a | @support.cpython_only |
---|
2184 | n/a | def test_testcapi_no_segfault(self): |
---|
2185 | n/a | # this segfaulted in 2.5b2 |
---|
2186 | n/a | try: |
---|
2187 | n/a | import _testcapi |
---|
2188 | n/a | except ImportError: |
---|
2189 | n/a | pass |
---|
2190 | n/a | else: |
---|
2191 | n/a | class X(object): |
---|
2192 | n/a | p = property(_testcapi.test_with_docstring) |
---|
2193 | n/a | |
---|
2194 | n/a | def test_properties_plus(self): |
---|
2195 | n/a | class C(object): |
---|
2196 | n/a | foo = property(doc="hello") |
---|
2197 | n/a | @foo.getter |
---|
2198 | n/a | def foo(self): |
---|
2199 | n/a | return self._foo |
---|
2200 | n/a | @foo.setter |
---|
2201 | n/a | def foo(self, value): |
---|
2202 | n/a | self._foo = abs(value) |
---|
2203 | n/a | @foo.deleter |
---|
2204 | n/a | def foo(self): |
---|
2205 | n/a | del self._foo |
---|
2206 | n/a | c = C() |
---|
2207 | n/a | self.assertEqual(C.foo.__doc__, "hello") |
---|
2208 | n/a | self.assertNotHasAttr(c, "foo") |
---|
2209 | n/a | c.foo = -42 |
---|
2210 | n/a | self.assertHasAttr(c, '_foo') |
---|
2211 | n/a | self.assertEqual(c._foo, 42) |
---|
2212 | n/a | self.assertEqual(c.foo, 42) |
---|
2213 | n/a | del c.foo |
---|
2214 | n/a | self.assertNotHasAttr(c, '_foo') |
---|
2215 | n/a | self.assertNotHasAttr(c, "foo") |
---|
2216 | n/a | |
---|
2217 | n/a | class D(C): |
---|
2218 | n/a | @C.foo.deleter |
---|
2219 | n/a | def foo(self): |
---|
2220 | n/a | try: |
---|
2221 | n/a | del self._foo |
---|
2222 | n/a | except AttributeError: |
---|
2223 | n/a | pass |
---|
2224 | n/a | d = D() |
---|
2225 | n/a | d.foo = 24 |
---|
2226 | n/a | self.assertEqual(d.foo, 24) |
---|
2227 | n/a | del d.foo |
---|
2228 | n/a | del d.foo |
---|
2229 | n/a | |
---|
2230 | n/a | class E(object): |
---|
2231 | n/a | @property |
---|
2232 | n/a | def foo(self): |
---|
2233 | n/a | return self._foo |
---|
2234 | n/a | @foo.setter |
---|
2235 | n/a | def foo(self, value): |
---|
2236 | n/a | raise RuntimeError |
---|
2237 | n/a | @foo.setter |
---|
2238 | n/a | def foo(self, value): |
---|
2239 | n/a | self._foo = abs(value) |
---|
2240 | n/a | @foo.deleter |
---|
2241 | n/a | def foo(self, value=None): |
---|
2242 | n/a | del self._foo |
---|
2243 | n/a | |
---|
2244 | n/a | e = E() |
---|
2245 | n/a | e.foo = -42 |
---|
2246 | n/a | self.assertEqual(e.foo, 42) |
---|
2247 | n/a | del e.foo |
---|
2248 | n/a | |
---|
2249 | n/a | class F(E): |
---|
2250 | n/a | @E.foo.deleter |
---|
2251 | n/a | def foo(self): |
---|
2252 | n/a | del self._foo |
---|
2253 | n/a | @foo.setter |
---|
2254 | n/a | def foo(self, value): |
---|
2255 | n/a | self._foo = max(0, value) |
---|
2256 | n/a | f = F() |
---|
2257 | n/a | f.foo = -10 |
---|
2258 | n/a | self.assertEqual(f.foo, 0) |
---|
2259 | n/a | del f.foo |
---|
2260 | n/a | |
---|
2261 | n/a | def test_dict_constructors(self): |
---|
2262 | n/a | # Testing dict constructor ... |
---|
2263 | n/a | d = dict() |
---|
2264 | n/a | self.assertEqual(d, {}) |
---|
2265 | n/a | d = dict({}) |
---|
2266 | n/a | self.assertEqual(d, {}) |
---|
2267 | n/a | d = dict({1: 2, 'a': 'b'}) |
---|
2268 | n/a | self.assertEqual(d, {1: 2, 'a': 'b'}) |
---|
2269 | n/a | self.assertEqual(d, dict(list(d.items()))) |
---|
2270 | n/a | self.assertEqual(d, dict(iter(d.items()))) |
---|
2271 | n/a | d = dict({'one':1, 'two':2}) |
---|
2272 | n/a | self.assertEqual(d, dict(one=1, two=2)) |
---|
2273 | n/a | self.assertEqual(d, dict(**d)) |
---|
2274 | n/a | self.assertEqual(d, dict({"one": 1}, two=2)) |
---|
2275 | n/a | self.assertEqual(d, dict([("two", 2)], one=1)) |
---|
2276 | n/a | self.assertEqual(d, dict([("one", 100), ("two", 200)], **d)) |
---|
2277 | n/a | self.assertEqual(d, dict(**d)) |
---|
2278 | n/a | |
---|
2279 | n/a | for badarg in 0, 0, 0j, "0", [0], (0,): |
---|
2280 | n/a | try: |
---|
2281 | n/a | dict(badarg) |
---|
2282 | n/a | except TypeError: |
---|
2283 | n/a | pass |
---|
2284 | n/a | except ValueError: |
---|
2285 | n/a | if badarg == "0": |
---|
2286 | n/a | # It's a sequence, and its elements are also sequences (gotta |
---|
2287 | n/a | # love strings <wink>), but they aren't of length 2, so this |
---|
2288 | n/a | # one seemed better as a ValueError than a TypeError. |
---|
2289 | n/a | pass |
---|
2290 | n/a | else: |
---|
2291 | n/a | self.fail("no TypeError from dict(%r)" % badarg) |
---|
2292 | n/a | else: |
---|
2293 | n/a | self.fail("no TypeError from dict(%r)" % badarg) |
---|
2294 | n/a | |
---|
2295 | n/a | try: |
---|
2296 | n/a | dict({}, {}) |
---|
2297 | n/a | except TypeError: |
---|
2298 | n/a | pass |
---|
2299 | n/a | else: |
---|
2300 | n/a | self.fail("no TypeError from dict({}, {})") |
---|
2301 | n/a | |
---|
2302 | n/a | class Mapping: |
---|
2303 | n/a | # Lacks a .keys() method; will be added later. |
---|
2304 | n/a | dict = {1:2, 3:4, 'a':1j} |
---|
2305 | n/a | |
---|
2306 | n/a | try: |
---|
2307 | n/a | dict(Mapping()) |
---|
2308 | n/a | except TypeError: |
---|
2309 | n/a | pass |
---|
2310 | n/a | else: |
---|
2311 | n/a | self.fail("no TypeError from dict(incomplete mapping)") |
---|
2312 | n/a | |
---|
2313 | n/a | Mapping.keys = lambda self: list(self.dict.keys()) |
---|
2314 | n/a | Mapping.__getitem__ = lambda self, i: self.dict[i] |
---|
2315 | n/a | d = dict(Mapping()) |
---|
2316 | n/a | self.assertEqual(d, Mapping.dict) |
---|
2317 | n/a | |
---|
2318 | n/a | # Init from sequence of iterable objects, each producing a 2-sequence. |
---|
2319 | n/a | class AddressBookEntry: |
---|
2320 | n/a | def __init__(self, first, last): |
---|
2321 | n/a | self.first = first |
---|
2322 | n/a | self.last = last |
---|
2323 | n/a | def __iter__(self): |
---|
2324 | n/a | return iter([self.first, self.last]) |
---|
2325 | n/a | |
---|
2326 | n/a | d = dict([AddressBookEntry('Tim', 'Warsaw'), |
---|
2327 | n/a | AddressBookEntry('Barry', 'Peters'), |
---|
2328 | n/a | AddressBookEntry('Tim', 'Peters'), |
---|
2329 | n/a | AddressBookEntry('Barry', 'Warsaw')]) |
---|
2330 | n/a | self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'}) |
---|
2331 | n/a | |
---|
2332 | n/a | d = dict(zip(range(4), range(1, 5))) |
---|
2333 | n/a | self.assertEqual(d, dict([(i, i+1) for i in range(4)])) |
---|
2334 | n/a | |
---|
2335 | n/a | # Bad sequence lengths. |
---|
2336 | n/a | for bad in [('tooshort',)], [('too', 'long', 'by 1')]: |
---|
2337 | n/a | try: |
---|
2338 | n/a | dict(bad) |
---|
2339 | n/a | except ValueError: |
---|
2340 | n/a | pass |
---|
2341 | n/a | else: |
---|
2342 | n/a | self.fail("no ValueError from dict(%r)" % bad) |
---|
2343 | n/a | |
---|
2344 | n/a | def test_dir(self): |
---|
2345 | n/a | # Testing dir() ... |
---|
2346 | n/a | junk = 12 |
---|
2347 | n/a | self.assertEqual(dir(), ['junk', 'self']) |
---|
2348 | n/a | del junk |
---|
2349 | n/a | |
---|
2350 | n/a | # Just make sure these don't blow up! |
---|
2351 | n/a | for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir: |
---|
2352 | n/a | dir(arg) |
---|
2353 | n/a | |
---|
2354 | n/a | # Test dir on new-style classes. Since these have object as a |
---|
2355 | n/a | # base class, a lot more gets sucked in. |
---|
2356 | n/a | def interesting(strings): |
---|
2357 | n/a | return [s for s in strings if not s.startswith('_')] |
---|
2358 | n/a | |
---|
2359 | n/a | class C(object): |
---|
2360 | n/a | Cdata = 1 |
---|
2361 | n/a | def Cmethod(self): pass |
---|
2362 | n/a | |
---|
2363 | n/a | cstuff = ['Cdata', 'Cmethod'] |
---|
2364 | n/a | self.assertEqual(interesting(dir(C)), cstuff) |
---|
2365 | n/a | |
---|
2366 | n/a | c = C() |
---|
2367 | n/a | self.assertEqual(interesting(dir(c)), cstuff) |
---|
2368 | n/a | ## self.assertIn('__self__', dir(C.Cmethod)) |
---|
2369 | n/a | |
---|
2370 | n/a | c.cdata = 2 |
---|
2371 | n/a | c.cmethod = lambda self: 0 |
---|
2372 | n/a | self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) |
---|
2373 | n/a | ## self.assertIn('__self__', dir(c.Cmethod)) |
---|
2374 | n/a | |
---|
2375 | n/a | class A(C): |
---|
2376 | n/a | Adata = 1 |
---|
2377 | n/a | def Amethod(self): pass |
---|
2378 | n/a | |
---|
2379 | n/a | astuff = ['Adata', 'Amethod'] + cstuff |
---|
2380 | n/a | self.assertEqual(interesting(dir(A)), astuff) |
---|
2381 | n/a | ## self.assertIn('__self__', dir(A.Amethod)) |
---|
2382 | n/a | a = A() |
---|
2383 | n/a | self.assertEqual(interesting(dir(a)), astuff) |
---|
2384 | n/a | a.adata = 42 |
---|
2385 | n/a | a.amethod = lambda self: 3 |
---|
2386 | n/a | self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) |
---|
2387 | n/a | ## self.assertIn('__self__', dir(a.Amethod)) |
---|
2388 | n/a | |
---|
2389 | n/a | # Try a module subclass. |
---|
2390 | n/a | class M(type(sys)): |
---|
2391 | n/a | pass |
---|
2392 | n/a | minstance = M("m") |
---|
2393 | n/a | minstance.b = 2 |
---|
2394 | n/a | minstance.a = 1 |
---|
2395 | n/a | default_attributes = ['__name__', '__doc__', '__package__', |
---|
2396 | n/a | '__loader__', '__spec__'] |
---|
2397 | n/a | names = [x for x in dir(minstance) if x not in default_attributes] |
---|
2398 | n/a | self.assertEqual(names, ['a', 'b']) |
---|
2399 | n/a | |
---|
2400 | n/a | class M2(M): |
---|
2401 | n/a | def getdict(self): |
---|
2402 | n/a | return "Not a dict!" |
---|
2403 | n/a | __dict__ = property(getdict) |
---|
2404 | n/a | |
---|
2405 | n/a | m2instance = M2("m2") |
---|
2406 | n/a | m2instance.b = 2 |
---|
2407 | n/a | m2instance.a = 1 |
---|
2408 | n/a | self.assertEqual(m2instance.__dict__, "Not a dict!") |
---|
2409 | n/a | try: |
---|
2410 | n/a | dir(m2instance) |
---|
2411 | n/a | except TypeError: |
---|
2412 | n/a | pass |
---|
2413 | n/a | |
---|
2414 | n/a | # Two essentially featureless objects, just inheriting stuff from |
---|
2415 | n/a | # object. |
---|
2416 | n/a | self.assertEqual(dir(NotImplemented), dir(Ellipsis)) |
---|
2417 | n/a | |
---|
2418 | n/a | # Nasty test case for proxied objects |
---|
2419 | n/a | class Wrapper(object): |
---|
2420 | n/a | def __init__(self, obj): |
---|
2421 | n/a | self.__obj = obj |
---|
2422 | n/a | def __repr__(self): |
---|
2423 | n/a | return "Wrapper(%s)" % repr(self.__obj) |
---|
2424 | n/a | def __getitem__(self, key): |
---|
2425 | n/a | return Wrapper(self.__obj[key]) |
---|
2426 | n/a | def __len__(self): |
---|
2427 | n/a | return len(self.__obj) |
---|
2428 | n/a | def __getattr__(self, name): |
---|
2429 | n/a | return Wrapper(getattr(self.__obj, name)) |
---|
2430 | n/a | |
---|
2431 | n/a | class C(object): |
---|
2432 | n/a | def __getclass(self): |
---|
2433 | n/a | return Wrapper(type(self)) |
---|
2434 | n/a | __class__ = property(__getclass) |
---|
2435 | n/a | |
---|
2436 | n/a | dir(C()) # This used to segfault |
---|
2437 | n/a | |
---|
2438 | n/a | def test_supers(self): |
---|
2439 | n/a | # Testing super... |
---|
2440 | n/a | |
---|
2441 | n/a | class A(object): |
---|
2442 | n/a | def meth(self, a): |
---|
2443 | n/a | return "A(%r)" % a |
---|
2444 | n/a | |
---|
2445 | n/a | self.assertEqual(A().meth(1), "A(1)") |
---|
2446 | n/a | |
---|
2447 | n/a | class B(A): |
---|
2448 | n/a | def __init__(self): |
---|
2449 | n/a | self.__super = super(B, self) |
---|
2450 | n/a | def meth(self, a): |
---|
2451 | n/a | return "B(%r)" % a + self.__super.meth(a) |
---|
2452 | n/a | |
---|
2453 | n/a | self.assertEqual(B().meth(2), "B(2)A(2)") |
---|
2454 | n/a | |
---|
2455 | n/a | class C(A): |
---|
2456 | n/a | def meth(self, a): |
---|
2457 | n/a | return "C(%r)" % a + self.__super.meth(a) |
---|
2458 | n/a | C._C__super = super(C) |
---|
2459 | n/a | |
---|
2460 | n/a | self.assertEqual(C().meth(3), "C(3)A(3)") |
---|
2461 | n/a | |
---|
2462 | n/a | class D(C, B): |
---|
2463 | n/a | def meth(self, a): |
---|
2464 | n/a | return "D(%r)" % a + super(D, self).meth(a) |
---|
2465 | n/a | |
---|
2466 | n/a | self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)") |
---|
2467 | n/a | |
---|
2468 | n/a | # Test for subclassing super |
---|
2469 | n/a | |
---|
2470 | n/a | class mysuper(super): |
---|
2471 | n/a | def __init__(self, *args): |
---|
2472 | n/a | return super(mysuper, self).__init__(*args) |
---|
2473 | n/a | |
---|
2474 | n/a | class E(D): |
---|
2475 | n/a | def meth(self, a): |
---|
2476 | n/a | return "E(%r)" % a + mysuper(E, self).meth(a) |
---|
2477 | n/a | |
---|
2478 | n/a | self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") |
---|
2479 | n/a | |
---|
2480 | n/a | class F(E): |
---|
2481 | n/a | def meth(self, a): |
---|
2482 | n/a | s = self.__super # == mysuper(F, self) |
---|
2483 | n/a | return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) |
---|
2484 | n/a | F._F__super = mysuper(F) |
---|
2485 | n/a | |
---|
2486 | n/a | self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") |
---|
2487 | n/a | |
---|
2488 | n/a | # Make sure certain errors are raised |
---|
2489 | n/a | |
---|
2490 | n/a | try: |
---|
2491 | n/a | super(D, 42) |
---|
2492 | n/a | except TypeError: |
---|
2493 | n/a | pass |
---|
2494 | n/a | else: |
---|
2495 | n/a | self.fail("shouldn't allow super(D, 42)") |
---|
2496 | n/a | |
---|
2497 | n/a | try: |
---|
2498 | n/a | super(D, C()) |
---|
2499 | n/a | except TypeError: |
---|
2500 | n/a | pass |
---|
2501 | n/a | else: |
---|
2502 | n/a | self.fail("shouldn't allow super(D, C())") |
---|
2503 | n/a | |
---|
2504 | n/a | try: |
---|
2505 | n/a | super(D).__get__(12) |
---|
2506 | n/a | except TypeError: |
---|
2507 | n/a | pass |
---|
2508 | n/a | else: |
---|
2509 | n/a | self.fail("shouldn't allow super(D).__get__(12)") |
---|
2510 | n/a | |
---|
2511 | n/a | try: |
---|
2512 | n/a | super(D).__get__(C()) |
---|
2513 | n/a | except TypeError: |
---|
2514 | n/a | pass |
---|
2515 | n/a | else: |
---|
2516 | n/a | self.fail("shouldn't allow super(D).__get__(C())") |
---|
2517 | n/a | |
---|
2518 | n/a | # Make sure data descriptors can be overridden and accessed via super |
---|
2519 | n/a | # (new feature in Python 2.3) |
---|
2520 | n/a | |
---|
2521 | n/a | class DDbase(object): |
---|
2522 | n/a | def getx(self): return 42 |
---|
2523 | n/a | x = property(getx) |
---|
2524 | n/a | |
---|
2525 | n/a | class DDsub(DDbase): |
---|
2526 | n/a | def getx(self): return "hello" |
---|
2527 | n/a | x = property(getx) |
---|
2528 | n/a | |
---|
2529 | n/a | dd = DDsub() |
---|
2530 | n/a | self.assertEqual(dd.x, "hello") |
---|
2531 | n/a | self.assertEqual(super(DDsub, dd).x, 42) |
---|
2532 | n/a | |
---|
2533 | n/a | # Ensure that super() lookup of descriptor from classmethod |
---|
2534 | n/a | # works (SF ID# 743627) |
---|
2535 | n/a | |
---|
2536 | n/a | class Base(object): |
---|
2537 | n/a | aProp = property(lambda self: "foo") |
---|
2538 | n/a | |
---|
2539 | n/a | class Sub(Base): |
---|
2540 | n/a | @classmethod |
---|
2541 | n/a | def test(klass): |
---|
2542 | n/a | return super(Sub,klass).aProp |
---|
2543 | n/a | |
---|
2544 | n/a | self.assertEqual(Sub.test(), Base.aProp) |
---|
2545 | n/a | |
---|
2546 | n/a | # Verify that super() doesn't allow keyword args |
---|
2547 | n/a | try: |
---|
2548 | n/a | super(Base, kw=1) |
---|
2549 | n/a | except TypeError: |
---|
2550 | n/a | pass |
---|
2551 | n/a | else: |
---|
2552 | n/a | self.assertEqual("super shouldn't accept keyword args") |
---|
2553 | n/a | |
---|
2554 | n/a | def test_basic_inheritance(self): |
---|
2555 | n/a | # Testing inheritance from basic types... |
---|
2556 | n/a | |
---|
2557 | n/a | class hexint(int): |
---|
2558 | n/a | def __repr__(self): |
---|
2559 | n/a | return hex(self) |
---|
2560 | n/a | def __add__(self, other): |
---|
2561 | n/a | return hexint(int.__add__(self, other)) |
---|
2562 | n/a | # (Note that overriding __radd__ doesn't work, |
---|
2563 | n/a | # because the int type gets first dibs.) |
---|
2564 | n/a | self.assertEqual(repr(hexint(7) + 9), "0x10") |
---|
2565 | n/a | self.assertEqual(repr(hexint(1000) + 7), "0x3ef") |
---|
2566 | n/a | a = hexint(12345) |
---|
2567 | n/a | self.assertEqual(a, 12345) |
---|
2568 | n/a | self.assertEqual(int(a), 12345) |
---|
2569 | n/a | self.assertIs(int(a).__class__, int) |
---|
2570 | n/a | self.assertEqual(hash(a), hash(12345)) |
---|
2571 | n/a | self.assertIs((+a).__class__, int) |
---|
2572 | n/a | self.assertIs((a >> 0).__class__, int) |
---|
2573 | n/a | self.assertIs((a << 0).__class__, int) |
---|
2574 | n/a | self.assertIs((hexint(0) << 12).__class__, int) |
---|
2575 | n/a | self.assertIs((hexint(0) >> 12).__class__, int) |
---|
2576 | n/a | |
---|
2577 | n/a | class octlong(int): |
---|
2578 | n/a | __slots__ = [] |
---|
2579 | n/a | def __str__(self): |
---|
2580 | n/a | return oct(self) |
---|
2581 | n/a | def __add__(self, other): |
---|
2582 | n/a | return self.__class__(super(octlong, self).__add__(other)) |
---|
2583 | n/a | __radd__ = __add__ |
---|
2584 | n/a | self.assertEqual(str(octlong(3) + 5), "0o10") |
---|
2585 | n/a | # (Note that overriding __radd__ here only seems to work |
---|
2586 | n/a | # because the example uses a short int left argument.) |
---|
2587 | n/a | self.assertEqual(str(5 + octlong(3000)), "0o5675") |
---|
2588 | n/a | a = octlong(12345) |
---|
2589 | n/a | self.assertEqual(a, 12345) |
---|
2590 | n/a | self.assertEqual(int(a), 12345) |
---|
2591 | n/a | self.assertEqual(hash(a), hash(12345)) |
---|
2592 | n/a | self.assertIs(int(a).__class__, int) |
---|
2593 | n/a | self.assertIs((+a).__class__, int) |
---|
2594 | n/a | self.assertIs((-a).__class__, int) |
---|
2595 | n/a | self.assertIs((-octlong(0)).__class__, int) |
---|
2596 | n/a | self.assertIs((a >> 0).__class__, int) |
---|
2597 | n/a | self.assertIs((a << 0).__class__, int) |
---|
2598 | n/a | self.assertIs((a - 0).__class__, int) |
---|
2599 | n/a | self.assertIs((a * 1).__class__, int) |
---|
2600 | n/a | self.assertIs((a ** 1).__class__, int) |
---|
2601 | n/a | self.assertIs((a // 1).__class__, int) |
---|
2602 | n/a | self.assertIs((1 * a).__class__, int) |
---|
2603 | n/a | self.assertIs((a | 0).__class__, int) |
---|
2604 | n/a | self.assertIs((a ^ 0).__class__, int) |
---|
2605 | n/a | self.assertIs((a & -1).__class__, int) |
---|
2606 | n/a | self.assertIs((octlong(0) << 12).__class__, int) |
---|
2607 | n/a | self.assertIs((octlong(0) >> 12).__class__, int) |
---|
2608 | n/a | self.assertIs(abs(octlong(0)).__class__, int) |
---|
2609 | n/a | |
---|
2610 | n/a | # Because octlong overrides __add__, we can't check the absence of +0 |
---|
2611 | n/a | # optimizations using octlong. |
---|
2612 | n/a | class longclone(int): |
---|
2613 | n/a | pass |
---|
2614 | n/a | a = longclone(1) |
---|
2615 | n/a | self.assertIs((a + 0).__class__, int) |
---|
2616 | n/a | self.assertIs((0 + a).__class__, int) |
---|
2617 | n/a | |
---|
2618 | n/a | # Check that negative clones don't segfault |
---|
2619 | n/a | a = longclone(-1) |
---|
2620 | n/a | self.assertEqual(a.__dict__, {}) |
---|
2621 | n/a | self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit |
---|
2622 | n/a | |
---|
2623 | n/a | class precfloat(float): |
---|
2624 | n/a | __slots__ = ['prec'] |
---|
2625 | n/a | def __init__(self, value=0.0, prec=12): |
---|
2626 | n/a | self.prec = int(prec) |
---|
2627 | n/a | def __repr__(self): |
---|
2628 | n/a | return "%.*g" % (self.prec, self) |
---|
2629 | n/a | self.assertEqual(repr(precfloat(1.1)), "1.1") |
---|
2630 | n/a | a = precfloat(12345) |
---|
2631 | n/a | self.assertEqual(a, 12345.0) |
---|
2632 | n/a | self.assertEqual(float(a), 12345.0) |
---|
2633 | n/a | self.assertIs(float(a).__class__, float) |
---|
2634 | n/a | self.assertEqual(hash(a), hash(12345.0)) |
---|
2635 | n/a | self.assertIs((+a).__class__, float) |
---|
2636 | n/a | |
---|
2637 | n/a | class madcomplex(complex): |
---|
2638 | n/a | def __repr__(self): |
---|
2639 | n/a | return "%.17gj%+.17g" % (self.imag, self.real) |
---|
2640 | n/a | a = madcomplex(-3, 4) |
---|
2641 | n/a | self.assertEqual(repr(a), "4j-3") |
---|
2642 | n/a | base = complex(-3, 4) |
---|
2643 | n/a | self.assertEqual(base.__class__, complex) |
---|
2644 | n/a | self.assertEqual(a, base) |
---|
2645 | n/a | self.assertEqual(complex(a), base) |
---|
2646 | n/a | self.assertEqual(complex(a).__class__, complex) |
---|
2647 | n/a | a = madcomplex(a) # just trying another form of the constructor |
---|
2648 | n/a | self.assertEqual(repr(a), "4j-3") |
---|
2649 | n/a | self.assertEqual(a, base) |
---|
2650 | n/a | self.assertEqual(complex(a), base) |
---|
2651 | n/a | self.assertEqual(complex(a).__class__, complex) |
---|
2652 | n/a | self.assertEqual(hash(a), hash(base)) |
---|
2653 | n/a | self.assertEqual((+a).__class__, complex) |
---|
2654 | n/a | self.assertEqual((a + 0).__class__, complex) |
---|
2655 | n/a | self.assertEqual(a + 0, base) |
---|
2656 | n/a | self.assertEqual((a - 0).__class__, complex) |
---|
2657 | n/a | self.assertEqual(a - 0, base) |
---|
2658 | n/a | self.assertEqual((a * 1).__class__, complex) |
---|
2659 | n/a | self.assertEqual(a * 1, base) |
---|
2660 | n/a | self.assertEqual((a / 1).__class__, complex) |
---|
2661 | n/a | self.assertEqual(a / 1, base) |
---|
2662 | n/a | |
---|
2663 | n/a | class madtuple(tuple): |
---|
2664 | n/a | _rev = None |
---|
2665 | n/a | def rev(self): |
---|
2666 | n/a | if self._rev is not None: |
---|
2667 | n/a | return self._rev |
---|
2668 | n/a | L = list(self) |
---|
2669 | n/a | L.reverse() |
---|
2670 | n/a | self._rev = self.__class__(L) |
---|
2671 | n/a | return self._rev |
---|
2672 | n/a | a = madtuple((1,2,3,4,5,6,7,8,9,0)) |
---|
2673 | n/a | self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0)) |
---|
2674 | n/a | self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) |
---|
2675 | n/a | self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) |
---|
2676 | n/a | for i in range(512): |
---|
2677 | n/a | t = madtuple(range(i)) |
---|
2678 | n/a | u = t.rev() |
---|
2679 | n/a | v = u.rev() |
---|
2680 | n/a | self.assertEqual(v, t) |
---|
2681 | n/a | a = madtuple((1,2,3,4,5)) |
---|
2682 | n/a | self.assertEqual(tuple(a), (1,2,3,4,5)) |
---|
2683 | n/a | self.assertIs(tuple(a).__class__, tuple) |
---|
2684 | n/a | self.assertEqual(hash(a), hash((1,2,3,4,5))) |
---|
2685 | n/a | self.assertIs(a[:].__class__, tuple) |
---|
2686 | n/a | self.assertIs((a * 1).__class__, tuple) |
---|
2687 | n/a | self.assertIs((a * 0).__class__, tuple) |
---|
2688 | n/a | self.assertIs((a + ()).__class__, tuple) |
---|
2689 | n/a | a = madtuple(()) |
---|
2690 | n/a | self.assertEqual(tuple(a), ()) |
---|
2691 | n/a | self.assertIs(tuple(a).__class__, tuple) |
---|
2692 | n/a | self.assertIs((a + a).__class__, tuple) |
---|
2693 | n/a | self.assertIs((a * 0).__class__, tuple) |
---|
2694 | n/a | self.assertIs((a * 1).__class__, tuple) |
---|
2695 | n/a | self.assertIs((a * 2).__class__, tuple) |
---|
2696 | n/a | self.assertIs(a[:].__class__, tuple) |
---|
2697 | n/a | |
---|
2698 | n/a | class madstring(str): |
---|
2699 | n/a | _rev = None |
---|
2700 | n/a | def rev(self): |
---|
2701 | n/a | if self._rev is not None: |
---|
2702 | n/a | return self._rev |
---|
2703 | n/a | L = list(self) |
---|
2704 | n/a | L.reverse() |
---|
2705 | n/a | self._rev = self.__class__("".join(L)) |
---|
2706 | n/a | return self._rev |
---|
2707 | n/a | s = madstring("abcdefghijklmnopqrstuvwxyz") |
---|
2708 | n/a | self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz") |
---|
2709 | n/a | self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) |
---|
2710 | n/a | self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) |
---|
2711 | n/a | for i in range(256): |
---|
2712 | n/a | s = madstring("".join(map(chr, range(i)))) |
---|
2713 | n/a | t = s.rev() |
---|
2714 | n/a | u = t.rev() |
---|
2715 | n/a | self.assertEqual(u, s) |
---|
2716 | n/a | s = madstring("12345") |
---|
2717 | n/a | self.assertEqual(str(s), "12345") |
---|
2718 | n/a | self.assertIs(str(s).__class__, str) |
---|
2719 | n/a | |
---|
2720 | n/a | base = "\x00" * 5 |
---|
2721 | n/a | s = madstring(base) |
---|
2722 | n/a | self.assertEqual(s, base) |
---|
2723 | n/a | self.assertEqual(str(s), base) |
---|
2724 | n/a | self.assertIs(str(s).__class__, str) |
---|
2725 | n/a | self.assertEqual(hash(s), hash(base)) |
---|
2726 | n/a | self.assertEqual({s: 1}[base], 1) |
---|
2727 | n/a | self.assertEqual({base: 1}[s], 1) |
---|
2728 | n/a | self.assertIs((s + "").__class__, str) |
---|
2729 | n/a | self.assertEqual(s + "", base) |
---|
2730 | n/a | self.assertIs(("" + s).__class__, str) |
---|
2731 | n/a | self.assertEqual("" + s, base) |
---|
2732 | n/a | self.assertIs((s * 0).__class__, str) |
---|
2733 | n/a | self.assertEqual(s * 0, "") |
---|
2734 | n/a | self.assertIs((s * 1).__class__, str) |
---|
2735 | n/a | self.assertEqual(s * 1, base) |
---|
2736 | n/a | self.assertIs((s * 2).__class__, str) |
---|
2737 | n/a | self.assertEqual(s * 2, base + base) |
---|
2738 | n/a | self.assertIs(s[:].__class__, str) |
---|
2739 | n/a | self.assertEqual(s[:], base) |
---|
2740 | n/a | self.assertIs(s[0:0].__class__, str) |
---|
2741 | n/a | self.assertEqual(s[0:0], "") |
---|
2742 | n/a | self.assertIs(s.strip().__class__, str) |
---|
2743 | n/a | self.assertEqual(s.strip(), base) |
---|
2744 | n/a | self.assertIs(s.lstrip().__class__, str) |
---|
2745 | n/a | self.assertEqual(s.lstrip(), base) |
---|
2746 | n/a | self.assertIs(s.rstrip().__class__, str) |
---|
2747 | n/a | self.assertEqual(s.rstrip(), base) |
---|
2748 | n/a | identitytab = {} |
---|
2749 | n/a | self.assertIs(s.translate(identitytab).__class__, str) |
---|
2750 | n/a | self.assertEqual(s.translate(identitytab), base) |
---|
2751 | n/a | self.assertIs(s.replace("x", "x").__class__, str) |
---|
2752 | n/a | self.assertEqual(s.replace("x", "x"), base) |
---|
2753 | n/a | self.assertIs(s.ljust(len(s)).__class__, str) |
---|
2754 | n/a | self.assertEqual(s.ljust(len(s)), base) |
---|
2755 | n/a | self.assertIs(s.rjust(len(s)).__class__, str) |
---|
2756 | n/a | self.assertEqual(s.rjust(len(s)), base) |
---|
2757 | n/a | self.assertIs(s.center(len(s)).__class__, str) |
---|
2758 | n/a | self.assertEqual(s.center(len(s)), base) |
---|
2759 | n/a | self.assertIs(s.lower().__class__, str) |
---|
2760 | n/a | self.assertEqual(s.lower(), base) |
---|
2761 | n/a | |
---|
2762 | n/a | class madunicode(str): |
---|
2763 | n/a | _rev = None |
---|
2764 | n/a | def rev(self): |
---|
2765 | n/a | if self._rev is not None: |
---|
2766 | n/a | return self._rev |
---|
2767 | n/a | L = list(self) |
---|
2768 | n/a | L.reverse() |
---|
2769 | n/a | self._rev = self.__class__("".join(L)) |
---|
2770 | n/a | return self._rev |
---|
2771 | n/a | u = madunicode("ABCDEF") |
---|
2772 | n/a | self.assertEqual(u, "ABCDEF") |
---|
2773 | n/a | self.assertEqual(u.rev(), madunicode("FEDCBA")) |
---|
2774 | n/a | self.assertEqual(u.rev().rev(), madunicode("ABCDEF")) |
---|
2775 | n/a | base = "12345" |
---|
2776 | n/a | u = madunicode(base) |
---|
2777 | n/a | self.assertEqual(str(u), base) |
---|
2778 | n/a | self.assertIs(str(u).__class__, str) |
---|
2779 | n/a | self.assertEqual(hash(u), hash(base)) |
---|
2780 | n/a | self.assertEqual({u: 1}[base], 1) |
---|
2781 | n/a | self.assertEqual({base: 1}[u], 1) |
---|
2782 | n/a | self.assertIs(u.strip().__class__, str) |
---|
2783 | n/a | self.assertEqual(u.strip(), base) |
---|
2784 | n/a | self.assertIs(u.lstrip().__class__, str) |
---|
2785 | n/a | self.assertEqual(u.lstrip(), base) |
---|
2786 | n/a | self.assertIs(u.rstrip().__class__, str) |
---|
2787 | n/a | self.assertEqual(u.rstrip(), base) |
---|
2788 | n/a | self.assertIs(u.replace("x", "x").__class__, str) |
---|
2789 | n/a | self.assertEqual(u.replace("x", "x"), base) |
---|
2790 | n/a | self.assertIs(u.replace("xy", "xy").__class__, str) |
---|
2791 | n/a | self.assertEqual(u.replace("xy", "xy"), base) |
---|
2792 | n/a | self.assertIs(u.center(len(u)).__class__, str) |
---|
2793 | n/a | self.assertEqual(u.center(len(u)), base) |
---|
2794 | n/a | self.assertIs(u.ljust(len(u)).__class__, str) |
---|
2795 | n/a | self.assertEqual(u.ljust(len(u)), base) |
---|
2796 | n/a | self.assertIs(u.rjust(len(u)).__class__, str) |
---|
2797 | n/a | self.assertEqual(u.rjust(len(u)), base) |
---|
2798 | n/a | self.assertIs(u.lower().__class__, str) |
---|
2799 | n/a | self.assertEqual(u.lower(), base) |
---|
2800 | n/a | self.assertIs(u.upper().__class__, str) |
---|
2801 | n/a | self.assertEqual(u.upper(), base) |
---|
2802 | n/a | self.assertIs(u.capitalize().__class__, str) |
---|
2803 | n/a | self.assertEqual(u.capitalize(), base) |
---|
2804 | n/a | self.assertIs(u.title().__class__, str) |
---|
2805 | n/a | self.assertEqual(u.title(), base) |
---|
2806 | n/a | self.assertIs((u + "").__class__, str) |
---|
2807 | n/a | self.assertEqual(u + "", base) |
---|
2808 | n/a | self.assertIs(("" + u).__class__, str) |
---|
2809 | n/a | self.assertEqual("" + u, base) |
---|
2810 | n/a | self.assertIs((u * 0).__class__, str) |
---|
2811 | n/a | self.assertEqual(u * 0, "") |
---|
2812 | n/a | self.assertIs((u * 1).__class__, str) |
---|
2813 | n/a | self.assertEqual(u * 1, base) |
---|
2814 | n/a | self.assertIs((u * 2).__class__, str) |
---|
2815 | n/a | self.assertEqual(u * 2, base + base) |
---|
2816 | n/a | self.assertIs(u[:].__class__, str) |
---|
2817 | n/a | self.assertEqual(u[:], base) |
---|
2818 | n/a | self.assertIs(u[0:0].__class__, str) |
---|
2819 | n/a | self.assertEqual(u[0:0], "") |
---|
2820 | n/a | |
---|
2821 | n/a | class sublist(list): |
---|
2822 | n/a | pass |
---|
2823 | n/a | a = sublist(range(5)) |
---|
2824 | n/a | self.assertEqual(a, list(range(5))) |
---|
2825 | n/a | a.append("hello") |
---|
2826 | n/a | self.assertEqual(a, list(range(5)) + ["hello"]) |
---|
2827 | n/a | a[5] = 5 |
---|
2828 | n/a | self.assertEqual(a, list(range(6))) |
---|
2829 | n/a | a.extend(range(6, 20)) |
---|
2830 | n/a | self.assertEqual(a, list(range(20))) |
---|
2831 | n/a | a[-5:] = [] |
---|
2832 | n/a | self.assertEqual(a, list(range(15))) |
---|
2833 | n/a | del a[10:15] |
---|
2834 | n/a | self.assertEqual(len(a), 10) |
---|
2835 | n/a | self.assertEqual(a, list(range(10))) |
---|
2836 | n/a | self.assertEqual(list(a), list(range(10))) |
---|
2837 | n/a | self.assertEqual(a[0], 0) |
---|
2838 | n/a | self.assertEqual(a[9], 9) |
---|
2839 | n/a | self.assertEqual(a[-10], 0) |
---|
2840 | n/a | self.assertEqual(a[-1], 9) |
---|
2841 | n/a | self.assertEqual(a[:5], list(range(5))) |
---|
2842 | n/a | |
---|
2843 | n/a | ## class CountedInput(file): |
---|
2844 | n/a | ## """Counts lines read by self.readline(). |
---|
2845 | n/a | ## |
---|
2846 | n/a | ## self.lineno is the 0-based ordinal of the last line read, up to |
---|
2847 | n/a | ## a maximum of one greater than the number of lines in the file. |
---|
2848 | n/a | ## |
---|
2849 | n/a | ## self.ateof is true if and only if the final "" line has been read, |
---|
2850 | n/a | ## at which point self.lineno stops incrementing, and further calls |
---|
2851 | n/a | ## to readline() continue to return "". |
---|
2852 | n/a | ## """ |
---|
2853 | n/a | ## |
---|
2854 | n/a | ## lineno = 0 |
---|
2855 | n/a | ## ateof = 0 |
---|
2856 | n/a | ## def readline(self): |
---|
2857 | n/a | ## if self.ateof: |
---|
2858 | n/a | ## return "" |
---|
2859 | n/a | ## s = file.readline(self) |
---|
2860 | n/a | ## # Next line works too. |
---|
2861 | n/a | ## # s = super(CountedInput, self).readline() |
---|
2862 | n/a | ## self.lineno += 1 |
---|
2863 | n/a | ## if s == "": |
---|
2864 | n/a | ## self.ateof = 1 |
---|
2865 | n/a | ## return s |
---|
2866 | n/a | ## |
---|
2867 | n/a | ## f = file(name=support.TESTFN, mode='w') |
---|
2868 | n/a | ## lines = ['a\n', 'b\n', 'c\n'] |
---|
2869 | n/a | ## try: |
---|
2870 | n/a | ## f.writelines(lines) |
---|
2871 | n/a | ## f.close() |
---|
2872 | n/a | ## f = CountedInput(support.TESTFN) |
---|
2873 | n/a | ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): |
---|
2874 | n/a | ## got = f.readline() |
---|
2875 | n/a | ## self.assertEqual(expected, got) |
---|
2876 | n/a | ## self.assertEqual(f.lineno, i) |
---|
2877 | n/a | ## self.assertEqual(f.ateof, (i > len(lines))) |
---|
2878 | n/a | ## f.close() |
---|
2879 | n/a | ## finally: |
---|
2880 | n/a | ## try: |
---|
2881 | n/a | ## f.close() |
---|
2882 | n/a | ## except: |
---|
2883 | n/a | ## pass |
---|
2884 | n/a | ## support.unlink(support.TESTFN) |
---|
2885 | n/a | |
---|
2886 | n/a | def test_keywords(self): |
---|
2887 | n/a | # Testing keyword args to basic type constructors ... |
---|
2888 | n/a | self.assertEqual(int(x=1), 1) |
---|
2889 | n/a | self.assertEqual(float(x=2), 2.0) |
---|
2890 | n/a | self.assertEqual(int(x=3), 3) |
---|
2891 | n/a | self.assertEqual(complex(imag=42, real=666), complex(666, 42)) |
---|
2892 | n/a | self.assertEqual(str(object=500), '500') |
---|
2893 | n/a | self.assertEqual(str(object=b'abc', errors='strict'), 'abc') |
---|
2894 | n/a | self.assertEqual(tuple(sequence=range(3)), (0, 1, 2)) |
---|
2895 | n/a | self.assertEqual(list(sequence=(0, 1, 2)), list(range(3))) |
---|
2896 | n/a | # note: as of Python 2.3, dict() no longer has an "items" keyword arg |
---|
2897 | n/a | |
---|
2898 | n/a | for constructor in (int, float, int, complex, str, str, |
---|
2899 | n/a | tuple, list): |
---|
2900 | n/a | try: |
---|
2901 | n/a | constructor(bogus_keyword_arg=1) |
---|
2902 | n/a | except TypeError: |
---|
2903 | n/a | pass |
---|
2904 | n/a | else: |
---|
2905 | n/a | self.fail("expected TypeError from bogus keyword argument to %r" |
---|
2906 | n/a | % constructor) |
---|
2907 | n/a | |
---|
2908 | n/a | def test_str_subclass_as_dict_key(self): |
---|
2909 | n/a | # Testing a str subclass used as dict key .. |
---|
2910 | n/a | |
---|
2911 | n/a | class cistr(str): |
---|
2912 | n/a | """Sublcass of str that computes __eq__ case-insensitively. |
---|
2913 | n/a | |
---|
2914 | n/a | Also computes a hash code of the string in canonical form. |
---|
2915 | n/a | """ |
---|
2916 | n/a | |
---|
2917 | n/a | def __init__(self, value): |
---|
2918 | n/a | self.canonical = value.lower() |
---|
2919 | n/a | self.hashcode = hash(self.canonical) |
---|
2920 | n/a | |
---|
2921 | n/a | def __eq__(self, other): |
---|
2922 | n/a | if not isinstance(other, cistr): |
---|
2923 | n/a | other = cistr(other) |
---|
2924 | n/a | return self.canonical == other.canonical |
---|
2925 | n/a | |
---|
2926 | n/a | def __hash__(self): |
---|
2927 | n/a | return self.hashcode |
---|
2928 | n/a | |
---|
2929 | n/a | self.assertEqual(cistr('ABC'), 'abc') |
---|
2930 | n/a | self.assertEqual('aBc', cistr('ABC')) |
---|
2931 | n/a | self.assertEqual(str(cistr('ABC')), 'ABC') |
---|
2932 | n/a | |
---|
2933 | n/a | d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} |
---|
2934 | n/a | self.assertEqual(d[cistr('one')], 1) |
---|
2935 | n/a | self.assertEqual(d[cistr('tWo')], 2) |
---|
2936 | n/a | self.assertEqual(d[cistr('THrEE')], 3) |
---|
2937 | n/a | self.assertIn(cistr('ONe'), d) |
---|
2938 | n/a | self.assertEqual(d.get(cistr('thrEE')), 3) |
---|
2939 | n/a | |
---|
2940 | n/a | def test_classic_comparisons(self): |
---|
2941 | n/a | # Testing classic comparisons... |
---|
2942 | n/a | class classic: |
---|
2943 | n/a | pass |
---|
2944 | n/a | |
---|
2945 | n/a | for base in (classic, int, object): |
---|
2946 | n/a | class C(base): |
---|
2947 | n/a | def __init__(self, value): |
---|
2948 | n/a | self.value = int(value) |
---|
2949 | n/a | def __eq__(self, other): |
---|
2950 | n/a | if isinstance(other, C): |
---|
2951 | n/a | return self.value == other.value |
---|
2952 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2953 | n/a | return self.value == other |
---|
2954 | n/a | return NotImplemented |
---|
2955 | n/a | def __ne__(self, other): |
---|
2956 | n/a | if isinstance(other, C): |
---|
2957 | n/a | return self.value != other.value |
---|
2958 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2959 | n/a | return self.value != other |
---|
2960 | n/a | return NotImplemented |
---|
2961 | n/a | def __lt__(self, other): |
---|
2962 | n/a | if isinstance(other, C): |
---|
2963 | n/a | return self.value < other.value |
---|
2964 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2965 | n/a | return self.value < other |
---|
2966 | n/a | return NotImplemented |
---|
2967 | n/a | def __le__(self, other): |
---|
2968 | n/a | if isinstance(other, C): |
---|
2969 | n/a | return self.value <= other.value |
---|
2970 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2971 | n/a | return self.value <= other |
---|
2972 | n/a | return NotImplemented |
---|
2973 | n/a | def __gt__(self, other): |
---|
2974 | n/a | if isinstance(other, C): |
---|
2975 | n/a | return self.value > other.value |
---|
2976 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2977 | n/a | return self.value > other |
---|
2978 | n/a | return NotImplemented |
---|
2979 | n/a | def __ge__(self, other): |
---|
2980 | n/a | if isinstance(other, C): |
---|
2981 | n/a | return self.value >= other.value |
---|
2982 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
2983 | n/a | return self.value >= other |
---|
2984 | n/a | return NotImplemented |
---|
2985 | n/a | |
---|
2986 | n/a | c1 = C(1) |
---|
2987 | n/a | c2 = C(2) |
---|
2988 | n/a | c3 = C(3) |
---|
2989 | n/a | self.assertEqual(c1, 1) |
---|
2990 | n/a | c = {1: c1, 2: c2, 3: c3} |
---|
2991 | n/a | for x in 1, 2, 3: |
---|
2992 | n/a | for y in 1, 2, 3: |
---|
2993 | n/a | for op in "<", "<=", "==", "!=", ">", ">=": |
---|
2994 | n/a | self.assertEqual(eval("c[x] %s c[y]" % op), |
---|
2995 | n/a | eval("x %s y" % op), |
---|
2996 | n/a | "x=%d, y=%d" % (x, y)) |
---|
2997 | n/a | self.assertEqual(eval("c[x] %s y" % op), |
---|
2998 | n/a | eval("x %s y" % op), |
---|
2999 | n/a | "x=%d, y=%d" % (x, y)) |
---|
3000 | n/a | self.assertEqual(eval("x %s c[y]" % op), |
---|
3001 | n/a | eval("x %s y" % op), |
---|
3002 | n/a | "x=%d, y=%d" % (x, y)) |
---|
3003 | n/a | |
---|
3004 | n/a | def test_rich_comparisons(self): |
---|
3005 | n/a | # Testing rich comparisons... |
---|
3006 | n/a | class Z(complex): |
---|
3007 | n/a | pass |
---|
3008 | n/a | z = Z(1) |
---|
3009 | n/a | self.assertEqual(z, 1+0j) |
---|
3010 | n/a | self.assertEqual(1+0j, z) |
---|
3011 | n/a | class ZZ(complex): |
---|
3012 | n/a | def __eq__(self, other): |
---|
3013 | n/a | try: |
---|
3014 | n/a | return abs(self - other) <= 1e-6 |
---|
3015 | n/a | except: |
---|
3016 | n/a | return NotImplemented |
---|
3017 | n/a | zz = ZZ(1.0000003) |
---|
3018 | n/a | self.assertEqual(zz, 1+0j) |
---|
3019 | n/a | self.assertEqual(1+0j, zz) |
---|
3020 | n/a | |
---|
3021 | n/a | class classic: |
---|
3022 | n/a | pass |
---|
3023 | n/a | for base in (classic, int, object, list): |
---|
3024 | n/a | class C(base): |
---|
3025 | n/a | def __init__(self, value): |
---|
3026 | n/a | self.value = int(value) |
---|
3027 | n/a | def __cmp__(self_, other): |
---|
3028 | n/a | self.fail("shouldn't call __cmp__") |
---|
3029 | n/a | def __eq__(self, other): |
---|
3030 | n/a | if isinstance(other, C): |
---|
3031 | n/a | return self.value == other.value |
---|
3032 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3033 | n/a | return self.value == other |
---|
3034 | n/a | return NotImplemented |
---|
3035 | n/a | def __ne__(self, other): |
---|
3036 | n/a | if isinstance(other, C): |
---|
3037 | n/a | return self.value != other.value |
---|
3038 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3039 | n/a | return self.value != other |
---|
3040 | n/a | return NotImplemented |
---|
3041 | n/a | def __lt__(self, other): |
---|
3042 | n/a | if isinstance(other, C): |
---|
3043 | n/a | return self.value < other.value |
---|
3044 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3045 | n/a | return self.value < other |
---|
3046 | n/a | return NotImplemented |
---|
3047 | n/a | def __le__(self, other): |
---|
3048 | n/a | if isinstance(other, C): |
---|
3049 | n/a | return self.value <= other.value |
---|
3050 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3051 | n/a | return self.value <= other |
---|
3052 | n/a | return NotImplemented |
---|
3053 | n/a | def __gt__(self, other): |
---|
3054 | n/a | if isinstance(other, C): |
---|
3055 | n/a | return self.value > other.value |
---|
3056 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3057 | n/a | return self.value > other |
---|
3058 | n/a | return NotImplemented |
---|
3059 | n/a | def __ge__(self, other): |
---|
3060 | n/a | if isinstance(other, C): |
---|
3061 | n/a | return self.value >= other.value |
---|
3062 | n/a | if isinstance(other, int) or isinstance(other, int): |
---|
3063 | n/a | return self.value >= other |
---|
3064 | n/a | return NotImplemented |
---|
3065 | n/a | c1 = C(1) |
---|
3066 | n/a | c2 = C(2) |
---|
3067 | n/a | c3 = C(3) |
---|
3068 | n/a | self.assertEqual(c1, 1) |
---|
3069 | n/a | c = {1: c1, 2: c2, 3: c3} |
---|
3070 | n/a | for x in 1, 2, 3: |
---|
3071 | n/a | for y in 1, 2, 3: |
---|
3072 | n/a | for op in "<", "<=", "==", "!=", ">", ">=": |
---|
3073 | n/a | self.assertEqual(eval("c[x] %s c[y]" % op), |
---|
3074 | n/a | eval("x %s y" % op), |
---|
3075 | n/a | "x=%d, y=%d" % (x, y)) |
---|
3076 | n/a | self.assertEqual(eval("c[x] %s y" % op), |
---|
3077 | n/a | eval("x %s y" % op), |
---|
3078 | n/a | "x=%d, y=%d" % (x, y)) |
---|
3079 | n/a | self.assertEqual(eval("x %s c[y]" % op), |
---|
3080 | n/a | eval("x %s y" % op), |
---|
3081 | n/a | "x=%d, y=%d" % (x, y)) |
---|
3082 | n/a | |
---|
3083 | n/a | def test_descrdoc(self): |
---|
3084 | n/a | # Testing descriptor doc strings... |
---|
3085 | n/a | from _io import FileIO |
---|
3086 | n/a | def check(descr, what): |
---|
3087 | n/a | self.assertEqual(descr.__doc__, what) |
---|
3088 | n/a | check(FileIO.closed, "True if the file is closed") # getset descriptor |
---|
3089 | n/a | check(complex.real, "the real part of a complex number") # member descriptor |
---|
3090 | n/a | |
---|
3091 | n/a | def test_doc_descriptor(self): |
---|
3092 | n/a | # Testing __doc__ descriptor... |
---|
3093 | n/a | # SF bug 542984 |
---|
3094 | n/a | class DocDescr(object): |
---|
3095 | n/a | def __get__(self, object, otype): |
---|
3096 | n/a | if object: |
---|
3097 | n/a | object = object.__class__.__name__ + ' instance' |
---|
3098 | n/a | if otype: |
---|
3099 | n/a | otype = otype.__name__ |
---|
3100 | n/a | return 'object=%s; type=%s' % (object, otype) |
---|
3101 | n/a | class OldClass: |
---|
3102 | n/a | __doc__ = DocDescr() |
---|
3103 | n/a | class NewClass(object): |
---|
3104 | n/a | __doc__ = DocDescr() |
---|
3105 | n/a | self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass') |
---|
3106 | n/a | self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass') |
---|
3107 | n/a | self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass') |
---|
3108 | n/a | self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass') |
---|
3109 | n/a | |
---|
3110 | n/a | def test_set_class(self): |
---|
3111 | n/a | # Testing __class__ assignment... |
---|
3112 | n/a | class C(object): pass |
---|
3113 | n/a | class D(object): pass |
---|
3114 | n/a | class E(object): pass |
---|
3115 | n/a | class F(D, E): pass |
---|
3116 | n/a | for cls in C, D, E, F: |
---|
3117 | n/a | for cls2 in C, D, E, F: |
---|
3118 | n/a | x = cls() |
---|
3119 | n/a | x.__class__ = cls2 |
---|
3120 | n/a | self.assertIs(x.__class__, cls2) |
---|
3121 | n/a | x.__class__ = cls |
---|
3122 | n/a | self.assertIs(x.__class__, cls) |
---|
3123 | n/a | def cant(x, C): |
---|
3124 | n/a | try: |
---|
3125 | n/a | x.__class__ = C |
---|
3126 | n/a | except TypeError: |
---|
3127 | n/a | pass |
---|
3128 | n/a | else: |
---|
3129 | n/a | self.fail("shouldn't allow %r.__class__ = %r" % (x, C)) |
---|
3130 | n/a | try: |
---|
3131 | n/a | delattr(x, "__class__") |
---|
3132 | n/a | except (TypeError, AttributeError): |
---|
3133 | n/a | pass |
---|
3134 | n/a | else: |
---|
3135 | n/a | self.fail("shouldn't allow del %r.__class__" % x) |
---|
3136 | n/a | cant(C(), list) |
---|
3137 | n/a | cant(list(), C) |
---|
3138 | n/a | cant(C(), 1) |
---|
3139 | n/a | cant(C(), object) |
---|
3140 | n/a | cant(object(), list) |
---|
3141 | n/a | cant(list(), object) |
---|
3142 | n/a | class Int(int): __slots__ = [] |
---|
3143 | n/a | cant(True, int) |
---|
3144 | n/a | cant(2, bool) |
---|
3145 | n/a | o = object() |
---|
3146 | n/a | cant(o, type(1)) |
---|
3147 | n/a | cant(o, type(None)) |
---|
3148 | n/a | del o |
---|
3149 | n/a | class G(object): |
---|
3150 | n/a | __slots__ = ["a", "b"] |
---|
3151 | n/a | class H(object): |
---|
3152 | n/a | __slots__ = ["b", "a"] |
---|
3153 | n/a | class I(object): |
---|
3154 | n/a | __slots__ = ["a", "b"] |
---|
3155 | n/a | class J(object): |
---|
3156 | n/a | __slots__ = ["c", "b"] |
---|
3157 | n/a | class K(object): |
---|
3158 | n/a | __slots__ = ["a", "b", "d"] |
---|
3159 | n/a | class L(H): |
---|
3160 | n/a | __slots__ = ["e"] |
---|
3161 | n/a | class M(I): |
---|
3162 | n/a | __slots__ = ["e"] |
---|
3163 | n/a | class N(J): |
---|
3164 | n/a | __slots__ = ["__weakref__"] |
---|
3165 | n/a | class P(J): |
---|
3166 | n/a | __slots__ = ["__dict__"] |
---|
3167 | n/a | class Q(J): |
---|
3168 | n/a | pass |
---|
3169 | n/a | class R(J): |
---|
3170 | n/a | __slots__ = ["__dict__", "__weakref__"] |
---|
3171 | n/a | |
---|
3172 | n/a | for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)): |
---|
3173 | n/a | x = cls() |
---|
3174 | n/a | x.a = 1 |
---|
3175 | n/a | x.__class__ = cls2 |
---|
3176 | n/a | self.assertIs(x.__class__, cls2, |
---|
3177 | n/a | "assigning %r as __class__ for %r silently failed" % (cls2, x)) |
---|
3178 | n/a | self.assertEqual(x.a, 1) |
---|
3179 | n/a | x.__class__ = cls |
---|
3180 | n/a | self.assertIs(x.__class__, cls, |
---|
3181 | n/a | "assigning %r as __class__ for %r silently failed" % (cls, x)) |
---|
3182 | n/a | self.assertEqual(x.a, 1) |
---|
3183 | n/a | for cls in G, J, K, L, M, N, P, R, list, Int: |
---|
3184 | n/a | for cls2 in G, J, K, L, M, N, P, R, list, Int: |
---|
3185 | n/a | if cls is cls2: |
---|
3186 | n/a | continue |
---|
3187 | n/a | cant(cls(), cls2) |
---|
3188 | n/a | |
---|
3189 | n/a | # Issue5283: when __class__ changes in __del__, the wrong |
---|
3190 | n/a | # type gets DECREF'd. |
---|
3191 | n/a | class O(object): |
---|
3192 | n/a | pass |
---|
3193 | n/a | class A(object): |
---|
3194 | n/a | def __del__(self): |
---|
3195 | n/a | self.__class__ = O |
---|
3196 | n/a | l = [A() for x in range(100)] |
---|
3197 | n/a | del l |
---|
3198 | n/a | |
---|
3199 | n/a | def test_set_dict(self): |
---|
3200 | n/a | # Testing __dict__ assignment... |
---|
3201 | n/a | class C(object): pass |
---|
3202 | n/a | a = C() |
---|
3203 | n/a | a.__dict__ = {'b': 1} |
---|
3204 | n/a | self.assertEqual(a.b, 1) |
---|
3205 | n/a | def cant(x, dict): |
---|
3206 | n/a | try: |
---|
3207 | n/a | x.__dict__ = dict |
---|
3208 | n/a | except (AttributeError, TypeError): |
---|
3209 | n/a | pass |
---|
3210 | n/a | else: |
---|
3211 | n/a | self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict)) |
---|
3212 | n/a | cant(a, None) |
---|
3213 | n/a | cant(a, []) |
---|
3214 | n/a | cant(a, 1) |
---|
3215 | n/a | del a.__dict__ # Deleting __dict__ is allowed |
---|
3216 | n/a | |
---|
3217 | n/a | class Base(object): |
---|
3218 | n/a | pass |
---|
3219 | n/a | def verify_dict_readonly(x): |
---|
3220 | n/a | """ |
---|
3221 | n/a | x has to be an instance of a class inheriting from Base. |
---|
3222 | n/a | """ |
---|
3223 | n/a | cant(x, {}) |
---|
3224 | n/a | try: |
---|
3225 | n/a | del x.__dict__ |
---|
3226 | n/a | except (AttributeError, TypeError): |
---|
3227 | n/a | pass |
---|
3228 | n/a | else: |
---|
3229 | n/a | self.fail("shouldn't allow del %r.__dict__" % x) |
---|
3230 | n/a | dict_descr = Base.__dict__["__dict__"] |
---|
3231 | n/a | try: |
---|
3232 | n/a | dict_descr.__set__(x, {}) |
---|
3233 | n/a | except (AttributeError, TypeError): |
---|
3234 | n/a | pass |
---|
3235 | n/a | else: |
---|
3236 | n/a | self.fail("dict_descr allowed access to %r's dict" % x) |
---|
3237 | n/a | |
---|
3238 | n/a | # Classes don't allow __dict__ assignment and have readonly dicts |
---|
3239 | n/a | class Meta1(type, Base): |
---|
3240 | n/a | pass |
---|
3241 | n/a | class Meta2(Base, type): |
---|
3242 | n/a | pass |
---|
3243 | n/a | class D(object, metaclass=Meta1): |
---|
3244 | n/a | pass |
---|
3245 | n/a | class E(object, metaclass=Meta2): |
---|
3246 | n/a | pass |
---|
3247 | n/a | for cls in C, D, E: |
---|
3248 | n/a | verify_dict_readonly(cls) |
---|
3249 | n/a | class_dict = cls.__dict__ |
---|
3250 | n/a | try: |
---|
3251 | n/a | class_dict["spam"] = "eggs" |
---|
3252 | n/a | except TypeError: |
---|
3253 | n/a | pass |
---|
3254 | n/a | else: |
---|
3255 | n/a | self.fail("%r's __dict__ can be modified" % cls) |
---|
3256 | n/a | |
---|
3257 | n/a | # Modules also disallow __dict__ assignment |
---|
3258 | n/a | class Module1(types.ModuleType, Base): |
---|
3259 | n/a | pass |
---|
3260 | n/a | class Module2(Base, types.ModuleType): |
---|
3261 | n/a | pass |
---|
3262 | n/a | for ModuleType in Module1, Module2: |
---|
3263 | n/a | mod = ModuleType("spam") |
---|
3264 | n/a | verify_dict_readonly(mod) |
---|
3265 | n/a | mod.__dict__["spam"] = "eggs" |
---|
3266 | n/a | |
---|
3267 | n/a | # Exception's __dict__ can be replaced, but not deleted |
---|
3268 | n/a | # (at least not any more than regular exception's __dict__ can |
---|
3269 | n/a | # be deleted; on CPython it is not the case, whereas on PyPy they |
---|
3270 | n/a | # can, just like any other new-style instance's __dict__.) |
---|
3271 | n/a | def can_delete_dict(e): |
---|
3272 | n/a | try: |
---|
3273 | n/a | del e.__dict__ |
---|
3274 | n/a | except (TypeError, AttributeError): |
---|
3275 | n/a | return False |
---|
3276 | n/a | else: |
---|
3277 | n/a | return True |
---|
3278 | n/a | class Exception1(Exception, Base): |
---|
3279 | n/a | pass |
---|
3280 | n/a | class Exception2(Base, Exception): |
---|
3281 | n/a | pass |
---|
3282 | n/a | for ExceptionType in Exception, Exception1, Exception2: |
---|
3283 | n/a | e = ExceptionType() |
---|
3284 | n/a | e.__dict__ = {"a": 1} |
---|
3285 | n/a | self.assertEqual(e.a, 1) |
---|
3286 | n/a | self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError())) |
---|
3287 | n/a | |
---|
3288 | n/a | def test_binary_operator_override(self): |
---|
3289 | n/a | # Testing overrides of binary operations... |
---|
3290 | n/a | class I(int): |
---|
3291 | n/a | def __repr__(self): |
---|
3292 | n/a | return "I(%r)" % int(self) |
---|
3293 | n/a | def __add__(self, other): |
---|
3294 | n/a | return I(int(self) + int(other)) |
---|
3295 | n/a | __radd__ = __add__ |
---|
3296 | n/a | def __pow__(self, other, mod=None): |
---|
3297 | n/a | if mod is None: |
---|
3298 | n/a | return I(pow(int(self), int(other))) |
---|
3299 | n/a | else: |
---|
3300 | n/a | return I(pow(int(self), int(other), int(mod))) |
---|
3301 | n/a | def __rpow__(self, other, mod=None): |
---|
3302 | n/a | if mod is None: |
---|
3303 | n/a | return I(pow(int(other), int(self), mod)) |
---|
3304 | n/a | else: |
---|
3305 | n/a | return I(pow(int(other), int(self), int(mod))) |
---|
3306 | n/a | |
---|
3307 | n/a | self.assertEqual(repr(I(1) + I(2)), "I(3)") |
---|
3308 | n/a | self.assertEqual(repr(I(1) + 2), "I(3)") |
---|
3309 | n/a | self.assertEqual(repr(1 + I(2)), "I(3)") |
---|
3310 | n/a | self.assertEqual(repr(I(2) ** I(3)), "I(8)") |
---|
3311 | n/a | self.assertEqual(repr(2 ** I(3)), "I(8)") |
---|
3312 | n/a | self.assertEqual(repr(I(2) ** 3), "I(8)") |
---|
3313 | n/a | self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)") |
---|
3314 | n/a | class S(str): |
---|
3315 | n/a | def __eq__(self, other): |
---|
3316 | n/a | return self.lower() == other.lower() |
---|
3317 | n/a | |
---|
3318 | n/a | def test_subclass_propagation(self): |
---|
3319 | n/a | # Testing propagation of slot functions to subclasses... |
---|
3320 | n/a | class A(object): |
---|
3321 | n/a | pass |
---|
3322 | n/a | class B(A): |
---|
3323 | n/a | pass |
---|
3324 | n/a | class C(A): |
---|
3325 | n/a | pass |
---|
3326 | n/a | class D(B, C): |
---|
3327 | n/a | pass |
---|
3328 | n/a | d = D() |
---|
3329 | n/a | orig_hash = hash(d) # related to id(d) in platform-dependent ways |
---|
3330 | n/a | A.__hash__ = lambda self: 42 |
---|
3331 | n/a | self.assertEqual(hash(d), 42) |
---|
3332 | n/a | C.__hash__ = lambda self: 314 |
---|
3333 | n/a | self.assertEqual(hash(d), 314) |
---|
3334 | n/a | B.__hash__ = lambda self: 144 |
---|
3335 | n/a | self.assertEqual(hash(d), 144) |
---|
3336 | n/a | D.__hash__ = lambda self: 100 |
---|
3337 | n/a | self.assertEqual(hash(d), 100) |
---|
3338 | n/a | D.__hash__ = None |
---|
3339 | n/a | self.assertRaises(TypeError, hash, d) |
---|
3340 | n/a | del D.__hash__ |
---|
3341 | n/a | self.assertEqual(hash(d), 144) |
---|
3342 | n/a | B.__hash__ = None |
---|
3343 | n/a | self.assertRaises(TypeError, hash, d) |
---|
3344 | n/a | del B.__hash__ |
---|
3345 | n/a | self.assertEqual(hash(d), 314) |
---|
3346 | n/a | C.__hash__ = None |
---|
3347 | n/a | self.assertRaises(TypeError, hash, d) |
---|
3348 | n/a | del C.__hash__ |
---|
3349 | n/a | self.assertEqual(hash(d), 42) |
---|
3350 | n/a | A.__hash__ = None |
---|
3351 | n/a | self.assertRaises(TypeError, hash, d) |
---|
3352 | n/a | del A.__hash__ |
---|
3353 | n/a | self.assertEqual(hash(d), orig_hash) |
---|
3354 | n/a | d.foo = 42 |
---|
3355 | n/a | d.bar = 42 |
---|
3356 | n/a | self.assertEqual(d.foo, 42) |
---|
3357 | n/a | self.assertEqual(d.bar, 42) |
---|
3358 | n/a | def __getattribute__(self, name): |
---|
3359 | n/a | if name == "foo": |
---|
3360 | n/a | return 24 |
---|
3361 | n/a | return object.__getattribute__(self, name) |
---|
3362 | n/a | A.__getattribute__ = __getattribute__ |
---|
3363 | n/a | self.assertEqual(d.foo, 24) |
---|
3364 | n/a | self.assertEqual(d.bar, 42) |
---|
3365 | n/a | def __getattr__(self, name): |
---|
3366 | n/a | if name in ("spam", "foo", "bar"): |
---|
3367 | n/a | return "hello" |
---|
3368 | n/a | raise AttributeError(name) |
---|
3369 | n/a | B.__getattr__ = __getattr__ |
---|
3370 | n/a | self.assertEqual(d.spam, "hello") |
---|
3371 | n/a | self.assertEqual(d.foo, 24) |
---|
3372 | n/a | self.assertEqual(d.bar, 42) |
---|
3373 | n/a | del A.__getattribute__ |
---|
3374 | n/a | self.assertEqual(d.foo, 42) |
---|
3375 | n/a | del d.foo |
---|
3376 | n/a | self.assertEqual(d.foo, "hello") |
---|
3377 | n/a | self.assertEqual(d.bar, 42) |
---|
3378 | n/a | del B.__getattr__ |
---|
3379 | n/a | try: |
---|
3380 | n/a | d.foo |
---|
3381 | n/a | except AttributeError: |
---|
3382 | n/a | pass |
---|
3383 | n/a | else: |
---|
3384 | n/a | self.fail("d.foo should be undefined now") |
---|
3385 | n/a | |
---|
3386 | n/a | # Test a nasty bug in recurse_down_subclasses() |
---|
3387 | n/a | class A(object): |
---|
3388 | n/a | pass |
---|
3389 | n/a | class B(A): |
---|
3390 | n/a | pass |
---|
3391 | n/a | del B |
---|
3392 | n/a | support.gc_collect() |
---|
3393 | n/a | A.__setitem__ = lambda *a: None # crash |
---|
3394 | n/a | |
---|
3395 | n/a | def test_buffer_inheritance(self): |
---|
3396 | n/a | # Testing that buffer interface is inherited ... |
---|
3397 | n/a | |
---|
3398 | n/a | import binascii |
---|
3399 | n/a | # SF bug [#470040] ParseTuple t# vs subclasses. |
---|
3400 | n/a | |
---|
3401 | n/a | class MyBytes(bytes): |
---|
3402 | n/a | pass |
---|
3403 | n/a | base = b'abc' |
---|
3404 | n/a | m = MyBytes(base) |
---|
3405 | n/a | # b2a_hex uses the buffer interface to get its argument's value, via |
---|
3406 | n/a | # PyArg_ParseTuple 't#' code. |
---|
3407 | n/a | self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base)) |
---|
3408 | n/a | |
---|
3409 | n/a | class MyInt(int): |
---|
3410 | n/a | pass |
---|
3411 | n/a | m = MyInt(42) |
---|
3412 | n/a | try: |
---|
3413 | n/a | binascii.b2a_hex(m) |
---|
3414 | n/a | self.fail('subclass of int should not have a buffer interface') |
---|
3415 | n/a | except TypeError: |
---|
3416 | n/a | pass |
---|
3417 | n/a | |
---|
3418 | n/a | def test_str_of_str_subclass(self): |
---|
3419 | n/a | # Testing __str__ defined in subclass of str ... |
---|
3420 | n/a | import binascii |
---|
3421 | n/a | import io |
---|
3422 | n/a | |
---|
3423 | n/a | class octetstring(str): |
---|
3424 | n/a | def __str__(self): |
---|
3425 | n/a | return binascii.b2a_hex(self.encode('ascii')).decode("ascii") |
---|
3426 | n/a | def __repr__(self): |
---|
3427 | n/a | return self + " repr" |
---|
3428 | n/a | |
---|
3429 | n/a | o = octetstring('A') |
---|
3430 | n/a | self.assertEqual(type(o), octetstring) |
---|
3431 | n/a | self.assertEqual(type(str(o)), str) |
---|
3432 | n/a | self.assertEqual(type(repr(o)), str) |
---|
3433 | n/a | self.assertEqual(ord(o), 0x41) |
---|
3434 | n/a | self.assertEqual(str(o), '41') |
---|
3435 | n/a | self.assertEqual(repr(o), 'A repr') |
---|
3436 | n/a | self.assertEqual(o.__str__(), '41') |
---|
3437 | n/a | self.assertEqual(o.__repr__(), 'A repr') |
---|
3438 | n/a | |
---|
3439 | n/a | capture = io.StringIO() |
---|
3440 | n/a | # Calling str() or not exercises different internal paths. |
---|
3441 | n/a | print(o, file=capture) |
---|
3442 | n/a | print(str(o), file=capture) |
---|
3443 | n/a | self.assertEqual(capture.getvalue(), '41\n41\n') |
---|
3444 | n/a | capture.close() |
---|
3445 | n/a | |
---|
3446 | n/a | def test_keyword_arguments(self): |
---|
3447 | n/a | # Testing keyword arguments to __init__, __call__... |
---|
3448 | n/a | def f(a): return a |
---|
3449 | n/a | self.assertEqual(f.__call__(a=42), 42) |
---|
3450 | n/a | a = [] |
---|
3451 | n/a | list.__init__(a, sequence=[0, 1, 2]) |
---|
3452 | n/a | self.assertEqual(a, [0, 1, 2]) |
---|
3453 | n/a | |
---|
3454 | n/a | def test_recursive_call(self): |
---|
3455 | n/a | # Testing recursive __call__() by setting to instance of class... |
---|
3456 | n/a | class A(object): |
---|
3457 | n/a | pass |
---|
3458 | n/a | |
---|
3459 | n/a | A.__call__ = A() |
---|
3460 | n/a | try: |
---|
3461 | n/a | A()() |
---|
3462 | n/a | except RecursionError: |
---|
3463 | n/a | pass |
---|
3464 | n/a | else: |
---|
3465 | n/a | self.fail("Recursion limit should have been reached for __call__()") |
---|
3466 | n/a | |
---|
3467 | n/a | def test_delete_hook(self): |
---|
3468 | n/a | # Testing __del__ hook... |
---|
3469 | n/a | log = [] |
---|
3470 | n/a | class C(object): |
---|
3471 | n/a | def __del__(self): |
---|
3472 | n/a | log.append(1) |
---|
3473 | n/a | c = C() |
---|
3474 | n/a | self.assertEqual(log, []) |
---|
3475 | n/a | del c |
---|
3476 | n/a | support.gc_collect() |
---|
3477 | n/a | self.assertEqual(log, [1]) |
---|
3478 | n/a | |
---|
3479 | n/a | class D(object): pass |
---|
3480 | n/a | d = D() |
---|
3481 | n/a | try: del d[0] |
---|
3482 | n/a | except TypeError: pass |
---|
3483 | n/a | else: self.fail("invalid del() didn't raise TypeError") |
---|
3484 | n/a | |
---|
3485 | n/a | def test_hash_inheritance(self): |
---|
3486 | n/a | # Testing hash of mutable subclasses... |
---|
3487 | n/a | |
---|
3488 | n/a | class mydict(dict): |
---|
3489 | n/a | pass |
---|
3490 | n/a | d = mydict() |
---|
3491 | n/a | try: |
---|
3492 | n/a | hash(d) |
---|
3493 | n/a | except TypeError: |
---|
3494 | n/a | pass |
---|
3495 | n/a | else: |
---|
3496 | n/a | self.fail("hash() of dict subclass should fail") |
---|
3497 | n/a | |
---|
3498 | n/a | class mylist(list): |
---|
3499 | n/a | pass |
---|
3500 | n/a | d = mylist() |
---|
3501 | n/a | try: |
---|
3502 | n/a | hash(d) |
---|
3503 | n/a | except TypeError: |
---|
3504 | n/a | pass |
---|
3505 | n/a | else: |
---|
3506 | n/a | self.fail("hash() of list subclass should fail") |
---|
3507 | n/a | |
---|
3508 | n/a | def test_str_operations(self): |
---|
3509 | n/a | try: 'a' + 5 |
---|
3510 | n/a | except TypeError: pass |
---|
3511 | n/a | else: self.fail("'' + 5 doesn't raise TypeError") |
---|
3512 | n/a | |
---|
3513 | n/a | try: ''.split('') |
---|
3514 | n/a | except ValueError: pass |
---|
3515 | n/a | else: self.fail("''.split('') doesn't raise ValueError") |
---|
3516 | n/a | |
---|
3517 | n/a | try: ''.join([0]) |
---|
3518 | n/a | except TypeError: pass |
---|
3519 | n/a | else: self.fail("''.join([0]) doesn't raise TypeError") |
---|
3520 | n/a | |
---|
3521 | n/a | try: ''.rindex('5') |
---|
3522 | n/a | except ValueError: pass |
---|
3523 | n/a | else: self.fail("''.rindex('5') doesn't raise ValueError") |
---|
3524 | n/a | |
---|
3525 | n/a | try: '%(n)s' % None |
---|
3526 | n/a | except TypeError: pass |
---|
3527 | n/a | else: self.fail("'%(n)s' % None doesn't raise TypeError") |
---|
3528 | n/a | |
---|
3529 | n/a | try: '%(n' % {} |
---|
3530 | n/a | except ValueError: pass |
---|
3531 | n/a | else: self.fail("'%(n' % {} '' doesn't raise ValueError") |
---|
3532 | n/a | |
---|
3533 | n/a | try: '%*s' % ('abc') |
---|
3534 | n/a | except TypeError: pass |
---|
3535 | n/a | else: self.fail("'%*s' % ('abc') doesn't raise TypeError") |
---|
3536 | n/a | |
---|
3537 | n/a | try: '%*.*s' % ('abc', 5) |
---|
3538 | n/a | except TypeError: pass |
---|
3539 | n/a | else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError") |
---|
3540 | n/a | |
---|
3541 | n/a | try: '%s' % (1, 2) |
---|
3542 | n/a | except TypeError: pass |
---|
3543 | n/a | else: self.fail("'%s' % (1, 2) doesn't raise TypeError") |
---|
3544 | n/a | |
---|
3545 | n/a | try: '%' % None |
---|
3546 | n/a | except ValueError: pass |
---|
3547 | n/a | else: self.fail("'%' % None doesn't raise ValueError") |
---|
3548 | n/a | |
---|
3549 | n/a | self.assertEqual('534253'.isdigit(), 1) |
---|
3550 | n/a | self.assertEqual('534253x'.isdigit(), 0) |
---|
3551 | n/a | self.assertEqual('%c' % 5, '\x05') |
---|
3552 | n/a | self.assertEqual('%c' % '5', '5') |
---|
3553 | n/a | |
---|
3554 | n/a | def test_deepcopy_recursive(self): |
---|
3555 | n/a | # Testing deepcopy of recursive objects... |
---|
3556 | n/a | class Node: |
---|
3557 | n/a | pass |
---|
3558 | n/a | a = Node() |
---|
3559 | n/a | b = Node() |
---|
3560 | n/a | a.b = b |
---|
3561 | n/a | b.a = a |
---|
3562 | n/a | z = deepcopy(a) # This blew up before |
---|
3563 | n/a | |
---|
3564 | n/a | def test_uninitialized_modules(self): |
---|
3565 | n/a | # Testing uninitialized module objects... |
---|
3566 | n/a | from types import ModuleType as M |
---|
3567 | n/a | m = M.__new__(M) |
---|
3568 | n/a | str(m) |
---|
3569 | n/a | self.assertNotHasAttr(m, "__name__") |
---|
3570 | n/a | self.assertNotHasAttr(m, "__file__") |
---|
3571 | n/a | self.assertNotHasAttr(m, "foo") |
---|
3572 | n/a | self.assertFalse(m.__dict__) # None or {} are both reasonable answers |
---|
3573 | n/a | m.foo = 1 |
---|
3574 | n/a | self.assertEqual(m.__dict__, {"foo": 1}) |
---|
3575 | n/a | |
---|
3576 | n/a | def test_funny_new(self): |
---|
3577 | n/a | # Testing __new__ returning something unexpected... |
---|
3578 | n/a | class C(object): |
---|
3579 | n/a | def __new__(cls, arg): |
---|
3580 | n/a | if isinstance(arg, str): return [1, 2, 3] |
---|
3581 | n/a | elif isinstance(arg, int): return object.__new__(D) |
---|
3582 | n/a | else: return object.__new__(cls) |
---|
3583 | n/a | class D(C): |
---|
3584 | n/a | def __init__(self, arg): |
---|
3585 | n/a | self.foo = arg |
---|
3586 | n/a | self.assertEqual(C("1"), [1, 2, 3]) |
---|
3587 | n/a | self.assertEqual(D("1"), [1, 2, 3]) |
---|
3588 | n/a | d = D(None) |
---|
3589 | n/a | self.assertEqual(d.foo, None) |
---|
3590 | n/a | d = C(1) |
---|
3591 | n/a | self.assertIsInstance(d, D) |
---|
3592 | n/a | self.assertEqual(d.foo, 1) |
---|
3593 | n/a | d = D(1) |
---|
3594 | n/a | self.assertIsInstance(d, D) |
---|
3595 | n/a | self.assertEqual(d.foo, 1) |
---|
3596 | n/a | |
---|
3597 | n/a | class C(object): |
---|
3598 | n/a | @staticmethod |
---|
3599 | n/a | def __new__(*args): |
---|
3600 | n/a | return args |
---|
3601 | n/a | self.assertEqual(C(1, 2), (C, 1, 2)) |
---|
3602 | n/a | class D(C): |
---|
3603 | n/a | pass |
---|
3604 | n/a | self.assertEqual(D(1, 2), (D, 1, 2)) |
---|
3605 | n/a | |
---|
3606 | n/a | class C(object): |
---|
3607 | n/a | @classmethod |
---|
3608 | n/a | def __new__(*args): |
---|
3609 | n/a | return args |
---|
3610 | n/a | self.assertEqual(C(1, 2), (C, C, 1, 2)) |
---|
3611 | n/a | class D(C): |
---|
3612 | n/a | pass |
---|
3613 | n/a | self.assertEqual(D(1, 2), (D, D, 1, 2)) |
---|
3614 | n/a | |
---|
3615 | n/a | def test_imul_bug(self): |
---|
3616 | n/a | # Testing for __imul__ problems... |
---|
3617 | n/a | # SF bug 544647 |
---|
3618 | n/a | class C(object): |
---|
3619 | n/a | def __imul__(self, other): |
---|
3620 | n/a | return (self, other) |
---|
3621 | n/a | x = C() |
---|
3622 | n/a | y = x |
---|
3623 | n/a | y *= 1.0 |
---|
3624 | n/a | self.assertEqual(y, (x, 1.0)) |
---|
3625 | n/a | y = x |
---|
3626 | n/a | y *= 2 |
---|
3627 | n/a | self.assertEqual(y, (x, 2)) |
---|
3628 | n/a | y = x |
---|
3629 | n/a | y *= 3 |
---|
3630 | n/a | self.assertEqual(y, (x, 3)) |
---|
3631 | n/a | y = x |
---|
3632 | n/a | y *= 1<<100 |
---|
3633 | n/a | self.assertEqual(y, (x, 1<<100)) |
---|
3634 | n/a | y = x |
---|
3635 | n/a | y *= None |
---|
3636 | n/a | self.assertEqual(y, (x, None)) |
---|
3637 | n/a | y = x |
---|
3638 | n/a | y *= "foo" |
---|
3639 | n/a | self.assertEqual(y, (x, "foo")) |
---|
3640 | n/a | |
---|
3641 | n/a | def test_copy_setstate(self): |
---|
3642 | n/a | # Testing that copy.*copy() correctly uses __setstate__... |
---|
3643 | n/a | import copy |
---|
3644 | n/a | class C(object): |
---|
3645 | n/a | def __init__(self, foo=None): |
---|
3646 | n/a | self.foo = foo |
---|
3647 | n/a | self.__foo = foo |
---|
3648 | n/a | def setfoo(self, foo=None): |
---|
3649 | n/a | self.foo = foo |
---|
3650 | n/a | def getfoo(self): |
---|
3651 | n/a | return self.__foo |
---|
3652 | n/a | def __getstate__(self): |
---|
3653 | n/a | return [self.foo] |
---|
3654 | n/a | def __setstate__(self_, lst): |
---|
3655 | n/a | self.assertEqual(len(lst), 1) |
---|
3656 | n/a | self_.__foo = self_.foo = lst[0] |
---|
3657 | n/a | a = C(42) |
---|
3658 | n/a | a.setfoo(24) |
---|
3659 | n/a | self.assertEqual(a.foo, 24) |
---|
3660 | n/a | self.assertEqual(a.getfoo(), 42) |
---|
3661 | n/a | b = copy.copy(a) |
---|
3662 | n/a | self.assertEqual(b.foo, 24) |
---|
3663 | n/a | self.assertEqual(b.getfoo(), 24) |
---|
3664 | n/a | b = copy.deepcopy(a) |
---|
3665 | n/a | self.assertEqual(b.foo, 24) |
---|
3666 | n/a | self.assertEqual(b.getfoo(), 24) |
---|
3667 | n/a | |
---|
3668 | n/a | def test_slices(self): |
---|
3669 | n/a | # Testing cases with slices and overridden __getitem__ ... |
---|
3670 | n/a | |
---|
3671 | n/a | # Strings |
---|
3672 | n/a | self.assertEqual("hello"[:4], "hell") |
---|
3673 | n/a | self.assertEqual("hello"[slice(4)], "hell") |
---|
3674 | n/a | self.assertEqual(str.__getitem__("hello", slice(4)), "hell") |
---|
3675 | n/a | class S(str): |
---|
3676 | n/a | def __getitem__(self, x): |
---|
3677 | n/a | return str.__getitem__(self, x) |
---|
3678 | n/a | self.assertEqual(S("hello")[:4], "hell") |
---|
3679 | n/a | self.assertEqual(S("hello")[slice(4)], "hell") |
---|
3680 | n/a | self.assertEqual(S("hello").__getitem__(slice(4)), "hell") |
---|
3681 | n/a | # Tuples |
---|
3682 | n/a | self.assertEqual((1,2,3)[:2], (1,2)) |
---|
3683 | n/a | self.assertEqual((1,2,3)[slice(2)], (1,2)) |
---|
3684 | n/a | self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2)) |
---|
3685 | n/a | class T(tuple): |
---|
3686 | n/a | def __getitem__(self, x): |
---|
3687 | n/a | return tuple.__getitem__(self, x) |
---|
3688 | n/a | self.assertEqual(T((1,2,3))[:2], (1,2)) |
---|
3689 | n/a | self.assertEqual(T((1,2,3))[slice(2)], (1,2)) |
---|
3690 | n/a | self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2)) |
---|
3691 | n/a | # Lists |
---|
3692 | n/a | self.assertEqual([1,2,3][:2], [1,2]) |
---|
3693 | n/a | self.assertEqual([1,2,3][slice(2)], [1,2]) |
---|
3694 | n/a | self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2]) |
---|
3695 | n/a | class L(list): |
---|
3696 | n/a | def __getitem__(self, x): |
---|
3697 | n/a | return list.__getitem__(self, x) |
---|
3698 | n/a | self.assertEqual(L([1,2,3])[:2], [1,2]) |
---|
3699 | n/a | self.assertEqual(L([1,2,3])[slice(2)], [1,2]) |
---|
3700 | n/a | self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2]) |
---|
3701 | n/a | # Now do lists and __setitem__ |
---|
3702 | n/a | a = L([1,2,3]) |
---|
3703 | n/a | a[slice(1, 3)] = [3,2] |
---|
3704 | n/a | self.assertEqual(a, [1,3,2]) |
---|
3705 | n/a | a[slice(0, 2, 1)] = [3,1] |
---|
3706 | n/a | self.assertEqual(a, [3,1,2]) |
---|
3707 | n/a | a.__setitem__(slice(1, 3), [2,1]) |
---|
3708 | n/a | self.assertEqual(a, [3,2,1]) |
---|
3709 | n/a | a.__setitem__(slice(0, 2, 1), [2,3]) |
---|
3710 | n/a | self.assertEqual(a, [2,3,1]) |
---|
3711 | n/a | |
---|
3712 | n/a | def test_subtype_resurrection(self): |
---|
3713 | n/a | # Testing resurrection of new-style instance... |
---|
3714 | n/a | |
---|
3715 | n/a | class C(object): |
---|
3716 | n/a | container = [] |
---|
3717 | n/a | |
---|
3718 | n/a | def __del__(self): |
---|
3719 | n/a | # resurrect the instance |
---|
3720 | n/a | C.container.append(self) |
---|
3721 | n/a | |
---|
3722 | n/a | c = C() |
---|
3723 | n/a | c.attr = 42 |
---|
3724 | n/a | |
---|
3725 | n/a | # The most interesting thing here is whether this blows up, due to |
---|
3726 | n/a | # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 |
---|
3727 | n/a | # bug). |
---|
3728 | n/a | del c |
---|
3729 | n/a | |
---|
3730 | n/a | support.gc_collect() |
---|
3731 | n/a | self.assertEqual(len(C.container), 1) |
---|
3732 | n/a | |
---|
3733 | n/a | # Make c mortal again, so that the test framework with -l doesn't report |
---|
3734 | n/a | # it as a leak. |
---|
3735 | n/a | del C.__del__ |
---|
3736 | n/a | |
---|
3737 | n/a | def test_slots_trash(self): |
---|
3738 | n/a | # Testing slot trash... |
---|
3739 | n/a | # Deallocating deeply nested slotted trash caused stack overflows |
---|
3740 | n/a | class trash(object): |
---|
3741 | n/a | __slots__ = ['x'] |
---|
3742 | n/a | def __init__(self, x): |
---|
3743 | n/a | self.x = x |
---|
3744 | n/a | o = None |
---|
3745 | n/a | for i in range(50000): |
---|
3746 | n/a | o = trash(o) |
---|
3747 | n/a | del o |
---|
3748 | n/a | |
---|
3749 | n/a | def test_slots_multiple_inheritance(self): |
---|
3750 | n/a | # SF bug 575229, multiple inheritance w/ slots dumps core |
---|
3751 | n/a | class A(object): |
---|
3752 | n/a | __slots__=() |
---|
3753 | n/a | class B(object): |
---|
3754 | n/a | pass |
---|
3755 | n/a | class C(A,B) : |
---|
3756 | n/a | __slots__=() |
---|
3757 | n/a | if support.check_impl_detail(): |
---|
3758 | n/a | self.assertEqual(C.__basicsize__, B.__basicsize__) |
---|
3759 | n/a | self.assertHasAttr(C, '__dict__') |
---|
3760 | n/a | self.assertHasAttr(C, '__weakref__') |
---|
3761 | n/a | C().x = 2 |
---|
3762 | n/a | |
---|
3763 | n/a | def test_rmul(self): |
---|
3764 | n/a | # Testing correct invocation of __rmul__... |
---|
3765 | n/a | # SF patch 592646 |
---|
3766 | n/a | class C(object): |
---|
3767 | n/a | def __mul__(self, other): |
---|
3768 | n/a | return "mul" |
---|
3769 | n/a | def __rmul__(self, other): |
---|
3770 | n/a | return "rmul" |
---|
3771 | n/a | a = C() |
---|
3772 | n/a | self.assertEqual(a*2, "mul") |
---|
3773 | n/a | self.assertEqual(a*2.2, "mul") |
---|
3774 | n/a | self.assertEqual(2*a, "rmul") |
---|
3775 | n/a | self.assertEqual(2.2*a, "rmul") |
---|
3776 | n/a | |
---|
3777 | n/a | def test_ipow(self): |
---|
3778 | n/a | # Testing correct invocation of __ipow__... |
---|
3779 | n/a | # [SF bug 620179] |
---|
3780 | n/a | class C(object): |
---|
3781 | n/a | def __ipow__(self, other): |
---|
3782 | n/a | pass |
---|
3783 | n/a | a = C() |
---|
3784 | n/a | a **= 2 |
---|
3785 | n/a | |
---|
3786 | n/a | def test_mutable_bases(self): |
---|
3787 | n/a | # Testing mutable bases... |
---|
3788 | n/a | |
---|
3789 | n/a | # stuff that should work: |
---|
3790 | n/a | class C(object): |
---|
3791 | n/a | pass |
---|
3792 | n/a | class C2(object): |
---|
3793 | n/a | def __getattribute__(self, attr): |
---|
3794 | n/a | if attr == 'a': |
---|
3795 | n/a | return 2 |
---|
3796 | n/a | else: |
---|
3797 | n/a | return super(C2, self).__getattribute__(attr) |
---|
3798 | n/a | def meth(self): |
---|
3799 | n/a | return 1 |
---|
3800 | n/a | class D(C): |
---|
3801 | n/a | pass |
---|
3802 | n/a | class E(D): |
---|
3803 | n/a | pass |
---|
3804 | n/a | d = D() |
---|
3805 | n/a | e = E() |
---|
3806 | n/a | D.__bases__ = (C,) |
---|
3807 | n/a | D.__bases__ = (C2,) |
---|
3808 | n/a | self.assertEqual(d.meth(), 1) |
---|
3809 | n/a | self.assertEqual(e.meth(), 1) |
---|
3810 | n/a | self.assertEqual(d.a, 2) |
---|
3811 | n/a | self.assertEqual(e.a, 2) |
---|
3812 | n/a | self.assertEqual(C2.__subclasses__(), [D]) |
---|
3813 | n/a | |
---|
3814 | n/a | try: |
---|
3815 | n/a | del D.__bases__ |
---|
3816 | n/a | except (TypeError, AttributeError): |
---|
3817 | n/a | pass |
---|
3818 | n/a | else: |
---|
3819 | n/a | self.fail("shouldn't be able to delete .__bases__") |
---|
3820 | n/a | |
---|
3821 | n/a | try: |
---|
3822 | n/a | D.__bases__ = () |
---|
3823 | n/a | except TypeError as msg: |
---|
3824 | n/a | if str(msg) == "a new-style class can't have only classic bases": |
---|
3825 | n/a | self.fail("wrong error message for .__bases__ = ()") |
---|
3826 | n/a | else: |
---|
3827 | n/a | self.fail("shouldn't be able to set .__bases__ to ()") |
---|
3828 | n/a | |
---|
3829 | n/a | try: |
---|
3830 | n/a | D.__bases__ = (D,) |
---|
3831 | n/a | except TypeError: |
---|
3832 | n/a | pass |
---|
3833 | n/a | else: |
---|
3834 | n/a | # actually, we'll have crashed by here... |
---|
3835 | n/a | self.fail("shouldn't be able to create inheritance cycles") |
---|
3836 | n/a | |
---|
3837 | n/a | try: |
---|
3838 | n/a | D.__bases__ = (C, C) |
---|
3839 | n/a | except TypeError: |
---|
3840 | n/a | pass |
---|
3841 | n/a | else: |
---|
3842 | n/a | self.fail("didn't detect repeated base classes") |
---|
3843 | n/a | |
---|
3844 | n/a | try: |
---|
3845 | n/a | D.__bases__ = (E,) |
---|
3846 | n/a | except TypeError: |
---|
3847 | n/a | pass |
---|
3848 | n/a | else: |
---|
3849 | n/a | self.fail("shouldn't be able to create inheritance cycles") |
---|
3850 | n/a | |
---|
3851 | n/a | def test_builtin_bases(self): |
---|
3852 | n/a | # Make sure all the builtin types can have their base queried without |
---|
3853 | n/a | # segfaulting. See issue #5787. |
---|
3854 | n/a | builtin_types = [tp for tp in builtins.__dict__.values() |
---|
3855 | n/a | if isinstance(tp, type)] |
---|
3856 | n/a | for tp in builtin_types: |
---|
3857 | n/a | object.__getattribute__(tp, "__bases__") |
---|
3858 | n/a | if tp is not object: |
---|
3859 | n/a | self.assertEqual(len(tp.__bases__), 1, tp) |
---|
3860 | n/a | |
---|
3861 | n/a | class L(list): |
---|
3862 | n/a | pass |
---|
3863 | n/a | |
---|
3864 | n/a | class C(object): |
---|
3865 | n/a | pass |
---|
3866 | n/a | |
---|
3867 | n/a | class D(C): |
---|
3868 | n/a | pass |
---|
3869 | n/a | |
---|
3870 | n/a | try: |
---|
3871 | n/a | L.__bases__ = (dict,) |
---|
3872 | n/a | except TypeError: |
---|
3873 | n/a | pass |
---|
3874 | n/a | else: |
---|
3875 | n/a | self.fail("shouldn't turn list subclass into dict subclass") |
---|
3876 | n/a | |
---|
3877 | n/a | try: |
---|
3878 | n/a | list.__bases__ = (dict,) |
---|
3879 | n/a | except TypeError: |
---|
3880 | n/a | pass |
---|
3881 | n/a | else: |
---|
3882 | n/a | self.fail("shouldn't be able to assign to list.__bases__") |
---|
3883 | n/a | |
---|
3884 | n/a | try: |
---|
3885 | n/a | D.__bases__ = (C, list) |
---|
3886 | n/a | except TypeError: |
---|
3887 | n/a | pass |
---|
3888 | n/a | else: |
---|
3889 | n/a | assert 0, "best_base calculation found wanting" |
---|
3890 | n/a | |
---|
3891 | n/a | def test_unsubclassable_types(self): |
---|
3892 | n/a | with self.assertRaises(TypeError): |
---|
3893 | n/a | class X(type(None)): |
---|
3894 | n/a | pass |
---|
3895 | n/a | with self.assertRaises(TypeError): |
---|
3896 | n/a | class X(object, type(None)): |
---|
3897 | n/a | pass |
---|
3898 | n/a | with self.assertRaises(TypeError): |
---|
3899 | n/a | class X(type(None), object): |
---|
3900 | n/a | pass |
---|
3901 | n/a | class O(object): |
---|
3902 | n/a | pass |
---|
3903 | n/a | with self.assertRaises(TypeError): |
---|
3904 | n/a | class X(O, type(None)): |
---|
3905 | n/a | pass |
---|
3906 | n/a | with self.assertRaises(TypeError): |
---|
3907 | n/a | class X(type(None), O): |
---|
3908 | n/a | pass |
---|
3909 | n/a | |
---|
3910 | n/a | class X(object): |
---|
3911 | n/a | pass |
---|
3912 | n/a | with self.assertRaises(TypeError): |
---|
3913 | n/a | X.__bases__ = type(None), |
---|
3914 | n/a | with self.assertRaises(TypeError): |
---|
3915 | n/a | X.__bases__ = object, type(None) |
---|
3916 | n/a | with self.assertRaises(TypeError): |
---|
3917 | n/a | X.__bases__ = type(None), object |
---|
3918 | n/a | with self.assertRaises(TypeError): |
---|
3919 | n/a | X.__bases__ = O, type(None) |
---|
3920 | n/a | with self.assertRaises(TypeError): |
---|
3921 | n/a | X.__bases__ = type(None), O |
---|
3922 | n/a | |
---|
3923 | n/a | def test_mutable_bases_with_failing_mro(self): |
---|
3924 | n/a | # Testing mutable bases with failing mro... |
---|
3925 | n/a | class WorkOnce(type): |
---|
3926 | n/a | def __new__(self, name, bases, ns): |
---|
3927 | n/a | self.flag = 0 |
---|
3928 | n/a | return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) |
---|
3929 | n/a | def mro(self): |
---|
3930 | n/a | if self.flag > 0: |
---|
3931 | n/a | raise RuntimeError("bozo") |
---|
3932 | n/a | else: |
---|
3933 | n/a | self.flag += 1 |
---|
3934 | n/a | return type.mro(self) |
---|
3935 | n/a | |
---|
3936 | n/a | class WorkAlways(type): |
---|
3937 | n/a | def mro(self): |
---|
3938 | n/a | # this is here to make sure that .mro()s aren't called |
---|
3939 | n/a | # with an exception set (which was possible at one point). |
---|
3940 | n/a | # An error message will be printed in a debug build. |
---|
3941 | n/a | # What's a good way to test for this? |
---|
3942 | n/a | return type.mro(self) |
---|
3943 | n/a | |
---|
3944 | n/a | class C(object): |
---|
3945 | n/a | pass |
---|
3946 | n/a | |
---|
3947 | n/a | class C2(object): |
---|
3948 | n/a | pass |
---|
3949 | n/a | |
---|
3950 | n/a | class D(C): |
---|
3951 | n/a | pass |
---|
3952 | n/a | |
---|
3953 | n/a | class E(D): |
---|
3954 | n/a | pass |
---|
3955 | n/a | |
---|
3956 | n/a | class F(D, metaclass=WorkOnce): |
---|
3957 | n/a | pass |
---|
3958 | n/a | |
---|
3959 | n/a | class G(D, metaclass=WorkAlways): |
---|
3960 | n/a | pass |
---|
3961 | n/a | |
---|
3962 | n/a | # Immediate subclasses have their mro's adjusted in alphabetical |
---|
3963 | n/a | # order, so E's will get adjusted before adjusting F's fails. We |
---|
3964 | n/a | # check here that E's gets restored. |
---|
3965 | n/a | |
---|
3966 | n/a | E_mro_before = E.__mro__ |
---|
3967 | n/a | D_mro_before = D.__mro__ |
---|
3968 | n/a | |
---|
3969 | n/a | try: |
---|
3970 | n/a | D.__bases__ = (C2,) |
---|
3971 | n/a | except RuntimeError: |
---|
3972 | n/a | self.assertEqual(E.__mro__, E_mro_before) |
---|
3973 | n/a | self.assertEqual(D.__mro__, D_mro_before) |
---|
3974 | n/a | else: |
---|
3975 | n/a | self.fail("exception not propagated") |
---|
3976 | n/a | |
---|
3977 | n/a | def test_mutable_bases_catch_mro_conflict(self): |
---|
3978 | n/a | # Testing mutable bases catch mro conflict... |
---|
3979 | n/a | class A(object): |
---|
3980 | n/a | pass |
---|
3981 | n/a | |
---|
3982 | n/a | class B(object): |
---|
3983 | n/a | pass |
---|
3984 | n/a | |
---|
3985 | n/a | class C(A, B): |
---|
3986 | n/a | pass |
---|
3987 | n/a | |
---|
3988 | n/a | class D(A, B): |
---|
3989 | n/a | pass |
---|
3990 | n/a | |
---|
3991 | n/a | class E(C, D): |
---|
3992 | n/a | pass |
---|
3993 | n/a | |
---|
3994 | n/a | try: |
---|
3995 | n/a | C.__bases__ = (B, A) |
---|
3996 | n/a | except TypeError: |
---|
3997 | n/a | pass |
---|
3998 | n/a | else: |
---|
3999 | n/a | self.fail("didn't catch MRO conflict") |
---|
4000 | n/a | |
---|
4001 | n/a | def test_mutable_names(self): |
---|
4002 | n/a | # Testing mutable names... |
---|
4003 | n/a | class C(object): |
---|
4004 | n/a | pass |
---|
4005 | n/a | |
---|
4006 | n/a | # C.__module__ could be 'test_descr' or '__main__' |
---|
4007 | n/a | mod = C.__module__ |
---|
4008 | n/a | |
---|
4009 | n/a | C.__name__ = 'D' |
---|
4010 | n/a | self.assertEqual((C.__module__, C.__name__), (mod, 'D')) |
---|
4011 | n/a | |
---|
4012 | n/a | C.__name__ = 'D.E' |
---|
4013 | n/a | self.assertEqual((C.__module__, C.__name__), (mod, 'D.E')) |
---|
4014 | n/a | |
---|
4015 | n/a | def test_evil_type_name(self): |
---|
4016 | n/a | # A badly placed Py_DECREF in type_set_name led to arbitrary code |
---|
4017 | n/a | # execution while the type structure was not in a sane state, and a |
---|
4018 | n/a | # possible segmentation fault as a result. See bug #16447. |
---|
4019 | n/a | class Nasty(str): |
---|
4020 | n/a | def __del__(self): |
---|
4021 | n/a | C.__name__ = "other" |
---|
4022 | n/a | |
---|
4023 | n/a | class C: |
---|
4024 | n/a | pass |
---|
4025 | n/a | |
---|
4026 | n/a | C.__name__ = Nasty("abc") |
---|
4027 | n/a | C.__name__ = "normal" |
---|
4028 | n/a | |
---|
4029 | n/a | def test_subclass_right_op(self): |
---|
4030 | n/a | # Testing correct dispatch of subclass overloading __r<op>__... |
---|
4031 | n/a | |
---|
4032 | n/a | # This code tests various cases where right-dispatch of a subclass |
---|
4033 | n/a | # should be preferred over left-dispatch of a base class. |
---|
4034 | n/a | |
---|
4035 | n/a | # Case 1: subclass of int; this tests code in abstract.c::binary_op1() |
---|
4036 | n/a | |
---|
4037 | n/a | class B(int): |
---|
4038 | n/a | def __floordiv__(self, other): |
---|
4039 | n/a | return "B.__floordiv__" |
---|
4040 | n/a | def __rfloordiv__(self, other): |
---|
4041 | n/a | return "B.__rfloordiv__" |
---|
4042 | n/a | |
---|
4043 | n/a | self.assertEqual(B(1) // 1, "B.__floordiv__") |
---|
4044 | n/a | self.assertEqual(1 // B(1), "B.__rfloordiv__") |
---|
4045 | n/a | |
---|
4046 | n/a | # Case 2: subclass of object; this is just the baseline for case 3 |
---|
4047 | n/a | |
---|
4048 | n/a | class C(object): |
---|
4049 | n/a | def __floordiv__(self, other): |
---|
4050 | n/a | return "C.__floordiv__" |
---|
4051 | n/a | def __rfloordiv__(self, other): |
---|
4052 | n/a | return "C.__rfloordiv__" |
---|
4053 | n/a | |
---|
4054 | n/a | self.assertEqual(C() // 1, "C.__floordiv__") |
---|
4055 | n/a | self.assertEqual(1 // C(), "C.__rfloordiv__") |
---|
4056 | n/a | |
---|
4057 | n/a | # Case 3: subclass of new-style class; here it gets interesting |
---|
4058 | n/a | |
---|
4059 | n/a | class D(C): |
---|
4060 | n/a | def __floordiv__(self, other): |
---|
4061 | n/a | return "D.__floordiv__" |
---|
4062 | n/a | def __rfloordiv__(self, other): |
---|
4063 | n/a | return "D.__rfloordiv__" |
---|
4064 | n/a | |
---|
4065 | n/a | self.assertEqual(D() // C(), "D.__floordiv__") |
---|
4066 | n/a | self.assertEqual(C() // D(), "D.__rfloordiv__") |
---|
4067 | n/a | |
---|
4068 | n/a | # Case 4: this didn't work right in 2.2.2 and 2.3a1 |
---|
4069 | n/a | |
---|
4070 | n/a | class E(C): |
---|
4071 | n/a | pass |
---|
4072 | n/a | |
---|
4073 | n/a | self.assertEqual(E.__rfloordiv__, C.__rfloordiv__) |
---|
4074 | n/a | |
---|
4075 | n/a | self.assertEqual(E() // 1, "C.__floordiv__") |
---|
4076 | n/a | self.assertEqual(1 // E(), "C.__rfloordiv__") |
---|
4077 | n/a | self.assertEqual(E() // C(), "C.__floordiv__") |
---|
4078 | n/a | self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail |
---|
4079 | n/a | |
---|
4080 | n/a | @support.impl_detail("testing an internal kind of method object") |
---|
4081 | n/a | def test_meth_class_get(self): |
---|
4082 | n/a | # Testing __get__ method of METH_CLASS C methods... |
---|
4083 | n/a | # Full coverage of descrobject.c::classmethod_get() |
---|
4084 | n/a | |
---|
4085 | n/a | # Baseline |
---|
4086 | n/a | arg = [1, 2, 3] |
---|
4087 | n/a | res = {1: None, 2: None, 3: None} |
---|
4088 | n/a | self.assertEqual(dict.fromkeys(arg), res) |
---|
4089 | n/a | self.assertEqual({}.fromkeys(arg), res) |
---|
4090 | n/a | |
---|
4091 | n/a | # Now get the descriptor |
---|
4092 | n/a | descr = dict.__dict__["fromkeys"] |
---|
4093 | n/a | |
---|
4094 | n/a | # More baseline using the descriptor directly |
---|
4095 | n/a | self.assertEqual(descr.__get__(None, dict)(arg), res) |
---|
4096 | n/a | self.assertEqual(descr.__get__({})(arg), res) |
---|
4097 | n/a | |
---|
4098 | n/a | # Now check various error cases |
---|
4099 | n/a | try: |
---|
4100 | n/a | descr.__get__(None, None) |
---|
4101 | n/a | except TypeError: |
---|
4102 | n/a | pass |
---|
4103 | n/a | else: |
---|
4104 | n/a | self.fail("shouldn't have allowed descr.__get__(None, None)") |
---|
4105 | n/a | try: |
---|
4106 | n/a | descr.__get__(42) |
---|
4107 | n/a | except TypeError: |
---|
4108 | n/a | pass |
---|
4109 | n/a | else: |
---|
4110 | n/a | self.fail("shouldn't have allowed descr.__get__(42)") |
---|
4111 | n/a | try: |
---|
4112 | n/a | descr.__get__(None, 42) |
---|
4113 | n/a | except TypeError: |
---|
4114 | n/a | pass |
---|
4115 | n/a | else: |
---|
4116 | n/a | self.fail("shouldn't have allowed descr.__get__(None, 42)") |
---|
4117 | n/a | try: |
---|
4118 | n/a | descr.__get__(None, int) |
---|
4119 | n/a | except TypeError: |
---|
4120 | n/a | pass |
---|
4121 | n/a | else: |
---|
4122 | n/a | self.fail("shouldn't have allowed descr.__get__(None, int)") |
---|
4123 | n/a | |
---|
4124 | n/a | def test_isinst_isclass(self): |
---|
4125 | n/a | # Testing proxy isinstance() and isclass()... |
---|
4126 | n/a | class Proxy(object): |
---|
4127 | n/a | def __init__(self, obj): |
---|
4128 | n/a | self.__obj = obj |
---|
4129 | n/a | def __getattribute__(self, name): |
---|
4130 | n/a | if name.startswith("_Proxy__"): |
---|
4131 | n/a | return object.__getattribute__(self, name) |
---|
4132 | n/a | else: |
---|
4133 | n/a | return getattr(self.__obj, name) |
---|
4134 | n/a | # Test with a classic class |
---|
4135 | n/a | class C: |
---|
4136 | n/a | pass |
---|
4137 | n/a | a = C() |
---|
4138 | n/a | pa = Proxy(a) |
---|
4139 | n/a | self.assertIsInstance(a, C) # Baseline |
---|
4140 | n/a | self.assertIsInstance(pa, C) # Test |
---|
4141 | n/a | # Test with a classic subclass |
---|
4142 | n/a | class D(C): |
---|
4143 | n/a | pass |
---|
4144 | n/a | a = D() |
---|
4145 | n/a | pa = Proxy(a) |
---|
4146 | n/a | self.assertIsInstance(a, C) # Baseline |
---|
4147 | n/a | self.assertIsInstance(pa, C) # Test |
---|
4148 | n/a | # Test with a new-style class |
---|
4149 | n/a | class C(object): |
---|
4150 | n/a | pass |
---|
4151 | n/a | a = C() |
---|
4152 | n/a | pa = Proxy(a) |
---|
4153 | n/a | self.assertIsInstance(a, C) # Baseline |
---|
4154 | n/a | self.assertIsInstance(pa, C) # Test |
---|
4155 | n/a | # Test with a new-style subclass |
---|
4156 | n/a | class D(C): |
---|
4157 | n/a | pass |
---|
4158 | n/a | a = D() |
---|
4159 | n/a | pa = Proxy(a) |
---|
4160 | n/a | self.assertIsInstance(a, C) # Baseline |
---|
4161 | n/a | self.assertIsInstance(pa, C) # Test |
---|
4162 | n/a | |
---|
4163 | n/a | def test_proxy_super(self): |
---|
4164 | n/a | # Testing super() for a proxy object... |
---|
4165 | n/a | class Proxy(object): |
---|
4166 | n/a | def __init__(self, obj): |
---|
4167 | n/a | self.__obj = obj |
---|
4168 | n/a | def __getattribute__(self, name): |
---|
4169 | n/a | if name.startswith("_Proxy__"): |
---|
4170 | n/a | return object.__getattribute__(self, name) |
---|
4171 | n/a | else: |
---|
4172 | n/a | return getattr(self.__obj, name) |
---|
4173 | n/a | |
---|
4174 | n/a | class B(object): |
---|
4175 | n/a | def f(self): |
---|
4176 | n/a | return "B.f" |
---|
4177 | n/a | |
---|
4178 | n/a | class C(B): |
---|
4179 | n/a | def f(self): |
---|
4180 | n/a | return super(C, self).f() + "->C.f" |
---|
4181 | n/a | |
---|
4182 | n/a | obj = C() |
---|
4183 | n/a | p = Proxy(obj) |
---|
4184 | n/a | self.assertEqual(C.__dict__["f"](p), "B.f->C.f") |
---|
4185 | n/a | |
---|
4186 | n/a | def test_carloverre(self): |
---|
4187 | n/a | # Testing prohibition of Carlo Verre's hack... |
---|
4188 | n/a | try: |
---|
4189 | n/a | object.__setattr__(str, "foo", 42) |
---|
4190 | n/a | except TypeError: |
---|
4191 | n/a | pass |
---|
4192 | n/a | else: |
---|
4193 | n/a | self.fail("Carlo Verre __setattr__ succeeded!") |
---|
4194 | n/a | try: |
---|
4195 | n/a | object.__delattr__(str, "lower") |
---|
4196 | n/a | except TypeError: |
---|
4197 | n/a | pass |
---|
4198 | n/a | else: |
---|
4199 | n/a | self.fail("Carlo Verre __delattr__ succeeded!") |
---|
4200 | n/a | |
---|
4201 | n/a | def test_weakref_segfault(self): |
---|
4202 | n/a | # Testing weakref segfault... |
---|
4203 | n/a | # SF 742911 |
---|
4204 | n/a | import weakref |
---|
4205 | n/a | |
---|
4206 | n/a | class Provoker: |
---|
4207 | n/a | def __init__(self, referrent): |
---|
4208 | n/a | self.ref = weakref.ref(referrent) |
---|
4209 | n/a | |
---|
4210 | n/a | def __del__(self): |
---|
4211 | n/a | x = self.ref() |
---|
4212 | n/a | |
---|
4213 | n/a | class Oops(object): |
---|
4214 | n/a | pass |
---|
4215 | n/a | |
---|
4216 | n/a | o = Oops() |
---|
4217 | n/a | o.whatever = Provoker(o) |
---|
4218 | n/a | del o |
---|
4219 | n/a | |
---|
4220 | n/a | def test_wrapper_segfault(self): |
---|
4221 | n/a | # SF 927248: deeply nested wrappers could cause stack overflow |
---|
4222 | n/a | f = lambda:None |
---|
4223 | n/a | for i in range(1000000): |
---|
4224 | n/a | f = f.__call__ |
---|
4225 | n/a | f = None |
---|
4226 | n/a | |
---|
4227 | n/a | def test_file_fault(self): |
---|
4228 | n/a | # Testing sys.stdout is changed in getattr... |
---|
4229 | n/a | test_stdout = sys.stdout |
---|
4230 | n/a | class StdoutGuard: |
---|
4231 | n/a | def __getattr__(self, attr): |
---|
4232 | n/a | sys.stdout = sys.__stdout__ |
---|
4233 | n/a | raise RuntimeError("Premature access to sys.stdout.%s" % attr) |
---|
4234 | n/a | sys.stdout = StdoutGuard() |
---|
4235 | n/a | try: |
---|
4236 | n/a | print("Oops!") |
---|
4237 | n/a | except RuntimeError: |
---|
4238 | n/a | pass |
---|
4239 | n/a | finally: |
---|
4240 | n/a | sys.stdout = test_stdout |
---|
4241 | n/a | |
---|
4242 | n/a | def test_vicious_descriptor_nonsense(self): |
---|
4243 | n/a | # Testing vicious_descriptor_nonsense... |
---|
4244 | n/a | |
---|
4245 | n/a | # A potential segfault spotted by Thomas Wouters in mail to |
---|
4246 | n/a | # python-dev 2003-04-17, turned into an example & fixed by Michael |
---|
4247 | n/a | # Hudson just less than four months later... |
---|
4248 | n/a | |
---|
4249 | n/a | class Evil(object): |
---|
4250 | n/a | def __hash__(self): |
---|
4251 | n/a | return hash('attr') |
---|
4252 | n/a | def __eq__(self, other): |
---|
4253 | n/a | del C.attr |
---|
4254 | n/a | return 0 |
---|
4255 | n/a | |
---|
4256 | n/a | class Descr(object): |
---|
4257 | n/a | def __get__(self, ob, type=None): |
---|
4258 | n/a | return 1 |
---|
4259 | n/a | |
---|
4260 | n/a | class C(object): |
---|
4261 | n/a | attr = Descr() |
---|
4262 | n/a | |
---|
4263 | n/a | c = C() |
---|
4264 | n/a | c.__dict__[Evil()] = 0 |
---|
4265 | n/a | |
---|
4266 | n/a | self.assertEqual(c.attr, 1) |
---|
4267 | n/a | # this makes a crash more likely: |
---|
4268 | n/a | support.gc_collect() |
---|
4269 | n/a | self.assertNotHasAttr(c, 'attr') |
---|
4270 | n/a | |
---|
4271 | n/a | def test_init(self): |
---|
4272 | n/a | # SF 1155938 |
---|
4273 | n/a | class Foo(object): |
---|
4274 | n/a | def __init__(self): |
---|
4275 | n/a | return 10 |
---|
4276 | n/a | try: |
---|
4277 | n/a | Foo() |
---|
4278 | n/a | except TypeError: |
---|
4279 | n/a | pass |
---|
4280 | n/a | else: |
---|
4281 | n/a | self.fail("did not test __init__() for None return") |
---|
4282 | n/a | |
---|
4283 | n/a | def test_method_wrapper(self): |
---|
4284 | n/a | # Testing method-wrapper objects... |
---|
4285 | n/a | # <type 'method-wrapper'> did not support any reflection before 2.5 |
---|
4286 | n/a | |
---|
4287 | n/a | # XXX should methods really support __eq__? |
---|
4288 | n/a | |
---|
4289 | n/a | l = [] |
---|
4290 | n/a | self.assertEqual(l.__add__, l.__add__) |
---|
4291 | n/a | self.assertEqual(l.__add__, [].__add__) |
---|
4292 | n/a | self.assertNotEqual(l.__add__, [5].__add__) |
---|
4293 | n/a | self.assertNotEqual(l.__add__, l.__mul__) |
---|
4294 | n/a | self.assertEqual(l.__add__.__name__, '__add__') |
---|
4295 | n/a | if hasattr(l.__add__, '__self__'): |
---|
4296 | n/a | # CPython |
---|
4297 | n/a | self.assertIs(l.__add__.__self__, l) |
---|
4298 | n/a | self.assertIs(l.__add__.__objclass__, list) |
---|
4299 | n/a | else: |
---|
4300 | n/a | # Python implementations where [].__add__ is a normal bound method |
---|
4301 | n/a | self.assertIs(l.__add__.im_self, l) |
---|
4302 | n/a | self.assertIs(l.__add__.im_class, list) |
---|
4303 | n/a | self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) |
---|
4304 | n/a | try: |
---|
4305 | n/a | hash(l.__add__) |
---|
4306 | n/a | except TypeError: |
---|
4307 | n/a | pass |
---|
4308 | n/a | else: |
---|
4309 | n/a | self.fail("no TypeError from hash([].__add__)") |
---|
4310 | n/a | |
---|
4311 | n/a | t = () |
---|
4312 | n/a | t += (7,) |
---|
4313 | n/a | self.assertEqual(t.__add__, (7,).__add__) |
---|
4314 | n/a | self.assertEqual(hash(t.__add__), hash((7,).__add__)) |
---|
4315 | n/a | |
---|
4316 | n/a | def test_not_implemented(self): |
---|
4317 | n/a | # Testing NotImplemented... |
---|
4318 | n/a | # all binary methods should be able to return a NotImplemented |
---|
4319 | n/a | import operator |
---|
4320 | n/a | |
---|
4321 | n/a | def specialmethod(self, other): |
---|
4322 | n/a | return NotImplemented |
---|
4323 | n/a | |
---|
4324 | n/a | def check(expr, x, y): |
---|
4325 | n/a | try: |
---|
4326 | n/a | exec(expr, {'x': x, 'y': y, 'operator': operator}) |
---|
4327 | n/a | except TypeError: |
---|
4328 | n/a | pass |
---|
4329 | n/a | else: |
---|
4330 | n/a | self.fail("no TypeError from %r" % (expr,)) |
---|
4331 | n/a | |
---|
4332 | n/a | N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of |
---|
4333 | n/a | # TypeErrors |
---|
4334 | n/a | N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger |
---|
4335 | n/a | # ValueErrors instead of TypeErrors |
---|
4336 | n/a | for name, expr, iexpr in [ |
---|
4337 | n/a | ('__add__', 'x + y', 'x += y'), |
---|
4338 | n/a | ('__sub__', 'x - y', 'x -= y'), |
---|
4339 | n/a | ('__mul__', 'x * y', 'x *= y'), |
---|
4340 | n/a | ('__matmul__', 'x @ y', 'x @= y'), |
---|
4341 | n/a | ('__truediv__', 'x / y', 'x /= y'), |
---|
4342 | n/a | ('__floordiv__', 'x // y', 'x //= y'), |
---|
4343 | n/a | ('__mod__', 'x % y', 'x %= y'), |
---|
4344 | n/a | ('__divmod__', 'divmod(x, y)', None), |
---|
4345 | n/a | ('__pow__', 'x ** y', 'x **= y'), |
---|
4346 | n/a | ('__lshift__', 'x << y', 'x <<= y'), |
---|
4347 | n/a | ('__rshift__', 'x >> y', 'x >>= y'), |
---|
4348 | n/a | ('__and__', 'x & y', 'x &= y'), |
---|
4349 | n/a | ('__or__', 'x | y', 'x |= y'), |
---|
4350 | n/a | ('__xor__', 'x ^ y', 'x ^= y')]: |
---|
4351 | n/a | rname = '__r' + name[2:] |
---|
4352 | n/a | A = type('A', (), {name: specialmethod}) |
---|
4353 | n/a | a = A() |
---|
4354 | n/a | check(expr, a, a) |
---|
4355 | n/a | check(expr, a, N1) |
---|
4356 | n/a | check(expr, a, N2) |
---|
4357 | n/a | if iexpr: |
---|
4358 | n/a | check(iexpr, a, a) |
---|
4359 | n/a | check(iexpr, a, N1) |
---|
4360 | n/a | check(iexpr, a, N2) |
---|
4361 | n/a | iname = '__i' + name[2:] |
---|
4362 | n/a | C = type('C', (), {iname: specialmethod}) |
---|
4363 | n/a | c = C() |
---|
4364 | n/a | check(iexpr, c, a) |
---|
4365 | n/a | check(iexpr, c, N1) |
---|
4366 | n/a | check(iexpr, c, N2) |
---|
4367 | n/a | |
---|
4368 | n/a | def test_assign_slice(self): |
---|
4369 | n/a | # ceval.c's assign_slice used to check for |
---|
4370 | n/a | # tp->tp_as_sequence->sq_slice instead of |
---|
4371 | n/a | # tp->tp_as_sequence->sq_ass_slice |
---|
4372 | n/a | |
---|
4373 | n/a | class C(object): |
---|
4374 | n/a | def __setitem__(self, idx, value): |
---|
4375 | n/a | self.value = value |
---|
4376 | n/a | |
---|
4377 | n/a | c = C() |
---|
4378 | n/a | c[1:2] = 3 |
---|
4379 | n/a | self.assertEqual(c.value, 3) |
---|
4380 | n/a | |
---|
4381 | n/a | def test_set_and_no_get(self): |
---|
4382 | n/a | # See |
---|
4383 | n/a | # http://mail.python.org/pipermail/python-dev/2010-January/095637.html |
---|
4384 | n/a | class Descr(object): |
---|
4385 | n/a | |
---|
4386 | n/a | def __init__(self, name): |
---|
4387 | n/a | self.name = name |
---|
4388 | n/a | |
---|
4389 | n/a | def __set__(self, obj, value): |
---|
4390 | n/a | obj.__dict__[self.name] = value |
---|
4391 | n/a | descr = Descr("a") |
---|
4392 | n/a | |
---|
4393 | n/a | class X(object): |
---|
4394 | n/a | a = descr |
---|
4395 | n/a | |
---|
4396 | n/a | x = X() |
---|
4397 | n/a | self.assertIs(x.a, descr) |
---|
4398 | n/a | x.a = 42 |
---|
4399 | n/a | self.assertEqual(x.a, 42) |
---|
4400 | n/a | |
---|
4401 | n/a | # Also check type_getattro for correctness. |
---|
4402 | n/a | class Meta(type): |
---|
4403 | n/a | pass |
---|
4404 | n/a | class X(metaclass=Meta): |
---|
4405 | n/a | pass |
---|
4406 | n/a | X.a = 42 |
---|
4407 | n/a | Meta.a = Descr("a") |
---|
4408 | n/a | self.assertEqual(X.a, 42) |
---|
4409 | n/a | |
---|
4410 | n/a | def test_getattr_hooks(self): |
---|
4411 | n/a | # issue 4230 |
---|
4412 | n/a | |
---|
4413 | n/a | class Descriptor(object): |
---|
4414 | n/a | counter = 0 |
---|
4415 | n/a | def __get__(self, obj, objtype=None): |
---|
4416 | n/a | def getter(name): |
---|
4417 | n/a | self.counter += 1 |
---|
4418 | n/a | raise AttributeError(name) |
---|
4419 | n/a | return getter |
---|
4420 | n/a | |
---|
4421 | n/a | descr = Descriptor() |
---|
4422 | n/a | class A(object): |
---|
4423 | n/a | __getattribute__ = descr |
---|
4424 | n/a | class B(object): |
---|
4425 | n/a | __getattr__ = descr |
---|
4426 | n/a | class C(object): |
---|
4427 | n/a | __getattribute__ = descr |
---|
4428 | n/a | __getattr__ = descr |
---|
4429 | n/a | |
---|
4430 | n/a | self.assertRaises(AttributeError, getattr, A(), "attr") |
---|
4431 | n/a | self.assertEqual(descr.counter, 1) |
---|
4432 | n/a | self.assertRaises(AttributeError, getattr, B(), "attr") |
---|
4433 | n/a | self.assertEqual(descr.counter, 2) |
---|
4434 | n/a | self.assertRaises(AttributeError, getattr, C(), "attr") |
---|
4435 | n/a | self.assertEqual(descr.counter, 4) |
---|
4436 | n/a | |
---|
4437 | n/a | class EvilGetattribute(object): |
---|
4438 | n/a | # This used to segfault |
---|
4439 | n/a | def __getattr__(self, name): |
---|
4440 | n/a | raise AttributeError(name) |
---|
4441 | n/a | def __getattribute__(self, name): |
---|
4442 | n/a | del EvilGetattribute.__getattr__ |
---|
4443 | n/a | for i in range(5): |
---|
4444 | n/a | gc.collect() |
---|
4445 | n/a | raise AttributeError(name) |
---|
4446 | n/a | |
---|
4447 | n/a | self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr") |
---|
4448 | n/a | |
---|
4449 | n/a | def test_type___getattribute__(self): |
---|
4450 | n/a | self.assertRaises(TypeError, type.__getattribute__, list, type) |
---|
4451 | n/a | |
---|
4452 | n/a | def test_abstractmethods(self): |
---|
4453 | n/a | # type pretends not to have __abstractmethods__. |
---|
4454 | n/a | self.assertRaises(AttributeError, getattr, type, "__abstractmethods__") |
---|
4455 | n/a | class meta(type): |
---|
4456 | n/a | pass |
---|
4457 | n/a | self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__") |
---|
4458 | n/a | class X(object): |
---|
4459 | n/a | pass |
---|
4460 | n/a | with self.assertRaises(AttributeError): |
---|
4461 | n/a | del X.__abstractmethods__ |
---|
4462 | n/a | |
---|
4463 | n/a | def test_proxy_call(self): |
---|
4464 | n/a | class FakeStr: |
---|
4465 | n/a | __class__ = str |
---|
4466 | n/a | |
---|
4467 | n/a | fake_str = FakeStr() |
---|
4468 | n/a | # isinstance() reads __class__ |
---|
4469 | n/a | self.assertIsInstance(fake_str, str) |
---|
4470 | n/a | |
---|
4471 | n/a | # call a method descriptor |
---|
4472 | n/a | with self.assertRaises(TypeError): |
---|
4473 | n/a | str.split(fake_str) |
---|
4474 | n/a | |
---|
4475 | n/a | # call a slot wrapper descriptor |
---|
4476 | n/a | with self.assertRaises(TypeError): |
---|
4477 | n/a | str.__add__(fake_str, "abc") |
---|
4478 | n/a | |
---|
4479 | n/a | def test_repr_as_str(self): |
---|
4480 | n/a | # Issue #11603: crash or infinite loop when rebinding __str__ as |
---|
4481 | n/a | # __repr__. |
---|
4482 | n/a | class Foo: |
---|
4483 | n/a | pass |
---|
4484 | n/a | Foo.__repr__ = Foo.__str__ |
---|
4485 | n/a | foo = Foo() |
---|
4486 | n/a | self.assertRaises(RecursionError, str, foo) |
---|
4487 | n/a | self.assertRaises(RecursionError, repr, foo) |
---|
4488 | n/a | |
---|
4489 | n/a | def test_mixing_slot_wrappers(self): |
---|
4490 | n/a | class X(dict): |
---|
4491 | n/a | __setattr__ = dict.__setitem__ |
---|
4492 | n/a | x = X() |
---|
4493 | n/a | x.y = 42 |
---|
4494 | n/a | self.assertEqual(x["y"], 42) |
---|
4495 | n/a | |
---|
4496 | n/a | def test_slot_shadows_class_variable(self): |
---|
4497 | n/a | with self.assertRaises(ValueError) as cm: |
---|
4498 | n/a | class X: |
---|
4499 | n/a | __slots__ = ["foo"] |
---|
4500 | n/a | foo = None |
---|
4501 | n/a | m = str(cm.exception) |
---|
4502 | n/a | self.assertEqual("'foo' in __slots__ conflicts with class variable", m) |
---|
4503 | n/a | |
---|
4504 | n/a | def test_set_doc(self): |
---|
4505 | n/a | class X: |
---|
4506 | n/a | "elephant" |
---|
4507 | n/a | X.__doc__ = "banana" |
---|
4508 | n/a | self.assertEqual(X.__doc__, "banana") |
---|
4509 | n/a | with self.assertRaises(TypeError) as cm: |
---|
4510 | n/a | type(list).__dict__["__doc__"].__set__(list, "blah") |
---|
4511 | n/a | self.assertIn("can't set list.__doc__", str(cm.exception)) |
---|
4512 | n/a | with self.assertRaises(TypeError) as cm: |
---|
4513 | n/a | type(X).__dict__["__doc__"].__delete__(X) |
---|
4514 | n/a | self.assertIn("can't delete X.__doc__", str(cm.exception)) |
---|
4515 | n/a | self.assertEqual(X.__doc__, "banana") |
---|
4516 | n/a | |
---|
4517 | n/a | def test_qualname(self): |
---|
4518 | n/a | descriptors = [str.lower, complex.real, float.real, int.__add__] |
---|
4519 | n/a | types = ['method', 'member', 'getset', 'wrapper'] |
---|
4520 | n/a | |
---|
4521 | n/a | # make sure we have an example of each type of descriptor |
---|
4522 | n/a | for d, n in zip(descriptors, types): |
---|
4523 | n/a | self.assertEqual(type(d).__name__, n + '_descriptor') |
---|
4524 | n/a | |
---|
4525 | n/a | for d in descriptors: |
---|
4526 | n/a | qualname = d.__objclass__.__qualname__ + '.' + d.__name__ |
---|
4527 | n/a | self.assertEqual(d.__qualname__, qualname) |
---|
4528 | n/a | |
---|
4529 | n/a | self.assertEqual(str.lower.__qualname__, 'str.lower') |
---|
4530 | n/a | self.assertEqual(complex.real.__qualname__, 'complex.real') |
---|
4531 | n/a | self.assertEqual(float.real.__qualname__, 'float.real') |
---|
4532 | n/a | self.assertEqual(int.__add__.__qualname__, 'int.__add__') |
---|
4533 | n/a | |
---|
4534 | n/a | class X: |
---|
4535 | n/a | pass |
---|
4536 | n/a | with self.assertRaises(TypeError): |
---|
4537 | n/a | del X.__qualname__ |
---|
4538 | n/a | |
---|
4539 | n/a | self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__, |
---|
4540 | n/a | str, 'Oink') |
---|
4541 | n/a | |
---|
4542 | n/a | global Y |
---|
4543 | n/a | class Y: |
---|
4544 | n/a | class Inside: |
---|
4545 | n/a | pass |
---|
4546 | n/a | self.assertEqual(Y.__qualname__, 'Y') |
---|
4547 | n/a | self.assertEqual(Y.Inside.__qualname__, 'Y.Inside') |
---|
4548 | n/a | |
---|
4549 | n/a | def test_qualname_dict(self): |
---|
4550 | n/a | ns = {'__qualname__': 'some.name'} |
---|
4551 | n/a | tp = type('Foo', (), ns) |
---|
4552 | n/a | self.assertEqual(tp.__qualname__, 'some.name') |
---|
4553 | n/a | self.assertNotIn('__qualname__', tp.__dict__) |
---|
4554 | n/a | self.assertEqual(ns, {'__qualname__': 'some.name'}) |
---|
4555 | n/a | |
---|
4556 | n/a | ns = {'__qualname__': 1} |
---|
4557 | n/a | self.assertRaises(TypeError, type, 'Foo', (), ns) |
---|
4558 | n/a | |
---|
4559 | n/a | def test_cycle_through_dict(self): |
---|
4560 | n/a | # See bug #1469629 |
---|
4561 | n/a | class X(dict): |
---|
4562 | n/a | def __init__(self): |
---|
4563 | n/a | dict.__init__(self) |
---|
4564 | n/a | self.__dict__ = self |
---|
4565 | n/a | x = X() |
---|
4566 | n/a | x.attr = 42 |
---|
4567 | n/a | wr = weakref.ref(x) |
---|
4568 | n/a | del x |
---|
4569 | n/a | support.gc_collect() |
---|
4570 | n/a | self.assertIsNone(wr()) |
---|
4571 | n/a | for o in gc.get_objects(): |
---|
4572 | n/a | self.assertIsNot(type(o), X) |
---|
4573 | n/a | |
---|
4574 | n/a | def test_object_new_and_init_with_parameters(self): |
---|
4575 | n/a | # See issue #1683368 |
---|
4576 | n/a | class OverrideNeither: |
---|
4577 | n/a | pass |
---|
4578 | n/a | self.assertRaises(TypeError, OverrideNeither, 1) |
---|
4579 | n/a | self.assertRaises(TypeError, OverrideNeither, kw=1) |
---|
4580 | n/a | class OverrideNew: |
---|
4581 | n/a | def __new__(cls, foo, kw=0, *args, **kwds): |
---|
4582 | n/a | return object.__new__(cls, *args, **kwds) |
---|
4583 | n/a | class OverrideInit: |
---|
4584 | n/a | def __init__(self, foo, kw=0, *args, **kwargs): |
---|
4585 | n/a | return object.__init__(self, *args, **kwargs) |
---|
4586 | n/a | class OverrideBoth(OverrideNew, OverrideInit): |
---|
4587 | n/a | pass |
---|
4588 | n/a | for case in OverrideNew, OverrideInit, OverrideBoth: |
---|
4589 | n/a | case(1) |
---|
4590 | n/a | case(1, kw=2) |
---|
4591 | n/a | self.assertRaises(TypeError, case, 1, 2, 3) |
---|
4592 | n/a | self.assertRaises(TypeError, case, 1, 2, foo=3) |
---|
4593 | n/a | |
---|
4594 | n/a | def test_subclassing_does_not_duplicate_dict_descriptors(self): |
---|
4595 | n/a | class Base: |
---|
4596 | n/a | pass |
---|
4597 | n/a | class Sub(Base): |
---|
4598 | n/a | pass |
---|
4599 | n/a | self.assertIn("__dict__", Base.__dict__) |
---|
4600 | n/a | self.assertNotIn("__dict__", Sub.__dict__) |
---|
4601 | n/a | |
---|
4602 | n/a | def test_bound_method_repr(self): |
---|
4603 | n/a | class Foo: |
---|
4604 | n/a | def method(self): |
---|
4605 | n/a | pass |
---|
4606 | n/a | self.assertRegex(repr(Foo().method), |
---|
4607 | n/a | r"<bound method .*Foo\.method of <.*Foo object at .*>>") |
---|
4608 | n/a | |
---|
4609 | n/a | |
---|
4610 | n/a | class Base: |
---|
4611 | n/a | def method(self): |
---|
4612 | n/a | pass |
---|
4613 | n/a | class Derived1(Base): |
---|
4614 | n/a | pass |
---|
4615 | n/a | class Derived2(Base): |
---|
4616 | n/a | def method(self): |
---|
4617 | n/a | pass |
---|
4618 | n/a | base = Base() |
---|
4619 | n/a | derived1 = Derived1() |
---|
4620 | n/a | derived2 = Derived2() |
---|
4621 | n/a | super_d2 = super(Derived2, derived2) |
---|
4622 | n/a | self.assertRegex(repr(base.method), |
---|
4623 | n/a | r"<bound method .*Base\.method of <.*Base object at .*>>") |
---|
4624 | n/a | self.assertRegex(repr(derived1.method), |
---|
4625 | n/a | r"<bound method .*Base\.method of <.*Derived1 object at .*>>") |
---|
4626 | n/a | self.assertRegex(repr(derived2.method), |
---|
4627 | n/a | r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>") |
---|
4628 | n/a | self.assertRegex(repr(super_d2.method), |
---|
4629 | n/a | r"<bound method .*Base\.method of <.*Derived2 object at .*>>") |
---|
4630 | n/a | |
---|
4631 | n/a | class Foo: |
---|
4632 | n/a | @classmethod |
---|
4633 | n/a | def method(cls): |
---|
4634 | n/a | pass |
---|
4635 | n/a | foo = Foo() |
---|
4636 | n/a | self.assertRegex(repr(foo.method), # access via instance |
---|
4637 | n/a | r"<bound method .*Foo\.method of <class '.*Foo'>>") |
---|
4638 | n/a | self.assertRegex(repr(Foo.method), # access via the class |
---|
4639 | n/a | r"<bound method .*Foo\.method of <class '.*Foo'>>") |
---|
4640 | n/a | |
---|
4641 | n/a | |
---|
4642 | n/a | class MyCallable: |
---|
4643 | n/a | def __call__(self, arg): |
---|
4644 | n/a | pass |
---|
4645 | n/a | func = MyCallable() # func has no __name__ or __qualname__ attributes |
---|
4646 | n/a | instance = object() |
---|
4647 | n/a | method = types.MethodType(func, instance) |
---|
4648 | n/a | self.assertRegex(repr(method), |
---|
4649 | n/a | r"<bound method \? of <object object at .*>>") |
---|
4650 | n/a | func.__name__ = "name" |
---|
4651 | n/a | self.assertRegex(repr(method), |
---|
4652 | n/a | r"<bound method name of <object object at .*>>") |
---|
4653 | n/a | func.__qualname__ = "qualname" |
---|
4654 | n/a | self.assertRegex(repr(method), |
---|
4655 | n/a | r"<bound method qualname of <object object at .*>>") |
---|
4656 | n/a | |
---|
4657 | n/a | |
---|
4658 | n/a | class DictProxyTests(unittest.TestCase): |
---|
4659 | n/a | def setUp(self): |
---|
4660 | n/a | class C(object): |
---|
4661 | n/a | def meth(self): |
---|
4662 | n/a | pass |
---|
4663 | n/a | self.C = C |
---|
4664 | n/a | |
---|
4665 | n/a | @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
---|
4666 | n/a | 'trace function introduces __local__') |
---|
4667 | n/a | def test_iter_keys(self): |
---|
4668 | n/a | # Testing dict-proxy keys... |
---|
4669 | n/a | it = self.C.__dict__.keys() |
---|
4670 | n/a | self.assertNotIsInstance(it, list) |
---|
4671 | n/a | keys = list(it) |
---|
4672 | n/a | keys.sort() |
---|
4673 | n/a | self.assertEqual(keys, ['__dict__', '__doc__', '__module__', |
---|
4674 | n/a | '__weakref__', 'meth']) |
---|
4675 | n/a | |
---|
4676 | n/a | @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
---|
4677 | n/a | 'trace function introduces __local__') |
---|
4678 | n/a | def test_iter_values(self): |
---|
4679 | n/a | # Testing dict-proxy values... |
---|
4680 | n/a | it = self.C.__dict__.values() |
---|
4681 | n/a | self.assertNotIsInstance(it, list) |
---|
4682 | n/a | values = list(it) |
---|
4683 | n/a | self.assertEqual(len(values), 5) |
---|
4684 | n/a | |
---|
4685 | n/a | @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
---|
4686 | n/a | 'trace function introduces __local__') |
---|
4687 | n/a | def test_iter_items(self): |
---|
4688 | n/a | # Testing dict-proxy iteritems... |
---|
4689 | n/a | it = self.C.__dict__.items() |
---|
4690 | n/a | self.assertNotIsInstance(it, list) |
---|
4691 | n/a | keys = [item[0] for item in it] |
---|
4692 | n/a | keys.sort() |
---|
4693 | n/a | self.assertEqual(keys, ['__dict__', '__doc__', '__module__', |
---|
4694 | n/a | '__weakref__', 'meth']) |
---|
4695 | n/a | |
---|
4696 | n/a | def test_dict_type_with_metaclass(self): |
---|
4697 | n/a | # Testing type of __dict__ when metaclass set... |
---|
4698 | n/a | class B(object): |
---|
4699 | n/a | pass |
---|
4700 | n/a | class M(type): |
---|
4701 | n/a | pass |
---|
4702 | n/a | class C(metaclass=M): |
---|
4703 | n/a | # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy |
---|
4704 | n/a | pass |
---|
4705 | n/a | self.assertEqual(type(C.__dict__), type(B.__dict__)) |
---|
4706 | n/a | |
---|
4707 | n/a | def test_repr(self): |
---|
4708 | n/a | # Testing mappingproxy.__repr__. |
---|
4709 | n/a | # We can't blindly compare with the repr of another dict as ordering |
---|
4710 | n/a | # of keys and values is arbitrary and may differ. |
---|
4711 | n/a | r = repr(self.C.__dict__) |
---|
4712 | n/a | self.assertTrue(r.startswith('mappingproxy('), r) |
---|
4713 | n/a | self.assertTrue(r.endswith(')'), r) |
---|
4714 | n/a | for k, v in self.C.__dict__.items(): |
---|
4715 | n/a | self.assertIn('{!r}: {!r}'.format(k, v), r) |
---|
4716 | n/a | |
---|
4717 | n/a | |
---|
4718 | n/a | class PTypesLongInitTest(unittest.TestCase): |
---|
4719 | n/a | # This is in its own TestCase so that it can be run before any other tests. |
---|
4720 | n/a | def test_pytype_long_ready(self): |
---|
4721 | n/a | # Testing SF bug 551412 ... |
---|
4722 | n/a | |
---|
4723 | n/a | # This dumps core when SF bug 551412 isn't fixed -- |
---|
4724 | n/a | # but only when test_descr.py is run separately. |
---|
4725 | n/a | # (That can't be helped -- as soon as PyType_Ready() |
---|
4726 | n/a | # is called for PyLong_Type, the bug is gone.) |
---|
4727 | n/a | class UserLong(object): |
---|
4728 | n/a | def __pow__(self, *args): |
---|
4729 | n/a | pass |
---|
4730 | n/a | try: |
---|
4731 | n/a | pow(0, UserLong(), 0) |
---|
4732 | n/a | except: |
---|
4733 | n/a | pass |
---|
4734 | n/a | |
---|
4735 | n/a | # Another segfault only when run early |
---|
4736 | n/a | # (before PyType_Ready(tuple) is called) |
---|
4737 | n/a | type.mro(tuple) |
---|
4738 | n/a | |
---|
4739 | n/a | |
---|
4740 | n/a | class MiscTests(unittest.TestCase): |
---|
4741 | n/a | def test_type_lookup_mro_reference(self): |
---|
4742 | n/a | # Issue #14199: _PyType_Lookup() has to keep a strong reference to |
---|
4743 | n/a | # the type MRO because it may be modified during the lookup, if |
---|
4744 | n/a | # __bases__ is set during the lookup for example. |
---|
4745 | n/a | class MyKey(object): |
---|
4746 | n/a | def __hash__(self): |
---|
4747 | n/a | return hash('mykey') |
---|
4748 | n/a | |
---|
4749 | n/a | def __eq__(self, other): |
---|
4750 | n/a | X.__bases__ = (Base2,) |
---|
4751 | n/a | |
---|
4752 | n/a | class Base(object): |
---|
4753 | n/a | mykey = 'from Base' |
---|
4754 | n/a | mykey2 = 'from Base' |
---|
4755 | n/a | |
---|
4756 | n/a | class Base2(object): |
---|
4757 | n/a | mykey = 'from Base2' |
---|
4758 | n/a | mykey2 = 'from Base2' |
---|
4759 | n/a | |
---|
4760 | n/a | X = type('X', (Base,), {MyKey(): 5}) |
---|
4761 | n/a | # mykey is read from Base |
---|
4762 | n/a | self.assertEqual(X.mykey, 'from Base') |
---|
4763 | n/a | # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__ |
---|
4764 | n/a | self.assertEqual(X.mykey2, 'from Base2') |
---|
4765 | n/a | |
---|
4766 | n/a | |
---|
4767 | n/a | class PicklingTests(unittest.TestCase): |
---|
4768 | n/a | |
---|
4769 | n/a | def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None, |
---|
4770 | n/a | listitems=None, dictitems=None): |
---|
4771 | n/a | if proto >= 2: |
---|
4772 | n/a | reduce_value = obj.__reduce_ex__(proto) |
---|
4773 | n/a | if kwargs: |
---|
4774 | n/a | self.assertEqual(reduce_value[0], copyreg.__newobj_ex__) |
---|
4775 | n/a | self.assertEqual(reduce_value[1], (type(obj), args, kwargs)) |
---|
4776 | n/a | else: |
---|
4777 | n/a | self.assertEqual(reduce_value[0], copyreg.__newobj__) |
---|
4778 | n/a | self.assertEqual(reduce_value[1], (type(obj),) + args) |
---|
4779 | n/a | self.assertEqual(reduce_value[2], state) |
---|
4780 | n/a | if listitems is not None: |
---|
4781 | n/a | self.assertListEqual(list(reduce_value[3]), listitems) |
---|
4782 | n/a | else: |
---|
4783 | n/a | self.assertIsNone(reduce_value[3]) |
---|
4784 | n/a | if dictitems is not None: |
---|
4785 | n/a | self.assertDictEqual(dict(reduce_value[4]), dictitems) |
---|
4786 | n/a | else: |
---|
4787 | n/a | self.assertIsNone(reduce_value[4]) |
---|
4788 | n/a | else: |
---|
4789 | n/a | base_type = type(obj).__base__ |
---|
4790 | n/a | reduce_value = (copyreg._reconstructor, |
---|
4791 | n/a | (type(obj), |
---|
4792 | n/a | base_type, |
---|
4793 | n/a | None if base_type is object else base_type(obj))) |
---|
4794 | n/a | if state is not None: |
---|
4795 | n/a | reduce_value += (state,) |
---|
4796 | n/a | self.assertEqual(obj.__reduce_ex__(proto), reduce_value) |
---|
4797 | n/a | self.assertEqual(obj.__reduce__(), reduce_value) |
---|
4798 | n/a | |
---|
4799 | n/a | def test_reduce(self): |
---|
4800 | n/a | protocols = range(pickle.HIGHEST_PROTOCOL + 1) |
---|
4801 | n/a | args = (-101, "spam") |
---|
4802 | n/a | kwargs = {'bacon': -201, 'fish': -301} |
---|
4803 | n/a | state = {'cheese': -401} |
---|
4804 | n/a | |
---|
4805 | n/a | class C1: |
---|
4806 | n/a | def __getnewargs__(self): |
---|
4807 | n/a | return args |
---|
4808 | n/a | obj = C1() |
---|
4809 | n/a | for proto in protocols: |
---|
4810 | n/a | self._check_reduce(proto, obj, args) |
---|
4811 | n/a | |
---|
4812 | n/a | for name, value in state.items(): |
---|
4813 | n/a | setattr(obj, name, value) |
---|
4814 | n/a | for proto in protocols: |
---|
4815 | n/a | self._check_reduce(proto, obj, args, state=state) |
---|
4816 | n/a | |
---|
4817 | n/a | class C2: |
---|
4818 | n/a | def __getnewargs__(self): |
---|
4819 | n/a | return "bad args" |
---|
4820 | n/a | obj = C2() |
---|
4821 | n/a | for proto in protocols: |
---|
4822 | n/a | if proto >= 2: |
---|
4823 | n/a | with self.assertRaises(TypeError): |
---|
4824 | n/a | obj.__reduce_ex__(proto) |
---|
4825 | n/a | |
---|
4826 | n/a | class C3: |
---|
4827 | n/a | def __getnewargs_ex__(self): |
---|
4828 | n/a | return (args, kwargs) |
---|
4829 | n/a | obj = C3() |
---|
4830 | n/a | for proto in protocols: |
---|
4831 | n/a | if proto >= 2: |
---|
4832 | n/a | self._check_reduce(proto, obj, args, kwargs) |
---|
4833 | n/a | |
---|
4834 | n/a | class C4: |
---|
4835 | n/a | def __getnewargs_ex__(self): |
---|
4836 | n/a | return (args, "bad dict") |
---|
4837 | n/a | class C5: |
---|
4838 | n/a | def __getnewargs_ex__(self): |
---|
4839 | n/a | return ("bad tuple", kwargs) |
---|
4840 | n/a | class C6: |
---|
4841 | n/a | def __getnewargs_ex__(self): |
---|
4842 | n/a | return () |
---|
4843 | n/a | class C7: |
---|
4844 | n/a | def __getnewargs_ex__(self): |
---|
4845 | n/a | return "bad args" |
---|
4846 | n/a | for proto in protocols: |
---|
4847 | n/a | for cls in C4, C5, C6, C7: |
---|
4848 | n/a | obj = cls() |
---|
4849 | n/a | if proto >= 2: |
---|
4850 | n/a | with self.assertRaises((TypeError, ValueError)): |
---|
4851 | n/a | obj.__reduce_ex__(proto) |
---|
4852 | n/a | |
---|
4853 | n/a | class C9: |
---|
4854 | n/a | def __getnewargs_ex__(self): |
---|
4855 | n/a | return (args, {}) |
---|
4856 | n/a | obj = C9() |
---|
4857 | n/a | for proto in protocols: |
---|
4858 | n/a | self._check_reduce(proto, obj, args) |
---|
4859 | n/a | |
---|
4860 | n/a | class C10: |
---|
4861 | n/a | def __getnewargs_ex__(self): |
---|
4862 | n/a | raise IndexError |
---|
4863 | n/a | obj = C10() |
---|
4864 | n/a | for proto in protocols: |
---|
4865 | n/a | if proto >= 2: |
---|
4866 | n/a | with self.assertRaises(IndexError): |
---|
4867 | n/a | obj.__reduce_ex__(proto) |
---|
4868 | n/a | |
---|
4869 | n/a | class C11: |
---|
4870 | n/a | def __getstate__(self): |
---|
4871 | n/a | return state |
---|
4872 | n/a | obj = C11() |
---|
4873 | n/a | for proto in protocols: |
---|
4874 | n/a | self._check_reduce(proto, obj, state=state) |
---|
4875 | n/a | |
---|
4876 | n/a | class C12: |
---|
4877 | n/a | def __getstate__(self): |
---|
4878 | n/a | return "not dict" |
---|
4879 | n/a | obj = C12() |
---|
4880 | n/a | for proto in protocols: |
---|
4881 | n/a | self._check_reduce(proto, obj, state="not dict") |
---|
4882 | n/a | |
---|
4883 | n/a | class C13: |
---|
4884 | n/a | def __getstate__(self): |
---|
4885 | n/a | raise IndexError |
---|
4886 | n/a | obj = C13() |
---|
4887 | n/a | for proto in protocols: |
---|
4888 | n/a | with self.assertRaises(IndexError): |
---|
4889 | n/a | obj.__reduce_ex__(proto) |
---|
4890 | n/a | if proto < 2: |
---|
4891 | n/a | with self.assertRaises(IndexError): |
---|
4892 | n/a | obj.__reduce__() |
---|
4893 | n/a | |
---|
4894 | n/a | class C14: |
---|
4895 | n/a | __slots__ = tuple(state) |
---|
4896 | n/a | def __init__(self): |
---|
4897 | n/a | for name, value in state.items(): |
---|
4898 | n/a | setattr(self, name, value) |
---|
4899 | n/a | |
---|
4900 | n/a | obj = C14() |
---|
4901 | n/a | for proto in protocols: |
---|
4902 | n/a | if proto >= 2: |
---|
4903 | n/a | self._check_reduce(proto, obj, state=(None, state)) |
---|
4904 | n/a | else: |
---|
4905 | n/a | with self.assertRaises(TypeError): |
---|
4906 | n/a | obj.__reduce_ex__(proto) |
---|
4907 | n/a | with self.assertRaises(TypeError): |
---|
4908 | n/a | obj.__reduce__() |
---|
4909 | n/a | |
---|
4910 | n/a | class C15(dict): |
---|
4911 | n/a | pass |
---|
4912 | n/a | obj = C15({"quebec": -601}) |
---|
4913 | n/a | for proto in protocols: |
---|
4914 | n/a | self._check_reduce(proto, obj, dictitems=dict(obj)) |
---|
4915 | n/a | |
---|
4916 | n/a | class C16(list): |
---|
4917 | n/a | pass |
---|
4918 | n/a | obj = C16(["yukon"]) |
---|
4919 | n/a | for proto in protocols: |
---|
4920 | n/a | self._check_reduce(proto, obj, listitems=list(obj)) |
---|
4921 | n/a | |
---|
4922 | n/a | def test_special_method_lookup(self): |
---|
4923 | n/a | protocols = range(pickle.HIGHEST_PROTOCOL + 1) |
---|
4924 | n/a | class Picky: |
---|
4925 | n/a | def __getstate__(self): |
---|
4926 | n/a | return {} |
---|
4927 | n/a | |
---|
4928 | n/a | def __getattr__(self, attr): |
---|
4929 | n/a | if attr in ("__getnewargs__", "__getnewargs_ex__"): |
---|
4930 | n/a | raise AssertionError(attr) |
---|
4931 | n/a | return None |
---|
4932 | n/a | for protocol in protocols: |
---|
4933 | n/a | state = {} if protocol >= 2 else None |
---|
4934 | n/a | self._check_reduce(protocol, Picky(), state=state) |
---|
4935 | n/a | |
---|
4936 | n/a | def _assert_is_copy(self, obj, objcopy, msg=None): |
---|
4937 | n/a | """Utility method to verify if two objects are copies of each others. |
---|
4938 | n/a | """ |
---|
4939 | n/a | if msg is None: |
---|
4940 | n/a | msg = "{!r} is not a copy of {!r}".format(obj, objcopy) |
---|
4941 | n/a | if type(obj).__repr__ is object.__repr__: |
---|
4942 | n/a | # We have this limitation for now because we use the object's repr |
---|
4943 | n/a | # to help us verify that the two objects are copies. This allows |
---|
4944 | n/a | # us to delegate the non-generic verification logic to the objects |
---|
4945 | n/a | # themselves. |
---|
4946 | n/a | raise ValueError("object passed to _assert_is_copy must " + |
---|
4947 | n/a | "override the __repr__ method.") |
---|
4948 | n/a | self.assertIsNot(obj, objcopy, msg=msg) |
---|
4949 | n/a | self.assertIs(type(obj), type(objcopy), msg=msg) |
---|
4950 | n/a | if hasattr(obj, '__dict__'): |
---|
4951 | n/a | self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg) |
---|
4952 | n/a | self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg) |
---|
4953 | n/a | if hasattr(obj, '__slots__'): |
---|
4954 | n/a | self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg) |
---|
4955 | n/a | for slot in obj.__slots__: |
---|
4956 | n/a | self.assertEqual( |
---|
4957 | n/a | hasattr(obj, slot), hasattr(objcopy, slot), msg=msg) |
---|
4958 | n/a | self.assertEqual(getattr(obj, slot, None), |
---|
4959 | n/a | getattr(objcopy, slot, None), msg=msg) |
---|
4960 | n/a | self.assertEqual(repr(obj), repr(objcopy), msg=msg) |
---|
4961 | n/a | |
---|
4962 | n/a | @staticmethod |
---|
4963 | n/a | def _generate_pickle_copiers(): |
---|
4964 | n/a | """Utility method to generate the many possible pickle configurations. |
---|
4965 | n/a | """ |
---|
4966 | n/a | class PickleCopier: |
---|
4967 | n/a | "This class copies object using pickle." |
---|
4968 | n/a | def __init__(self, proto, dumps, loads): |
---|
4969 | n/a | self.proto = proto |
---|
4970 | n/a | self.dumps = dumps |
---|
4971 | n/a | self.loads = loads |
---|
4972 | n/a | def copy(self, obj): |
---|
4973 | n/a | return self.loads(self.dumps(obj, self.proto)) |
---|
4974 | n/a | def __repr__(self): |
---|
4975 | n/a | # We try to be as descriptive as possible here since this is |
---|
4976 | n/a | # the string which we will allow us to tell the pickle |
---|
4977 | n/a | # configuration we are using during debugging. |
---|
4978 | n/a | return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})" |
---|
4979 | n/a | .format(self.proto, |
---|
4980 | n/a | self.dumps.__module__, self.dumps.__qualname__, |
---|
4981 | n/a | self.loads.__module__, self.loads.__qualname__)) |
---|
4982 | n/a | return (PickleCopier(*args) for args in |
---|
4983 | n/a | itertools.product(range(pickle.HIGHEST_PROTOCOL + 1), |
---|
4984 | n/a | {pickle.dumps, pickle._dumps}, |
---|
4985 | n/a | {pickle.loads, pickle._loads})) |
---|
4986 | n/a | |
---|
4987 | n/a | def test_pickle_slots(self): |
---|
4988 | n/a | # Tests pickling of classes with __slots__. |
---|
4989 | n/a | |
---|
4990 | n/a | # Pickling of classes with __slots__ but without __getstate__ should |
---|
4991 | n/a | # fail (if using protocol 0 or 1) |
---|
4992 | n/a | global C |
---|
4993 | n/a | class C: |
---|
4994 | n/a | __slots__ = ['a'] |
---|
4995 | n/a | with self.assertRaises(TypeError): |
---|
4996 | n/a | pickle.dumps(C(), 0) |
---|
4997 | n/a | |
---|
4998 | n/a | global D |
---|
4999 | n/a | class D(C): |
---|
5000 | n/a | pass |
---|
5001 | n/a | with self.assertRaises(TypeError): |
---|
5002 | n/a | pickle.dumps(D(), 0) |
---|
5003 | n/a | |
---|
5004 | n/a | class C: |
---|
5005 | n/a | "A class with __getstate__ and __setstate__ implemented." |
---|
5006 | n/a | __slots__ = ['a'] |
---|
5007 | n/a | def __getstate__(self): |
---|
5008 | n/a | state = getattr(self, '__dict__', {}).copy() |
---|
5009 | n/a | for cls in type(self).__mro__: |
---|
5010 | n/a | for slot in cls.__dict__.get('__slots__', ()): |
---|
5011 | n/a | try: |
---|
5012 | n/a | state[slot] = getattr(self, slot) |
---|
5013 | n/a | except AttributeError: |
---|
5014 | n/a | pass |
---|
5015 | n/a | return state |
---|
5016 | n/a | def __setstate__(self, state): |
---|
5017 | n/a | for k, v in state.items(): |
---|
5018 | n/a | setattr(self, k, v) |
---|
5019 | n/a | def __repr__(self): |
---|
5020 | n/a | return "%s()<%r>" % (type(self).__name__, self.__getstate__()) |
---|
5021 | n/a | |
---|
5022 | n/a | class D(C): |
---|
5023 | n/a | "A subclass of a class with slots." |
---|
5024 | n/a | pass |
---|
5025 | n/a | |
---|
5026 | n/a | global E |
---|
5027 | n/a | class E(C): |
---|
5028 | n/a | "A subclass with an extra slot." |
---|
5029 | n/a | __slots__ = ['b'] |
---|
5030 | n/a | |
---|
5031 | n/a | # Now it should work |
---|
5032 | n/a | for pickle_copier in self._generate_pickle_copiers(): |
---|
5033 | n/a | with self.subTest(pickle_copier=pickle_copier): |
---|
5034 | n/a | x = C() |
---|
5035 | n/a | y = pickle_copier.copy(x) |
---|
5036 | n/a | self._assert_is_copy(x, y) |
---|
5037 | n/a | |
---|
5038 | n/a | x.a = 42 |
---|
5039 | n/a | y = pickle_copier.copy(x) |
---|
5040 | n/a | self._assert_is_copy(x, y) |
---|
5041 | n/a | |
---|
5042 | n/a | x = D() |
---|
5043 | n/a | x.a = 42 |
---|
5044 | n/a | x.b = 100 |
---|
5045 | n/a | y = pickle_copier.copy(x) |
---|
5046 | n/a | self._assert_is_copy(x, y) |
---|
5047 | n/a | |
---|
5048 | n/a | x = E() |
---|
5049 | n/a | x.a = 42 |
---|
5050 | n/a | x.b = "foo" |
---|
5051 | n/a | y = pickle_copier.copy(x) |
---|
5052 | n/a | self._assert_is_copy(x, y) |
---|
5053 | n/a | |
---|
5054 | n/a | def test_reduce_copying(self): |
---|
5055 | n/a | # Tests pickling and copying new-style classes and objects. |
---|
5056 | n/a | global C1 |
---|
5057 | n/a | class C1: |
---|
5058 | n/a | "The state of this class is copyable via its instance dict." |
---|
5059 | n/a | ARGS = (1, 2) |
---|
5060 | n/a | NEED_DICT_COPYING = True |
---|
5061 | n/a | def __init__(self, a, b): |
---|
5062 | n/a | super().__init__() |
---|
5063 | n/a | self.a = a |
---|
5064 | n/a | self.b = b |
---|
5065 | n/a | def __repr__(self): |
---|
5066 | n/a | return "C1(%r, %r)" % (self.a, self.b) |
---|
5067 | n/a | |
---|
5068 | n/a | global C2 |
---|
5069 | n/a | class C2(list): |
---|
5070 | n/a | "A list subclass copyable via __getnewargs__." |
---|
5071 | n/a | ARGS = (1, 2) |
---|
5072 | n/a | NEED_DICT_COPYING = False |
---|
5073 | n/a | def __new__(cls, a, b): |
---|
5074 | n/a | self = super().__new__(cls) |
---|
5075 | n/a | self.a = a |
---|
5076 | n/a | self.b = b |
---|
5077 | n/a | return self |
---|
5078 | n/a | def __init__(self, *args): |
---|
5079 | n/a | super().__init__() |
---|
5080 | n/a | # This helps testing that __init__ is not called during the |
---|
5081 | n/a | # unpickling process, which would cause extra appends. |
---|
5082 | n/a | self.append("cheese") |
---|
5083 | n/a | @classmethod |
---|
5084 | n/a | def __getnewargs__(cls): |
---|
5085 | n/a | return cls.ARGS |
---|
5086 | n/a | def __repr__(self): |
---|
5087 | n/a | return "C2(%r, %r)<%r>" % (self.a, self.b, list(self)) |
---|
5088 | n/a | |
---|
5089 | n/a | global C3 |
---|
5090 | n/a | class C3(list): |
---|
5091 | n/a | "A list subclass copyable via __getstate__." |
---|
5092 | n/a | ARGS = (1, 2) |
---|
5093 | n/a | NEED_DICT_COPYING = False |
---|
5094 | n/a | def __init__(self, a, b): |
---|
5095 | n/a | self.a = a |
---|
5096 | n/a | self.b = b |
---|
5097 | n/a | # This helps testing that __init__ is not called during the |
---|
5098 | n/a | # unpickling process, which would cause extra appends. |
---|
5099 | n/a | self.append("cheese") |
---|
5100 | n/a | @classmethod |
---|
5101 | n/a | def __getstate__(cls): |
---|
5102 | n/a | return cls.ARGS |
---|
5103 | n/a | def __setstate__(self, state): |
---|
5104 | n/a | a, b = state |
---|
5105 | n/a | self.a = a |
---|
5106 | n/a | self.b = b |
---|
5107 | n/a | def __repr__(self): |
---|
5108 | n/a | return "C3(%r, %r)<%r>" % (self.a, self.b, list(self)) |
---|
5109 | n/a | |
---|
5110 | n/a | global C4 |
---|
5111 | n/a | class C4(int): |
---|
5112 | n/a | "An int subclass copyable via __getnewargs__." |
---|
5113 | n/a | ARGS = ("hello", "world", 1) |
---|
5114 | n/a | NEED_DICT_COPYING = False |
---|
5115 | n/a | def __new__(cls, a, b, value): |
---|
5116 | n/a | self = super().__new__(cls, value) |
---|
5117 | n/a | self.a = a |
---|
5118 | n/a | self.b = b |
---|
5119 | n/a | return self |
---|
5120 | n/a | @classmethod |
---|
5121 | n/a | def __getnewargs__(cls): |
---|
5122 | n/a | return cls.ARGS |
---|
5123 | n/a | def __repr__(self): |
---|
5124 | n/a | return "C4(%r, %r)<%r>" % (self.a, self.b, int(self)) |
---|
5125 | n/a | |
---|
5126 | n/a | global C5 |
---|
5127 | n/a | class C5(int): |
---|
5128 | n/a | "An int subclass copyable via __getnewargs_ex__." |
---|
5129 | n/a | ARGS = (1, 2) |
---|
5130 | n/a | KWARGS = {'value': 3} |
---|
5131 | n/a | NEED_DICT_COPYING = False |
---|
5132 | n/a | def __new__(cls, a, b, *, value=0): |
---|
5133 | n/a | self = super().__new__(cls, value) |
---|
5134 | n/a | self.a = a |
---|
5135 | n/a | self.b = b |
---|
5136 | n/a | return self |
---|
5137 | n/a | @classmethod |
---|
5138 | n/a | def __getnewargs_ex__(cls): |
---|
5139 | n/a | return (cls.ARGS, cls.KWARGS) |
---|
5140 | n/a | def __repr__(self): |
---|
5141 | n/a | return "C5(%r, %r)<%r>" % (self.a, self.b, int(self)) |
---|
5142 | n/a | |
---|
5143 | n/a | test_classes = (C1, C2, C3, C4, C5) |
---|
5144 | n/a | # Testing copying through pickle |
---|
5145 | n/a | pickle_copiers = self._generate_pickle_copiers() |
---|
5146 | n/a | for cls, pickle_copier in itertools.product(test_classes, pickle_copiers): |
---|
5147 | n/a | with self.subTest(cls=cls, pickle_copier=pickle_copier): |
---|
5148 | n/a | kwargs = getattr(cls, 'KWARGS', {}) |
---|
5149 | n/a | obj = cls(*cls.ARGS, **kwargs) |
---|
5150 | n/a | proto = pickle_copier.proto |
---|
5151 | n/a | objcopy = pickle_copier.copy(obj) |
---|
5152 | n/a | self._assert_is_copy(obj, objcopy) |
---|
5153 | n/a | # For test classes that supports this, make sure we didn't go |
---|
5154 | n/a | # around the reduce protocol by simply copying the attribute |
---|
5155 | n/a | # dictionary. We clear attributes using the previous copy to |
---|
5156 | n/a | # not mutate the original argument. |
---|
5157 | n/a | if proto >= 2 and not cls.NEED_DICT_COPYING: |
---|
5158 | n/a | objcopy.__dict__.clear() |
---|
5159 | n/a | objcopy2 = pickle_copier.copy(objcopy) |
---|
5160 | n/a | self._assert_is_copy(obj, objcopy2) |
---|
5161 | n/a | |
---|
5162 | n/a | # Testing copying through copy.deepcopy() |
---|
5163 | n/a | for cls in test_classes: |
---|
5164 | n/a | with self.subTest(cls=cls): |
---|
5165 | n/a | kwargs = getattr(cls, 'KWARGS', {}) |
---|
5166 | n/a | obj = cls(*cls.ARGS, **kwargs) |
---|
5167 | n/a | objcopy = deepcopy(obj) |
---|
5168 | n/a | self._assert_is_copy(obj, objcopy) |
---|
5169 | n/a | # For test classes that supports this, make sure we didn't go |
---|
5170 | n/a | # around the reduce protocol by simply copying the attribute |
---|
5171 | n/a | # dictionary. We clear attributes using the previous copy to |
---|
5172 | n/a | # not mutate the original argument. |
---|
5173 | n/a | if not cls.NEED_DICT_COPYING: |
---|
5174 | n/a | objcopy.__dict__.clear() |
---|
5175 | n/a | objcopy2 = deepcopy(objcopy) |
---|
5176 | n/a | self._assert_is_copy(obj, objcopy2) |
---|
5177 | n/a | |
---|
5178 | n/a | def test_issue24097(self): |
---|
5179 | n/a | # Slot name is freed inside __getattr__ and is later used. |
---|
5180 | n/a | class S(str): # Not interned |
---|
5181 | n/a | pass |
---|
5182 | n/a | class A: |
---|
5183 | n/a | __slotnames__ = [S('spam')] |
---|
5184 | n/a | def __getattr__(self, attr): |
---|
5185 | n/a | if attr == 'spam': |
---|
5186 | n/a | A.__slotnames__[:] = [S('spam')] |
---|
5187 | n/a | return 42 |
---|
5188 | n/a | else: |
---|
5189 | n/a | raise AttributeError |
---|
5190 | n/a | |
---|
5191 | n/a | import copyreg |
---|
5192 | n/a | expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None) |
---|
5193 | n/a | self.assertEqual(A().__reduce__(2), expected) # Shouldn't crash |
---|
5194 | n/a | |
---|
5195 | n/a | |
---|
5196 | n/a | class SharedKeyTests(unittest.TestCase): |
---|
5197 | n/a | |
---|
5198 | n/a | @support.cpython_only |
---|
5199 | n/a | def test_subclasses(self): |
---|
5200 | n/a | # Verify that subclasses can share keys (per PEP 412) |
---|
5201 | n/a | class A: |
---|
5202 | n/a | pass |
---|
5203 | n/a | class B(A): |
---|
5204 | n/a | pass |
---|
5205 | n/a | |
---|
5206 | n/a | a, b = A(), B() |
---|
5207 | n/a | self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b))) |
---|
5208 | n/a | self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({})) |
---|
5209 | n/a | # Initial hash table can contain at most 5 elements. |
---|
5210 | n/a | # Set 6 attributes to cause internal resizing. |
---|
5211 | n/a | a.x, a.y, a.z, a.w, a.v, a.u = range(6) |
---|
5212 | n/a | self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b))) |
---|
5213 | n/a | a2 = A() |
---|
5214 | n/a | self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2))) |
---|
5215 | n/a | self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({})) |
---|
5216 | n/a | b.u, b.v, b.w, b.t, b.s, b.r = range(6) |
---|
5217 | n/a | self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({})) |
---|
5218 | n/a | |
---|
5219 | n/a | |
---|
5220 | n/a | class DebugHelperMeta(type): |
---|
5221 | n/a | """ |
---|
5222 | n/a | Sets default __doc__ and simplifies repr() output. |
---|
5223 | n/a | """ |
---|
5224 | n/a | def __new__(mcls, name, bases, attrs): |
---|
5225 | n/a | if attrs.get('__doc__') is None: |
---|
5226 | n/a | attrs['__doc__'] = name # helps when debugging with gdb |
---|
5227 | n/a | return type.__new__(mcls, name, bases, attrs) |
---|
5228 | n/a | def __repr__(cls): |
---|
5229 | n/a | return repr(cls.__name__) |
---|
5230 | n/a | |
---|
5231 | n/a | |
---|
5232 | n/a | class MroTest(unittest.TestCase): |
---|
5233 | n/a | """ |
---|
5234 | n/a | Regressions for some bugs revealed through |
---|
5235 | n/a | mcsl.mro() customization (typeobject.c: mro_internal()) and |
---|
5236 | n/a | cls.__bases__ assignment (typeobject.c: type_set_bases()). |
---|
5237 | n/a | """ |
---|
5238 | n/a | |
---|
5239 | n/a | def setUp(self): |
---|
5240 | n/a | self.step = 0 |
---|
5241 | n/a | self.ready = False |
---|
5242 | n/a | |
---|
5243 | n/a | def step_until(self, limit): |
---|
5244 | n/a | ret = (self.step < limit) |
---|
5245 | n/a | if ret: |
---|
5246 | n/a | self.step += 1 |
---|
5247 | n/a | return ret |
---|
5248 | n/a | |
---|
5249 | n/a | def test_incomplete_set_bases_on_self(self): |
---|
5250 | n/a | """ |
---|
5251 | n/a | type_set_bases must be aware that type->tp_mro can be NULL. |
---|
5252 | n/a | """ |
---|
5253 | n/a | class M(DebugHelperMeta): |
---|
5254 | n/a | def mro(cls): |
---|
5255 | n/a | if self.step_until(1): |
---|
5256 | n/a | assert cls.__mro__ is None |
---|
5257 | n/a | cls.__bases__ += () |
---|
5258 | n/a | |
---|
5259 | n/a | return type.mro(cls) |
---|
5260 | n/a | |
---|
5261 | n/a | class A(metaclass=M): |
---|
5262 | n/a | pass |
---|
5263 | n/a | |
---|
5264 | n/a | def test_reent_set_bases_on_base(self): |
---|
5265 | n/a | """ |
---|
5266 | n/a | Deep reentrancy must not over-decref old_mro. |
---|
5267 | n/a | """ |
---|
5268 | n/a | class M(DebugHelperMeta): |
---|
5269 | n/a | def mro(cls): |
---|
5270 | n/a | if cls.__mro__ is not None and cls.__name__ == 'B': |
---|
5271 | n/a | # 4-5 steps are usually enough to make it crash somewhere |
---|
5272 | n/a | if self.step_until(10): |
---|
5273 | n/a | A.__bases__ += () |
---|
5274 | n/a | |
---|
5275 | n/a | return type.mro(cls) |
---|
5276 | n/a | |
---|
5277 | n/a | class A(metaclass=M): |
---|
5278 | n/a | pass |
---|
5279 | n/a | class B(A): |
---|
5280 | n/a | pass |
---|
5281 | n/a | B.__bases__ += () |
---|
5282 | n/a | |
---|
5283 | n/a | def test_reent_set_bases_on_direct_base(self): |
---|
5284 | n/a | """ |
---|
5285 | n/a | Similar to test_reent_set_bases_on_base, but may crash differently. |
---|
5286 | n/a | """ |
---|
5287 | n/a | class M(DebugHelperMeta): |
---|
5288 | n/a | def mro(cls): |
---|
5289 | n/a | base = cls.__bases__[0] |
---|
5290 | n/a | if base is not object: |
---|
5291 | n/a | if self.step_until(5): |
---|
5292 | n/a | base.__bases__ += () |
---|
5293 | n/a | |
---|
5294 | n/a | return type.mro(cls) |
---|
5295 | n/a | |
---|
5296 | n/a | class A(metaclass=M): |
---|
5297 | n/a | pass |
---|
5298 | n/a | class B(A): |
---|
5299 | n/a | pass |
---|
5300 | n/a | class C(B): |
---|
5301 | n/a | pass |
---|
5302 | n/a | |
---|
5303 | n/a | def test_reent_set_bases_tp_base_cycle(self): |
---|
5304 | n/a | """ |
---|
5305 | n/a | type_set_bases must check for an inheritance cycle not only through |
---|
5306 | n/a | MRO of the type, which may be not yet updated in case of reentrance, |
---|
5307 | n/a | but also through tp_base chain, which is assigned before diving into |
---|
5308 | n/a | inner calls to mro(). |
---|
5309 | n/a | |
---|
5310 | n/a | Otherwise, the following snippet can loop forever: |
---|
5311 | n/a | do { |
---|
5312 | n/a | // ... |
---|
5313 | n/a | type = type->tp_base; |
---|
5314 | n/a | } while (type != NULL); |
---|
5315 | n/a | |
---|
5316 | n/a | Functions that rely on tp_base (like solid_base and PyType_IsSubtype) |
---|
5317 | n/a | would not be happy in that case, causing a stack overflow. |
---|
5318 | n/a | """ |
---|
5319 | n/a | class M(DebugHelperMeta): |
---|
5320 | n/a | def mro(cls): |
---|
5321 | n/a | if self.ready: |
---|
5322 | n/a | if cls.__name__ == 'B1': |
---|
5323 | n/a | B2.__bases__ = (B1,) |
---|
5324 | n/a | if cls.__name__ == 'B2': |
---|
5325 | n/a | B1.__bases__ = (B2,) |
---|
5326 | n/a | return type.mro(cls) |
---|
5327 | n/a | |
---|
5328 | n/a | class A(metaclass=M): |
---|
5329 | n/a | pass |
---|
5330 | n/a | class B1(A): |
---|
5331 | n/a | pass |
---|
5332 | n/a | class B2(A): |
---|
5333 | n/a | pass |
---|
5334 | n/a | |
---|
5335 | n/a | self.ready = True |
---|
5336 | n/a | with self.assertRaises(TypeError): |
---|
5337 | n/a | B1.__bases__ += () |
---|
5338 | n/a | |
---|
5339 | n/a | def test_tp_subclasses_cycle_in_update_slots(self): |
---|
5340 | n/a | """ |
---|
5341 | n/a | type_set_bases must check for reentrancy upon finishing its job |
---|
5342 | n/a | by updating tp_subclasses of old/new bases of the type. |
---|
5343 | n/a | Otherwise, an implicit inheritance cycle through tp_subclasses |
---|
5344 | n/a | can break functions that recurse on elements of that field |
---|
5345 | n/a | (like recurse_down_subclasses and mro_hierarchy) eventually |
---|
5346 | n/a | leading to a stack overflow. |
---|
5347 | n/a | """ |
---|
5348 | n/a | class M(DebugHelperMeta): |
---|
5349 | n/a | def mro(cls): |
---|
5350 | n/a | if self.ready and cls.__name__ == 'C': |
---|
5351 | n/a | self.ready = False |
---|
5352 | n/a | C.__bases__ = (B2,) |
---|
5353 | n/a | return type.mro(cls) |
---|
5354 | n/a | |
---|
5355 | n/a | class A(metaclass=M): |
---|
5356 | n/a | pass |
---|
5357 | n/a | class B1(A): |
---|
5358 | n/a | pass |
---|
5359 | n/a | class B2(A): |
---|
5360 | n/a | pass |
---|
5361 | n/a | class C(A): |
---|
5362 | n/a | pass |
---|
5363 | n/a | |
---|
5364 | n/a | self.ready = True |
---|
5365 | n/a | C.__bases__ = (B1,) |
---|
5366 | n/a | B1.__bases__ = (C,) |
---|
5367 | n/a | |
---|
5368 | n/a | self.assertEqual(C.__bases__, (B2,)) |
---|
5369 | n/a | self.assertEqual(B2.__subclasses__(), [C]) |
---|
5370 | n/a | self.assertEqual(B1.__subclasses__(), []) |
---|
5371 | n/a | |
---|
5372 | n/a | self.assertEqual(B1.__bases__, (C,)) |
---|
5373 | n/a | self.assertEqual(C.__subclasses__(), [B1]) |
---|
5374 | n/a | |
---|
5375 | n/a | def test_tp_subclasses_cycle_error_return_path(self): |
---|
5376 | n/a | """ |
---|
5377 | n/a | The same as test_tp_subclasses_cycle_in_update_slots, but tests |
---|
5378 | n/a | a code path executed on error (goto bail). |
---|
5379 | n/a | """ |
---|
5380 | n/a | class E(Exception): |
---|
5381 | n/a | pass |
---|
5382 | n/a | class M(DebugHelperMeta): |
---|
5383 | n/a | def mro(cls): |
---|
5384 | n/a | if self.ready and cls.__name__ == 'C': |
---|
5385 | n/a | if C.__bases__ == (B2,): |
---|
5386 | n/a | self.ready = False |
---|
5387 | n/a | else: |
---|
5388 | n/a | C.__bases__ = (B2,) |
---|
5389 | n/a | raise E |
---|
5390 | n/a | return type.mro(cls) |
---|
5391 | n/a | |
---|
5392 | n/a | class A(metaclass=M): |
---|
5393 | n/a | pass |
---|
5394 | n/a | class B1(A): |
---|
5395 | n/a | pass |
---|
5396 | n/a | class B2(A): |
---|
5397 | n/a | pass |
---|
5398 | n/a | class C(A): |
---|
5399 | n/a | pass |
---|
5400 | n/a | |
---|
5401 | n/a | self.ready = True |
---|
5402 | n/a | with self.assertRaises(E): |
---|
5403 | n/a | C.__bases__ = (B1,) |
---|
5404 | n/a | B1.__bases__ = (C,) |
---|
5405 | n/a | |
---|
5406 | n/a | self.assertEqual(C.__bases__, (B2,)) |
---|
5407 | n/a | self.assertEqual(C.__mro__, tuple(type.mro(C))) |
---|
5408 | n/a | |
---|
5409 | n/a | def test_incomplete_extend(self): |
---|
5410 | n/a | """ |
---|
5411 | n/a | Extending an unitialized type with type->tp_mro == NULL must |
---|
5412 | n/a | throw a reasonable TypeError exception, instead of failing |
---|
5413 | n/a | with PyErr_BadInternalCall. |
---|
5414 | n/a | """ |
---|
5415 | n/a | class M(DebugHelperMeta): |
---|
5416 | n/a | def mro(cls): |
---|
5417 | n/a | if cls.__mro__ is None and cls.__name__ != 'X': |
---|
5418 | n/a | with self.assertRaises(TypeError): |
---|
5419 | n/a | class X(cls): |
---|
5420 | n/a | pass |
---|
5421 | n/a | |
---|
5422 | n/a | return type.mro(cls) |
---|
5423 | n/a | |
---|
5424 | n/a | class A(metaclass=M): |
---|
5425 | n/a | pass |
---|
5426 | n/a | |
---|
5427 | n/a | def test_incomplete_super(self): |
---|
5428 | n/a | """ |
---|
5429 | n/a | Attrubute lookup on a super object must be aware that |
---|
5430 | n/a | its target type can be uninitialized (type->tp_mro == NULL). |
---|
5431 | n/a | """ |
---|
5432 | n/a | class M(DebugHelperMeta): |
---|
5433 | n/a | def mro(cls): |
---|
5434 | n/a | if cls.__mro__ is None: |
---|
5435 | n/a | with self.assertRaises(AttributeError): |
---|
5436 | n/a | super(cls, cls).xxx |
---|
5437 | n/a | |
---|
5438 | n/a | return type.mro(cls) |
---|
5439 | n/a | |
---|
5440 | n/a | class A(metaclass=M): |
---|
5441 | n/a | pass |
---|
5442 | n/a | |
---|
5443 | n/a | |
---|
5444 | n/a | def test_main(): |
---|
5445 | n/a | # Run all local test cases, with PTypesLongInitTest first. |
---|
5446 | n/a | support.run_unittest(PTypesLongInitTest, OperatorsTest, |
---|
5447 | n/a | ClassPropertiesAndMethods, DictProxyTests, |
---|
5448 | n/a | MiscTests, PicklingTests, SharedKeyTests, |
---|
5449 | n/a | MroTest) |
---|
5450 | n/a | |
---|
5451 | n/a | if __name__ == "__main__": |
---|
5452 | n/a | test_main() |
---|