ยปCore Development>Code coverage>Lib/test/test_descr.py

Python code coverage for Lib/test/test_descr.py

#countcontent
1n/aimport builtins
2n/aimport copyreg
3n/aimport gc
4n/aimport itertools
5n/aimport math
6n/aimport pickle
7n/aimport sys
8n/aimport types
9n/aimport unittest
10n/aimport warnings
11n/aimport weakref
12n/a
13n/afrom copy import deepcopy
14n/afrom test import support
15n/a
16n/a
17n/aclass OperatorsTest(unittest.TestCase):
18n/a
19n/a def __init__(self, *args, **kwargs):
20n/a unittest.TestCase.__init__(self, *args, **kwargs)
21n/a self.binops = {
22n/a 'add': '+',
23n/a 'sub': '-',
24n/a 'mul': '*',
25n/a 'matmul': '@',
26n/a 'truediv': '/',
27n/a 'floordiv': '//',
28n/a 'divmod': 'divmod',
29n/a 'pow': '**',
30n/a 'lshift': '<<',
31n/a 'rshift': '>>',
32n/a 'and': '&',
33n/a 'xor': '^',
34n/a 'or': '|',
35n/a 'cmp': 'cmp',
36n/a 'lt': '<',
37n/a 'le': '<=',
38n/a 'eq': '==',
39n/a 'ne': '!=',
40n/a 'gt': '>',
41n/a 'ge': '>=',
42n/a }
43n/a
44n/a for name, expr in list(self.binops.items()):
45n/a if expr.islower():
46n/a expr = expr + "(a, b)"
47n/a else:
48n/a expr = 'a %s b' % expr
49n/a self.binops[name] = expr
50n/a
51n/a self.unops = {
52n/a 'pos': '+',
53n/a 'neg': '-',
54n/a 'abs': 'abs',
55n/a 'invert': '~',
56n/a 'int': 'int',
57n/a 'float': 'float',
58n/a }
59n/a
60n/a for name, expr in list(self.unops.items()):
61n/a if expr.islower():
62n/a expr = expr + "(a)"
63n/a else:
64n/a expr = '%s a' % expr
65n/a self.unops[name] = expr
66n/a
67n/a def unop_test(self, a, res, expr="len(a)", meth="__len__"):
68n/a d = {'a': a}
69n/a self.assertEqual(eval(expr, d), res)
70n/a t = type(a)
71n/a m = getattr(t, meth)
72n/a
73n/a # Find method in parent class
74n/a while meth not in t.__dict__:
75n/a t = t.__bases__[0]
76n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
77n/a # method object; the getattr() below obtains its underlying function.
78n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
79n/a self.assertEqual(m(a), res)
80n/a bm = getattr(a, meth)
81n/a self.assertEqual(bm(), res)
82n/a
83n/a def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
84n/a d = {'a': a, 'b': b}
85n/a
86n/a self.assertEqual(eval(expr, d), res)
87n/a t = type(a)
88n/a m = getattr(t, meth)
89n/a while meth not in t.__dict__:
90n/a t = t.__bases__[0]
91n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92n/a # method object; the getattr() below obtains its underlying function.
93n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
94n/a self.assertEqual(m(a, b), res)
95n/a bm = getattr(a, meth)
96n/a self.assertEqual(bm(b), res)
97n/a
98n/a def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99n/a d = {'a': a, 'b': b, 'c': c}
100n/a self.assertEqual(eval(expr, d), res)
101n/a t = type(a)
102n/a m = getattr(t, meth)
103n/a while meth not in t.__dict__:
104n/a t = t.__bases__[0]
105n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106n/a # method object; the getattr() below obtains its underlying function.
107n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
108n/a self.assertEqual(m(a, slice(b, c)), res)
109n/a bm = getattr(a, meth)
110n/a self.assertEqual(bm(slice(b, c)), res)
111n/a
112n/a def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113n/a d = {'a': deepcopy(a), 'b': b}
114n/a exec(stmt, d)
115n/a self.assertEqual(d['a'], res)
116n/a t = type(a)
117n/a m = getattr(t, meth)
118n/a while meth not in t.__dict__:
119n/a t = t.__bases__[0]
120n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121n/a # method object; the getattr() below obtains its underlying function.
122n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
123n/a d['a'] = deepcopy(a)
124n/a m(d['a'], b)
125n/a self.assertEqual(d['a'], res)
126n/a d['a'] = deepcopy(a)
127n/a bm = getattr(d['a'], meth)
128n/a bm(b)
129n/a self.assertEqual(d['a'], res)
130n/a
131n/a def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132n/a d = {'a': deepcopy(a), 'b': b, 'c': c}
133n/a exec(stmt, d)
134n/a self.assertEqual(d['a'], res)
135n/a t = type(a)
136n/a m = getattr(t, meth)
137n/a while meth not in t.__dict__:
138n/a t = t.__bases__[0]
139n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140n/a # method object; the getattr() below obtains its underlying function.
141n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
142n/a d['a'] = deepcopy(a)
143n/a m(d['a'], b, c)
144n/a self.assertEqual(d['a'], res)
145n/a d['a'] = deepcopy(a)
146n/a bm = getattr(d['a'], meth)
147n/a bm(b, c)
148n/a self.assertEqual(d['a'], res)
149n/a
150n/a def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151n/a dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152n/a exec(stmt, dictionary)
153n/a self.assertEqual(dictionary['a'], res)
154n/a t = type(a)
155n/a while meth not in t.__dict__:
156n/a t = t.__bases__[0]
157n/a m = getattr(t, meth)
158n/a # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159n/a # method object; the getattr() below obtains its underlying function.
160n/a self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
161n/a dictionary['a'] = deepcopy(a)
162n/a m(dictionary['a'], slice(b, c), d)
163n/a self.assertEqual(dictionary['a'], res)
164n/a dictionary['a'] = deepcopy(a)
165n/a bm = getattr(dictionary['a'], meth)
166n/a bm(slice(b, c), d)
167n/a self.assertEqual(dictionary['a'], res)
168n/a
169n/a def test_lists(self):
170n/a # Testing list operations...
171n/a # Asserts are within individual test methods
172n/a self.binop_test([1], [2], [1,2], "a+b", "__add__")
173n/a self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174n/a self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175n/a self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176n/a self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177n/a self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178n/a self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179n/a self.unop_test([1,2,3], 3, "len(a)", "__len__")
180n/a self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181n/a self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182n/a self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183n/a self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184n/a "__setitem__")
185n/a
186n/a def test_dicts(self):
187n/a # Testing dict operations...
188n/a self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189n/a self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190n/a self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191n/a
192n/a d = {1:2, 3:4}
193n/a l1 = []
194n/a for i in list(d.keys()):
195n/a l1.append(i)
196n/a l = []
197n/a for i in iter(d):
198n/a l.append(i)
199n/a self.assertEqual(l, l1)
200n/a l = []
201n/a for i in d.__iter__():
202n/a l.append(i)
203n/a self.assertEqual(l, l1)
204n/a l = []
205n/a for i in dict.__iter__(d):
206n/a l.append(i)
207n/a self.assertEqual(l, l1)
208n/a d = {1:2, 3:4}
209n/a self.unop_test(d, 2, "len(a)", "__len__")
210n/a self.assertEqual(eval(repr(d), {}), d)
211n/a self.assertEqual(eval(d.__repr__(), {}), d)
212n/a self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213n/a "__setitem__")
214n/a
215n/a # Tests for unary and binary operators
216n/a def number_operators(self, a, b, skip=[]):
217n/a dict = {'a': a, 'b': b}
218n/a
219n/a for name, expr in self.binops.items():
220n/a if name not in skip:
221n/a name = "__%s__" % name
222n/a if hasattr(a, name):
223n/a res = eval(expr, dict)
224n/a self.binop_test(a, b, res, expr, name)
225n/a
226n/a for name, expr in list(self.unops.items()):
227n/a if name not in skip:
228n/a name = "__%s__" % name
229n/a if hasattr(a, name):
230n/a res = eval(expr, dict)
231n/a self.unop_test(a, res, expr, name)
232n/a
233n/a def test_ints(self):
234n/a # Testing int operations...
235n/a self.number_operators(100, 3)
236n/a # The following crashes in Python 2.2
237n/a self.assertEqual((1).__bool__(), 1)
238n/a self.assertEqual((0).__bool__(), 0)
239n/a # This returns 'NotImplemented' in Python 2.2
240n/a class C(int):
241n/a def __add__(self, other):
242n/a return NotImplemented
243n/a self.assertEqual(C(5), 5)
244n/a try:
245n/a C() + ""
246n/a except TypeError:
247n/a pass
248n/a else:
249n/a self.fail("NotImplemented should have caused TypeError")
250n/a
251n/a def test_floats(self):
252n/a # Testing float operations...
253n/a self.number_operators(100.0, 3.0)
254n/a
255n/a def test_complexes(self):
256n/a # Testing complex operations...
257n/a self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
258n/a 'int', 'float',
259n/a 'floordiv', 'divmod', 'mod'])
260n/a
261n/a class Number(complex):
262n/a __slots__ = ['prec']
263n/a def __new__(cls, *args, **kwds):
264n/a result = complex.__new__(cls, *args)
265n/a result.prec = kwds.get('prec', 12)
266n/a return result
267n/a def __repr__(self):
268n/a prec = self.prec
269n/a if self.imag == 0.0:
270n/a return "%.*g" % (prec, self.real)
271n/a if self.real == 0.0:
272n/a return "%.*gj" % (prec, self.imag)
273n/a return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
274n/a __str__ = __repr__
275n/a
276n/a a = Number(3.14, prec=6)
277n/a self.assertEqual(repr(a), "3.14")
278n/a self.assertEqual(a.prec, 6)
279n/a
280n/a a = Number(a, prec=2)
281n/a self.assertEqual(repr(a), "3.1")
282n/a self.assertEqual(a.prec, 2)
283n/a
284n/a a = Number(234.5)
285n/a self.assertEqual(repr(a), "234.5")
286n/a self.assertEqual(a.prec, 12)
287n/a
288n/a def test_explicit_reverse_methods(self):
289n/a # see issue 9930
290n/a self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
291n/a self.assertEqual(float.__rsub__(3.0, 1), -2.0)
292n/a
293n/a @support.impl_detail("the module 'xxsubtype' is internal")
294n/a def test_spam_lists(self):
295n/a # Testing spamlist operations...
296n/a import copy, xxsubtype as spam
297n/a
298n/a def spamlist(l, memo=None):
299n/a import xxsubtype as spam
300n/a return spam.spamlist(l)
301n/a
302n/a # This is an ugly hack:
303n/a copy._deepcopy_dispatch[spam.spamlist] = spamlist
304n/a
305n/a self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
306n/a "__add__")
307n/a self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
308n/a self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
309n/a self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
310n/a self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
311n/a "__getitem__")
312n/a self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
313n/a "__iadd__")
314n/a self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
315n/a "__imul__")
316n/a self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
317n/a self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
318n/a "__mul__")
319n/a self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
320n/a "__rmul__")
321n/a self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
322n/a "__setitem__")
323n/a self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
324n/a spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
325n/a # Test subclassing
326n/a class C(spam.spamlist):
327n/a def foo(self): return 1
328n/a a = C()
329n/a self.assertEqual(a, [])
330n/a self.assertEqual(a.foo(), 1)
331n/a a.append(100)
332n/a self.assertEqual(a, [100])
333n/a self.assertEqual(a.getstate(), 0)
334n/a a.setstate(42)
335n/a self.assertEqual(a.getstate(), 42)
336n/a
337n/a @support.impl_detail("the module 'xxsubtype' is internal")
338n/a def test_spam_dicts(self):
339n/a # Testing spamdict operations...
340n/a import copy, xxsubtype as spam
341n/a def spamdict(d, memo=None):
342n/a import xxsubtype as spam
343n/a sd = spam.spamdict()
344n/a for k, v in list(d.items()):
345n/a sd[k] = v
346n/a return sd
347n/a # This is an ugly hack:
348n/a copy._deepcopy_dispatch[spam.spamdict] = spamdict
349n/a
350n/a self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
351n/a self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
352n/a self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
353n/a d = spamdict({1:2,3:4})
354n/a l1 = []
355n/a for i in list(d.keys()):
356n/a l1.append(i)
357n/a l = []
358n/a for i in iter(d):
359n/a l.append(i)
360n/a self.assertEqual(l, l1)
361n/a l = []
362n/a for i in d.__iter__():
363n/a l.append(i)
364n/a self.assertEqual(l, l1)
365n/a l = []
366n/a for i in type(spamdict({})).__iter__(d):
367n/a l.append(i)
368n/a self.assertEqual(l, l1)
369n/a straightd = {1:2, 3:4}
370n/a spamd = spamdict(straightd)
371n/a self.unop_test(spamd, 2, "len(a)", "__len__")
372n/a self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
373n/a self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
374n/a "a[b]=c", "__setitem__")
375n/a # Test subclassing
376n/a class C(spam.spamdict):
377n/a def foo(self): return 1
378n/a a = C()
379n/a self.assertEqual(list(a.items()), [])
380n/a self.assertEqual(a.foo(), 1)
381n/a a['foo'] = 'bar'
382n/a self.assertEqual(list(a.items()), [('foo', 'bar')])
383n/a self.assertEqual(a.getstate(), 0)
384n/a a.setstate(100)
385n/a self.assertEqual(a.getstate(), 100)
386n/a
387n/aclass ClassPropertiesAndMethods(unittest.TestCase):
388n/a
389n/a def assertHasAttr(self, obj, name):
390n/a self.assertTrue(hasattr(obj, name),
391n/a '%r has no attribute %r' % (obj, name))
392n/a
393n/a def assertNotHasAttr(self, obj, name):
394n/a self.assertFalse(hasattr(obj, name),
395n/a '%r has unexpected attribute %r' % (obj, name))
396n/a
397n/a def test_python_dicts(self):
398n/a # Testing Python subclass of dict...
399n/a self.assertTrue(issubclass(dict, dict))
400n/a self.assertIsInstance({}, dict)
401n/a d = dict()
402n/a self.assertEqual(d, {})
403n/a self.assertIs(d.__class__, dict)
404n/a self.assertIsInstance(d, dict)
405n/a class C(dict):
406n/a state = -1
407n/a def __init__(self_local, *a, **kw):
408n/a if a:
409n/a self.assertEqual(len(a), 1)
410n/a self_local.state = a[0]
411n/a if kw:
412n/a for k, v in list(kw.items()):
413n/a self_local[v] = k
414n/a def __getitem__(self, key):
415n/a return self.get(key, 0)
416n/a def __setitem__(self_local, key, value):
417n/a self.assertIsInstance(key, type(0))
418n/a dict.__setitem__(self_local, key, value)
419n/a def setstate(self, state):
420n/a self.state = state
421n/a def getstate(self):
422n/a return self.state
423n/a self.assertTrue(issubclass(C, dict))
424n/a a1 = C(12)
425n/a self.assertEqual(a1.state, 12)
426n/a a2 = C(foo=1, bar=2)
427n/a self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
428n/a a = C()
429n/a self.assertEqual(a.state, -1)
430n/a self.assertEqual(a.getstate(), -1)
431n/a a.setstate(0)
432n/a self.assertEqual(a.state, 0)
433n/a self.assertEqual(a.getstate(), 0)
434n/a a.setstate(10)
435n/a self.assertEqual(a.state, 10)
436n/a self.assertEqual(a.getstate(), 10)
437n/a self.assertEqual(a[42], 0)
438n/a a[42] = 24
439n/a self.assertEqual(a[42], 24)
440n/a N = 50
441n/a for i in range(N):
442n/a a[i] = C()
443n/a for j in range(N):
444n/a a[i][j] = i*j
445n/a for i in range(N):
446n/a for j in range(N):
447n/a self.assertEqual(a[i][j], i*j)
448n/a
449n/a def test_python_lists(self):
450n/a # Testing Python subclass of list...
451n/a class C(list):
452n/a def __getitem__(self, i):
453n/a if isinstance(i, slice):
454n/a return i.start, i.stop
455n/a return list.__getitem__(self, i) + 100
456n/a a = C()
457n/a a.extend([0,1,2])
458n/a self.assertEqual(a[0], 100)
459n/a self.assertEqual(a[1], 101)
460n/a self.assertEqual(a[2], 102)
461n/a self.assertEqual(a[100:200], (100,200))
462n/a
463n/a def test_metaclass(self):
464n/a # Testing metaclasses...
465n/a class C(metaclass=type):
466n/a def __init__(self):
467n/a self.__state = 0
468n/a def getstate(self):
469n/a return self.__state
470n/a def setstate(self, state):
471n/a self.__state = state
472n/a a = C()
473n/a self.assertEqual(a.getstate(), 0)
474n/a a.setstate(10)
475n/a self.assertEqual(a.getstate(), 10)
476n/a class _metaclass(type):
477n/a def myself(cls): return cls
478n/a class D(metaclass=_metaclass):
479n/a pass
480n/a self.assertEqual(D.myself(), D)
481n/a d = D()
482n/a self.assertEqual(d.__class__, D)
483n/a class M1(type):
484n/a def __new__(cls, name, bases, dict):
485n/a dict['__spam__'] = 1
486n/a return type.__new__(cls, name, bases, dict)
487n/a class C(metaclass=M1):
488n/a pass
489n/a self.assertEqual(C.__spam__, 1)
490n/a c = C()
491n/a self.assertEqual(c.__spam__, 1)
492n/a
493n/a class _instance(object):
494n/a pass
495n/a class M2(object):
496n/a @staticmethod
497n/a def __new__(cls, name, bases, dict):
498n/a self = object.__new__(cls)
499n/a self.name = name
500n/a self.bases = bases
501n/a self.dict = dict
502n/a return self
503n/a def __call__(self):
504n/a it = _instance()
505n/a # Early binding of methods
506n/a for key in self.dict:
507n/a if key.startswith("__"):
508n/a continue
509n/a setattr(it, key, self.dict[key].__get__(it, self))
510n/a return it
511n/a class C(metaclass=M2):
512n/a def spam(self):
513n/a return 42
514n/a self.assertEqual(C.name, 'C')
515n/a self.assertEqual(C.bases, ())
516n/a self.assertIn('spam', C.dict)
517n/a c = C()
518n/a self.assertEqual(c.spam(), 42)
519n/a
520n/a # More metaclass examples
521n/a
522n/a class autosuper(type):
523n/a # Automatically add __super to the class
524n/a # This trick only works for dynamic classes
525n/a def __new__(metaclass, name, bases, dict):
526n/a cls = super(autosuper, metaclass).__new__(metaclass,
527n/a name, bases, dict)
528n/a # Name mangling for __super removes leading underscores
529n/a while name[:1] == "_":
530n/a name = name[1:]
531n/a if name:
532n/a name = "_%s__super" % name
533n/a else:
534n/a name = "__super"
535n/a setattr(cls, name, super(cls))
536n/a return cls
537n/a class A(metaclass=autosuper):
538n/a def meth(self):
539n/a return "A"
540n/a class B(A):
541n/a def meth(self):
542n/a return "B" + self.__super.meth()
543n/a class C(A):
544n/a def meth(self):
545n/a return "C" + self.__super.meth()
546n/a class D(C, B):
547n/a def meth(self):
548n/a return "D" + self.__super.meth()
549n/a self.assertEqual(D().meth(), "DCBA")
550n/a class E(B, C):
551n/a def meth(self):
552n/a return "E" + self.__super.meth()
553n/a self.assertEqual(E().meth(), "EBCA")
554n/a
555n/a class autoproperty(type):
556n/a # Automatically create property attributes when methods
557n/a # named _get_x and/or _set_x are found
558n/a def __new__(metaclass, name, bases, dict):
559n/a hits = {}
560n/a for key, val in dict.items():
561n/a if key.startswith("_get_"):
562n/a key = key[5:]
563n/a get, set = hits.get(key, (None, None))
564n/a get = val
565n/a hits[key] = get, set
566n/a elif key.startswith("_set_"):
567n/a key = key[5:]
568n/a get, set = hits.get(key, (None, None))
569n/a set = val
570n/a hits[key] = get, set
571n/a for key, (get, set) in hits.items():
572n/a dict[key] = property(get, set)
573n/a return super(autoproperty, metaclass).__new__(metaclass,
574n/a name, bases, dict)
575n/a class A(metaclass=autoproperty):
576n/a def _get_x(self):
577n/a return -self.__x
578n/a def _set_x(self, x):
579n/a self.__x = -x
580n/a a = A()
581n/a self.assertNotHasAttr(a, "x")
582n/a a.x = 12
583n/a self.assertEqual(a.x, 12)
584n/a self.assertEqual(a._A__x, -12)
585n/a
586n/a class multimetaclass(autoproperty, autosuper):
587n/a # Merge of multiple cooperating metaclasses
588n/a pass
589n/a class A(metaclass=multimetaclass):
590n/a def _get_x(self):
591n/a return "A"
592n/a class B(A):
593n/a def _get_x(self):
594n/a return "B" + self.__super._get_x()
595n/a class C(A):
596n/a def _get_x(self):
597n/a return "C" + self.__super._get_x()
598n/a class D(C, B):
599n/a def _get_x(self):
600n/a return "D" + self.__super._get_x()
601n/a self.assertEqual(D().x, "DCBA")
602n/a
603n/a # Make sure type(x) doesn't call x.__class__.__init__
604n/a class T(type):
605n/a counter = 0
606n/a def __init__(self, *args):
607n/a T.counter += 1
608n/a class C(metaclass=T):
609n/a pass
610n/a self.assertEqual(T.counter, 1)
611n/a a = C()
612n/a self.assertEqual(type(a), C)
613n/a self.assertEqual(T.counter, 1)
614n/a
615n/a class C(object): pass
616n/a c = C()
617n/a try: c()
618n/a except TypeError: pass
619n/a else: self.fail("calling object w/o call method should raise "
620n/a "TypeError")
621n/a
622n/a # Testing code to find most derived baseclass
623n/a class A(type):
624n/a def __new__(*args, **kwargs):
625n/a return type.__new__(*args, **kwargs)
626n/a
627n/a class B(object):
628n/a pass
629n/a
630n/a class C(object, metaclass=A):
631n/a pass
632n/a
633n/a # The most derived metaclass of D is A rather than type.
634n/a class D(B, C):
635n/a pass
636n/a self.assertIs(A, type(D))
637n/a
638n/a # issue1294232: correct metaclass calculation
639n/a new_calls = [] # to check the order of __new__ calls
640n/a class AMeta(type):
641n/a @staticmethod
642n/a def __new__(mcls, name, bases, ns):
643n/a new_calls.append('AMeta')
644n/a return super().__new__(mcls, name, bases, ns)
645n/a @classmethod
646n/a def __prepare__(mcls, name, bases):
647n/a return {}
648n/a
649n/a class BMeta(AMeta):
650n/a @staticmethod
651n/a def __new__(mcls, name, bases, ns):
652n/a new_calls.append('BMeta')
653n/a return super().__new__(mcls, name, bases, ns)
654n/a @classmethod
655n/a def __prepare__(mcls, name, bases):
656n/a ns = super().__prepare__(name, bases)
657n/a ns['BMeta_was_here'] = True
658n/a return ns
659n/a
660n/a class A(metaclass=AMeta):
661n/a pass
662n/a self.assertEqual(['AMeta'], new_calls)
663n/a new_calls.clear()
664n/a
665n/a class B(metaclass=BMeta):
666n/a pass
667n/a # BMeta.__new__ calls AMeta.__new__ with super:
668n/a self.assertEqual(['BMeta', 'AMeta'], new_calls)
669n/a new_calls.clear()
670n/a
671n/a class C(A, B):
672n/a pass
673n/a # The most derived metaclass is BMeta:
674n/a self.assertEqual(['BMeta', 'AMeta'], new_calls)
675n/a new_calls.clear()
676n/a # BMeta.__prepare__ should've been called:
677n/a self.assertIn('BMeta_was_here', C.__dict__)
678n/a
679n/a # The order of the bases shouldn't matter:
680n/a class C2(B, A):
681n/a pass
682n/a self.assertEqual(['BMeta', 'AMeta'], new_calls)
683n/a new_calls.clear()
684n/a self.assertIn('BMeta_was_here', C2.__dict__)
685n/a
686n/a # Check correct metaclass calculation when a metaclass is declared:
687n/a class D(C, metaclass=type):
688n/a pass
689n/a self.assertEqual(['BMeta', 'AMeta'], new_calls)
690n/a new_calls.clear()
691n/a self.assertIn('BMeta_was_here', D.__dict__)
692n/a
693n/a class E(C, metaclass=AMeta):
694n/a pass
695n/a self.assertEqual(['BMeta', 'AMeta'], new_calls)
696n/a new_calls.clear()
697n/a self.assertIn('BMeta_was_here', E.__dict__)
698n/a
699n/a # Special case: the given metaclass isn't a class,
700n/a # so there is no metaclass calculation.
701n/a marker = object()
702n/a def func(*args, **kwargs):
703n/a return marker
704n/a class X(metaclass=func):
705n/a pass
706n/a class Y(object, metaclass=func):
707n/a pass
708n/a class Z(D, metaclass=func):
709n/a pass
710n/a self.assertIs(marker, X)
711n/a self.assertIs(marker, Y)
712n/a self.assertIs(marker, Z)
713n/a
714n/a # The given metaclass is a class,
715n/a # but not a descendant of type.
716n/a prepare_calls = [] # to track __prepare__ calls
717n/a class ANotMeta:
718n/a def __new__(mcls, *args, **kwargs):
719n/a new_calls.append('ANotMeta')
720n/a return super().__new__(mcls)
721n/a @classmethod
722n/a def __prepare__(mcls, name, bases):
723n/a prepare_calls.append('ANotMeta')
724n/a return {}
725n/a class BNotMeta(ANotMeta):
726n/a def __new__(mcls, *args, **kwargs):
727n/a new_calls.append('BNotMeta')
728n/a return super().__new__(mcls)
729n/a @classmethod
730n/a def __prepare__(mcls, name, bases):
731n/a prepare_calls.append('BNotMeta')
732n/a return super().__prepare__(name, bases)
733n/a
734n/a class A(metaclass=ANotMeta):
735n/a pass
736n/a self.assertIs(ANotMeta, type(A))
737n/a self.assertEqual(['ANotMeta'], prepare_calls)
738n/a prepare_calls.clear()
739n/a self.assertEqual(['ANotMeta'], new_calls)
740n/a new_calls.clear()
741n/a
742n/a class B(metaclass=BNotMeta):
743n/a pass
744n/a self.assertIs(BNotMeta, type(B))
745n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
746n/a prepare_calls.clear()
747n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
748n/a new_calls.clear()
749n/a
750n/a class C(A, B):
751n/a pass
752n/a self.assertIs(BNotMeta, type(C))
753n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
754n/a new_calls.clear()
755n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
756n/a prepare_calls.clear()
757n/a
758n/a class C2(B, A):
759n/a pass
760n/a self.assertIs(BNotMeta, type(C2))
761n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
762n/a new_calls.clear()
763n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
764n/a prepare_calls.clear()
765n/a
766n/a # This is a TypeError, because of a metaclass conflict:
767n/a # BNotMeta is neither a subclass, nor a superclass of type
768n/a with self.assertRaises(TypeError):
769n/a class D(C, metaclass=type):
770n/a pass
771n/a
772n/a class E(C, metaclass=ANotMeta):
773n/a pass
774n/a self.assertIs(BNotMeta, type(E))
775n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
776n/a new_calls.clear()
777n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
778n/a prepare_calls.clear()
779n/a
780n/a class F(object(), C):
781n/a pass
782n/a self.assertIs(BNotMeta, type(F))
783n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
784n/a new_calls.clear()
785n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
786n/a prepare_calls.clear()
787n/a
788n/a class F2(C, object()):
789n/a pass
790n/a self.assertIs(BNotMeta, type(F2))
791n/a self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
792n/a new_calls.clear()
793n/a self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
794n/a prepare_calls.clear()
795n/a
796n/a # TypeError: BNotMeta is neither a
797n/a # subclass, nor a superclass of int
798n/a with self.assertRaises(TypeError):
799n/a class X(C, int()):
800n/a pass
801n/a with self.assertRaises(TypeError):
802n/a class X(int(), C):
803n/a pass
804n/a
805n/a def test_module_subclasses(self):
806n/a # Testing Python subclass of module...
807n/a log = []
808n/a MT = type(sys)
809n/a class MM(MT):
810n/a def __init__(self, name):
811n/a MT.__init__(self, name)
812n/a def __getattribute__(self, name):
813n/a log.append(("getattr", name))
814n/a return MT.__getattribute__(self, name)
815n/a def __setattr__(self, name, value):
816n/a log.append(("setattr", name, value))
817n/a MT.__setattr__(self, name, value)
818n/a def __delattr__(self, name):
819n/a log.append(("delattr", name))
820n/a MT.__delattr__(self, name)
821n/a a = MM("a")
822n/a a.foo = 12
823n/a x = a.foo
824n/a del a.foo
825n/a self.assertEqual(log, [("setattr", "foo", 12),
826n/a ("getattr", "foo"),
827n/a ("delattr", "foo")])
828n/a
829n/a # http://python.org/sf/1174712
830n/a try:
831n/a class Module(types.ModuleType, str):
832n/a pass
833n/a except TypeError:
834n/a pass
835n/a else:
836n/a self.fail("inheriting from ModuleType and str at the same time "
837n/a "should fail")
838n/a
839n/a def test_multiple_inheritance(self):
840n/a # Testing multiple inheritance...
841n/a class C(object):
842n/a def __init__(self):
843n/a self.__state = 0
844n/a def getstate(self):
845n/a return self.__state
846n/a def setstate(self, state):
847n/a self.__state = state
848n/a a = C()
849n/a self.assertEqual(a.getstate(), 0)
850n/a a.setstate(10)
851n/a self.assertEqual(a.getstate(), 10)
852n/a class D(dict, C):
853n/a def __init__(self):
854n/a type({}).__init__(self)
855n/a C.__init__(self)
856n/a d = D()
857n/a self.assertEqual(list(d.keys()), [])
858n/a d["hello"] = "world"
859n/a self.assertEqual(list(d.items()), [("hello", "world")])
860n/a self.assertEqual(d["hello"], "world")
861n/a self.assertEqual(d.getstate(), 0)
862n/a d.setstate(10)
863n/a self.assertEqual(d.getstate(), 10)
864n/a self.assertEqual(D.__mro__, (D, dict, C, object))
865n/a
866n/a # SF bug #442833
867n/a class Node(object):
868n/a def __int__(self):
869n/a return int(self.foo())
870n/a def foo(self):
871n/a return "23"
872n/a class Frag(Node, list):
873n/a def foo(self):
874n/a return "42"
875n/a self.assertEqual(Node().__int__(), 23)
876n/a self.assertEqual(int(Node()), 23)
877n/a self.assertEqual(Frag().__int__(), 42)
878n/a self.assertEqual(int(Frag()), 42)
879n/a
880n/a def test_diamond_inheritance(self):
881n/a # Testing multiple inheritance special cases...
882n/a class A(object):
883n/a def spam(self): return "A"
884n/a self.assertEqual(A().spam(), "A")
885n/a class B(A):
886n/a def boo(self): return "B"
887n/a def spam(self): return "B"
888n/a self.assertEqual(B().spam(), "B")
889n/a self.assertEqual(B().boo(), "B")
890n/a class C(A):
891n/a def boo(self): return "C"
892n/a self.assertEqual(C().spam(), "A")
893n/a self.assertEqual(C().boo(), "C")
894n/a class D(B, C): pass
895n/a self.assertEqual(D().spam(), "B")
896n/a self.assertEqual(D().boo(), "B")
897n/a self.assertEqual(D.__mro__, (D, B, C, A, object))
898n/a class E(C, B): pass
899n/a self.assertEqual(E().spam(), "B")
900n/a self.assertEqual(E().boo(), "C")
901n/a self.assertEqual(E.__mro__, (E, C, B, A, object))
902n/a # MRO order disagreement
903n/a try:
904n/a class F(D, E): pass
905n/a except TypeError:
906n/a pass
907n/a else:
908n/a self.fail("expected MRO order disagreement (F)")
909n/a try:
910n/a class G(E, D): pass
911n/a except TypeError:
912n/a pass
913n/a else:
914n/a self.fail("expected MRO order disagreement (G)")
915n/a
916n/a # see thread python-dev/2002-October/029035.html
917n/a def test_ex5_from_c3_switch(self):
918n/a # Testing ex5 from C3 switch discussion...
919n/a class A(object): pass
920n/a class B(object): pass
921n/a class C(object): pass
922n/a class X(A): pass
923n/a class Y(A): pass
924n/a class Z(X,B,Y,C): pass
925n/a self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
926n/a
927n/a # see "A Monotonic Superclass Linearization for Dylan",
928n/a # by Kim Barrett et al. (OOPSLA 1996)
929n/a def test_monotonicity(self):
930n/a # Testing MRO monotonicity...
931n/a class Boat(object): pass
932n/a class DayBoat(Boat): pass
933n/a class WheelBoat(Boat): pass
934n/a class EngineLess(DayBoat): pass
935n/a class SmallMultihull(DayBoat): pass
936n/a class PedalWheelBoat(EngineLess,WheelBoat): pass
937n/a class SmallCatamaran(SmallMultihull): pass
938n/a class Pedalo(PedalWheelBoat,SmallCatamaran): pass
939n/a
940n/a self.assertEqual(PedalWheelBoat.__mro__,
941n/a (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
942n/a self.assertEqual(SmallCatamaran.__mro__,
943n/a (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
944n/a self.assertEqual(Pedalo.__mro__,
945n/a (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
946n/a SmallMultihull, DayBoat, WheelBoat, Boat, object))
947n/a
948n/a # see "A Monotonic Superclass Linearization for Dylan",
949n/a # by Kim Barrett et al. (OOPSLA 1996)
950n/a def test_consistency_with_epg(self):
951n/a # Testing consistency with EPG...
952n/a class Pane(object): pass
953n/a class ScrollingMixin(object): pass
954n/a class EditingMixin(object): pass
955n/a class ScrollablePane(Pane,ScrollingMixin): pass
956n/a class EditablePane(Pane,EditingMixin): pass
957n/a class EditableScrollablePane(ScrollablePane,EditablePane): pass
958n/a
959n/a self.assertEqual(EditableScrollablePane.__mro__,
960n/a (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
961n/a ScrollingMixin, EditingMixin, object))
962n/a
963n/a def test_mro_disagreement(self):
964n/a # Testing error messages for MRO disagreement...
965n/a mro_err_msg = """Cannot create a consistent method resolution
966n/aorder (MRO) for bases """
967n/a
968n/a def raises(exc, expected, callable, *args):
969n/a try:
970n/a callable(*args)
971n/a except exc as msg:
972n/a # the exact msg is generally considered an impl detail
973n/a if support.check_impl_detail():
974n/a if not str(msg).startswith(expected):
975n/a self.fail("Message %r, expected %r" %
976n/a (str(msg), expected))
977n/a else:
978n/a self.fail("Expected %s" % exc)
979n/a
980n/a class A(object): pass
981n/a class B(A): pass
982n/a class C(object): pass
983n/a
984n/a # Test some very simple errors
985n/a raises(TypeError, "duplicate base class A",
986n/a type, "X", (A, A), {})
987n/a raises(TypeError, mro_err_msg,
988n/a type, "X", (A, B), {})
989n/a raises(TypeError, mro_err_msg,
990n/a type, "X", (A, C, B), {})
991n/a # Test a slightly more complex error
992n/a class GridLayout(object): pass
993n/a class HorizontalGrid(GridLayout): pass
994n/a class VerticalGrid(GridLayout): pass
995n/a class HVGrid(HorizontalGrid, VerticalGrid): pass
996n/a class VHGrid(VerticalGrid, HorizontalGrid): pass
997n/a raises(TypeError, mro_err_msg,
998n/a type, "ConfusedGrid", (HVGrid, VHGrid), {})
999n/a
1000n/a def test_object_class(self):
1001n/a # Testing object class...
1002n/a a = object()
1003n/a self.assertEqual(a.__class__, object)
1004n/a self.assertEqual(type(a), object)
1005n/a b = object()
1006n/a self.assertNotEqual(a, b)
1007n/a self.assertNotHasAttr(a, "foo")
1008n/a try:
1009n/a a.foo = 12
1010n/a except (AttributeError, TypeError):
1011n/a pass
1012n/a else:
1013n/a self.fail("object() should not allow setting a foo attribute")
1014n/a self.assertNotHasAttr(object(), "__dict__")
1015n/a
1016n/a class Cdict(object):
1017n/a pass
1018n/a x = Cdict()
1019n/a self.assertEqual(x.__dict__, {})
1020n/a x.foo = 1
1021n/a self.assertEqual(x.foo, 1)
1022n/a self.assertEqual(x.__dict__, {'foo': 1})
1023n/a
1024n/a def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1025n/a class SubType(types.ModuleType):
1026n/a a = 1
1027n/a
1028n/a m = types.ModuleType("m")
1029n/a self.assertTrue(m.__class__ is types.ModuleType)
1030n/a self.assertFalse(hasattr(m, "a"))
1031n/a
1032n/a m.__class__ = SubType
1033n/a self.assertTrue(m.__class__ is SubType)
1034n/a self.assertTrue(hasattr(m, "a"))
1035n/a
1036n/a m.__class__ = types.ModuleType
1037n/a self.assertTrue(m.__class__ is types.ModuleType)
1038n/a self.assertFalse(hasattr(m, "a"))
1039n/a
1040n/a # Make sure that builtin immutable objects don't support __class__
1041n/a # assignment, because the object instances may be interned.
1042n/a # We set __slots__ = () to ensure that the subclasses are
1043n/a # memory-layout compatible, and thus otherwise reasonable candidates
1044n/a # for __class__ assignment.
1045n/a
1046n/a # The following types have immutable instances, but are not
1047n/a # subclassable and thus don't need to be checked:
1048n/a # NoneType, bool
1049n/a
1050n/a class MyInt(int):
1051n/a __slots__ = ()
1052n/a with self.assertRaises(TypeError):
1053n/a (1).__class__ = MyInt
1054n/a
1055n/a class MyFloat(float):
1056n/a __slots__ = ()
1057n/a with self.assertRaises(TypeError):
1058n/a (1.0).__class__ = MyFloat
1059n/a
1060n/a class MyComplex(complex):
1061n/a __slots__ = ()
1062n/a with self.assertRaises(TypeError):
1063n/a (1 + 2j).__class__ = MyComplex
1064n/a
1065n/a class MyStr(str):
1066n/a __slots__ = ()
1067n/a with self.assertRaises(TypeError):
1068n/a "a".__class__ = MyStr
1069n/a
1070n/a class MyBytes(bytes):
1071n/a __slots__ = ()
1072n/a with self.assertRaises(TypeError):
1073n/a b"a".__class__ = MyBytes
1074n/a
1075n/a class MyTuple(tuple):
1076n/a __slots__ = ()
1077n/a with self.assertRaises(TypeError):
1078n/a ().__class__ = MyTuple
1079n/a
1080n/a class MyFrozenSet(frozenset):
1081n/a __slots__ = ()
1082n/a with self.assertRaises(TypeError):
1083n/a frozenset().__class__ = MyFrozenSet
1084n/a
1085n/a def test_slots(self):
1086n/a # Testing __slots__...
1087n/a class C0(object):
1088n/a __slots__ = []
1089n/a x = C0()
1090n/a self.assertNotHasAttr(x, "__dict__")
1091n/a self.assertNotHasAttr(x, "foo")
1092n/a
1093n/a class C1(object):
1094n/a __slots__ = ['a']
1095n/a x = C1()
1096n/a self.assertNotHasAttr(x, "__dict__")
1097n/a self.assertNotHasAttr(x, "a")
1098n/a x.a = 1
1099n/a self.assertEqual(x.a, 1)
1100n/a x.a = None
1101n/a self.assertEqual(x.a, None)
1102n/a del x.a
1103n/a self.assertNotHasAttr(x, "a")
1104n/a
1105n/a class C3(object):
1106n/a __slots__ = ['a', 'b', 'c']
1107n/a x = C3()
1108n/a self.assertNotHasAttr(x, "__dict__")
1109n/a self.assertNotHasAttr(x, 'a')
1110n/a self.assertNotHasAttr(x, 'b')
1111n/a self.assertNotHasAttr(x, 'c')
1112n/a x.a = 1
1113n/a x.b = 2
1114n/a x.c = 3
1115n/a self.assertEqual(x.a, 1)
1116n/a self.assertEqual(x.b, 2)
1117n/a self.assertEqual(x.c, 3)
1118n/a
1119n/a class C4(object):
1120n/a """Validate name mangling"""
1121n/a __slots__ = ['__a']
1122n/a def __init__(self, value):
1123n/a self.__a = value
1124n/a def get(self):
1125n/a return self.__a
1126n/a x = C4(5)
1127n/a self.assertNotHasAttr(x, '__dict__')
1128n/a self.assertNotHasAttr(x, '__a')
1129n/a self.assertEqual(x.get(), 5)
1130n/a try:
1131n/a x.__a = 6
1132n/a except AttributeError:
1133n/a pass
1134n/a else:
1135n/a self.fail("Double underscored names not mangled")
1136n/a
1137n/a # Make sure slot names are proper identifiers
1138n/a try:
1139n/a class C(object):
1140n/a __slots__ = [None]
1141n/a except TypeError:
1142n/a pass
1143n/a else:
1144n/a self.fail("[None] slots not caught")
1145n/a try:
1146n/a class C(object):
1147n/a __slots__ = ["foo bar"]
1148n/a except TypeError:
1149n/a pass
1150n/a else:
1151n/a self.fail("['foo bar'] slots not caught")
1152n/a try:
1153n/a class C(object):
1154n/a __slots__ = ["foo\0bar"]
1155n/a except TypeError:
1156n/a pass
1157n/a else:
1158n/a self.fail("['foo\\0bar'] slots not caught")
1159n/a try:
1160n/a class C(object):
1161n/a __slots__ = ["1"]
1162n/a except TypeError:
1163n/a pass
1164n/a else:
1165n/a self.fail("['1'] slots not caught")
1166n/a try:
1167n/a class C(object):
1168n/a __slots__ = [""]
1169n/a except TypeError:
1170n/a pass
1171n/a else:
1172n/a self.fail("[''] slots not caught")
1173n/a class C(object):
1174n/a __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1175n/a # XXX(nnorwitz): was there supposed to be something tested
1176n/a # from the class above?
1177n/a
1178n/a # Test a single string is not expanded as a sequence.
1179n/a class C(object):
1180n/a __slots__ = "abc"
1181n/a c = C()
1182n/a c.abc = 5
1183n/a self.assertEqual(c.abc, 5)
1184n/a
1185n/a # Test unicode slot names
1186n/a # Test a single unicode string is not expanded as a sequence.
1187n/a class C(object):
1188n/a __slots__ = "abc"
1189n/a c = C()
1190n/a c.abc = 5
1191n/a self.assertEqual(c.abc, 5)
1192n/a
1193n/a # _unicode_to_string used to modify slots in certain circumstances
1194n/a slots = ("foo", "bar")
1195n/a class C(object):
1196n/a __slots__ = slots
1197n/a x = C()
1198n/a x.foo = 5
1199n/a self.assertEqual(x.foo, 5)
1200n/a self.assertIs(type(slots[0]), str)
1201n/a # this used to leak references
1202n/a try:
1203n/a class C(object):
1204n/a __slots__ = [chr(128)]
1205n/a except (TypeError, UnicodeEncodeError):
1206n/a pass
1207n/a else:
1208n/a self.fail("[chr(128)] slots not caught")
1209n/a
1210n/a # Test leaks
1211n/a class Counted(object):
1212n/a counter = 0 # counts the number of instances alive
1213n/a def __init__(self):
1214n/a Counted.counter += 1
1215n/a def __del__(self):
1216n/a Counted.counter -= 1
1217n/a class C(object):
1218n/a __slots__ = ['a', 'b', 'c']
1219n/a x = C()
1220n/a x.a = Counted()
1221n/a x.b = Counted()
1222n/a x.c = Counted()
1223n/a self.assertEqual(Counted.counter, 3)
1224n/a del x
1225n/a support.gc_collect()
1226n/a self.assertEqual(Counted.counter, 0)
1227n/a class D(C):
1228n/a pass
1229n/a x = D()
1230n/a x.a = Counted()
1231n/a x.z = Counted()
1232n/a self.assertEqual(Counted.counter, 2)
1233n/a del x
1234n/a support.gc_collect()
1235n/a self.assertEqual(Counted.counter, 0)
1236n/a class E(D):
1237n/a __slots__ = ['e']
1238n/a x = E()
1239n/a x.a = Counted()
1240n/a x.z = Counted()
1241n/a x.e = Counted()
1242n/a self.assertEqual(Counted.counter, 3)
1243n/a del x
1244n/a support.gc_collect()
1245n/a self.assertEqual(Counted.counter, 0)
1246n/a
1247n/a # Test cyclical leaks [SF bug 519621]
1248n/a class F(object):
1249n/a __slots__ = ['a', 'b']
1250n/a s = F()
1251n/a s.a = [Counted(), s]
1252n/a self.assertEqual(Counted.counter, 1)
1253n/a s = None
1254n/a support.gc_collect()
1255n/a self.assertEqual(Counted.counter, 0)
1256n/a
1257n/a # Test lookup leaks [SF bug 572567]
1258n/a if hasattr(gc, 'get_objects'):
1259n/a class G(object):
1260n/a def __eq__(self, other):
1261n/a return False
1262n/a g = G()
1263n/a orig_objects = len(gc.get_objects())
1264n/a for i in range(10):
1265n/a g==g
1266n/a new_objects = len(gc.get_objects())
1267n/a self.assertEqual(orig_objects, new_objects)
1268n/a
1269n/a class H(object):
1270n/a __slots__ = ['a', 'b']
1271n/a def __init__(self):
1272n/a self.a = 1
1273n/a self.b = 2
1274n/a def __del__(self_):
1275n/a self.assertEqual(self_.a, 1)
1276n/a self.assertEqual(self_.b, 2)
1277n/a with support.captured_output('stderr') as s:
1278n/a h = H()
1279n/a del h
1280n/a self.assertEqual(s.getvalue(), '')
1281n/a
1282n/a class X(object):
1283n/a __slots__ = "a"
1284n/a with self.assertRaises(AttributeError):
1285n/a del X().a
1286n/a
1287n/a def test_slots_special(self):
1288n/a # Testing __dict__ and __weakref__ in __slots__...
1289n/a class D(object):
1290n/a __slots__ = ["__dict__"]
1291n/a a = D()
1292n/a self.assertHasAttr(a, "__dict__")
1293n/a self.assertNotHasAttr(a, "__weakref__")
1294n/a a.foo = 42
1295n/a self.assertEqual(a.__dict__, {"foo": 42})
1296n/a
1297n/a class W(object):
1298n/a __slots__ = ["__weakref__"]
1299n/a a = W()
1300n/a self.assertHasAttr(a, "__weakref__")
1301n/a self.assertNotHasAttr(a, "__dict__")
1302n/a try:
1303n/a a.foo = 42
1304n/a except AttributeError:
1305n/a pass
1306n/a else:
1307n/a self.fail("shouldn't be allowed to set a.foo")
1308n/a
1309n/a class C1(W, D):
1310n/a __slots__ = []
1311n/a a = C1()
1312n/a self.assertHasAttr(a, "__dict__")
1313n/a self.assertHasAttr(a, "__weakref__")
1314n/a a.foo = 42
1315n/a self.assertEqual(a.__dict__, {"foo": 42})
1316n/a
1317n/a class C2(D, W):
1318n/a __slots__ = []
1319n/a a = C2()
1320n/a self.assertHasAttr(a, "__dict__")
1321n/a self.assertHasAttr(a, "__weakref__")
1322n/a a.foo = 42
1323n/a self.assertEqual(a.__dict__, {"foo": 42})
1324n/a
1325n/a def test_slots_descriptor(self):
1326n/a # Issue2115: slot descriptors did not correctly check
1327n/a # the type of the given object
1328n/a import abc
1329n/a class MyABC(metaclass=abc.ABCMeta):
1330n/a __slots__ = "a"
1331n/a
1332n/a class Unrelated(object):
1333n/a pass
1334n/a MyABC.register(Unrelated)
1335n/a
1336n/a u = Unrelated()
1337n/a self.assertIsInstance(u, MyABC)
1338n/a
1339n/a # This used to crash
1340n/a self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1341n/a
1342n/a def test_dynamics(self):
1343n/a # Testing class attribute propagation...
1344n/a class D(object):
1345n/a pass
1346n/a class E(D):
1347n/a pass
1348n/a class F(D):
1349n/a pass
1350n/a D.foo = 1
1351n/a self.assertEqual(D.foo, 1)
1352n/a # Test that dynamic attributes are inherited
1353n/a self.assertEqual(E.foo, 1)
1354n/a self.assertEqual(F.foo, 1)
1355n/a # Test dynamic instances
1356n/a class C(object):
1357n/a pass
1358n/a a = C()
1359n/a self.assertNotHasAttr(a, "foobar")
1360n/a C.foobar = 2
1361n/a self.assertEqual(a.foobar, 2)
1362n/a C.method = lambda self: 42
1363n/a self.assertEqual(a.method(), 42)
1364n/a C.__repr__ = lambda self: "C()"
1365n/a self.assertEqual(repr(a), "C()")
1366n/a C.__int__ = lambda self: 100
1367n/a self.assertEqual(int(a), 100)
1368n/a self.assertEqual(a.foobar, 2)
1369n/a self.assertNotHasAttr(a, "spam")
1370n/a def mygetattr(self, name):
1371n/a if name == "spam":
1372n/a return "spam"
1373n/a raise AttributeError
1374n/a C.__getattr__ = mygetattr
1375n/a self.assertEqual(a.spam, "spam")
1376n/a a.new = 12
1377n/a self.assertEqual(a.new, 12)
1378n/a def mysetattr(self, name, value):
1379n/a if name == "spam":
1380n/a raise AttributeError
1381n/a return object.__setattr__(self, name, value)
1382n/a C.__setattr__ = mysetattr
1383n/a try:
1384n/a a.spam = "not spam"
1385n/a except AttributeError:
1386n/a pass
1387n/a else:
1388n/a self.fail("expected AttributeError")
1389n/a self.assertEqual(a.spam, "spam")
1390n/a class D(C):
1391n/a pass
1392n/a d = D()
1393n/a d.foo = 1
1394n/a self.assertEqual(d.foo, 1)
1395n/a
1396n/a # Test handling of int*seq and seq*int
1397n/a class I(int):
1398n/a pass
1399n/a self.assertEqual("a"*I(2), "aa")
1400n/a self.assertEqual(I(2)*"a", "aa")
1401n/a self.assertEqual(2*I(3), 6)
1402n/a self.assertEqual(I(3)*2, 6)
1403n/a self.assertEqual(I(3)*I(2), 6)
1404n/a
1405n/a # Test comparison of classes with dynamic metaclasses
1406n/a class dynamicmetaclass(type):
1407n/a pass
1408n/a class someclass(metaclass=dynamicmetaclass):
1409n/a pass
1410n/a self.assertNotEqual(someclass, object)
1411n/a
1412n/a def test_errors(self):
1413n/a # Testing errors...
1414n/a try:
1415n/a class C(list, dict):
1416n/a pass
1417n/a except TypeError:
1418n/a pass
1419n/a else:
1420n/a self.fail("inheritance from both list and dict should be illegal")
1421n/a
1422n/a try:
1423n/a class C(object, None):
1424n/a pass
1425n/a except TypeError:
1426n/a pass
1427n/a else:
1428n/a self.fail("inheritance from non-type should be illegal")
1429n/a class Classic:
1430n/a pass
1431n/a
1432n/a try:
1433n/a class C(type(len)):
1434n/a pass
1435n/a except TypeError:
1436n/a pass
1437n/a else:
1438n/a self.fail("inheritance from CFunction should be illegal")
1439n/a
1440n/a try:
1441n/a class C(object):
1442n/a __slots__ = 1
1443n/a except TypeError:
1444n/a pass
1445n/a else:
1446n/a self.fail("__slots__ = 1 should be illegal")
1447n/a
1448n/a try:
1449n/a class C(object):
1450n/a __slots__ = [1]
1451n/a except TypeError:
1452n/a pass
1453n/a else:
1454n/a self.fail("__slots__ = [1] should be illegal")
1455n/a
1456n/a class M1(type):
1457n/a pass
1458n/a class M2(type):
1459n/a pass
1460n/a class A1(object, metaclass=M1):
1461n/a pass
1462n/a class A2(object, metaclass=M2):
1463n/a pass
1464n/a try:
1465n/a class B(A1, A2):
1466n/a pass
1467n/a except TypeError:
1468n/a pass
1469n/a else:
1470n/a self.fail("finding the most derived metaclass should have failed")
1471n/a
1472n/a def test_classmethods(self):
1473n/a # Testing class methods...
1474n/a class C(object):
1475n/a def foo(*a): return a
1476n/a goo = classmethod(foo)
1477n/a c = C()
1478n/a self.assertEqual(C.goo(1), (C, 1))
1479n/a self.assertEqual(c.goo(1), (C, 1))
1480n/a self.assertEqual(c.foo(1), (c, 1))
1481n/a class D(C):
1482n/a pass
1483n/a d = D()
1484n/a self.assertEqual(D.goo(1), (D, 1))
1485n/a self.assertEqual(d.goo(1), (D, 1))
1486n/a self.assertEqual(d.foo(1), (d, 1))
1487n/a self.assertEqual(D.foo(d, 1), (d, 1))
1488n/a # Test for a specific crash (SF bug 528132)
1489n/a def f(cls, arg): return (cls, arg)
1490n/a ff = classmethod(f)
1491n/a self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1492n/a self.assertEqual(ff.__get__(0)(42), (int, 42))
1493n/a
1494n/a # Test super() with classmethods (SF bug 535444)
1495n/a self.assertEqual(C.goo.__self__, C)
1496n/a self.assertEqual(D.goo.__self__, D)
1497n/a self.assertEqual(super(D,D).goo.__self__, D)
1498n/a self.assertEqual(super(D,d).goo.__self__, D)
1499n/a self.assertEqual(super(D,D).goo(), (D,))
1500n/a self.assertEqual(super(D,d).goo(), (D,))
1501n/a
1502n/a # Verify that a non-callable will raise
1503n/a meth = classmethod(1).__get__(1)
1504n/a self.assertRaises(TypeError, meth)
1505n/a
1506n/a # Verify that classmethod() doesn't allow keyword args
1507n/a try:
1508n/a classmethod(f, kw=1)
1509n/a except TypeError:
1510n/a pass
1511n/a else:
1512n/a self.fail("classmethod shouldn't accept keyword args")
1513n/a
1514n/a cm = classmethod(f)
1515n/a self.assertEqual(cm.__dict__, {})
1516n/a cm.x = 42
1517n/a self.assertEqual(cm.x, 42)
1518n/a self.assertEqual(cm.__dict__, {"x" : 42})
1519n/a del cm.x
1520n/a self.assertNotHasAttr(cm, "x")
1521n/a
1522n/a @support.impl_detail("the module 'xxsubtype' is internal")
1523n/a def test_classmethods_in_c(self):
1524n/a # Testing C-based class methods...
1525n/a import xxsubtype as spam
1526n/a a = (1, 2, 3)
1527n/a d = {'abc': 123}
1528n/a x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1529n/a self.assertEqual(x, spam.spamlist)
1530n/a self.assertEqual(a, a1)
1531n/a self.assertEqual(d, d1)
1532n/a x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1533n/a self.assertEqual(x, spam.spamlist)
1534n/a self.assertEqual(a, a1)
1535n/a self.assertEqual(d, d1)
1536n/a spam_cm = spam.spamlist.__dict__['classmeth']
1537n/a x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1538n/a self.assertEqual(x2, spam.spamlist)
1539n/a self.assertEqual(a2, a1)
1540n/a self.assertEqual(d2, d1)
1541n/a class SubSpam(spam.spamlist): pass
1542n/a x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1543n/a self.assertEqual(x2, SubSpam)
1544n/a self.assertEqual(a2, a1)
1545n/a self.assertEqual(d2, d1)
1546n/a with self.assertRaises(TypeError):
1547n/a spam_cm()
1548n/a with self.assertRaises(TypeError):
1549n/a spam_cm(spam.spamlist())
1550n/a with self.assertRaises(TypeError):
1551n/a spam_cm(list)
1552n/a
1553n/a def test_staticmethods(self):
1554n/a # Testing static methods...
1555n/a class C(object):
1556n/a def foo(*a): return a
1557n/a goo = staticmethod(foo)
1558n/a c = C()
1559n/a self.assertEqual(C.goo(1), (1,))
1560n/a self.assertEqual(c.goo(1), (1,))
1561n/a self.assertEqual(c.foo(1), (c, 1,))
1562n/a class D(C):
1563n/a pass
1564n/a d = D()
1565n/a self.assertEqual(D.goo(1), (1,))
1566n/a self.assertEqual(d.goo(1), (1,))
1567n/a self.assertEqual(d.foo(1), (d, 1))
1568n/a self.assertEqual(D.foo(d, 1), (d, 1))
1569n/a sm = staticmethod(None)
1570n/a self.assertEqual(sm.__dict__, {})
1571n/a sm.x = 42
1572n/a self.assertEqual(sm.x, 42)
1573n/a self.assertEqual(sm.__dict__, {"x" : 42})
1574n/a del sm.x
1575n/a self.assertNotHasAttr(sm, "x")
1576n/a
1577n/a @support.impl_detail("the module 'xxsubtype' is internal")
1578n/a def test_staticmethods_in_c(self):
1579n/a # Testing C-based static methods...
1580n/a import xxsubtype as spam
1581n/a a = (1, 2, 3)
1582n/a d = {"abc": 123}
1583n/a x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1584n/a self.assertEqual(x, None)
1585n/a self.assertEqual(a, a1)
1586n/a self.assertEqual(d, d1)
1587n/a x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1588n/a self.assertEqual(x, None)
1589n/a self.assertEqual(a, a1)
1590n/a self.assertEqual(d, d1)
1591n/a
1592n/a def test_classic(self):
1593n/a # Testing classic classes...
1594n/a class C:
1595n/a def foo(*a): return a
1596n/a goo = classmethod(foo)
1597n/a c = C()
1598n/a self.assertEqual(C.goo(1), (C, 1))
1599n/a self.assertEqual(c.goo(1), (C, 1))
1600n/a self.assertEqual(c.foo(1), (c, 1))
1601n/a class D(C):
1602n/a pass
1603n/a d = D()
1604n/a self.assertEqual(D.goo(1), (D, 1))
1605n/a self.assertEqual(d.goo(1), (D, 1))
1606n/a self.assertEqual(d.foo(1), (d, 1))
1607n/a self.assertEqual(D.foo(d, 1), (d, 1))
1608n/a class E: # *not* subclassing from C
1609n/a foo = C.foo
1610n/a self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1611n/a self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
1612n/a
1613n/a def test_compattr(self):
1614n/a # Testing computed attributes...
1615n/a class C(object):
1616n/a class computed_attribute(object):
1617n/a def __init__(self, get, set=None, delete=None):
1618n/a self.__get = get
1619n/a self.__set = set
1620n/a self.__delete = delete
1621n/a def __get__(self, obj, type=None):
1622n/a return self.__get(obj)
1623n/a def __set__(self, obj, value):
1624n/a return self.__set(obj, value)
1625n/a def __delete__(self, obj):
1626n/a return self.__delete(obj)
1627n/a def __init__(self):
1628n/a self.__x = 0
1629n/a def __get_x(self):
1630n/a x = self.__x
1631n/a self.__x = x+1
1632n/a return x
1633n/a def __set_x(self, x):
1634n/a self.__x = x
1635n/a def __delete_x(self):
1636n/a del self.__x
1637n/a x = computed_attribute(__get_x, __set_x, __delete_x)
1638n/a a = C()
1639n/a self.assertEqual(a.x, 0)
1640n/a self.assertEqual(a.x, 1)
1641n/a a.x = 10
1642n/a self.assertEqual(a.x, 10)
1643n/a self.assertEqual(a.x, 11)
1644n/a del a.x
1645n/a self.assertNotHasAttr(a, 'x')
1646n/a
1647n/a def test_newslots(self):
1648n/a # Testing __new__ slot override...
1649n/a class C(list):
1650n/a def __new__(cls):
1651n/a self = list.__new__(cls)
1652n/a self.foo = 1
1653n/a return self
1654n/a def __init__(self):
1655n/a self.foo = self.foo + 2
1656n/a a = C()
1657n/a self.assertEqual(a.foo, 3)
1658n/a self.assertEqual(a.__class__, C)
1659n/a class D(C):
1660n/a pass
1661n/a b = D()
1662n/a self.assertEqual(b.foo, 3)
1663n/a self.assertEqual(b.__class__, D)
1664n/a
1665n/a @unittest.expectedFailure
1666n/a def test_bad_new(self):
1667n/a self.assertRaises(TypeError, object.__new__)
1668n/a self.assertRaises(TypeError, object.__new__, '')
1669n/a self.assertRaises(TypeError, list.__new__, object)
1670n/a self.assertRaises(TypeError, object.__new__, list)
1671n/a class C(object):
1672n/a __new__ = list.__new__
1673n/a self.assertRaises(TypeError, C)
1674n/a class C(list):
1675n/a __new__ = object.__new__
1676n/a self.assertRaises(TypeError, C)
1677n/a
1678n/a def test_object_new(self):
1679n/a class A(object):
1680n/a pass
1681n/a object.__new__(A)
1682n/a self.assertRaises(TypeError, object.__new__, A, 5)
1683n/a object.__init__(A())
1684n/a self.assertRaises(TypeError, object.__init__, A(), 5)
1685n/a
1686n/a class A(object):
1687n/a def __init__(self, foo):
1688n/a self.foo = foo
1689n/a object.__new__(A)
1690n/a object.__new__(A, 5)
1691n/a object.__init__(A(3))
1692n/a self.assertRaises(TypeError, object.__init__, A(3), 5)
1693n/a
1694n/a class A(object):
1695n/a def __new__(cls, foo):
1696n/a return object.__new__(cls)
1697n/a object.__new__(A)
1698n/a self.assertRaises(TypeError, object.__new__, A, 5)
1699n/a object.__init__(A(3))
1700n/a object.__init__(A(3), 5)
1701n/a
1702n/a class A(object):
1703n/a def __new__(cls, foo):
1704n/a return object.__new__(cls)
1705n/a def __init__(self, foo):
1706n/a self.foo = foo
1707n/a object.__new__(A)
1708n/a self.assertRaises(TypeError, object.__new__, A, 5)
1709n/a object.__init__(A(3))
1710n/a self.assertRaises(TypeError, object.__init__, A(3), 5)
1711n/a
1712n/a @unittest.expectedFailure
1713n/a def test_restored_object_new(self):
1714n/a class A(object):
1715n/a def __new__(cls, *args, **kwargs):
1716n/a raise AssertionError
1717n/a self.assertRaises(AssertionError, A)
1718n/a class B(A):
1719n/a __new__ = object.__new__
1720n/a def __init__(self, foo):
1721n/a self.foo = foo
1722n/a with warnings.catch_warnings():
1723n/a warnings.simplefilter('error', DeprecationWarning)
1724n/a b = B(3)
1725n/a self.assertEqual(b.foo, 3)
1726n/a self.assertEqual(b.__class__, B)
1727n/a del B.__new__
1728n/a self.assertRaises(AssertionError, B)
1729n/a del A.__new__
1730n/a with warnings.catch_warnings():
1731n/a warnings.simplefilter('error', DeprecationWarning)
1732n/a b = B(3)
1733n/a self.assertEqual(b.foo, 3)
1734n/a self.assertEqual(b.__class__, B)
1735n/a
1736n/a def test_altmro(self):
1737n/a # Testing mro() and overriding it...
1738n/a class A(object):
1739n/a def f(self): return "A"
1740n/a class B(A):
1741n/a pass
1742n/a class C(A):
1743n/a def f(self): return "C"
1744n/a class D(B, C):
1745n/a pass
1746n/a self.assertEqual(D.mro(), [D, B, C, A, object])
1747n/a self.assertEqual(D.__mro__, (D, B, C, A, object))
1748n/a self.assertEqual(D().f(), "C")
1749n/a
1750n/a class PerverseMetaType(type):
1751n/a def mro(cls):
1752n/a L = type.mro(cls)
1753n/a L.reverse()
1754n/a return L
1755n/a class X(D,B,C,A, metaclass=PerverseMetaType):
1756n/a pass
1757n/a self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1758n/a self.assertEqual(X().f(), "A")
1759n/a
1760n/a try:
1761n/a class _metaclass(type):
1762n/a def mro(self):
1763n/a return [self, dict, object]
1764n/a class X(object, metaclass=_metaclass):
1765n/a pass
1766n/a # In CPython, the class creation above already raises
1767n/a # TypeError, as a protection against the fact that
1768n/a # instances of X would segfault it. In other Python
1769n/a # implementations it would be ok to let the class X
1770n/a # be created, but instead get a clean TypeError on the
1771n/a # __setitem__ below.
1772n/a x = object.__new__(X)
1773n/a x[5] = 6
1774n/a except TypeError:
1775n/a pass
1776n/a else:
1777n/a self.fail("devious mro() return not caught")
1778n/a
1779n/a try:
1780n/a class _metaclass(type):
1781n/a def mro(self):
1782n/a return [1]
1783n/a class X(object, metaclass=_metaclass):
1784n/a pass
1785n/a except TypeError:
1786n/a pass
1787n/a else:
1788n/a self.fail("non-class mro() return not caught")
1789n/a
1790n/a try:
1791n/a class _metaclass(type):
1792n/a def mro(self):
1793n/a return 1
1794n/a class X(object, metaclass=_metaclass):
1795n/a pass
1796n/a except TypeError:
1797n/a pass
1798n/a else:
1799n/a self.fail("non-sequence mro() return not caught")
1800n/a
1801n/a def test_overloading(self):
1802n/a # Testing operator overloading...
1803n/a
1804n/a class B(object):
1805n/a "Intermediate class because object doesn't have a __setattr__"
1806n/a
1807n/a class C(B):
1808n/a def __getattr__(self, name):
1809n/a if name == "foo":
1810n/a return ("getattr", name)
1811n/a else:
1812n/a raise AttributeError
1813n/a def __setattr__(self, name, value):
1814n/a if name == "foo":
1815n/a self.setattr = (name, value)
1816n/a else:
1817n/a return B.__setattr__(self, name, value)
1818n/a def __delattr__(self, name):
1819n/a if name == "foo":
1820n/a self.delattr = name
1821n/a else:
1822n/a return B.__delattr__(self, name)
1823n/a
1824n/a def __getitem__(self, key):
1825n/a return ("getitem", key)
1826n/a def __setitem__(self, key, value):
1827n/a self.setitem = (key, value)
1828n/a def __delitem__(self, key):
1829n/a self.delitem = key
1830n/a
1831n/a a = C()
1832n/a self.assertEqual(a.foo, ("getattr", "foo"))
1833n/a a.foo = 12
1834n/a self.assertEqual(a.setattr, ("foo", 12))
1835n/a del a.foo
1836n/a self.assertEqual(a.delattr, "foo")
1837n/a
1838n/a self.assertEqual(a[12], ("getitem", 12))
1839n/a a[12] = 21
1840n/a self.assertEqual(a.setitem, (12, 21))
1841n/a del a[12]
1842n/a self.assertEqual(a.delitem, 12)
1843n/a
1844n/a self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1845n/a a[0:10] = "foo"
1846n/a self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1847n/a del a[0:10]
1848n/a self.assertEqual(a.delitem, (slice(0, 10)))
1849n/a
1850n/a def test_methods(self):
1851n/a # Testing methods...
1852n/a class C(object):
1853n/a def __init__(self, x):
1854n/a self.x = x
1855n/a def foo(self):
1856n/a return self.x
1857n/a c1 = C(1)
1858n/a self.assertEqual(c1.foo(), 1)
1859n/a class D(C):
1860n/a boo = C.foo
1861n/a goo = c1.foo
1862n/a d2 = D(2)
1863n/a self.assertEqual(d2.foo(), 2)
1864n/a self.assertEqual(d2.boo(), 2)
1865n/a self.assertEqual(d2.goo(), 1)
1866n/a class E(object):
1867n/a foo = C.foo
1868n/a self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1869n/a self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1870n/a
1871n/a def test_special_method_lookup(self):
1872n/a # The lookup of special methods bypasses __getattr__ and
1873n/a # __getattribute__, but they still can be descriptors.
1874n/a
1875n/a def run_context(manager):
1876n/a with manager:
1877n/a pass
1878n/a def iden(self):
1879n/a return self
1880n/a def hello(self):
1881n/a return b"hello"
1882n/a def empty_seq(self):
1883n/a return []
1884n/a def zero(self):
1885n/a return 0
1886n/a def complex_num(self):
1887n/a return 1j
1888n/a def stop(self):
1889n/a raise StopIteration
1890n/a def return_true(self, thing=None):
1891n/a return True
1892n/a def do_isinstance(obj):
1893n/a return isinstance(int, obj)
1894n/a def do_issubclass(obj):
1895n/a return issubclass(int, obj)
1896n/a def do_dict_missing(checker):
1897n/a class DictSub(checker.__class__, dict):
1898n/a pass
1899n/a self.assertEqual(DictSub()["hi"], 4)
1900n/a def some_number(self_, key):
1901n/a self.assertEqual(key, "hi")
1902n/a return 4
1903n/a def swallow(*args): pass
1904n/a def format_impl(self, spec):
1905n/a return "hello"
1906n/a
1907n/a # It would be nice to have every special method tested here, but I'm
1908n/a # only listing the ones I can remember outside of typeobject.c, since it
1909n/a # does it right.
1910n/a specials = [
1911n/a ("__bytes__", bytes, hello, set(), {}),
1912n/a ("__reversed__", reversed, empty_seq, set(), {}),
1913n/a ("__length_hint__", list, zero, set(),
1914n/a {"__iter__" : iden, "__next__" : stop}),
1915n/a ("__sizeof__", sys.getsizeof, zero, set(), {}),
1916n/a ("__instancecheck__", do_isinstance, return_true, set(), {}),
1917n/a ("__missing__", do_dict_missing, some_number,
1918n/a set(("__class__",)), {}),
1919n/a ("__subclasscheck__", do_issubclass, return_true,
1920n/a set(("__bases__",)), {}),
1921n/a ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1922n/a ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
1923n/a ("__complex__", complex, complex_num, set(), {}),
1924n/a ("__format__", format, format_impl, set(), {}),
1925n/a ("__floor__", math.floor, zero, set(), {}),
1926n/a ("__trunc__", math.trunc, zero, set(), {}),
1927n/a ("__trunc__", int, zero, set(), {}),
1928n/a ("__ceil__", math.ceil, zero, set(), {}),
1929n/a ("__dir__", dir, empty_seq, set(), {}),
1930n/a ("__round__", round, zero, set(), {}),
1931n/a ]
1932n/a
1933n/a class Checker(object):
1934n/a def __getattr__(self, attr, test=self):
1935n/a test.fail("__getattr__ called with {0}".format(attr))
1936n/a def __getattribute__(self, attr, test=self):
1937n/a if attr not in ok:
1938n/a test.fail("__getattribute__ called with {0}".format(attr))
1939n/a return object.__getattribute__(self, attr)
1940n/a class SpecialDescr(object):
1941n/a def __init__(self, impl):
1942n/a self.impl = impl
1943n/a def __get__(self, obj, owner):
1944n/a record.append(1)
1945n/a return self.impl.__get__(obj, owner)
1946n/a class MyException(Exception):
1947n/a pass
1948n/a class ErrDescr(object):
1949n/a def __get__(self, obj, owner):
1950n/a raise MyException
1951n/a
1952n/a for name, runner, meth_impl, ok, env in specials:
1953n/a class X(Checker):
1954n/a pass
1955n/a for attr, obj in env.items():
1956n/a setattr(X, attr, obj)
1957n/a setattr(X, name, meth_impl)
1958n/a runner(X())
1959n/a
1960n/a record = []
1961n/a class X(Checker):
1962n/a pass
1963n/a for attr, obj in env.items():
1964n/a setattr(X, attr, obj)
1965n/a setattr(X, name, SpecialDescr(meth_impl))
1966n/a runner(X())
1967n/a self.assertEqual(record, [1], name)
1968n/a
1969n/a class X(Checker):
1970n/a pass
1971n/a for attr, obj in env.items():
1972n/a setattr(X, attr, obj)
1973n/a setattr(X, name, ErrDescr())
1974n/a self.assertRaises(MyException, runner, X())
1975n/a
1976n/a def test_specials(self):
1977n/a # Testing special operators...
1978n/a # Test operators like __hash__ for which a built-in default exists
1979n/a
1980n/a # Test the default behavior for static classes
1981n/a class C(object):
1982n/a def __getitem__(self, i):
1983n/a if 0 <= i < 10: return i
1984n/a raise IndexError
1985n/a c1 = C()
1986n/a c2 = C()
1987n/a self.assertFalse(not c1)
1988n/a self.assertNotEqual(id(c1), id(c2))
1989n/a hash(c1)
1990n/a hash(c2)
1991n/a self.assertEqual(c1, c1)
1992n/a self.assertTrue(c1 != c2)
1993n/a self.assertFalse(c1 != c1)
1994n/a self.assertFalse(c1 == c2)
1995n/a # Note that the module name appears in str/repr, and that varies
1996n/a # depending on whether this test is run standalone or from a framework.
1997n/a self.assertGreaterEqual(str(c1).find('C object at '), 0)
1998n/a self.assertEqual(str(c1), repr(c1))
1999n/a self.assertNotIn(-1, c1)
2000n/a for i in range(10):
2001n/a self.assertIn(i, c1)
2002n/a self.assertNotIn(10, c1)
2003n/a # Test the default behavior for dynamic classes
2004n/a class D(object):
2005n/a def __getitem__(self, i):
2006n/a if 0 <= i < 10: return i
2007n/a raise IndexError
2008n/a d1 = D()
2009n/a d2 = D()
2010n/a self.assertFalse(not d1)
2011n/a self.assertNotEqual(id(d1), id(d2))
2012n/a hash(d1)
2013n/a hash(d2)
2014n/a self.assertEqual(d1, d1)
2015n/a self.assertNotEqual(d1, d2)
2016n/a self.assertFalse(d1 != d1)
2017n/a self.assertFalse(d1 == d2)
2018n/a # Note that the module name appears in str/repr, and that varies
2019n/a # depending on whether this test is run standalone or from a framework.
2020n/a self.assertGreaterEqual(str(d1).find('D object at '), 0)
2021n/a self.assertEqual(str(d1), repr(d1))
2022n/a self.assertNotIn(-1, d1)
2023n/a for i in range(10):
2024n/a self.assertIn(i, d1)
2025n/a self.assertNotIn(10, d1)
2026n/a # Test overridden behavior
2027n/a class Proxy(object):
2028n/a def __init__(self, x):
2029n/a self.x = x
2030n/a def __bool__(self):
2031n/a return not not self.x
2032n/a def __hash__(self):
2033n/a return hash(self.x)
2034n/a def __eq__(self, other):
2035n/a return self.x == other
2036n/a def __ne__(self, other):
2037n/a return self.x != other
2038n/a def __ge__(self, other):
2039n/a return self.x >= other
2040n/a def __gt__(self, other):
2041n/a return self.x > other
2042n/a def __le__(self, other):
2043n/a return self.x <= other
2044n/a def __lt__(self, other):
2045n/a return self.x < other
2046n/a def __str__(self):
2047n/a return "Proxy:%s" % self.x
2048n/a def __repr__(self):
2049n/a return "Proxy(%r)" % self.x
2050n/a def __contains__(self, value):
2051n/a return value in self.x
2052n/a p0 = Proxy(0)
2053n/a p1 = Proxy(1)
2054n/a p_1 = Proxy(-1)
2055n/a self.assertFalse(p0)
2056n/a self.assertFalse(not p1)
2057n/a self.assertEqual(hash(p0), hash(0))
2058n/a self.assertEqual(p0, p0)
2059n/a self.assertNotEqual(p0, p1)
2060n/a self.assertFalse(p0 != p0)
2061n/a self.assertEqual(not p0, p1)
2062n/a self.assertTrue(p0 < p1)
2063n/a self.assertTrue(p0 <= p1)
2064n/a self.assertTrue(p1 > p0)
2065n/a self.assertTrue(p1 >= p0)
2066n/a self.assertEqual(str(p0), "Proxy:0")
2067n/a self.assertEqual(repr(p0), "Proxy(0)")
2068n/a p10 = Proxy(range(10))
2069n/a self.assertNotIn(-1, p10)
2070n/a for i in range(10):
2071n/a self.assertIn(i, p10)
2072n/a self.assertNotIn(10, p10)
2073n/a
2074n/a def test_weakrefs(self):
2075n/a # Testing weak references...
2076n/a import weakref
2077n/a class C(object):
2078n/a pass
2079n/a c = C()
2080n/a r = weakref.ref(c)
2081n/a self.assertEqual(r(), c)
2082n/a del c
2083n/a support.gc_collect()
2084n/a self.assertEqual(r(), None)
2085n/a del r
2086n/a class NoWeak(object):
2087n/a __slots__ = ['foo']
2088n/a no = NoWeak()
2089n/a try:
2090n/a weakref.ref(no)
2091n/a except TypeError as msg:
2092n/a self.assertIn("weak reference", str(msg))
2093n/a else:
2094n/a self.fail("weakref.ref(no) should be illegal")
2095n/a class Weak(object):
2096n/a __slots__ = ['foo', '__weakref__']
2097n/a yes = Weak()
2098n/a r = weakref.ref(yes)
2099n/a self.assertEqual(r(), yes)
2100n/a del yes
2101n/a support.gc_collect()
2102n/a self.assertEqual(r(), None)
2103n/a del r
2104n/a
2105n/a def test_properties(self):
2106n/a # Testing property...
2107n/a class C(object):
2108n/a def getx(self):
2109n/a return self.__x
2110n/a def setx(self, value):
2111n/a self.__x = value
2112n/a def delx(self):
2113n/a del self.__x
2114n/a x = property(getx, setx, delx, doc="I'm the x property.")
2115n/a a = C()
2116n/a self.assertNotHasAttr(a, "x")
2117n/a a.x = 42
2118n/a self.assertEqual(a._C__x, 42)
2119n/a self.assertEqual(a.x, 42)
2120n/a del a.x
2121n/a self.assertNotHasAttr(a, "x")
2122n/a self.assertNotHasAttr(a, "_C__x")
2123n/a C.x.__set__(a, 100)
2124n/a self.assertEqual(C.x.__get__(a), 100)
2125n/a C.x.__delete__(a)
2126n/a self.assertNotHasAttr(a, "x")
2127n/a
2128n/a raw = C.__dict__['x']
2129n/a self.assertIsInstance(raw, property)
2130n/a
2131n/a attrs = dir(raw)
2132n/a self.assertIn("__doc__", attrs)
2133n/a self.assertIn("fget", attrs)
2134n/a self.assertIn("fset", attrs)
2135n/a self.assertIn("fdel", attrs)
2136n/a
2137n/a self.assertEqual(raw.__doc__, "I'm the x property.")
2138n/a self.assertIs(raw.fget, C.__dict__['getx'])
2139n/a self.assertIs(raw.fset, C.__dict__['setx'])
2140n/a self.assertIs(raw.fdel, C.__dict__['delx'])
2141n/a
2142n/a for attr in "fget", "fset", "fdel":
2143n/a try:
2144n/a setattr(raw, attr, 42)
2145n/a except AttributeError as msg:
2146n/a if str(msg).find('readonly') < 0:
2147n/a self.fail("when setting readonly attr %r on a property, "
2148n/a "got unexpected AttributeError msg %r" % (attr, str(msg)))
2149n/a else:
2150n/a self.fail("expected AttributeError from trying to set readonly %r "
2151n/a "attr on a property" % attr)
2152n/a
2153n/a raw.__doc__ = 42
2154n/a self.assertEqual(raw.__doc__, 42)
2155n/a
2156n/a class D(object):
2157n/a __getitem__ = property(lambda s: 1/0)
2158n/a
2159n/a d = D()
2160n/a try:
2161n/a for i in d:
2162n/a str(i)
2163n/a except ZeroDivisionError:
2164n/a pass
2165n/a else:
2166n/a self.fail("expected ZeroDivisionError from bad property")
2167n/a
2168n/a @unittest.skipIf(sys.flags.optimize >= 2,
2169n/a "Docstrings are omitted with -O2 and above")
2170n/a def test_properties_doc_attrib(self):
2171n/a class E(object):
2172n/a def getter(self):
2173n/a "getter method"
2174n/a return 0
2175n/a def setter(self_, value):
2176n/a "setter method"
2177n/a pass
2178n/a prop = property(getter)
2179n/a self.assertEqual(prop.__doc__, "getter method")
2180n/a prop2 = property(fset=setter)
2181n/a self.assertEqual(prop2.__doc__, None)
2182n/a
2183n/a @support.cpython_only
2184n/a def test_testcapi_no_segfault(self):
2185n/a # this segfaulted in 2.5b2
2186n/a try:
2187n/a import _testcapi
2188n/a except ImportError:
2189n/a pass
2190n/a else:
2191n/a class X(object):
2192n/a p = property(_testcapi.test_with_docstring)
2193n/a
2194n/a def test_properties_plus(self):
2195n/a class C(object):
2196n/a foo = property(doc="hello")
2197n/a @foo.getter
2198n/a def foo(self):
2199n/a return self._foo
2200n/a @foo.setter
2201n/a def foo(self, value):
2202n/a self._foo = abs(value)
2203n/a @foo.deleter
2204n/a def foo(self):
2205n/a del self._foo
2206n/a c = C()
2207n/a self.assertEqual(C.foo.__doc__, "hello")
2208n/a self.assertNotHasAttr(c, "foo")
2209n/a c.foo = -42
2210n/a self.assertHasAttr(c, '_foo')
2211n/a self.assertEqual(c._foo, 42)
2212n/a self.assertEqual(c.foo, 42)
2213n/a del c.foo
2214n/a self.assertNotHasAttr(c, '_foo')
2215n/a self.assertNotHasAttr(c, "foo")
2216n/a
2217n/a class D(C):
2218n/a @C.foo.deleter
2219n/a def foo(self):
2220n/a try:
2221n/a del self._foo
2222n/a except AttributeError:
2223n/a pass
2224n/a d = D()
2225n/a d.foo = 24
2226n/a self.assertEqual(d.foo, 24)
2227n/a del d.foo
2228n/a del d.foo
2229n/a
2230n/a class E(object):
2231n/a @property
2232n/a def foo(self):
2233n/a return self._foo
2234n/a @foo.setter
2235n/a def foo(self, value):
2236n/a raise RuntimeError
2237n/a @foo.setter
2238n/a def foo(self, value):
2239n/a self._foo = abs(value)
2240n/a @foo.deleter
2241n/a def foo(self, value=None):
2242n/a del self._foo
2243n/a
2244n/a e = E()
2245n/a e.foo = -42
2246n/a self.assertEqual(e.foo, 42)
2247n/a del e.foo
2248n/a
2249n/a class F(E):
2250n/a @E.foo.deleter
2251n/a def foo(self):
2252n/a del self._foo
2253n/a @foo.setter
2254n/a def foo(self, value):
2255n/a self._foo = max(0, value)
2256n/a f = F()
2257n/a f.foo = -10
2258n/a self.assertEqual(f.foo, 0)
2259n/a del f.foo
2260n/a
2261n/a def test_dict_constructors(self):
2262n/a # Testing dict constructor ...
2263n/a d = dict()
2264n/a self.assertEqual(d, {})
2265n/a d = dict({})
2266n/a self.assertEqual(d, {})
2267n/a d = dict({1: 2, 'a': 'b'})
2268n/a self.assertEqual(d, {1: 2, 'a': 'b'})
2269n/a self.assertEqual(d, dict(list(d.items())))
2270n/a self.assertEqual(d, dict(iter(d.items())))
2271n/a d = dict({'one':1, 'two':2})
2272n/a self.assertEqual(d, dict(one=1, two=2))
2273n/a self.assertEqual(d, dict(**d))
2274n/a self.assertEqual(d, dict({"one": 1}, two=2))
2275n/a self.assertEqual(d, dict([("two", 2)], one=1))
2276n/a self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2277n/a self.assertEqual(d, dict(**d))
2278n/a
2279n/a for badarg in 0, 0, 0j, "0", [0], (0,):
2280n/a try:
2281n/a dict(badarg)
2282n/a except TypeError:
2283n/a pass
2284n/a except ValueError:
2285n/a if badarg == "0":
2286n/a # It's a sequence, and its elements are also sequences (gotta
2287n/a # love strings <wink>), but they aren't of length 2, so this
2288n/a # one seemed better as a ValueError than a TypeError.
2289n/a pass
2290n/a else:
2291n/a self.fail("no TypeError from dict(%r)" % badarg)
2292n/a else:
2293n/a self.fail("no TypeError from dict(%r)" % badarg)
2294n/a
2295n/a try:
2296n/a dict({}, {})
2297n/a except TypeError:
2298n/a pass
2299n/a else:
2300n/a self.fail("no TypeError from dict({}, {})")
2301n/a
2302n/a class Mapping:
2303n/a # Lacks a .keys() method; will be added later.
2304n/a dict = {1:2, 3:4, 'a':1j}
2305n/a
2306n/a try:
2307n/a dict(Mapping())
2308n/a except TypeError:
2309n/a pass
2310n/a else:
2311n/a self.fail("no TypeError from dict(incomplete mapping)")
2312n/a
2313n/a Mapping.keys = lambda self: list(self.dict.keys())
2314n/a Mapping.__getitem__ = lambda self, i: self.dict[i]
2315n/a d = dict(Mapping())
2316n/a self.assertEqual(d, Mapping.dict)
2317n/a
2318n/a # Init from sequence of iterable objects, each producing a 2-sequence.
2319n/a class AddressBookEntry:
2320n/a def __init__(self, first, last):
2321n/a self.first = first
2322n/a self.last = last
2323n/a def __iter__(self):
2324n/a return iter([self.first, self.last])
2325n/a
2326n/a d = dict([AddressBookEntry('Tim', 'Warsaw'),
2327n/a AddressBookEntry('Barry', 'Peters'),
2328n/a AddressBookEntry('Tim', 'Peters'),
2329n/a AddressBookEntry('Barry', 'Warsaw')])
2330n/a self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2331n/a
2332n/a d = dict(zip(range(4), range(1, 5)))
2333n/a self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2334n/a
2335n/a # Bad sequence lengths.
2336n/a for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2337n/a try:
2338n/a dict(bad)
2339n/a except ValueError:
2340n/a pass
2341n/a else:
2342n/a self.fail("no ValueError from dict(%r)" % bad)
2343n/a
2344n/a def test_dir(self):
2345n/a # Testing dir() ...
2346n/a junk = 12
2347n/a self.assertEqual(dir(), ['junk', 'self'])
2348n/a del junk
2349n/a
2350n/a # Just make sure these don't blow up!
2351n/a for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2352n/a dir(arg)
2353n/a
2354n/a # Test dir on new-style classes. Since these have object as a
2355n/a # base class, a lot more gets sucked in.
2356n/a def interesting(strings):
2357n/a return [s for s in strings if not s.startswith('_')]
2358n/a
2359n/a class C(object):
2360n/a Cdata = 1
2361n/a def Cmethod(self): pass
2362n/a
2363n/a cstuff = ['Cdata', 'Cmethod']
2364n/a self.assertEqual(interesting(dir(C)), cstuff)
2365n/a
2366n/a c = C()
2367n/a self.assertEqual(interesting(dir(c)), cstuff)
2368n/a ## self.assertIn('__self__', dir(C.Cmethod))
2369n/a
2370n/a c.cdata = 2
2371n/a c.cmethod = lambda self: 0
2372n/a self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2373n/a ## self.assertIn('__self__', dir(c.Cmethod))
2374n/a
2375n/a class A(C):
2376n/a Adata = 1
2377n/a def Amethod(self): pass
2378n/a
2379n/a astuff = ['Adata', 'Amethod'] + cstuff
2380n/a self.assertEqual(interesting(dir(A)), astuff)
2381n/a ## self.assertIn('__self__', dir(A.Amethod))
2382n/a a = A()
2383n/a self.assertEqual(interesting(dir(a)), astuff)
2384n/a a.adata = 42
2385n/a a.amethod = lambda self: 3
2386n/a self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2387n/a ## self.assertIn('__self__', dir(a.Amethod))
2388n/a
2389n/a # Try a module subclass.
2390n/a class M(type(sys)):
2391n/a pass
2392n/a minstance = M("m")
2393n/a minstance.b = 2
2394n/a minstance.a = 1
2395n/a default_attributes = ['__name__', '__doc__', '__package__',
2396n/a '__loader__', '__spec__']
2397n/a names = [x for x in dir(minstance) if x not in default_attributes]
2398n/a self.assertEqual(names, ['a', 'b'])
2399n/a
2400n/a class M2(M):
2401n/a def getdict(self):
2402n/a return "Not a dict!"
2403n/a __dict__ = property(getdict)
2404n/a
2405n/a m2instance = M2("m2")
2406n/a m2instance.b = 2
2407n/a m2instance.a = 1
2408n/a self.assertEqual(m2instance.__dict__, "Not a dict!")
2409n/a try:
2410n/a dir(m2instance)
2411n/a except TypeError:
2412n/a pass
2413n/a
2414n/a # Two essentially featureless objects, just inheriting stuff from
2415n/a # object.
2416n/a self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2417n/a
2418n/a # Nasty test case for proxied objects
2419n/a class Wrapper(object):
2420n/a def __init__(self, obj):
2421n/a self.__obj = obj
2422n/a def __repr__(self):
2423n/a return "Wrapper(%s)" % repr(self.__obj)
2424n/a def __getitem__(self, key):
2425n/a return Wrapper(self.__obj[key])
2426n/a def __len__(self):
2427n/a return len(self.__obj)
2428n/a def __getattr__(self, name):
2429n/a return Wrapper(getattr(self.__obj, name))
2430n/a
2431n/a class C(object):
2432n/a def __getclass(self):
2433n/a return Wrapper(type(self))
2434n/a __class__ = property(__getclass)
2435n/a
2436n/a dir(C()) # This used to segfault
2437n/a
2438n/a def test_supers(self):
2439n/a # Testing super...
2440n/a
2441n/a class A(object):
2442n/a def meth(self, a):
2443n/a return "A(%r)" % a
2444n/a
2445n/a self.assertEqual(A().meth(1), "A(1)")
2446n/a
2447n/a class B(A):
2448n/a def __init__(self):
2449n/a self.__super = super(B, self)
2450n/a def meth(self, a):
2451n/a return "B(%r)" % a + self.__super.meth(a)
2452n/a
2453n/a self.assertEqual(B().meth(2), "B(2)A(2)")
2454n/a
2455n/a class C(A):
2456n/a def meth(self, a):
2457n/a return "C(%r)" % a + self.__super.meth(a)
2458n/a C._C__super = super(C)
2459n/a
2460n/a self.assertEqual(C().meth(3), "C(3)A(3)")
2461n/a
2462n/a class D(C, B):
2463n/a def meth(self, a):
2464n/a return "D(%r)" % a + super(D, self).meth(a)
2465n/a
2466n/a self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2467n/a
2468n/a # Test for subclassing super
2469n/a
2470n/a class mysuper(super):
2471n/a def __init__(self, *args):
2472n/a return super(mysuper, self).__init__(*args)
2473n/a
2474n/a class E(D):
2475n/a def meth(self, a):
2476n/a return "E(%r)" % a + mysuper(E, self).meth(a)
2477n/a
2478n/a self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2479n/a
2480n/a class F(E):
2481n/a def meth(self, a):
2482n/a s = self.__super # == mysuper(F, self)
2483n/a return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2484n/a F._F__super = mysuper(F)
2485n/a
2486n/a self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2487n/a
2488n/a # Make sure certain errors are raised
2489n/a
2490n/a try:
2491n/a super(D, 42)
2492n/a except TypeError:
2493n/a pass
2494n/a else:
2495n/a self.fail("shouldn't allow super(D, 42)")
2496n/a
2497n/a try:
2498n/a super(D, C())
2499n/a except TypeError:
2500n/a pass
2501n/a else:
2502n/a self.fail("shouldn't allow super(D, C())")
2503n/a
2504n/a try:
2505n/a super(D).__get__(12)
2506n/a except TypeError:
2507n/a pass
2508n/a else:
2509n/a self.fail("shouldn't allow super(D).__get__(12)")
2510n/a
2511n/a try:
2512n/a super(D).__get__(C())
2513n/a except TypeError:
2514n/a pass
2515n/a else:
2516n/a self.fail("shouldn't allow super(D).__get__(C())")
2517n/a
2518n/a # Make sure data descriptors can be overridden and accessed via super
2519n/a # (new feature in Python 2.3)
2520n/a
2521n/a class DDbase(object):
2522n/a def getx(self): return 42
2523n/a x = property(getx)
2524n/a
2525n/a class DDsub(DDbase):
2526n/a def getx(self): return "hello"
2527n/a x = property(getx)
2528n/a
2529n/a dd = DDsub()
2530n/a self.assertEqual(dd.x, "hello")
2531n/a self.assertEqual(super(DDsub, dd).x, 42)
2532n/a
2533n/a # Ensure that super() lookup of descriptor from classmethod
2534n/a # works (SF ID# 743627)
2535n/a
2536n/a class Base(object):
2537n/a aProp = property(lambda self: "foo")
2538n/a
2539n/a class Sub(Base):
2540n/a @classmethod
2541n/a def test(klass):
2542n/a return super(Sub,klass).aProp
2543n/a
2544n/a self.assertEqual(Sub.test(), Base.aProp)
2545n/a
2546n/a # Verify that super() doesn't allow keyword args
2547n/a try:
2548n/a super(Base, kw=1)
2549n/a except TypeError:
2550n/a pass
2551n/a else:
2552n/a self.assertEqual("super shouldn't accept keyword args")
2553n/a
2554n/a def test_basic_inheritance(self):
2555n/a # Testing inheritance from basic types...
2556n/a
2557n/a class hexint(int):
2558n/a def __repr__(self):
2559n/a return hex(self)
2560n/a def __add__(self, other):
2561n/a return hexint(int.__add__(self, other))
2562n/a # (Note that overriding __radd__ doesn't work,
2563n/a # because the int type gets first dibs.)
2564n/a self.assertEqual(repr(hexint(7) + 9), "0x10")
2565n/a self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2566n/a a = hexint(12345)
2567n/a self.assertEqual(a, 12345)
2568n/a self.assertEqual(int(a), 12345)
2569n/a self.assertIs(int(a).__class__, int)
2570n/a self.assertEqual(hash(a), hash(12345))
2571n/a self.assertIs((+a).__class__, int)
2572n/a self.assertIs((a >> 0).__class__, int)
2573n/a self.assertIs((a << 0).__class__, int)
2574n/a self.assertIs((hexint(0) << 12).__class__, int)
2575n/a self.assertIs((hexint(0) >> 12).__class__, int)
2576n/a
2577n/a class octlong(int):
2578n/a __slots__ = []
2579n/a def __str__(self):
2580n/a return oct(self)
2581n/a def __add__(self, other):
2582n/a return self.__class__(super(octlong, self).__add__(other))
2583n/a __radd__ = __add__
2584n/a self.assertEqual(str(octlong(3) + 5), "0o10")
2585n/a # (Note that overriding __radd__ here only seems to work
2586n/a # because the example uses a short int left argument.)
2587n/a self.assertEqual(str(5 + octlong(3000)), "0o5675")
2588n/a a = octlong(12345)
2589n/a self.assertEqual(a, 12345)
2590n/a self.assertEqual(int(a), 12345)
2591n/a self.assertEqual(hash(a), hash(12345))
2592n/a self.assertIs(int(a).__class__, int)
2593n/a self.assertIs((+a).__class__, int)
2594n/a self.assertIs((-a).__class__, int)
2595n/a self.assertIs((-octlong(0)).__class__, int)
2596n/a self.assertIs((a >> 0).__class__, int)
2597n/a self.assertIs((a << 0).__class__, int)
2598n/a self.assertIs((a - 0).__class__, int)
2599n/a self.assertIs((a * 1).__class__, int)
2600n/a self.assertIs((a ** 1).__class__, int)
2601n/a self.assertIs((a // 1).__class__, int)
2602n/a self.assertIs((1 * a).__class__, int)
2603n/a self.assertIs((a | 0).__class__, int)
2604n/a self.assertIs((a ^ 0).__class__, int)
2605n/a self.assertIs((a & -1).__class__, int)
2606n/a self.assertIs((octlong(0) << 12).__class__, int)
2607n/a self.assertIs((octlong(0) >> 12).__class__, int)
2608n/a self.assertIs(abs(octlong(0)).__class__, int)
2609n/a
2610n/a # Because octlong overrides __add__, we can't check the absence of +0
2611n/a # optimizations using octlong.
2612n/a class longclone(int):
2613n/a pass
2614n/a a = longclone(1)
2615n/a self.assertIs((a + 0).__class__, int)
2616n/a self.assertIs((0 + a).__class__, int)
2617n/a
2618n/a # Check that negative clones don't segfault
2619n/a a = longclone(-1)
2620n/a self.assertEqual(a.__dict__, {})
2621n/a self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2622n/a
2623n/a class precfloat(float):
2624n/a __slots__ = ['prec']
2625n/a def __init__(self, value=0.0, prec=12):
2626n/a self.prec = int(prec)
2627n/a def __repr__(self):
2628n/a return "%.*g" % (self.prec, self)
2629n/a self.assertEqual(repr(precfloat(1.1)), "1.1")
2630n/a a = precfloat(12345)
2631n/a self.assertEqual(a, 12345.0)
2632n/a self.assertEqual(float(a), 12345.0)
2633n/a self.assertIs(float(a).__class__, float)
2634n/a self.assertEqual(hash(a), hash(12345.0))
2635n/a self.assertIs((+a).__class__, float)
2636n/a
2637n/a class madcomplex(complex):
2638n/a def __repr__(self):
2639n/a return "%.17gj%+.17g" % (self.imag, self.real)
2640n/a a = madcomplex(-3, 4)
2641n/a self.assertEqual(repr(a), "4j-3")
2642n/a base = complex(-3, 4)
2643n/a self.assertEqual(base.__class__, complex)
2644n/a self.assertEqual(a, base)
2645n/a self.assertEqual(complex(a), base)
2646n/a self.assertEqual(complex(a).__class__, complex)
2647n/a a = madcomplex(a) # just trying another form of the constructor
2648n/a self.assertEqual(repr(a), "4j-3")
2649n/a self.assertEqual(a, base)
2650n/a self.assertEqual(complex(a), base)
2651n/a self.assertEqual(complex(a).__class__, complex)
2652n/a self.assertEqual(hash(a), hash(base))
2653n/a self.assertEqual((+a).__class__, complex)
2654n/a self.assertEqual((a + 0).__class__, complex)
2655n/a self.assertEqual(a + 0, base)
2656n/a self.assertEqual((a - 0).__class__, complex)
2657n/a self.assertEqual(a - 0, base)
2658n/a self.assertEqual((a * 1).__class__, complex)
2659n/a self.assertEqual(a * 1, base)
2660n/a self.assertEqual((a / 1).__class__, complex)
2661n/a self.assertEqual(a / 1, base)
2662n/a
2663n/a class madtuple(tuple):
2664n/a _rev = None
2665n/a def rev(self):
2666n/a if self._rev is not None:
2667n/a return self._rev
2668n/a L = list(self)
2669n/a L.reverse()
2670n/a self._rev = self.__class__(L)
2671n/a return self._rev
2672n/a a = madtuple((1,2,3,4,5,6,7,8,9,0))
2673n/a self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2674n/a self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2675n/a self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2676n/a for i in range(512):
2677n/a t = madtuple(range(i))
2678n/a u = t.rev()
2679n/a v = u.rev()
2680n/a self.assertEqual(v, t)
2681n/a a = madtuple((1,2,3,4,5))
2682n/a self.assertEqual(tuple(a), (1,2,3,4,5))
2683n/a self.assertIs(tuple(a).__class__, tuple)
2684n/a self.assertEqual(hash(a), hash((1,2,3,4,5)))
2685n/a self.assertIs(a[:].__class__, tuple)
2686n/a self.assertIs((a * 1).__class__, tuple)
2687n/a self.assertIs((a * 0).__class__, tuple)
2688n/a self.assertIs((a + ()).__class__, tuple)
2689n/a a = madtuple(())
2690n/a self.assertEqual(tuple(a), ())
2691n/a self.assertIs(tuple(a).__class__, tuple)
2692n/a self.assertIs((a + a).__class__, tuple)
2693n/a self.assertIs((a * 0).__class__, tuple)
2694n/a self.assertIs((a * 1).__class__, tuple)
2695n/a self.assertIs((a * 2).__class__, tuple)
2696n/a self.assertIs(a[:].__class__, tuple)
2697n/a
2698n/a class madstring(str):
2699n/a _rev = None
2700n/a def rev(self):
2701n/a if self._rev is not None:
2702n/a return self._rev
2703n/a L = list(self)
2704n/a L.reverse()
2705n/a self._rev = self.__class__("".join(L))
2706n/a return self._rev
2707n/a s = madstring("abcdefghijklmnopqrstuvwxyz")
2708n/a self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2709n/a self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2710n/a self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2711n/a for i in range(256):
2712n/a s = madstring("".join(map(chr, range(i))))
2713n/a t = s.rev()
2714n/a u = t.rev()
2715n/a self.assertEqual(u, s)
2716n/a s = madstring("12345")
2717n/a self.assertEqual(str(s), "12345")
2718n/a self.assertIs(str(s).__class__, str)
2719n/a
2720n/a base = "\x00" * 5
2721n/a s = madstring(base)
2722n/a self.assertEqual(s, base)
2723n/a self.assertEqual(str(s), base)
2724n/a self.assertIs(str(s).__class__, str)
2725n/a self.assertEqual(hash(s), hash(base))
2726n/a self.assertEqual({s: 1}[base], 1)
2727n/a self.assertEqual({base: 1}[s], 1)
2728n/a self.assertIs((s + "").__class__, str)
2729n/a self.assertEqual(s + "", base)
2730n/a self.assertIs(("" + s).__class__, str)
2731n/a self.assertEqual("" + s, base)
2732n/a self.assertIs((s * 0).__class__, str)
2733n/a self.assertEqual(s * 0, "")
2734n/a self.assertIs((s * 1).__class__, str)
2735n/a self.assertEqual(s * 1, base)
2736n/a self.assertIs((s * 2).__class__, str)
2737n/a self.assertEqual(s * 2, base + base)
2738n/a self.assertIs(s[:].__class__, str)
2739n/a self.assertEqual(s[:], base)
2740n/a self.assertIs(s[0:0].__class__, str)
2741n/a self.assertEqual(s[0:0], "")
2742n/a self.assertIs(s.strip().__class__, str)
2743n/a self.assertEqual(s.strip(), base)
2744n/a self.assertIs(s.lstrip().__class__, str)
2745n/a self.assertEqual(s.lstrip(), base)
2746n/a self.assertIs(s.rstrip().__class__, str)
2747n/a self.assertEqual(s.rstrip(), base)
2748n/a identitytab = {}
2749n/a self.assertIs(s.translate(identitytab).__class__, str)
2750n/a self.assertEqual(s.translate(identitytab), base)
2751n/a self.assertIs(s.replace("x", "x").__class__, str)
2752n/a self.assertEqual(s.replace("x", "x"), base)
2753n/a self.assertIs(s.ljust(len(s)).__class__, str)
2754n/a self.assertEqual(s.ljust(len(s)), base)
2755n/a self.assertIs(s.rjust(len(s)).__class__, str)
2756n/a self.assertEqual(s.rjust(len(s)), base)
2757n/a self.assertIs(s.center(len(s)).__class__, str)
2758n/a self.assertEqual(s.center(len(s)), base)
2759n/a self.assertIs(s.lower().__class__, str)
2760n/a self.assertEqual(s.lower(), base)
2761n/a
2762n/a class madunicode(str):
2763n/a _rev = None
2764n/a def rev(self):
2765n/a if self._rev is not None:
2766n/a return self._rev
2767n/a L = list(self)
2768n/a L.reverse()
2769n/a self._rev = self.__class__("".join(L))
2770n/a return self._rev
2771n/a u = madunicode("ABCDEF")
2772n/a self.assertEqual(u, "ABCDEF")
2773n/a self.assertEqual(u.rev(), madunicode("FEDCBA"))
2774n/a self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2775n/a base = "12345"
2776n/a u = madunicode(base)
2777n/a self.assertEqual(str(u), base)
2778n/a self.assertIs(str(u).__class__, str)
2779n/a self.assertEqual(hash(u), hash(base))
2780n/a self.assertEqual({u: 1}[base], 1)
2781n/a self.assertEqual({base: 1}[u], 1)
2782n/a self.assertIs(u.strip().__class__, str)
2783n/a self.assertEqual(u.strip(), base)
2784n/a self.assertIs(u.lstrip().__class__, str)
2785n/a self.assertEqual(u.lstrip(), base)
2786n/a self.assertIs(u.rstrip().__class__, str)
2787n/a self.assertEqual(u.rstrip(), base)
2788n/a self.assertIs(u.replace("x", "x").__class__, str)
2789n/a self.assertEqual(u.replace("x", "x"), base)
2790n/a self.assertIs(u.replace("xy", "xy").__class__, str)
2791n/a self.assertEqual(u.replace("xy", "xy"), base)
2792n/a self.assertIs(u.center(len(u)).__class__, str)
2793n/a self.assertEqual(u.center(len(u)), base)
2794n/a self.assertIs(u.ljust(len(u)).__class__, str)
2795n/a self.assertEqual(u.ljust(len(u)), base)
2796n/a self.assertIs(u.rjust(len(u)).__class__, str)
2797n/a self.assertEqual(u.rjust(len(u)), base)
2798n/a self.assertIs(u.lower().__class__, str)
2799n/a self.assertEqual(u.lower(), base)
2800n/a self.assertIs(u.upper().__class__, str)
2801n/a self.assertEqual(u.upper(), base)
2802n/a self.assertIs(u.capitalize().__class__, str)
2803n/a self.assertEqual(u.capitalize(), base)
2804n/a self.assertIs(u.title().__class__, str)
2805n/a self.assertEqual(u.title(), base)
2806n/a self.assertIs((u + "").__class__, str)
2807n/a self.assertEqual(u + "", base)
2808n/a self.assertIs(("" + u).__class__, str)
2809n/a self.assertEqual("" + u, base)
2810n/a self.assertIs((u * 0).__class__, str)
2811n/a self.assertEqual(u * 0, "")
2812n/a self.assertIs((u * 1).__class__, str)
2813n/a self.assertEqual(u * 1, base)
2814n/a self.assertIs((u * 2).__class__, str)
2815n/a self.assertEqual(u * 2, base + base)
2816n/a self.assertIs(u[:].__class__, str)
2817n/a self.assertEqual(u[:], base)
2818n/a self.assertIs(u[0:0].__class__, str)
2819n/a self.assertEqual(u[0:0], "")
2820n/a
2821n/a class sublist(list):
2822n/a pass
2823n/a a = sublist(range(5))
2824n/a self.assertEqual(a, list(range(5)))
2825n/a a.append("hello")
2826n/a self.assertEqual(a, list(range(5)) + ["hello"])
2827n/a a[5] = 5
2828n/a self.assertEqual(a, list(range(6)))
2829n/a a.extend(range(6, 20))
2830n/a self.assertEqual(a, list(range(20)))
2831n/a a[-5:] = []
2832n/a self.assertEqual(a, list(range(15)))
2833n/a del a[10:15]
2834n/a self.assertEqual(len(a), 10)
2835n/a self.assertEqual(a, list(range(10)))
2836n/a self.assertEqual(list(a), list(range(10)))
2837n/a self.assertEqual(a[0], 0)
2838n/a self.assertEqual(a[9], 9)
2839n/a self.assertEqual(a[-10], 0)
2840n/a self.assertEqual(a[-1], 9)
2841n/a self.assertEqual(a[:5], list(range(5)))
2842n/a
2843n/a ## class CountedInput(file):
2844n/a ## """Counts lines read by self.readline().
2845n/a ##
2846n/a ## self.lineno is the 0-based ordinal of the last line read, up to
2847n/a ## a maximum of one greater than the number of lines in the file.
2848n/a ##
2849n/a ## self.ateof is true if and only if the final "" line has been read,
2850n/a ## at which point self.lineno stops incrementing, and further calls
2851n/a ## to readline() continue to return "".
2852n/a ## """
2853n/a ##
2854n/a ## lineno = 0
2855n/a ## ateof = 0
2856n/a ## def readline(self):
2857n/a ## if self.ateof:
2858n/a ## return ""
2859n/a ## s = file.readline(self)
2860n/a ## # Next line works too.
2861n/a ## # s = super(CountedInput, self).readline()
2862n/a ## self.lineno += 1
2863n/a ## if s == "":
2864n/a ## self.ateof = 1
2865n/a ## return s
2866n/a ##
2867n/a ## f = file(name=support.TESTFN, mode='w')
2868n/a ## lines = ['a\n', 'b\n', 'c\n']
2869n/a ## try:
2870n/a ## f.writelines(lines)
2871n/a ## f.close()
2872n/a ## f = CountedInput(support.TESTFN)
2873n/a ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2874n/a ## got = f.readline()
2875n/a ## self.assertEqual(expected, got)
2876n/a ## self.assertEqual(f.lineno, i)
2877n/a ## self.assertEqual(f.ateof, (i > len(lines)))
2878n/a ## f.close()
2879n/a ## finally:
2880n/a ## try:
2881n/a ## f.close()
2882n/a ## except:
2883n/a ## pass
2884n/a ## support.unlink(support.TESTFN)
2885n/a
2886n/a def test_keywords(self):
2887n/a # Testing keyword args to basic type constructors ...
2888n/a self.assertEqual(int(x=1), 1)
2889n/a self.assertEqual(float(x=2), 2.0)
2890n/a self.assertEqual(int(x=3), 3)
2891n/a self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2892n/a self.assertEqual(str(object=500), '500')
2893n/a self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2894n/a self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2895n/a self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2896n/a # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2897n/a
2898n/a for constructor in (int, float, int, complex, str, str,
2899n/a tuple, list):
2900n/a try:
2901n/a constructor(bogus_keyword_arg=1)
2902n/a except TypeError:
2903n/a pass
2904n/a else:
2905n/a self.fail("expected TypeError from bogus keyword argument to %r"
2906n/a % constructor)
2907n/a
2908n/a def test_str_subclass_as_dict_key(self):
2909n/a # Testing a str subclass used as dict key ..
2910n/a
2911n/a class cistr(str):
2912n/a """Sublcass of str that computes __eq__ case-insensitively.
2913n/a
2914n/a Also computes a hash code of the string in canonical form.
2915n/a """
2916n/a
2917n/a def __init__(self, value):
2918n/a self.canonical = value.lower()
2919n/a self.hashcode = hash(self.canonical)
2920n/a
2921n/a def __eq__(self, other):
2922n/a if not isinstance(other, cistr):
2923n/a other = cistr(other)
2924n/a return self.canonical == other.canonical
2925n/a
2926n/a def __hash__(self):
2927n/a return self.hashcode
2928n/a
2929n/a self.assertEqual(cistr('ABC'), 'abc')
2930n/a self.assertEqual('aBc', cistr('ABC'))
2931n/a self.assertEqual(str(cistr('ABC')), 'ABC')
2932n/a
2933n/a d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2934n/a self.assertEqual(d[cistr('one')], 1)
2935n/a self.assertEqual(d[cistr('tWo')], 2)
2936n/a self.assertEqual(d[cistr('THrEE')], 3)
2937n/a self.assertIn(cistr('ONe'), d)
2938n/a self.assertEqual(d.get(cistr('thrEE')), 3)
2939n/a
2940n/a def test_classic_comparisons(self):
2941n/a # Testing classic comparisons...
2942n/a class classic:
2943n/a pass
2944n/a
2945n/a for base in (classic, int, object):
2946n/a class C(base):
2947n/a def __init__(self, value):
2948n/a self.value = int(value)
2949n/a def __eq__(self, other):
2950n/a if isinstance(other, C):
2951n/a return self.value == other.value
2952n/a if isinstance(other, int) or isinstance(other, int):
2953n/a return self.value == other
2954n/a return NotImplemented
2955n/a def __ne__(self, other):
2956n/a if isinstance(other, C):
2957n/a return self.value != other.value
2958n/a if isinstance(other, int) or isinstance(other, int):
2959n/a return self.value != other
2960n/a return NotImplemented
2961n/a def __lt__(self, other):
2962n/a if isinstance(other, C):
2963n/a return self.value < other.value
2964n/a if isinstance(other, int) or isinstance(other, int):
2965n/a return self.value < other
2966n/a return NotImplemented
2967n/a def __le__(self, other):
2968n/a if isinstance(other, C):
2969n/a return self.value <= other.value
2970n/a if isinstance(other, int) or isinstance(other, int):
2971n/a return self.value <= other
2972n/a return NotImplemented
2973n/a def __gt__(self, other):
2974n/a if isinstance(other, C):
2975n/a return self.value > other.value
2976n/a if isinstance(other, int) or isinstance(other, int):
2977n/a return self.value > other
2978n/a return NotImplemented
2979n/a def __ge__(self, other):
2980n/a if isinstance(other, C):
2981n/a return self.value >= other.value
2982n/a if isinstance(other, int) or isinstance(other, int):
2983n/a return self.value >= other
2984n/a return NotImplemented
2985n/a
2986n/a c1 = C(1)
2987n/a c2 = C(2)
2988n/a c3 = C(3)
2989n/a self.assertEqual(c1, 1)
2990n/a c = {1: c1, 2: c2, 3: c3}
2991n/a for x in 1, 2, 3:
2992n/a for y in 1, 2, 3:
2993n/a for op in "<", "<=", "==", "!=", ">", ">=":
2994n/a self.assertEqual(eval("c[x] %s c[y]" % op),
2995n/a eval("x %s y" % op),
2996n/a "x=%d, y=%d" % (x, y))
2997n/a self.assertEqual(eval("c[x] %s y" % op),
2998n/a eval("x %s y" % op),
2999n/a "x=%d, y=%d" % (x, y))
3000n/a self.assertEqual(eval("x %s c[y]" % op),
3001n/a eval("x %s y" % op),
3002n/a "x=%d, y=%d" % (x, y))
3003n/a
3004n/a def test_rich_comparisons(self):
3005n/a # Testing rich comparisons...
3006n/a class Z(complex):
3007n/a pass
3008n/a z = Z(1)
3009n/a self.assertEqual(z, 1+0j)
3010n/a self.assertEqual(1+0j, z)
3011n/a class ZZ(complex):
3012n/a def __eq__(self, other):
3013n/a try:
3014n/a return abs(self - other) <= 1e-6
3015n/a except:
3016n/a return NotImplemented
3017n/a zz = ZZ(1.0000003)
3018n/a self.assertEqual(zz, 1+0j)
3019n/a self.assertEqual(1+0j, zz)
3020n/a
3021n/a class classic:
3022n/a pass
3023n/a for base in (classic, int, object, list):
3024n/a class C(base):
3025n/a def __init__(self, value):
3026n/a self.value = int(value)
3027n/a def __cmp__(self_, other):
3028n/a self.fail("shouldn't call __cmp__")
3029n/a def __eq__(self, other):
3030n/a if isinstance(other, C):
3031n/a return self.value == other.value
3032n/a if isinstance(other, int) or isinstance(other, int):
3033n/a return self.value == other
3034n/a return NotImplemented
3035n/a def __ne__(self, other):
3036n/a if isinstance(other, C):
3037n/a return self.value != other.value
3038n/a if isinstance(other, int) or isinstance(other, int):
3039n/a return self.value != other
3040n/a return NotImplemented
3041n/a def __lt__(self, other):
3042n/a if isinstance(other, C):
3043n/a return self.value < other.value
3044n/a if isinstance(other, int) or isinstance(other, int):
3045n/a return self.value < other
3046n/a return NotImplemented
3047n/a def __le__(self, other):
3048n/a if isinstance(other, C):
3049n/a return self.value <= other.value
3050n/a if isinstance(other, int) or isinstance(other, int):
3051n/a return self.value <= other
3052n/a return NotImplemented
3053n/a def __gt__(self, other):
3054n/a if isinstance(other, C):
3055n/a return self.value > other.value
3056n/a if isinstance(other, int) or isinstance(other, int):
3057n/a return self.value > other
3058n/a return NotImplemented
3059n/a def __ge__(self, other):
3060n/a if isinstance(other, C):
3061n/a return self.value >= other.value
3062n/a if isinstance(other, int) or isinstance(other, int):
3063n/a return self.value >= other
3064n/a return NotImplemented
3065n/a c1 = C(1)
3066n/a c2 = C(2)
3067n/a c3 = C(3)
3068n/a self.assertEqual(c1, 1)
3069n/a c = {1: c1, 2: c2, 3: c3}
3070n/a for x in 1, 2, 3:
3071n/a for y in 1, 2, 3:
3072n/a for op in "<", "<=", "==", "!=", ">", ">=":
3073n/a self.assertEqual(eval("c[x] %s c[y]" % op),
3074n/a eval("x %s y" % op),
3075n/a "x=%d, y=%d" % (x, y))
3076n/a self.assertEqual(eval("c[x] %s y" % op),
3077n/a eval("x %s y" % op),
3078n/a "x=%d, y=%d" % (x, y))
3079n/a self.assertEqual(eval("x %s c[y]" % op),
3080n/a eval("x %s y" % op),
3081n/a "x=%d, y=%d" % (x, y))
3082n/a
3083n/a def test_descrdoc(self):
3084n/a # Testing descriptor doc strings...
3085n/a from _io import FileIO
3086n/a def check(descr, what):
3087n/a self.assertEqual(descr.__doc__, what)
3088n/a check(FileIO.closed, "True if the file is closed") # getset descriptor
3089n/a check(complex.real, "the real part of a complex number") # member descriptor
3090n/a
3091n/a def test_doc_descriptor(self):
3092n/a # Testing __doc__ descriptor...
3093n/a # SF bug 542984
3094n/a class DocDescr(object):
3095n/a def __get__(self, object, otype):
3096n/a if object:
3097n/a object = object.__class__.__name__ + ' instance'
3098n/a if otype:
3099n/a otype = otype.__name__
3100n/a return 'object=%s; type=%s' % (object, otype)
3101n/a class OldClass:
3102n/a __doc__ = DocDescr()
3103n/a class NewClass(object):
3104n/a __doc__ = DocDescr()
3105n/a self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3106n/a self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3107n/a self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3108n/a self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3109n/a
3110n/a def test_set_class(self):
3111n/a # Testing __class__ assignment...
3112n/a class C(object): pass
3113n/a class D(object): pass
3114n/a class E(object): pass
3115n/a class F(D, E): pass
3116n/a for cls in C, D, E, F:
3117n/a for cls2 in C, D, E, F:
3118n/a x = cls()
3119n/a x.__class__ = cls2
3120n/a self.assertIs(x.__class__, cls2)
3121n/a x.__class__ = cls
3122n/a self.assertIs(x.__class__, cls)
3123n/a def cant(x, C):
3124n/a try:
3125n/a x.__class__ = C
3126n/a except TypeError:
3127n/a pass
3128n/a else:
3129n/a self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3130n/a try:
3131n/a delattr(x, "__class__")
3132n/a except (TypeError, AttributeError):
3133n/a pass
3134n/a else:
3135n/a self.fail("shouldn't allow del %r.__class__" % x)
3136n/a cant(C(), list)
3137n/a cant(list(), C)
3138n/a cant(C(), 1)
3139n/a cant(C(), object)
3140n/a cant(object(), list)
3141n/a cant(list(), object)
3142n/a class Int(int): __slots__ = []
3143n/a cant(True, int)
3144n/a cant(2, bool)
3145n/a o = object()
3146n/a cant(o, type(1))
3147n/a cant(o, type(None))
3148n/a del o
3149n/a class G(object):
3150n/a __slots__ = ["a", "b"]
3151n/a class H(object):
3152n/a __slots__ = ["b", "a"]
3153n/a class I(object):
3154n/a __slots__ = ["a", "b"]
3155n/a class J(object):
3156n/a __slots__ = ["c", "b"]
3157n/a class K(object):
3158n/a __slots__ = ["a", "b", "d"]
3159n/a class L(H):
3160n/a __slots__ = ["e"]
3161n/a class M(I):
3162n/a __slots__ = ["e"]
3163n/a class N(J):
3164n/a __slots__ = ["__weakref__"]
3165n/a class P(J):
3166n/a __slots__ = ["__dict__"]
3167n/a class Q(J):
3168n/a pass
3169n/a class R(J):
3170n/a __slots__ = ["__dict__", "__weakref__"]
3171n/a
3172n/a for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3173n/a x = cls()
3174n/a x.a = 1
3175n/a x.__class__ = cls2
3176n/a self.assertIs(x.__class__, cls2,
3177n/a "assigning %r as __class__ for %r silently failed" % (cls2, x))
3178n/a self.assertEqual(x.a, 1)
3179n/a x.__class__ = cls
3180n/a self.assertIs(x.__class__, cls,
3181n/a "assigning %r as __class__ for %r silently failed" % (cls, x))
3182n/a self.assertEqual(x.a, 1)
3183n/a for cls in G, J, K, L, M, N, P, R, list, Int:
3184n/a for cls2 in G, J, K, L, M, N, P, R, list, Int:
3185n/a if cls is cls2:
3186n/a continue
3187n/a cant(cls(), cls2)
3188n/a
3189n/a # Issue5283: when __class__ changes in __del__, the wrong
3190n/a # type gets DECREF'd.
3191n/a class O(object):
3192n/a pass
3193n/a class A(object):
3194n/a def __del__(self):
3195n/a self.__class__ = O
3196n/a l = [A() for x in range(100)]
3197n/a del l
3198n/a
3199n/a def test_set_dict(self):
3200n/a # Testing __dict__ assignment...
3201n/a class C(object): pass
3202n/a a = C()
3203n/a a.__dict__ = {'b': 1}
3204n/a self.assertEqual(a.b, 1)
3205n/a def cant(x, dict):
3206n/a try:
3207n/a x.__dict__ = dict
3208n/a except (AttributeError, TypeError):
3209n/a pass
3210n/a else:
3211n/a self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3212n/a cant(a, None)
3213n/a cant(a, [])
3214n/a cant(a, 1)
3215n/a del a.__dict__ # Deleting __dict__ is allowed
3216n/a
3217n/a class Base(object):
3218n/a pass
3219n/a def verify_dict_readonly(x):
3220n/a """
3221n/a x has to be an instance of a class inheriting from Base.
3222n/a """
3223n/a cant(x, {})
3224n/a try:
3225n/a del x.__dict__
3226n/a except (AttributeError, TypeError):
3227n/a pass
3228n/a else:
3229n/a self.fail("shouldn't allow del %r.__dict__" % x)
3230n/a dict_descr = Base.__dict__["__dict__"]
3231n/a try:
3232n/a dict_descr.__set__(x, {})
3233n/a except (AttributeError, TypeError):
3234n/a pass
3235n/a else:
3236n/a self.fail("dict_descr allowed access to %r's dict" % x)
3237n/a
3238n/a # Classes don't allow __dict__ assignment and have readonly dicts
3239n/a class Meta1(type, Base):
3240n/a pass
3241n/a class Meta2(Base, type):
3242n/a pass
3243n/a class D(object, metaclass=Meta1):
3244n/a pass
3245n/a class E(object, metaclass=Meta2):
3246n/a pass
3247n/a for cls in C, D, E:
3248n/a verify_dict_readonly(cls)
3249n/a class_dict = cls.__dict__
3250n/a try:
3251n/a class_dict["spam"] = "eggs"
3252n/a except TypeError:
3253n/a pass
3254n/a else:
3255n/a self.fail("%r's __dict__ can be modified" % cls)
3256n/a
3257n/a # Modules also disallow __dict__ assignment
3258n/a class Module1(types.ModuleType, Base):
3259n/a pass
3260n/a class Module2(Base, types.ModuleType):
3261n/a pass
3262n/a for ModuleType in Module1, Module2:
3263n/a mod = ModuleType("spam")
3264n/a verify_dict_readonly(mod)
3265n/a mod.__dict__["spam"] = "eggs"
3266n/a
3267n/a # Exception's __dict__ can be replaced, but not deleted
3268n/a # (at least not any more than regular exception's __dict__ can
3269n/a # be deleted; on CPython it is not the case, whereas on PyPy they
3270n/a # can, just like any other new-style instance's __dict__.)
3271n/a def can_delete_dict(e):
3272n/a try:
3273n/a del e.__dict__
3274n/a except (TypeError, AttributeError):
3275n/a return False
3276n/a else:
3277n/a return True
3278n/a class Exception1(Exception, Base):
3279n/a pass
3280n/a class Exception2(Base, Exception):
3281n/a pass
3282n/a for ExceptionType in Exception, Exception1, Exception2:
3283n/a e = ExceptionType()
3284n/a e.__dict__ = {"a": 1}
3285n/a self.assertEqual(e.a, 1)
3286n/a self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
3287n/a
3288n/a def test_binary_operator_override(self):
3289n/a # Testing overrides of binary operations...
3290n/a class I(int):
3291n/a def __repr__(self):
3292n/a return "I(%r)" % int(self)
3293n/a def __add__(self, other):
3294n/a return I(int(self) + int(other))
3295n/a __radd__ = __add__
3296n/a def __pow__(self, other, mod=None):
3297n/a if mod is None:
3298n/a return I(pow(int(self), int(other)))
3299n/a else:
3300n/a return I(pow(int(self), int(other), int(mod)))
3301n/a def __rpow__(self, other, mod=None):
3302n/a if mod is None:
3303n/a return I(pow(int(other), int(self), mod))
3304n/a else:
3305n/a return I(pow(int(other), int(self), int(mod)))
3306n/a
3307n/a self.assertEqual(repr(I(1) + I(2)), "I(3)")
3308n/a self.assertEqual(repr(I(1) + 2), "I(3)")
3309n/a self.assertEqual(repr(1 + I(2)), "I(3)")
3310n/a self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3311n/a self.assertEqual(repr(2 ** I(3)), "I(8)")
3312n/a self.assertEqual(repr(I(2) ** 3), "I(8)")
3313n/a self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3314n/a class S(str):
3315n/a def __eq__(self, other):
3316n/a return self.lower() == other.lower()
3317n/a
3318n/a def test_subclass_propagation(self):
3319n/a # Testing propagation of slot functions to subclasses...
3320n/a class A(object):
3321n/a pass
3322n/a class B(A):
3323n/a pass
3324n/a class C(A):
3325n/a pass
3326n/a class D(B, C):
3327n/a pass
3328n/a d = D()
3329n/a orig_hash = hash(d) # related to id(d) in platform-dependent ways
3330n/a A.__hash__ = lambda self: 42
3331n/a self.assertEqual(hash(d), 42)
3332n/a C.__hash__ = lambda self: 314
3333n/a self.assertEqual(hash(d), 314)
3334n/a B.__hash__ = lambda self: 144
3335n/a self.assertEqual(hash(d), 144)
3336n/a D.__hash__ = lambda self: 100
3337n/a self.assertEqual(hash(d), 100)
3338n/a D.__hash__ = None
3339n/a self.assertRaises(TypeError, hash, d)
3340n/a del D.__hash__
3341n/a self.assertEqual(hash(d), 144)
3342n/a B.__hash__ = None
3343n/a self.assertRaises(TypeError, hash, d)
3344n/a del B.__hash__
3345n/a self.assertEqual(hash(d), 314)
3346n/a C.__hash__ = None
3347n/a self.assertRaises(TypeError, hash, d)
3348n/a del C.__hash__
3349n/a self.assertEqual(hash(d), 42)
3350n/a A.__hash__ = None
3351n/a self.assertRaises(TypeError, hash, d)
3352n/a del A.__hash__
3353n/a self.assertEqual(hash(d), orig_hash)
3354n/a d.foo = 42
3355n/a d.bar = 42
3356n/a self.assertEqual(d.foo, 42)
3357n/a self.assertEqual(d.bar, 42)
3358n/a def __getattribute__(self, name):
3359n/a if name == "foo":
3360n/a return 24
3361n/a return object.__getattribute__(self, name)
3362n/a A.__getattribute__ = __getattribute__
3363n/a self.assertEqual(d.foo, 24)
3364n/a self.assertEqual(d.bar, 42)
3365n/a def __getattr__(self, name):
3366n/a if name in ("spam", "foo", "bar"):
3367n/a return "hello"
3368n/a raise AttributeError(name)
3369n/a B.__getattr__ = __getattr__
3370n/a self.assertEqual(d.spam, "hello")
3371n/a self.assertEqual(d.foo, 24)
3372n/a self.assertEqual(d.bar, 42)
3373n/a del A.__getattribute__
3374n/a self.assertEqual(d.foo, 42)
3375n/a del d.foo
3376n/a self.assertEqual(d.foo, "hello")
3377n/a self.assertEqual(d.bar, 42)
3378n/a del B.__getattr__
3379n/a try:
3380n/a d.foo
3381n/a except AttributeError:
3382n/a pass
3383n/a else:
3384n/a self.fail("d.foo should be undefined now")
3385n/a
3386n/a # Test a nasty bug in recurse_down_subclasses()
3387n/a class A(object):
3388n/a pass
3389n/a class B(A):
3390n/a pass
3391n/a del B
3392n/a support.gc_collect()
3393n/a A.__setitem__ = lambda *a: None # crash
3394n/a
3395n/a def test_buffer_inheritance(self):
3396n/a # Testing that buffer interface is inherited ...
3397n/a
3398n/a import binascii
3399n/a # SF bug [#470040] ParseTuple t# vs subclasses.
3400n/a
3401n/a class MyBytes(bytes):
3402n/a pass
3403n/a base = b'abc'
3404n/a m = MyBytes(base)
3405n/a # b2a_hex uses the buffer interface to get its argument's value, via
3406n/a # PyArg_ParseTuple 't#' code.
3407n/a self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3408n/a
3409n/a class MyInt(int):
3410n/a pass
3411n/a m = MyInt(42)
3412n/a try:
3413n/a binascii.b2a_hex(m)
3414n/a self.fail('subclass of int should not have a buffer interface')
3415n/a except TypeError:
3416n/a pass
3417n/a
3418n/a def test_str_of_str_subclass(self):
3419n/a # Testing __str__ defined in subclass of str ...
3420n/a import binascii
3421n/a import io
3422n/a
3423n/a class octetstring(str):
3424n/a def __str__(self):
3425n/a return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
3426n/a def __repr__(self):
3427n/a return self + " repr"
3428n/a
3429n/a o = octetstring('A')
3430n/a self.assertEqual(type(o), octetstring)
3431n/a self.assertEqual(type(str(o)), str)
3432n/a self.assertEqual(type(repr(o)), str)
3433n/a self.assertEqual(ord(o), 0x41)
3434n/a self.assertEqual(str(o), '41')
3435n/a self.assertEqual(repr(o), 'A repr')
3436n/a self.assertEqual(o.__str__(), '41')
3437n/a self.assertEqual(o.__repr__(), 'A repr')
3438n/a
3439n/a capture = io.StringIO()
3440n/a # Calling str() or not exercises different internal paths.
3441n/a print(o, file=capture)
3442n/a print(str(o), file=capture)
3443n/a self.assertEqual(capture.getvalue(), '41\n41\n')
3444n/a capture.close()
3445n/a
3446n/a def test_keyword_arguments(self):
3447n/a # Testing keyword arguments to __init__, __call__...
3448n/a def f(a): return a
3449n/a self.assertEqual(f.__call__(a=42), 42)
3450n/a a = []
3451n/a list.__init__(a, sequence=[0, 1, 2])
3452n/a self.assertEqual(a, [0, 1, 2])
3453n/a
3454n/a def test_recursive_call(self):
3455n/a # Testing recursive __call__() by setting to instance of class...
3456n/a class A(object):
3457n/a pass
3458n/a
3459n/a A.__call__ = A()
3460n/a try:
3461n/a A()()
3462n/a except RecursionError:
3463n/a pass
3464n/a else:
3465n/a self.fail("Recursion limit should have been reached for __call__()")
3466n/a
3467n/a def test_delete_hook(self):
3468n/a # Testing __del__ hook...
3469n/a log = []
3470n/a class C(object):
3471n/a def __del__(self):
3472n/a log.append(1)
3473n/a c = C()
3474n/a self.assertEqual(log, [])
3475n/a del c
3476n/a support.gc_collect()
3477n/a self.assertEqual(log, [1])
3478n/a
3479n/a class D(object): pass
3480n/a d = D()
3481n/a try: del d[0]
3482n/a except TypeError: pass
3483n/a else: self.fail("invalid del() didn't raise TypeError")
3484n/a
3485n/a def test_hash_inheritance(self):
3486n/a # Testing hash of mutable subclasses...
3487n/a
3488n/a class mydict(dict):
3489n/a pass
3490n/a d = mydict()
3491n/a try:
3492n/a hash(d)
3493n/a except TypeError:
3494n/a pass
3495n/a else:
3496n/a self.fail("hash() of dict subclass should fail")
3497n/a
3498n/a class mylist(list):
3499n/a pass
3500n/a d = mylist()
3501n/a try:
3502n/a hash(d)
3503n/a except TypeError:
3504n/a pass
3505n/a else:
3506n/a self.fail("hash() of list subclass should fail")
3507n/a
3508n/a def test_str_operations(self):
3509n/a try: 'a' + 5
3510n/a except TypeError: pass
3511n/a else: self.fail("'' + 5 doesn't raise TypeError")
3512n/a
3513n/a try: ''.split('')
3514n/a except ValueError: pass
3515n/a else: self.fail("''.split('') doesn't raise ValueError")
3516n/a
3517n/a try: ''.join([0])
3518n/a except TypeError: pass
3519n/a else: self.fail("''.join([0]) doesn't raise TypeError")
3520n/a
3521n/a try: ''.rindex('5')
3522n/a except ValueError: pass
3523n/a else: self.fail("''.rindex('5') doesn't raise ValueError")
3524n/a
3525n/a try: '%(n)s' % None
3526n/a except TypeError: pass
3527n/a else: self.fail("'%(n)s' % None doesn't raise TypeError")
3528n/a
3529n/a try: '%(n' % {}
3530n/a except ValueError: pass
3531n/a else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3532n/a
3533n/a try: '%*s' % ('abc')
3534n/a except TypeError: pass
3535n/a else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3536n/a
3537n/a try: '%*.*s' % ('abc', 5)
3538n/a except TypeError: pass
3539n/a else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3540n/a
3541n/a try: '%s' % (1, 2)
3542n/a except TypeError: pass
3543n/a else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3544n/a
3545n/a try: '%' % None
3546n/a except ValueError: pass
3547n/a else: self.fail("'%' % None doesn't raise ValueError")
3548n/a
3549n/a self.assertEqual('534253'.isdigit(), 1)
3550n/a self.assertEqual('534253x'.isdigit(), 0)
3551n/a self.assertEqual('%c' % 5, '\x05')
3552n/a self.assertEqual('%c' % '5', '5')
3553n/a
3554n/a def test_deepcopy_recursive(self):
3555n/a # Testing deepcopy of recursive objects...
3556n/a class Node:
3557n/a pass
3558n/a a = Node()
3559n/a b = Node()
3560n/a a.b = b
3561n/a b.a = a
3562n/a z = deepcopy(a) # This blew up before
3563n/a
3564n/a def test_uninitialized_modules(self):
3565n/a # Testing uninitialized module objects...
3566n/a from types import ModuleType as M
3567n/a m = M.__new__(M)
3568n/a str(m)
3569n/a self.assertNotHasAttr(m, "__name__")
3570n/a self.assertNotHasAttr(m, "__file__")
3571n/a self.assertNotHasAttr(m, "foo")
3572n/a self.assertFalse(m.__dict__) # None or {} are both reasonable answers
3573n/a m.foo = 1
3574n/a self.assertEqual(m.__dict__, {"foo": 1})
3575n/a
3576n/a def test_funny_new(self):
3577n/a # Testing __new__ returning something unexpected...
3578n/a class C(object):
3579n/a def __new__(cls, arg):
3580n/a if isinstance(arg, str): return [1, 2, 3]
3581n/a elif isinstance(arg, int): return object.__new__(D)
3582n/a else: return object.__new__(cls)
3583n/a class D(C):
3584n/a def __init__(self, arg):
3585n/a self.foo = arg
3586n/a self.assertEqual(C("1"), [1, 2, 3])
3587n/a self.assertEqual(D("1"), [1, 2, 3])
3588n/a d = D(None)
3589n/a self.assertEqual(d.foo, None)
3590n/a d = C(1)
3591n/a self.assertIsInstance(d, D)
3592n/a self.assertEqual(d.foo, 1)
3593n/a d = D(1)
3594n/a self.assertIsInstance(d, D)
3595n/a self.assertEqual(d.foo, 1)
3596n/a
3597n/a class C(object):
3598n/a @staticmethod
3599n/a def __new__(*args):
3600n/a return args
3601n/a self.assertEqual(C(1, 2), (C, 1, 2))
3602n/a class D(C):
3603n/a pass
3604n/a self.assertEqual(D(1, 2), (D, 1, 2))
3605n/a
3606n/a class C(object):
3607n/a @classmethod
3608n/a def __new__(*args):
3609n/a return args
3610n/a self.assertEqual(C(1, 2), (C, C, 1, 2))
3611n/a class D(C):
3612n/a pass
3613n/a self.assertEqual(D(1, 2), (D, D, 1, 2))
3614n/a
3615n/a def test_imul_bug(self):
3616n/a # Testing for __imul__ problems...
3617n/a # SF bug 544647
3618n/a class C(object):
3619n/a def __imul__(self, other):
3620n/a return (self, other)
3621n/a x = C()
3622n/a y = x
3623n/a y *= 1.0
3624n/a self.assertEqual(y, (x, 1.0))
3625n/a y = x
3626n/a y *= 2
3627n/a self.assertEqual(y, (x, 2))
3628n/a y = x
3629n/a y *= 3
3630n/a self.assertEqual(y, (x, 3))
3631n/a y = x
3632n/a y *= 1<<100
3633n/a self.assertEqual(y, (x, 1<<100))
3634n/a y = x
3635n/a y *= None
3636n/a self.assertEqual(y, (x, None))
3637n/a y = x
3638n/a y *= "foo"
3639n/a self.assertEqual(y, (x, "foo"))
3640n/a
3641n/a def test_copy_setstate(self):
3642n/a # Testing that copy.*copy() correctly uses __setstate__...
3643n/a import copy
3644n/a class C(object):
3645n/a def __init__(self, foo=None):
3646n/a self.foo = foo
3647n/a self.__foo = foo
3648n/a def setfoo(self, foo=None):
3649n/a self.foo = foo
3650n/a def getfoo(self):
3651n/a return self.__foo
3652n/a def __getstate__(self):
3653n/a return [self.foo]
3654n/a def __setstate__(self_, lst):
3655n/a self.assertEqual(len(lst), 1)
3656n/a self_.__foo = self_.foo = lst[0]
3657n/a a = C(42)
3658n/a a.setfoo(24)
3659n/a self.assertEqual(a.foo, 24)
3660n/a self.assertEqual(a.getfoo(), 42)
3661n/a b = copy.copy(a)
3662n/a self.assertEqual(b.foo, 24)
3663n/a self.assertEqual(b.getfoo(), 24)
3664n/a b = copy.deepcopy(a)
3665n/a self.assertEqual(b.foo, 24)
3666n/a self.assertEqual(b.getfoo(), 24)
3667n/a
3668n/a def test_slices(self):
3669n/a # Testing cases with slices and overridden __getitem__ ...
3670n/a
3671n/a # Strings
3672n/a self.assertEqual("hello"[:4], "hell")
3673n/a self.assertEqual("hello"[slice(4)], "hell")
3674n/a self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3675n/a class S(str):
3676n/a def __getitem__(self, x):
3677n/a return str.__getitem__(self, x)
3678n/a self.assertEqual(S("hello")[:4], "hell")
3679n/a self.assertEqual(S("hello")[slice(4)], "hell")
3680n/a self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3681n/a # Tuples
3682n/a self.assertEqual((1,2,3)[:2], (1,2))
3683n/a self.assertEqual((1,2,3)[slice(2)], (1,2))
3684n/a self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3685n/a class T(tuple):
3686n/a def __getitem__(self, x):
3687n/a return tuple.__getitem__(self, x)
3688n/a self.assertEqual(T((1,2,3))[:2], (1,2))
3689n/a self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3690n/a self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3691n/a # Lists
3692n/a self.assertEqual([1,2,3][:2], [1,2])
3693n/a self.assertEqual([1,2,3][slice(2)], [1,2])
3694n/a self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3695n/a class L(list):
3696n/a def __getitem__(self, x):
3697n/a return list.__getitem__(self, x)
3698n/a self.assertEqual(L([1,2,3])[:2], [1,2])
3699n/a self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3700n/a self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3701n/a # Now do lists and __setitem__
3702n/a a = L([1,2,3])
3703n/a a[slice(1, 3)] = [3,2]
3704n/a self.assertEqual(a, [1,3,2])
3705n/a a[slice(0, 2, 1)] = [3,1]
3706n/a self.assertEqual(a, [3,1,2])
3707n/a a.__setitem__(slice(1, 3), [2,1])
3708n/a self.assertEqual(a, [3,2,1])
3709n/a a.__setitem__(slice(0, 2, 1), [2,3])
3710n/a self.assertEqual(a, [2,3,1])
3711n/a
3712n/a def test_subtype_resurrection(self):
3713n/a # Testing resurrection of new-style instance...
3714n/a
3715n/a class C(object):
3716n/a container = []
3717n/a
3718n/a def __del__(self):
3719n/a # resurrect the instance
3720n/a C.container.append(self)
3721n/a
3722n/a c = C()
3723n/a c.attr = 42
3724n/a
3725n/a # The most interesting thing here is whether this blows up, due to
3726n/a # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3727n/a # bug).
3728n/a del c
3729n/a
3730n/a support.gc_collect()
3731n/a self.assertEqual(len(C.container), 1)
3732n/a
3733n/a # Make c mortal again, so that the test framework with -l doesn't report
3734n/a # it as a leak.
3735n/a del C.__del__
3736n/a
3737n/a def test_slots_trash(self):
3738n/a # Testing slot trash...
3739n/a # Deallocating deeply nested slotted trash caused stack overflows
3740n/a class trash(object):
3741n/a __slots__ = ['x']
3742n/a def __init__(self, x):
3743n/a self.x = x
3744n/a o = None
3745n/a for i in range(50000):
3746n/a o = trash(o)
3747n/a del o
3748n/a
3749n/a def test_slots_multiple_inheritance(self):
3750n/a # SF bug 575229, multiple inheritance w/ slots dumps core
3751n/a class A(object):
3752n/a __slots__=()
3753n/a class B(object):
3754n/a pass
3755n/a class C(A,B) :
3756n/a __slots__=()
3757n/a if support.check_impl_detail():
3758n/a self.assertEqual(C.__basicsize__, B.__basicsize__)
3759n/a self.assertHasAttr(C, '__dict__')
3760n/a self.assertHasAttr(C, '__weakref__')
3761n/a C().x = 2
3762n/a
3763n/a def test_rmul(self):
3764n/a # Testing correct invocation of __rmul__...
3765n/a # SF patch 592646
3766n/a class C(object):
3767n/a def __mul__(self, other):
3768n/a return "mul"
3769n/a def __rmul__(self, other):
3770n/a return "rmul"
3771n/a a = C()
3772n/a self.assertEqual(a*2, "mul")
3773n/a self.assertEqual(a*2.2, "mul")
3774n/a self.assertEqual(2*a, "rmul")
3775n/a self.assertEqual(2.2*a, "rmul")
3776n/a
3777n/a def test_ipow(self):
3778n/a # Testing correct invocation of __ipow__...
3779n/a # [SF bug 620179]
3780n/a class C(object):
3781n/a def __ipow__(self, other):
3782n/a pass
3783n/a a = C()
3784n/a a **= 2
3785n/a
3786n/a def test_mutable_bases(self):
3787n/a # Testing mutable bases...
3788n/a
3789n/a # stuff that should work:
3790n/a class C(object):
3791n/a pass
3792n/a class C2(object):
3793n/a def __getattribute__(self, attr):
3794n/a if attr == 'a':
3795n/a return 2
3796n/a else:
3797n/a return super(C2, self).__getattribute__(attr)
3798n/a def meth(self):
3799n/a return 1
3800n/a class D(C):
3801n/a pass
3802n/a class E(D):
3803n/a pass
3804n/a d = D()
3805n/a e = E()
3806n/a D.__bases__ = (C,)
3807n/a D.__bases__ = (C2,)
3808n/a self.assertEqual(d.meth(), 1)
3809n/a self.assertEqual(e.meth(), 1)
3810n/a self.assertEqual(d.a, 2)
3811n/a self.assertEqual(e.a, 2)
3812n/a self.assertEqual(C2.__subclasses__(), [D])
3813n/a
3814n/a try:
3815n/a del D.__bases__
3816n/a except (TypeError, AttributeError):
3817n/a pass
3818n/a else:
3819n/a self.fail("shouldn't be able to delete .__bases__")
3820n/a
3821n/a try:
3822n/a D.__bases__ = ()
3823n/a except TypeError as msg:
3824n/a if str(msg) == "a new-style class can't have only classic bases":
3825n/a self.fail("wrong error message for .__bases__ = ()")
3826n/a else:
3827n/a self.fail("shouldn't be able to set .__bases__ to ()")
3828n/a
3829n/a try:
3830n/a D.__bases__ = (D,)
3831n/a except TypeError:
3832n/a pass
3833n/a else:
3834n/a # actually, we'll have crashed by here...
3835n/a self.fail("shouldn't be able to create inheritance cycles")
3836n/a
3837n/a try:
3838n/a D.__bases__ = (C, C)
3839n/a except TypeError:
3840n/a pass
3841n/a else:
3842n/a self.fail("didn't detect repeated base classes")
3843n/a
3844n/a try:
3845n/a D.__bases__ = (E,)
3846n/a except TypeError:
3847n/a pass
3848n/a else:
3849n/a self.fail("shouldn't be able to create inheritance cycles")
3850n/a
3851n/a def test_builtin_bases(self):
3852n/a # Make sure all the builtin types can have their base queried without
3853n/a # segfaulting. See issue #5787.
3854n/a builtin_types = [tp for tp in builtins.__dict__.values()
3855n/a if isinstance(tp, type)]
3856n/a for tp in builtin_types:
3857n/a object.__getattribute__(tp, "__bases__")
3858n/a if tp is not object:
3859n/a self.assertEqual(len(tp.__bases__), 1, tp)
3860n/a
3861n/a class L(list):
3862n/a pass
3863n/a
3864n/a class C(object):
3865n/a pass
3866n/a
3867n/a class D(C):
3868n/a pass
3869n/a
3870n/a try:
3871n/a L.__bases__ = (dict,)
3872n/a except TypeError:
3873n/a pass
3874n/a else:
3875n/a self.fail("shouldn't turn list subclass into dict subclass")
3876n/a
3877n/a try:
3878n/a list.__bases__ = (dict,)
3879n/a except TypeError:
3880n/a pass
3881n/a else:
3882n/a self.fail("shouldn't be able to assign to list.__bases__")
3883n/a
3884n/a try:
3885n/a D.__bases__ = (C, list)
3886n/a except TypeError:
3887n/a pass
3888n/a else:
3889n/a assert 0, "best_base calculation found wanting"
3890n/a
3891n/a def test_unsubclassable_types(self):
3892n/a with self.assertRaises(TypeError):
3893n/a class X(type(None)):
3894n/a pass
3895n/a with self.assertRaises(TypeError):
3896n/a class X(object, type(None)):
3897n/a pass
3898n/a with self.assertRaises(TypeError):
3899n/a class X(type(None), object):
3900n/a pass
3901n/a class O(object):
3902n/a pass
3903n/a with self.assertRaises(TypeError):
3904n/a class X(O, type(None)):
3905n/a pass
3906n/a with self.assertRaises(TypeError):
3907n/a class X(type(None), O):
3908n/a pass
3909n/a
3910n/a class X(object):
3911n/a pass
3912n/a with self.assertRaises(TypeError):
3913n/a X.__bases__ = type(None),
3914n/a with self.assertRaises(TypeError):
3915n/a X.__bases__ = object, type(None)
3916n/a with self.assertRaises(TypeError):
3917n/a X.__bases__ = type(None), object
3918n/a with self.assertRaises(TypeError):
3919n/a X.__bases__ = O, type(None)
3920n/a with self.assertRaises(TypeError):
3921n/a X.__bases__ = type(None), O
3922n/a
3923n/a def test_mutable_bases_with_failing_mro(self):
3924n/a # Testing mutable bases with failing mro...
3925n/a class WorkOnce(type):
3926n/a def __new__(self, name, bases, ns):
3927n/a self.flag = 0
3928n/a return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3929n/a def mro(self):
3930n/a if self.flag > 0:
3931n/a raise RuntimeError("bozo")
3932n/a else:
3933n/a self.flag += 1
3934n/a return type.mro(self)
3935n/a
3936n/a class WorkAlways(type):
3937n/a def mro(self):
3938n/a # this is here to make sure that .mro()s aren't called
3939n/a # with an exception set (which was possible at one point).
3940n/a # An error message will be printed in a debug build.
3941n/a # What's a good way to test for this?
3942n/a return type.mro(self)
3943n/a
3944n/a class C(object):
3945n/a pass
3946n/a
3947n/a class C2(object):
3948n/a pass
3949n/a
3950n/a class D(C):
3951n/a pass
3952n/a
3953n/a class E(D):
3954n/a pass
3955n/a
3956n/a class F(D, metaclass=WorkOnce):
3957n/a pass
3958n/a
3959n/a class G(D, metaclass=WorkAlways):
3960n/a pass
3961n/a
3962n/a # Immediate subclasses have their mro's adjusted in alphabetical
3963n/a # order, so E's will get adjusted before adjusting F's fails. We
3964n/a # check here that E's gets restored.
3965n/a
3966n/a E_mro_before = E.__mro__
3967n/a D_mro_before = D.__mro__
3968n/a
3969n/a try:
3970n/a D.__bases__ = (C2,)
3971n/a except RuntimeError:
3972n/a self.assertEqual(E.__mro__, E_mro_before)
3973n/a self.assertEqual(D.__mro__, D_mro_before)
3974n/a else:
3975n/a self.fail("exception not propagated")
3976n/a
3977n/a def test_mutable_bases_catch_mro_conflict(self):
3978n/a # Testing mutable bases catch mro conflict...
3979n/a class A(object):
3980n/a pass
3981n/a
3982n/a class B(object):
3983n/a pass
3984n/a
3985n/a class C(A, B):
3986n/a pass
3987n/a
3988n/a class D(A, B):
3989n/a pass
3990n/a
3991n/a class E(C, D):
3992n/a pass
3993n/a
3994n/a try:
3995n/a C.__bases__ = (B, A)
3996n/a except TypeError:
3997n/a pass
3998n/a else:
3999n/a self.fail("didn't catch MRO conflict")
4000n/a
4001n/a def test_mutable_names(self):
4002n/a # Testing mutable names...
4003n/a class C(object):
4004n/a pass
4005n/a
4006n/a # C.__module__ could be 'test_descr' or '__main__'
4007n/a mod = C.__module__
4008n/a
4009n/a C.__name__ = 'D'
4010n/a self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4011n/a
4012n/a C.__name__ = 'D.E'
4013n/a self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4014n/a
4015n/a def test_evil_type_name(self):
4016n/a # A badly placed Py_DECREF in type_set_name led to arbitrary code
4017n/a # execution while the type structure was not in a sane state, and a
4018n/a # possible segmentation fault as a result. See bug #16447.
4019n/a class Nasty(str):
4020n/a def __del__(self):
4021n/a C.__name__ = "other"
4022n/a
4023n/a class C:
4024n/a pass
4025n/a
4026n/a C.__name__ = Nasty("abc")
4027n/a C.__name__ = "normal"
4028n/a
4029n/a def test_subclass_right_op(self):
4030n/a # Testing correct dispatch of subclass overloading __r<op>__...
4031n/a
4032n/a # This code tests various cases where right-dispatch of a subclass
4033n/a # should be preferred over left-dispatch of a base class.
4034n/a
4035n/a # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4036n/a
4037n/a class B(int):
4038n/a def __floordiv__(self, other):
4039n/a return "B.__floordiv__"
4040n/a def __rfloordiv__(self, other):
4041n/a return "B.__rfloordiv__"
4042n/a
4043n/a self.assertEqual(B(1) // 1, "B.__floordiv__")
4044n/a self.assertEqual(1 // B(1), "B.__rfloordiv__")
4045n/a
4046n/a # Case 2: subclass of object; this is just the baseline for case 3
4047n/a
4048n/a class C(object):
4049n/a def __floordiv__(self, other):
4050n/a return "C.__floordiv__"
4051n/a def __rfloordiv__(self, other):
4052n/a return "C.__rfloordiv__"
4053n/a
4054n/a self.assertEqual(C() // 1, "C.__floordiv__")
4055n/a self.assertEqual(1 // C(), "C.__rfloordiv__")
4056n/a
4057n/a # Case 3: subclass of new-style class; here it gets interesting
4058n/a
4059n/a class D(C):
4060n/a def __floordiv__(self, other):
4061n/a return "D.__floordiv__"
4062n/a def __rfloordiv__(self, other):
4063n/a return "D.__rfloordiv__"
4064n/a
4065n/a self.assertEqual(D() // C(), "D.__floordiv__")
4066n/a self.assertEqual(C() // D(), "D.__rfloordiv__")
4067n/a
4068n/a # Case 4: this didn't work right in 2.2.2 and 2.3a1
4069n/a
4070n/a class E(C):
4071n/a pass
4072n/a
4073n/a self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4074n/a
4075n/a self.assertEqual(E() // 1, "C.__floordiv__")
4076n/a self.assertEqual(1 // E(), "C.__rfloordiv__")
4077n/a self.assertEqual(E() // C(), "C.__floordiv__")
4078n/a self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4079n/a
4080n/a @support.impl_detail("testing an internal kind of method object")
4081n/a def test_meth_class_get(self):
4082n/a # Testing __get__ method of METH_CLASS C methods...
4083n/a # Full coverage of descrobject.c::classmethod_get()
4084n/a
4085n/a # Baseline
4086n/a arg = [1, 2, 3]
4087n/a res = {1: None, 2: None, 3: None}
4088n/a self.assertEqual(dict.fromkeys(arg), res)
4089n/a self.assertEqual({}.fromkeys(arg), res)
4090n/a
4091n/a # Now get the descriptor
4092n/a descr = dict.__dict__["fromkeys"]
4093n/a
4094n/a # More baseline using the descriptor directly
4095n/a self.assertEqual(descr.__get__(None, dict)(arg), res)
4096n/a self.assertEqual(descr.__get__({})(arg), res)
4097n/a
4098n/a # Now check various error cases
4099n/a try:
4100n/a descr.__get__(None, None)
4101n/a except TypeError:
4102n/a pass
4103n/a else:
4104n/a self.fail("shouldn't have allowed descr.__get__(None, None)")
4105n/a try:
4106n/a descr.__get__(42)
4107n/a except TypeError:
4108n/a pass
4109n/a else:
4110n/a self.fail("shouldn't have allowed descr.__get__(42)")
4111n/a try:
4112n/a descr.__get__(None, 42)
4113n/a except TypeError:
4114n/a pass
4115n/a else:
4116n/a self.fail("shouldn't have allowed descr.__get__(None, 42)")
4117n/a try:
4118n/a descr.__get__(None, int)
4119n/a except TypeError:
4120n/a pass
4121n/a else:
4122n/a self.fail("shouldn't have allowed descr.__get__(None, int)")
4123n/a
4124n/a def test_isinst_isclass(self):
4125n/a # Testing proxy isinstance() and isclass()...
4126n/a class Proxy(object):
4127n/a def __init__(self, obj):
4128n/a self.__obj = obj
4129n/a def __getattribute__(self, name):
4130n/a if name.startswith("_Proxy__"):
4131n/a return object.__getattribute__(self, name)
4132n/a else:
4133n/a return getattr(self.__obj, name)
4134n/a # Test with a classic class
4135n/a class C:
4136n/a pass
4137n/a a = C()
4138n/a pa = Proxy(a)
4139n/a self.assertIsInstance(a, C) # Baseline
4140n/a self.assertIsInstance(pa, C) # Test
4141n/a # Test with a classic subclass
4142n/a class D(C):
4143n/a pass
4144n/a a = D()
4145n/a pa = Proxy(a)
4146n/a self.assertIsInstance(a, C) # Baseline
4147n/a self.assertIsInstance(pa, C) # Test
4148n/a # Test with a new-style class
4149n/a class C(object):
4150n/a pass
4151n/a a = C()
4152n/a pa = Proxy(a)
4153n/a self.assertIsInstance(a, C) # Baseline
4154n/a self.assertIsInstance(pa, C) # Test
4155n/a # Test with a new-style subclass
4156n/a class D(C):
4157n/a pass
4158n/a a = D()
4159n/a pa = Proxy(a)
4160n/a self.assertIsInstance(a, C) # Baseline
4161n/a self.assertIsInstance(pa, C) # Test
4162n/a
4163n/a def test_proxy_super(self):
4164n/a # Testing super() for a proxy object...
4165n/a class Proxy(object):
4166n/a def __init__(self, obj):
4167n/a self.__obj = obj
4168n/a def __getattribute__(self, name):
4169n/a if name.startswith("_Proxy__"):
4170n/a return object.__getattribute__(self, name)
4171n/a else:
4172n/a return getattr(self.__obj, name)
4173n/a
4174n/a class B(object):
4175n/a def f(self):
4176n/a return "B.f"
4177n/a
4178n/a class C(B):
4179n/a def f(self):
4180n/a return super(C, self).f() + "->C.f"
4181n/a
4182n/a obj = C()
4183n/a p = Proxy(obj)
4184n/a self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4185n/a
4186n/a def test_carloverre(self):
4187n/a # Testing prohibition of Carlo Verre's hack...
4188n/a try:
4189n/a object.__setattr__(str, "foo", 42)
4190n/a except TypeError:
4191n/a pass
4192n/a else:
4193n/a self.fail("Carlo Verre __setattr__ succeeded!")
4194n/a try:
4195n/a object.__delattr__(str, "lower")
4196n/a except TypeError:
4197n/a pass
4198n/a else:
4199n/a self.fail("Carlo Verre __delattr__ succeeded!")
4200n/a
4201n/a def test_weakref_segfault(self):
4202n/a # Testing weakref segfault...
4203n/a # SF 742911
4204n/a import weakref
4205n/a
4206n/a class Provoker:
4207n/a def __init__(self, referrent):
4208n/a self.ref = weakref.ref(referrent)
4209n/a
4210n/a def __del__(self):
4211n/a x = self.ref()
4212n/a
4213n/a class Oops(object):
4214n/a pass
4215n/a
4216n/a o = Oops()
4217n/a o.whatever = Provoker(o)
4218n/a del o
4219n/a
4220n/a def test_wrapper_segfault(self):
4221n/a # SF 927248: deeply nested wrappers could cause stack overflow
4222n/a f = lambda:None
4223n/a for i in range(1000000):
4224n/a f = f.__call__
4225n/a f = None
4226n/a
4227n/a def test_file_fault(self):
4228n/a # Testing sys.stdout is changed in getattr...
4229n/a test_stdout = sys.stdout
4230n/a class StdoutGuard:
4231n/a def __getattr__(self, attr):
4232n/a sys.stdout = sys.__stdout__
4233n/a raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4234n/a sys.stdout = StdoutGuard()
4235n/a try:
4236n/a print("Oops!")
4237n/a except RuntimeError:
4238n/a pass
4239n/a finally:
4240n/a sys.stdout = test_stdout
4241n/a
4242n/a def test_vicious_descriptor_nonsense(self):
4243n/a # Testing vicious_descriptor_nonsense...
4244n/a
4245n/a # A potential segfault spotted by Thomas Wouters in mail to
4246n/a # python-dev 2003-04-17, turned into an example & fixed by Michael
4247n/a # Hudson just less than four months later...
4248n/a
4249n/a class Evil(object):
4250n/a def __hash__(self):
4251n/a return hash('attr')
4252n/a def __eq__(self, other):
4253n/a del C.attr
4254n/a return 0
4255n/a
4256n/a class Descr(object):
4257n/a def __get__(self, ob, type=None):
4258n/a return 1
4259n/a
4260n/a class C(object):
4261n/a attr = Descr()
4262n/a
4263n/a c = C()
4264n/a c.__dict__[Evil()] = 0
4265n/a
4266n/a self.assertEqual(c.attr, 1)
4267n/a # this makes a crash more likely:
4268n/a support.gc_collect()
4269n/a self.assertNotHasAttr(c, 'attr')
4270n/a
4271n/a def test_init(self):
4272n/a # SF 1155938
4273n/a class Foo(object):
4274n/a def __init__(self):
4275n/a return 10
4276n/a try:
4277n/a Foo()
4278n/a except TypeError:
4279n/a pass
4280n/a else:
4281n/a self.fail("did not test __init__() for None return")
4282n/a
4283n/a def test_method_wrapper(self):
4284n/a # Testing method-wrapper objects...
4285n/a # <type 'method-wrapper'> did not support any reflection before 2.5
4286n/a
4287n/a # XXX should methods really support __eq__?
4288n/a
4289n/a l = []
4290n/a self.assertEqual(l.__add__, l.__add__)
4291n/a self.assertEqual(l.__add__, [].__add__)
4292n/a self.assertNotEqual(l.__add__, [5].__add__)
4293n/a self.assertNotEqual(l.__add__, l.__mul__)
4294n/a self.assertEqual(l.__add__.__name__, '__add__')
4295n/a if hasattr(l.__add__, '__self__'):
4296n/a # CPython
4297n/a self.assertIs(l.__add__.__self__, l)
4298n/a self.assertIs(l.__add__.__objclass__, list)
4299n/a else:
4300n/a # Python implementations where [].__add__ is a normal bound method
4301n/a self.assertIs(l.__add__.im_self, l)
4302n/a self.assertIs(l.__add__.im_class, list)
4303n/a self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4304n/a try:
4305n/a hash(l.__add__)
4306n/a except TypeError:
4307n/a pass
4308n/a else:
4309n/a self.fail("no TypeError from hash([].__add__)")
4310n/a
4311n/a t = ()
4312n/a t += (7,)
4313n/a self.assertEqual(t.__add__, (7,).__add__)
4314n/a self.assertEqual(hash(t.__add__), hash((7,).__add__))
4315n/a
4316n/a def test_not_implemented(self):
4317n/a # Testing NotImplemented...
4318n/a # all binary methods should be able to return a NotImplemented
4319n/a import operator
4320n/a
4321n/a def specialmethod(self, other):
4322n/a return NotImplemented
4323n/a
4324n/a def check(expr, x, y):
4325n/a try:
4326n/a exec(expr, {'x': x, 'y': y, 'operator': operator})
4327n/a except TypeError:
4328n/a pass
4329n/a else:
4330n/a self.fail("no TypeError from %r" % (expr,))
4331n/a
4332n/a N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4333n/a # TypeErrors
4334n/a N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4335n/a # ValueErrors instead of TypeErrors
4336n/a for name, expr, iexpr in [
4337n/a ('__add__', 'x + y', 'x += y'),
4338n/a ('__sub__', 'x - y', 'x -= y'),
4339n/a ('__mul__', 'x * y', 'x *= y'),
4340n/a ('__matmul__', 'x @ y', 'x @= y'),
4341n/a ('__truediv__', 'x / y', 'x /= y'),
4342n/a ('__floordiv__', 'x // y', 'x //= y'),
4343n/a ('__mod__', 'x % y', 'x %= y'),
4344n/a ('__divmod__', 'divmod(x, y)', None),
4345n/a ('__pow__', 'x ** y', 'x **= y'),
4346n/a ('__lshift__', 'x << y', 'x <<= y'),
4347n/a ('__rshift__', 'x >> y', 'x >>= y'),
4348n/a ('__and__', 'x & y', 'x &= y'),
4349n/a ('__or__', 'x | y', 'x |= y'),
4350n/a ('__xor__', 'x ^ y', 'x ^= y')]:
4351n/a rname = '__r' + name[2:]
4352n/a A = type('A', (), {name: specialmethod})
4353n/a a = A()
4354n/a check(expr, a, a)
4355n/a check(expr, a, N1)
4356n/a check(expr, a, N2)
4357n/a if iexpr:
4358n/a check(iexpr, a, a)
4359n/a check(iexpr, a, N1)
4360n/a check(iexpr, a, N2)
4361n/a iname = '__i' + name[2:]
4362n/a C = type('C', (), {iname: specialmethod})
4363n/a c = C()
4364n/a check(iexpr, c, a)
4365n/a check(iexpr, c, N1)
4366n/a check(iexpr, c, N2)
4367n/a
4368n/a def test_assign_slice(self):
4369n/a # ceval.c's assign_slice used to check for
4370n/a # tp->tp_as_sequence->sq_slice instead of
4371n/a # tp->tp_as_sequence->sq_ass_slice
4372n/a
4373n/a class C(object):
4374n/a def __setitem__(self, idx, value):
4375n/a self.value = value
4376n/a
4377n/a c = C()
4378n/a c[1:2] = 3
4379n/a self.assertEqual(c.value, 3)
4380n/a
4381n/a def test_set_and_no_get(self):
4382n/a # See
4383n/a # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4384n/a class Descr(object):
4385n/a
4386n/a def __init__(self, name):
4387n/a self.name = name
4388n/a
4389n/a def __set__(self, obj, value):
4390n/a obj.__dict__[self.name] = value
4391n/a descr = Descr("a")
4392n/a
4393n/a class X(object):
4394n/a a = descr
4395n/a
4396n/a x = X()
4397n/a self.assertIs(x.a, descr)
4398n/a x.a = 42
4399n/a self.assertEqual(x.a, 42)
4400n/a
4401n/a # Also check type_getattro for correctness.
4402n/a class Meta(type):
4403n/a pass
4404n/a class X(metaclass=Meta):
4405n/a pass
4406n/a X.a = 42
4407n/a Meta.a = Descr("a")
4408n/a self.assertEqual(X.a, 42)
4409n/a
4410n/a def test_getattr_hooks(self):
4411n/a # issue 4230
4412n/a
4413n/a class Descriptor(object):
4414n/a counter = 0
4415n/a def __get__(self, obj, objtype=None):
4416n/a def getter(name):
4417n/a self.counter += 1
4418n/a raise AttributeError(name)
4419n/a return getter
4420n/a
4421n/a descr = Descriptor()
4422n/a class A(object):
4423n/a __getattribute__ = descr
4424n/a class B(object):
4425n/a __getattr__ = descr
4426n/a class C(object):
4427n/a __getattribute__ = descr
4428n/a __getattr__ = descr
4429n/a
4430n/a self.assertRaises(AttributeError, getattr, A(), "attr")
4431n/a self.assertEqual(descr.counter, 1)
4432n/a self.assertRaises(AttributeError, getattr, B(), "attr")
4433n/a self.assertEqual(descr.counter, 2)
4434n/a self.assertRaises(AttributeError, getattr, C(), "attr")
4435n/a self.assertEqual(descr.counter, 4)
4436n/a
4437n/a class EvilGetattribute(object):
4438n/a # This used to segfault
4439n/a def __getattr__(self, name):
4440n/a raise AttributeError(name)
4441n/a def __getattribute__(self, name):
4442n/a del EvilGetattribute.__getattr__
4443n/a for i in range(5):
4444n/a gc.collect()
4445n/a raise AttributeError(name)
4446n/a
4447n/a self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4448n/a
4449n/a def test_type___getattribute__(self):
4450n/a self.assertRaises(TypeError, type.__getattribute__, list, type)
4451n/a
4452n/a def test_abstractmethods(self):
4453n/a # type pretends not to have __abstractmethods__.
4454n/a self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4455n/a class meta(type):
4456n/a pass
4457n/a self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4458n/a class X(object):
4459n/a pass
4460n/a with self.assertRaises(AttributeError):
4461n/a del X.__abstractmethods__
4462n/a
4463n/a def test_proxy_call(self):
4464n/a class FakeStr:
4465n/a __class__ = str
4466n/a
4467n/a fake_str = FakeStr()
4468n/a # isinstance() reads __class__
4469n/a self.assertIsInstance(fake_str, str)
4470n/a
4471n/a # call a method descriptor
4472n/a with self.assertRaises(TypeError):
4473n/a str.split(fake_str)
4474n/a
4475n/a # call a slot wrapper descriptor
4476n/a with self.assertRaises(TypeError):
4477n/a str.__add__(fake_str, "abc")
4478n/a
4479n/a def test_repr_as_str(self):
4480n/a # Issue #11603: crash or infinite loop when rebinding __str__ as
4481n/a # __repr__.
4482n/a class Foo:
4483n/a pass
4484n/a Foo.__repr__ = Foo.__str__
4485n/a foo = Foo()
4486n/a self.assertRaises(RecursionError, str, foo)
4487n/a self.assertRaises(RecursionError, repr, foo)
4488n/a
4489n/a def test_mixing_slot_wrappers(self):
4490n/a class X(dict):
4491n/a __setattr__ = dict.__setitem__
4492n/a x = X()
4493n/a x.y = 42
4494n/a self.assertEqual(x["y"], 42)
4495n/a
4496n/a def test_slot_shadows_class_variable(self):
4497n/a with self.assertRaises(ValueError) as cm:
4498n/a class X:
4499n/a __slots__ = ["foo"]
4500n/a foo = None
4501n/a m = str(cm.exception)
4502n/a self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4503n/a
4504n/a def test_set_doc(self):
4505n/a class X:
4506n/a "elephant"
4507n/a X.__doc__ = "banana"
4508n/a self.assertEqual(X.__doc__, "banana")
4509n/a with self.assertRaises(TypeError) as cm:
4510n/a type(list).__dict__["__doc__"].__set__(list, "blah")
4511n/a self.assertIn("can't set list.__doc__", str(cm.exception))
4512n/a with self.assertRaises(TypeError) as cm:
4513n/a type(X).__dict__["__doc__"].__delete__(X)
4514n/a self.assertIn("can't delete X.__doc__", str(cm.exception))
4515n/a self.assertEqual(X.__doc__, "banana")
4516n/a
4517n/a def test_qualname(self):
4518n/a descriptors = [str.lower, complex.real, float.real, int.__add__]
4519n/a types = ['method', 'member', 'getset', 'wrapper']
4520n/a
4521n/a # make sure we have an example of each type of descriptor
4522n/a for d, n in zip(descriptors, types):
4523n/a self.assertEqual(type(d).__name__, n + '_descriptor')
4524n/a
4525n/a for d in descriptors:
4526n/a qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4527n/a self.assertEqual(d.__qualname__, qualname)
4528n/a
4529n/a self.assertEqual(str.lower.__qualname__, 'str.lower')
4530n/a self.assertEqual(complex.real.__qualname__, 'complex.real')
4531n/a self.assertEqual(float.real.__qualname__, 'float.real')
4532n/a self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4533n/a
4534n/a class X:
4535n/a pass
4536n/a with self.assertRaises(TypeError):
4537n/a del X.__qualname__
4538n/a
4539n/a self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4540n/a str, 'Oink')
4541n/a
4542n/a global Y
4543n/a class Y:
4544n/a class Inside:
4545n/a pass
4546n/a self.assertEqual(Y.__qualname__, 'Y')
4547n/a self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
4548n/a
4549n/a def test_qualname_dict(self):
4550n/a ns = {'__qualname__': 'some.name'}
4551n/a tp = type('Foo', (), ns)
4552n/a self.assertEqual(tp.__qualname__, 'some.name')
4553n/a self.assertNotIn('__qualname__', tp.__dict__)
4554n/a self.assertEqual(ns, {'__qualname__': 'some.name'})
4555n/a
4556n/a ns = {'__qualname__': 1}
4557n/a self.assertRaises(TypeError, type, 'Foo', (), ns)
4558n/a
4559n/a def test_cycle_through_dict(self):
4560n/a # See bug #1469629
4561n/a class X(dict):
4562n/a def __init__(self):
4563n/a dict.__init__(self)
4564n/a self.__dict__ = self
4565n/a x = X()
4566n/a x.attr = 42
4567n/a wr = weakref.ref(x)
4568n/a del x
4569n/a support.gc_collect()
4570n/a self.assertIsNone(wr())
4571n/a for o in gc.get_objects():
4572n/a self.assertIsNot(type(o), X)
4573n/a
4574n/a def test_object_new_and_init_with_parameters(self):
4575n/a # See issue #1683368
4576n/a class OverrideNeither:
4577n/a pass
4578n/a self.assertRaises(TypeError, OverrideNeither, 1)
4579n/a self.assertRaises(TypeError, OverrideNeither, kw=1)
4580n/a class OverrideNew:
4581n/a def __new__(cls, foo, kw=0, *args, **kwds):
4582n/a return object.__new__(cls, *args, **kwds)
4583n/a class OverrideInit:
4584n/a def __init__(self, foo, kw=0, *args, **kwargs):
4585n/a return object.__init__(self, *args, **kwargs)
4586n/a class OverrideBoth(OverrideNew, OverrideInit):
4587n/a pass
4588n/a for case in OverrideNew, OverrideInit, OverrideBoth:
4589n/a case(1)
4590n/a case(1, kw=2)
4591n/a self.assertRaises(TypeError, case, 1, 2, 3)
4592n/a self.assertRaises(TypeError, case, 1, 2, foo=3)
4593n/a
4594n/a def test_subclassing_does_not_duplicate_dict_descriptors(self):
4595n/a class Base:
4596n/a pass
4597n/a class Sub(Base):
4598n/a pass
4599n/a self.assertIn("__dict__", Base.__dict__)
4600n/a self.assertNotIn("__dict__", Sub.__dict__)
4601n/a
4602n/a def test_bound_method_repr(self):
4603n/a class Foo:
4604n/a def method(self):
4605n/a pass
4606n/a self.assertRegex(repr(Foo().method),
4607n/a r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4608n/a
4609n/a
4610n/a class Base:
4611n/a def method(self):
4612n/a pass
4613n/a class Derived1(Base):
4614n/a pass
4615n/a class Derived2(Base):
4616n/a def method(self):
4617n/a pass
4618n/a base = Base()
4619n/a derived1 = Derived1()
4620n/a derived2 = Derived2()
4621n/a super_d2 = super(Derived2, derived2)
4622n/a self.assertRegex(repr(base.method),
4623n/a r"<bound method .*Base\.method of <.*Base object at .*>>")
4624n/a self.assertRegex(repr(derived1.method),
4625n/a r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4626n/a self.assertRegex(repr(derived2.method),
4627n/a r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4628n/a self.assertRegex(repr(super_d2.method),
4629n/a r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4630n/a
4631n/a class Foo:
4632n/a @classmethod
4633n/a def method(cls):
4634n/a pass
4635n/a foo = Foo()
4636n/a self.assertRegex(repr(foo.method), # access via instance
4637n/a r"<bound method .*Foo\.method of <class '.*Foo'>>")
4638n/a self.assertRegex(repr(Foo.method), # access via the class
4639n/a r"<bound method .*Foo\.method of <class '.*Foo'>>")
4640n/a
4641n/a
4642n/a class MyCallable:
4643n/a def __call__(self, arg):
4644n/a pass
4645n/a func = MyCallable() # func has no __name__ or __qualname__ attributes
4646n/a instance = object()
4647n/a method = types.MethodType(func, instance)
4648n/a self.assertRegex(repr(method),
4649n/a r"<bound method \? of <object object at .*>>")
4650n/a func.__name__ = "name"
4651n/a self.assertRegex(repr(method),
4652n/a r"<bound method name of <object object at .*>>")
4653n/a func.__qualname__ = "qualname"
4654n/a self.assertRegex(repr(method),
4655n/a r"<bound method qualname of <object object at .*>>")
4656n/a
4657n/a
4658n/aclass DictProxyTests(unittest.TestCase):
4659n/a def setUp(self):
4660n/a class C(object):
4661n/a def meth(self):
4662n/a pass
4663n/a self.C = C
4664n/a
4665n/a @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4666n/a 'trace function introduces __local__')
4667n/a def test_iter_keys(self):
4668n/a # Testing dict-proxy keys...
4669n/a it = self.C.__dict__.keys()
4670n/a self.assertNotIsInstance(it, list)
4671n/a keys = list(it)
4672n/a keys.sort()
4673n/a self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4674n/a '__weakref__', 'meth'])
4675n/a
4676n/a @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4677n/a 'trace function introduces __local__')
4678n/a def test_iter_values(self):
4679n/a # Testing dict-proxy values...
4680n/a it = self.C.__dict__.values()
4681n/a self.assertNotIsInstance(it, list)
4682n/a values = list(it)
4683n/a self.assertEqual(len(values), 5)
4684n/a
4685n/a @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4686n/a 'trace function introduces __local__')
4687n/a def test_iter_items(self):
4688n/a # Testing dict-proxy iteritems...
4689n/a it = self.C.__dict__.items()
4690n/a self.assertNotIsInstance(it, list)
4691n/a keys = [item[0] for item in it]
4692n/a keys.sort()
4693n/a self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4694n/a '__weakref__', 'meth'])
4695n/a
4696n/a def test_dict_type_with_metaclass(self):
4697n/a # Testing type of __dict__ when metaclass set...
4698n/a class B(object):
4699n/a pass
4700n/a class M(type):
4701n/a pass
4702n/a class C(metaclass=M):
4703n/a # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4704n/a pass
4705n/a self.assertEqual(type(C.__dict__), type(B.__dict__))
4706n/a
4707n/a def test_repr(self):
4708n/a # Testing mappingproxy.__repr__.
4709n/a # We can't blindly compare with the repr of another dict as ordering
4710n/a # of keys and values is arbitrary and may differ.
4711n/a r = repr(self.C.__dict__)
4712n/a self.assertTrue(r.startswith('mappingproxy('), r)
4713n/a self.assertTrue(r.endswith(')'), r)
4714n/a for k, v in self.C.__dict__.items():
4715n/a self.assertIn('{!r}: {!r}'.format(k, v), r)
4716n/a
4717n/a
4718n/aclass PTypesLongInitTest(unittest.TestCase):
4719n/a # This is in its own TestCase so that it can be run before any other tests.
4720n/a def test_pytype_long_ready(self):
4721n/a # Testing SF bug 551412 ...
4722n/a
4723n/a # This dumps core when SF bug 551412 isn't fixed --
4724n/a # but only when test_descr.py is run separately.
4725n/a # (That can't be helped -- as soon as PyType_Ready()
4726n/a # is called for PyLong_Type, the bug is gone.)
4727n/a class UserLong(object):
4728n/a def __pow__(self, *args):
4729n/a pass
4730n/a try:
4731n/a pow(0, UserLong(), 0)
4732n/a except:
4733n/a pass
4734n/a
4735n/a # Another segfault only when run early
4736n/a # (before PyType_Ready(tuple) is called)
4737n/a type.mro(tuple)
4738n/a
4739n/a
4740n/aclass MiscTests(unittest.TestCase):
4741n/a def test_type_lookup_mro_reference(self):
4742n/a # Issue #14199: _PyType_Lookup() has to keep a strong reference to
4743n/a # the type MRO because it may be modified during the lookup, if
4744n/a # __bases__ is set during the lookup for example.
4745n/a class MyKey(object):
4746n/a def __hash__(self):
4747n/a return hash('mykey')
4748n/a
4749n/a def __eq__(self, other):
4750n/a X.__bases__ = (Base2,)
4751n/a
4752n/a class Base(object):
4753n/a mykey = 'from Base'
4754n/a mykey2 = 'from Base'
4755n/a
4756n/a class Base2(object):
4757n/a mykey = 'from Base2'
4758n/a mykey2 = 'from Base2'
4759n/a
4760n/a X = type('X', (Base,), {MyKey(): 5})
4761n/a # mykey is read from Base
4762n/a self.assertEqual(X.mykey, 'from Base')
4763n/a # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
4764n/a self.assertEqual(X.mykey2, 'from Base2')
4765n/a
4766n/a
4767n/aclass PicklingTests(unittest.TestCase):
4768n/a
4769n/a def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
4770n/a listitems=None, dictitems=None):
4771n/a if proto >= 2:
4772n/a reduce_value = obj.__reduce_ex__(proto)
4773n/a if kwargs:
4774n/a self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
4775n/a self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
4776n/a else:
4777n/a self.assertEqual(reduce_value[0], copyreg.__newobj__)
4778n/a self.assertEqual(reduce_value[1], (type(obj),) + args)
4779n/a self.assertEqual(reduce_value[2], state)
4780n/a if listitems is not None:
4781n/a self.assertListEqual(list(reduce_value[3]), listitems)
4782n/a else:
4783n/a self.assertIsNone(reduce_value[3])
4784n/a if dictitems is not None:
4785n/a self.assertDictEqual(dict(reduce_value[4]), dictitems)
4786n/a else:
4787n/a self.assertIsNone(reduce_value[4])
4788n/a else:
4789n/a base_type = type(obj).__base__
4790n/a reduce_value = (copyreg._reconstructor,
4791n/a (type(obj),
4792n/a base_type,
4793n/a None if base_type is object else base_type(obj)))
4794n/a if state is not None:
4795n/a reduce_value += (state,)
4796n/a self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
4797n/a self.assertEqual(obj.__reduce__(), reduce_value)
4798n/a
4799n/a def test_reduce(self):
4800n/a protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4801n/a args = (-101, "spam")
4802n/a kwargs = {'bacon': -201, 'fish': -301}
4803n/a state = {'cheese': -401}
4804n/a
4805n/a class C1:
4806n/a def __getnewargs__(self):
4807n/a return args
4808n/a obj = C1()
4809n/a for proto in protocols:
4810n/a self._check_reduce(proto, obj, args)
4811n/a
4812n/a for name, value in state.items():
4813n/a setattr(obj, name, value)
4814n/a for proto in protocols:
4815n/a self._check_reduce(proto, obj, args, state=state)
4816n/a
4817n/a class C2:
4818n/a def __getnewargs__(self):
4819n/a return "bad args"
4820n/a obj = C2()
4821n/a for proto in protocols:
4822n/a if proto >= 2:
4823n/a with self.assertRaises(TypeError):
4824n/a obj.__reduce_ex__(proto)
4825n/a
4826n/a class C3:
4827n/a def __getnewargs_ex__(self):
4828n/a return (args, kwargs)
4829n/a obj = C3()
4830n/a for proto in protocols:
4831n/a if proto >= 2:
4832n/a self._check_reduce(proto, obj, args, kwargs)
4833n/a
4834n/a class C4:
4835n/a def __getnewargs_ex__(self):
4836n/a return (args, "bad dict")
4837n/a class C5:
4838n/a def __getnewargs_ex__(self):
4839n/a return ("bad tuple", kwargs)
4840n/a class C6:
4841n/a def __getnewargs_ex__(self):
4842n/a return ()
4843n/a class C7:
4844n/a def __getnewargs_ex__(self):
4845n/a return "bad args"
4846n/a for proto in protocols:
4847n/a for cls in C4, C5, C6, C7:
4848n/a obj = cls()
4849n/a if proto >= 2:
4850n/a with self.assertRaises((TypeError, ValueError)):
4851n/a obj.__reduce_ex__(proto)
4852n/a
4853n/a class C9:
4854n/a def __getnewargs_ex__(self):
4855n/a return (args, {})
4856n/a obj = C9()
4857n/a for proto in protocols:
4858n/a self._check_reduce(proto, obj, args)
4859n/a
4860n/a class C10:
4861n/a def __getnewargs_ex__(self):
4862n/a raise IndexError
4863n/a obj = C10()
4864n/a for proto in protocols:
4865n/a if proto >= 2:
4866n/a with self.assertRaises(IndexError):
4867n/a obj.__reduce_ex__(proto)
4868n/a
4869n/a class C11:
4870n/a def __getstate__(self):
4871n/a return state
4872n/a obj = C11()
4873n/a for proto in protocols:
4874n/a self._check_reduce(proto, obj, state=state)
4875n/a
4876n/a class C12:
4877n/a def __getstate__(self):
4878n/a return "not dict"
4879n/a obj = C12()
4880n/a for proto in protocols:
4881n/a self._check_reduce(proto, obj, state="not dict")
4882n/a
4883n/a class C13:
4884n/a def __getstate__(self):
4885n/a raise IndexError
4886n/a obj = C13()
4887n/a for proto in protocols:
4888n/a with self.assertRaises(IndexError):
4889n/a obj.__reduce_ex__(proto)
4890n/a if proto < 2:
4891n/a with self.assertRaises(IndexError):
4892n/a obj.__reduce__()
4893n/a
4894n/a class C14:
4895n/a __slots__ = tuple(state)
4896n/a def __init__(self):
4897n/a for name, value in state.items():
4898n/a setattr(self, name, value)
4899n/a
4900n/a obj = C14()
4901n/a for proto in protocols:
4902n/a if proto >= 2:
4903n/a self._check_reduce(proto, obj, state=(None, state))
4904n/a else:
4905n/a with self.assertRaises(TypeError):
4906n/a obj.__reduce_ex__(proto)
4907n/a with self.assertRaises(TypeError):
4908n/a obj.__reduce__()
4909n/a
4910n/a class C15(dict):
4911n/a pass
4912n/a obj = C15({"quebec": -601})
4913n/a for proto in protocols:
4914n/a self._check_reduce(proto, obj, dictitems=dict(obj))
4915n/a
4916n/a class C16(list):
4917n/a pass
4918n/a obj = C16(["yukon"])
4919n/a for proto in protocols:
4920n/a self._check_reduce(proto, obj, listitems=list(obj))
4921n/a
4922n/a def test_special_method_lookup(self):
4923n/a protocols = range(pickle.HIGHEST_PROTOCOL + 1)
4924n/a class Picky:
4925n/a def __getstate__(self):
4926n/a return {}
4927n/a
4928n/a def __getattr__(self, attr):
4929n/a if attr in ("__getnewargs__", "__getnewargs_ex__"):
4930n/a raise AssertionError(attr)
4931n/a return None
4932n/a for protocol in protocols:
4933n/a state = {} if protocol >= 2 else None
4934n/a self._check_reduce(protocol, Picky(), state=state)
4935n/a
4936n/a def _assert_is_copy(self, obj, objcopy, msg=None):
4937n/a """Utility method to verify if two objects are copies of each others.
4938n/a """
4939n/a if msg is None:
4940n/a msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
4941n/a if type(obj).__repr__ is object.__repr__:
4942n/a # We have this limitation for now because we use the object's repr
4943n/a # to help us verify that the two objects are copies. This allows
4944n/a # us to delegate the non-generic verification logic to the objects
4945n/a # themselves.
4946n/a raise ValueError("object passed to _assert_is_copy must " +
4947n/a "override the __repr__ method.")
4948n/a self.assertIsNot(obj, objcopy, msg=msg)
4949n/a self.assertIs(type(obj), type(objcopy), msg=msg)
4950n/a if hasattr(obj, '__dict__'):
4951n/a self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
4952n/a self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
4953n/a if hasattr(obj, '__slots__'):
4954n/a self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
4955n/a for slot in obj.__slots__:
4956n/a self.assertEqual(
4957n/a hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
4958n/a self.assertEqual(getattr(obj, slot, None),
4959n/a getattr(objcopy, slot, None), msg=msg)
4960n/a self.assertEqual(repr(obj), repr(objcopy), msg=msg)
4961n/a
4962n/a @staticmethod
4963n/a def _generate_pickle_copiers():
4964n/a """Utility method to generate the many possible pickle configurations.
4965n/a """
4966n/a class PickleCopier:
4967n/a "This class copies object using pickle."
4968n/a def __init__(self, proto, dumps, loads):
4969n/a self.proto = proto
4970n/a self.dumps = dumps
4971n/a self.loads = loads
4972n/a def copy(self, obj):
4973n/a return self.loads(self.dumps(obj, self.proto))
4974n/a def __repr__(self):
4975n/a # We try to be as descriptive as possible here since this is
4976n/a # the string which we will allow us to tell the pickle
4977n/a # configuration we are using during debugging.
4978n/a return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
4979n/a .format(self.proto,
4980n/a self.dumps.__module__, self.dumps.__qualname__,
4981n/a self.loads.__module__, self.loads.__qualname__))
4982n/a return (PickleCopier(*args) for args in
4983n/a itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
4984n/a {pickle.dumps, pickle._dumps},
4985n/a {pickle.loads, pickle._loads}))
4986n/a
4987n/a def test_pickle_slots(self):
4988n/a # Tests pickling of classes with __slots__.
4989n/a
4990n/a # Pickling of classes with __slots__ but without __getstate__ should
4991n/a # fail (if using protocol 0 or 1)
4992n/a global C
4993n/a class C:
4994n/a __slots__ = ['a']
4995n/a with self.assertRaises(TypeError):
4996n/a pickle.dumps(C(), 0)
4997n/a
4998n/a global D
4999n/a class D(C):
5000n/a pass
5001n/a with self.assertRaises(TypeError):
5002n/a pickle.dumps(D(), 0)
5003n/a
5004n/a class C:
5005n/a "A class with __getstate__ and __setstate__ implemented."
5006n/a __slots__ = ['a']
5007n/a def __getstate__(self):
5008n/a state = getattr(self, '__dict__', {}).copy()
5009n/a for cls in type(self).__mro__:
5010n/a for slot in cls.__dict__.get('__slots__', ()):
5011n/a try:
5012n/a state[slot] = getattr(self, slot)
5013n/a except AttributeError:
5014n/a pass
5015n/a return state
5016n/a def __setstate__(self, state):
5017n/a for k, v in state.items():
5018n/a setattr(self, k, v)
5019n/a def __repr__(self):
5020n/a return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5021n/a
5022n/a class D(C):
5023n/a "A subclass of a class with slots."
5024n/a pass
5025n/a
5026n/a global E
5027n/a class E(C):
5028n/a "A subclass with an extra slot."
5029n/a __slots__ = ['b']
5030n/a
5031n/a # Now it should work
5032n/a for pickle_copier in self._generate_pickle_copiers():
5033n/a with self.subTest(pickle_copier=pickle_copier):
5034n/a x = C()
5035n/a y = pickle_copier.copy(x)
5036n/a self._assert_is_copy(x, y)
5037n/a
5038n/a x.a = 42
5039n/a y = pickle_copier.copy(x)
5040n/a self._assert_is_copy(x, y)
5041n/a
5042n/a x = D()
5043n/a x.a = 42
5044n/a x.b = 100
5045n/a y = pickle_copier.copy(x)
5046n/a self._assert_is_copy(x, y)
5047n/a
5048n/a x = E()
5049n/a x.a = 42
5050n/a x.b = "foo"
5051n/a y = pickle_copier.copy(x)
5052n/a self._assert_is_copy(x, y)
5053n/a
5054n/a def test_reduce_copying(self):
5055n/a # Tests pickling and copying new-style classes and objects.
5056n/a global C1
5057n/a class C1:
5058n/a "The state of this class is copyable via its instance dict."
5059n/a ARGS = (1, 2)
5060n/a NEED_DICT_COPYING = True
5061n/a def __init__(self, a, b):
5062n/a super().__init__()
5063n/a self.a = a
5064n/a self.b = b
5065n/a def __repr__(self):
5066n/a return "C1(%r, %r)" % (self.a, self.b)
5067n/a
5068n/a global C2
5069n/a class C2(list):
5070n/a "A list subclass copyable via __getnewargs__."
5071n/a ARGS = (1, 2)
5072n/a NEED_DICT_COPYING = False
5073n/a def __new__(cls, a, b):
5074n/a self = super().__new__(cls)
5075n/a self.a = a
5076n/a self.b = b
5077n/a return self
5078n/a def __init__(self, *args):
5079n/a super().__init__()
5080n/a # This helps testing that __init__ is not called during the
5081n/a # unpickling process, which would cause extra appends.
5082n/a self.append("cheese")
5083n/a @classmethod
5084n/a def __getnewargs__(cls):
5085n/a return cls.ARGS
5086n/a def __repr__(self):
5087n/a return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5088n/a
5089n/a global C3
5090n/a class C3(list):
5091n/a "A list subclass copyable via __getstate__."
5092n/a ARGS = (1, 2)
5093n/a NEED_DICT_COPYING = False
5094n/a def __init__(self, a, b):
5095n/a self.a = a
5096n/a self.b = b
5097n/a # This helps testing that __init__ is not called during the
5098n/a # unpickling process, which would cause extra appends.
5099n/a self.append("cheese")
5100n/a @classmethod
5101n/a def __getstate__(cls):
5102n/a return cls.ARGS
5103n/a def __setstate__(self, state):
5104n/a a, b = state
5105n/a self.a = a
5106n/a self.b = b
5107n/a def __repr__(self):
5108n/a return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5109n/a
5110n/a global C4
5111n/a class C4(int):
5112n/a "An int subclass copyable via __getnewargs__."
5113n/a ARGS = ("hello", "world", 1)
5114n/a NEED_DICT_COPYING = False
5115n/a def __new__(cls, a, b, value):
5116n/a self = super().__new__(cls, value)
5117n/a self.a = a
5118n/a self.b = b
5119n/a return self
5120n/a @classmethod
5121n/a def __getnewargs__(cls):
5122n/a return cls.ARGS
5123n/a def __repr__(self):
5124n/a return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5125n/a
5126n/a global C5
5127n/a class C5(int):
5128n/a "An int subclass copyable via __getnewargs_ex__."
5129n/a ARGS = (1, 2)
5130n/a KWARGS = {'value': 3}
5131n/a NEED_DICT_COPYING = False
5132n/a def __new__(cls, a, b, *, value=0):
5133n/a self = super().__new__(cls, value)
5134n/a self.a = a
5135n/a self.b = b
5136n/a return self
5137n/a @classmethod
5138n/a def __getnewargs_ex__(cls):
5139n/a return (cls.ARGS, cls.KWARGS)
5140n/a def __repr__(self):
5141n/a return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5142n/a
5143n/a test_classes = (C1, C2, C3, C4, C5)
5144n/a # Testing copying through pickle
5145n/a pickle_copiers = self._generate_pickle_copiers()
5146n/a for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5147n/a with self.subTest(cls=cls, pickle_copier=pickle_copier):
5148n/a kwargs = getattr(cls, 'KWARGS', {})
5149n/a obj = cls(*cls.ARGS, **kwargs)
5150n/a proto = pickle_copier.proto
5151n/a objcopy = pickle_copier.copy(obj)
5152n/a self._assert_is_copy(obj, objcopy)
5153n/a # For test classes that supports this, make sure we didn't go
5154n/a # around the reduce protocol by simply copying the attribute
5155n/a # dictionary. We clear attributes using the previous copy to
5156n/a # not mutate the original argument.
5157n/a if proto >= 2 and not cls.NEED_DICT_COPYING:
5158n/a objcopy.__dict__.clear()
5159n/a objcopy2 = pickle_copier.copy(objcopy)
5160n/a self._assert_is_copy(obj, objcopy2)
5161n/a
5162n/a # Testing copying through copy.deepcopy()
5163n/a for cls in test_classes:
5164n/a with self.subTest(cls=cls):
5165n/a kwargs = getattr(cls, 'KWARGS', {})
5166n/a obj = cls(*cls.ARGS, **kwargs)
5167n/a objcopy = deepcopy(obj)
5168n/a self._assert_is_copy(obj, objcopy)
5169n/a # For test classes that supports this, make sure we didn't go
5170n/a # around the reduce protocol by simply copying the attribute
5171n/a # dictionary. We clear attributes using the previous copy to
5172n/a # not mutate the original argument.
5173n/a if not cls.NEED_DICT_COPYING:
5174n/a objcopy.__dict__.clear()
5175n/a objcopy2 = deepcopy(objcopy)
5176n/a self._assert_is_copy(obj, objcopy2)
5177n/a
5178n/a def test_issue24097(self):
5179n/a # Slot name is freed inside __getattr__ and is later used.
5180n/a class S(str): # Not interned
5181n/a pass
5182n/a class A:
5183n/a __slotnames__ = [S('spam')]
5184n/a def __getattr__(self, attr):
5185n/a if attr == 'spam':
5186n/a A.__slotnames__[:] = [S('spam')]
5187n/a return 42
5188n/a else:
5189n/a raise AttributeError
5190n/a
5191n/a import copyreg
5192n/a expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
5193n/a self.assertEqual(A().__reduce__(2), expected) # Shouldn't crash
5194n/a
5195n/a
5196n/aclass SharedKeyTests(unittest.TestCase):
5197n/a
5198n/a @support.cpython_only
5199n/a def test_subclasses(self):
5200n/a # Verify that subclasses can share keys (per PEP 412)
5201n/a class A:
5202n/a pass
5203n/a class B(A):
5204n/a pass
5205n/a
5206n/a a, b = A(), B()
5207n/a self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5208n/a self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5209n/a # Initial hash table can contain at most 5 elements.
5210n/a # Set 6 attributes to cause internal resizing.
5211n/a a.x, a.y, a.z, a.w, a.v, a.u = range(6)
5212n/a self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5213n/a a2 = A()
5214n/a self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5215n/a self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({}))
5216n/a b.u, b.v, b.w, b.t, b.s, b.r = range(6)
5217n/a self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({}))
5218n/a
5219n/a
5220n/aclass DebugHelperMeta(type):
5221n/a """
5222n/a Sets default __doc__ and simplifies repr() output.
5223n/a """
5224n/a def __new__(mcls, name, bases, attrs):
5225n/a if attrs.get('__doc__') is None:
5226n/a attrs['__doc__'] = name # helps when debugging with gdb
5227n/a return type.__new__(mcls, name, bases, attrs)
5228n/a def __repr__(cls):
5229n/a return repr(cls.__name__)
5230n/a
5231n/a
5232n/aclass MroTest(unittest.TestCase):
5233n/a """
5234n/a Regressions for some bugs revealed through
5235n/a mcsl.mro() customization (typeobject.c: mro_internal()) and
5236n/a cls.__bases__ assignment (typeobject.c: type_set_bases()).
5237n/a """
5238n/a
5239n/a def setUp(self):
5240n/a self.step = 0
5241n/a self.ready = False
5242n/a
5243n/a def step_until(self, limit):
5244n/a ret = (self.step < limit)
5245n/a if ret:
5246n/a self.step += 1
5247n/a return ret
5248n/a
5249n/a def test_incomplete_set_bases_on_self(self):
5250n/a """
5251n/a type_set_bases must be aware that type->tp_mro can be NULL.
5252n/a """
5253n/a class M(DebugHelperMeta):
5254n/a def mro(cls):
5255n/a if self.step_until(1):
5256n/a assert cls.__mro__ is None
5257n/a cls.__bases__ += ()
5258n/a
5259n/a return type.mro(cls)
5260n/a
5261n/a class A(metaclass=M):
5262n/a pass
5263n/a
5264n/a def test_reent_set_bases_on_base(self):
5265n/a """
5266n/a Deep reentrancy must not over-decref old_mro.
5267n/a """
5268n/a class M(DebugHelperMeta):
5269n/a def mro(cls):
5270n/a if cls.__mro__ is not None and cls.__name__ == 'B':
5271n/a # 4-5 steps are usually enough to make it crash somewhere
5272n/a if self.step_until(10):
5273n/a A.__bases__ += ()
5274n/a
5275n/a return type.mro(cls)
5276n/a
5277n/a class A(metaclass=M):
5278n/a pass
5279n/a class B(A):
5280n/a pass
5281n/a B.__bases__ += ()
5282n/a
5283n/a def test_reent_set_bases_on_direct_base(self):
5284n/a """
5285n/a Similar to test_reent_set_bases_on_base, but may crash differently.
5286n/a """
5287n/a class M(DebugHelperMeta):
5288n/a def mro(cls):
5289n/a base = cls.__bases__[0]
5290n/a if base is not object:
5291n/a if self.step_until(5):
5292n/a base.__bases__ += ()
5293n/a
5294n/a return type.mro(cls)
5295n/a
5296n/a class A(metaclass=M):
5297n/a pass
5298n/a class B(A):
5299n/a pass
5300n/a class C(B):
5301n/a pass
5302n/a
5303n/a def test_reent_set_bases_tp_base_cycle(self):
5304n/a """
5305n/a type_set_bases must check for an inheritance cycle not only through
5306n/a MRO of the type, which may be not yet updated in case of reentrance,
5307n/a but also through tp_base chain, which is assigned before diving into
5308n/a inner calls to mro().
5309n/a
5310n/a Otherwise, the following snippet can loop forever:
5311n/a do {
5312n/a // ...
5313n/a type = type->tp_base;
5314n/a } while (type != NULL);
5315n/a
5316n/a Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5317n/a would not be happy in that case, causing a stack overflow.
5318n/a """
5319n/a class M(DebugHelperMeta):
5320n/a def mro(cls):
5321n/a if self.ready:
5322n/a if cls.__name__ == 'B1':
5323n/a B2.__bases__ = (B1,)
5324n/a if cls.__name__ == 'B2':
5325n/a B1.__bases__ = (B2,)
5326n/a return type.mro(cls)
5327n/a
5328n/a class A(metaclass=M):
5329n/a pass
5330n/a class B1(A):
5331n/a pass
5332n/a class B2(A):
5333n/a pass
5334n/a
5335n/a self.ready = True
5336n/a with self.assertRaises(TypeError):
5337n/a B1.__bases__ += ()
5338n/a
5339n/a def test_tp_subclasses_cycle_in_update_slots(self):
5340n/a """
5341n/a type_set_bases must check for reentrancy upon finishing its job
5342n/a by updating tp_subclasses of old/new bases of the type.
5343n/a Otherwise, an implicit inheritance cycle through tp_subclasses
5344n/a can break functions that recurse on elements of that field
5345n/a (like recurse_down_subclasses and mro_hierarchy) eventually
5346n/a leading to a stack overflow.
5347n/a """
5348n/a class M(DebugHelperMeta):
5349n/a def mro(cls):
5350n/a if self.ready and cls.__name__ == 'C':
5351n/a self.ready = False
5352n/a C.__bases__ = (B2,)
5353n/a return type.mro(cls)
5354n/a
5355n/a class A(metaclass=M):
5356n/a pass
5357n/a class B1(A):
5358n/a pass
5359n/a class B2(A):
5360n/a pass
5361n/a class C(A):
5362n/a pass
5363n/a
5364n/a self.ready = True
5365n/a C.__bases__ = (B1,)
5366n/a B1.__bases__ = (C,)
5367n/a
5368n/a self.assertEqual(C.__bases__, (B2,))
5369n/a self.assertEqual(B2.__subclasses__(), [C])
5370n/a self.assertEqual(B1.__subclasses__(), [])
5371n/a
5372n/a self.assertEqual(B1.__bases__, (C,))
5373n/a self.assertEqual(C.__subclasses__(), [B1])
5374n/a
5375n/a def test_tp_subclasses_cycle_error_return_path(self):
5376n/a """
5377n/a The same as test_tp_subclasses_cycle_in_update_slots, but tests
5378n/a a code path executed on error (goto bail).
5379n/a """
5380n/a class E(Exception):
5381n/a pass
5382n/a class M(DebugHelperMeta):
5383n/a def mro(cls):
5384n/a if self.ready and cls.__name__ == 'C':
5385n/a if C.__bases__ == (B2,):
5386n/a self.ready = False
5387n/a else:
5388n/a C.__bases__ = (B2,)
5389n/a raise E
5390n/a return type.mro(cls)
5391n/a
5392n/a class A(metaclass=M):
5393n/a pass
5394n/a class B1(A):
5395n/a pass
5396n/a class B2(A):
5397n/a pass
5398n/a class C(A):
5399n/a pass
5400n/a
5401n/a self.ready = True
5402n/a with self.assertRaises(E):
5403n/a C.__bases__ = (B1,)
5404n/a B1.__bases__ = (C,)
5405n/a
5406n/a self.assertEqual(C.__bases__, (B2,))
5407n/a self.assertEqual(C.__mro__, tuple(type.mro(C)))
5408n/a
5409n/a def test_incomplete_extend(self):
5410n/a """
5411n/a Extending an unitialized type with type->tp_mro == NULL must
5412n/a throw a reasonable TypeError exception, instead of failing
5413n/a with PyErr_BadInternalCall.
5414n/a """
5415n/a class M(DebugHelperMeta):
5416n/a def mro(cls):
5417n/a if cls.__mro__ is None and cls.__name__ != 'X':
5418n/a with self.assertRaises(TypeError):
5419n/a class X(cls):
5420n/a pass
5421n/a
5422n/a return type.mro(cls)
5423n/a
5424n/a class A(metaclass=M):
5425n/a pass
5426n/a
5427n/a def test_incomplete_super(self):
5428n/a """
5429n/a Attrubute lookup on a super object must be aware that
5430n/a its target type can be uninitialized (type->tp_mro == NULL).
5431n/a """
5432n/a class M(DebugHelperMeta):
5433n/a def mro(cls):
5434n/a if cls.__mro__ is None:
5435n/a with self.assertRaises(AttributeError):
5436n/a super(cls, cls).xxx
5437n/a
5438n/a return type.mro(cls)
5439n/a
5440n/a class A(metaclass=M):
5441n/a pass
5442n/a
5443n/a
5444n/adef test_main():
5445n/a # Run all local test cases, with PTypesLongInitTest first.
5446n/a support.run_unittest(PTypesLongInitTest, OperatorsTest,
5447n/a ClassPropertiesAndMethods, DictProxyTests,
5448n/a MiscTests, PicklingTests, SharedKeyTests,
5449n/a MroTest)
5450n/a
5451n/aif __name__ == "__main__":
5452n/a test_main()