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