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