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