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