Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1 | # Test descriptor-related enhancements |
| 2 | |
Tim Peters | 59c9a64 | 2001-09-13 05:38:56 +0000 | [diff] [blame] | 3 | from test_support import verify, verbose, TestFailed, TESTFN |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 4 | from copy import deepcopy |
| 5 | |
| 6 | def testunop(a, res, expr="len(a)", meth="__len__"): |
| 7 | if verbose: print "checking", expr |
| 8 | dict = {'a': a} |
| 9 | verify(eval(expr, dict) == res) |
| 10 | t = type(a) |
| 11 | m = getattr(t, meth) |
| 12 | verify(m == t.__dict__[meth]) |
| 13 | verify(m(a) == res) |
| 14 | bm = getattr(a, meth) |
| 15 | verify(bm() == res) |
| 16 | |
| 17 | def testbinop(a, b, res, expr="a+b", meth="__add__"): |
| 18 | if verbose: print "checking", expr |
| 19 | dict = {'a': a, 'b': b} |
| 20 | verify(eval(expr, dict) == res) |
| 21 | t = type(a) |
| 22 | m = getattr(t, meth) |
| 23 | verify(m == t.__dict__[meth]) |
| 24 | verify(m(a, b) == res) |
| 25 | bm = getattr(a, meth) |
| 26 | verify(bm(b) == res) |
| 27 | |
| 28 | def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"): |
| 29 | if verbose: print "checking", expr |
| 30 | dict = {'a': a, 'b': b, 'c': c} |
| 31 | verify(eval(expr, dict) == res) |
| 32 | t = type(a) |
| 33 | m = getattr(t, meth) |
| 34 | verify(m == t.__dict__[meth]) |
| 35 | verify(m(a, b, c) == res) |
| 36 | bm = getattr(a, meth) |
| 37 | verify(bm(b, c) == res) |
| 38 | |
| 39 | def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"): |
| 40 | if verbose: print "checking", stmt |
| 41 | dict = {'a': deepcopy(a), 'b': b} |
| 42 | exec stmt in dict |
| 43 | verify(dict['a'] == res) |
| 44 | t = type(a) |
| 45 | m = getattr(t, meth) |
| 46 | verify(m == t.__dict__[meth]) |
| 47 | dict['a'] = deepcopy(a) |
| 48 | m(dict['a'], b) |
| 49 | verify(dict['a'] == res) |
| 50 | dict['a'] = deepcopy(a) |
| 51 | bm = getattr(dict['a'], meth) |
| 52 | bm(b) |
| 53 | verify(dict['a'] == res) |
| 54 | |
| 55 | def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"): |
| 56 | if verbose: print "checking", stmt |
| 57 | dict = {'a': deepcopy(a), 'b': b, 'c': c} |
| 58 | exec stmt in dict |
| 59 | verify(dict['a'] == res) |
| 60 | t = type(a) |
| 61 | m = getattr(t, meth) |
| 62 | verify(m == t.__dict__[meth]) |
| 63 | dict['a'] = deepcopy(a) |
| 64 | m(dict['a'], b, c) |
| 65 | verify(dict['a'] == res) |
| 66 | dict['a'] = deepcopy(a) |
| 67 | bm = getattr(dict['a'], meth) |
| 68 | bm(b, c) |
| 69 | verify(dict['a'] == res) |
| 70 | |
| 71 | def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"): |
| 72 | if verbose: print "checking", stmt |
| 73 | dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} |
| 74 | exec stmt in dict |
| 75 | verify(dict['a'] == res) |
| 76 | t = type(a) |
| 77 | m = getattr(t, meth) |
| 78 | verify(m == t.__dict__[meth]) |
| 79 | dict['a'] = deepcopy(a) |
| 80 | m(dict['a'], b, c, d) |
| 81 | verify(dict['a'] == res) |
| 82 | dict['a'] = deepcopy(a) |
| 83 | bm = getattr(dict['a'], meth) |
| 84 | bm(b, c, d) |
| 85 | verify(dict['a'] == res) |
| 86 | |
| 87 | def lists(): |
| 88 | if verbose: print "Testing list operations..." |
| 89 | testbinop([1], [2], [1,2], "a+b", "__add__") |
| 90 | testbinop([1,2,3], 2, 1, "b in a", "__contains__") |
| 91 | testbinop([1,2,3], 4, 0, "b in a", "__contains__") |
| 92 | testbinop([1,2,3], 1, 2, "a[b]", "__getitem__") |
| 93 | testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__") |
| 94 | testsetop([1], [2], [1,2], "a+=b", "__iadd__") |
| 95 | testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__") |
| 96 | testunop([1,2,3], 3, "len(a)", "__len__") |
| 97 | testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__") |
| 98 | testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__") |
| 99 | testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__") |
| 100 | testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__") |
| 101 | |
| 102 | def dicts(): |
| 103 | if verbose: print "Testing dict operations..." |
| 104 | testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") |
| 105 | testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") |
| 106 | testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") |
| 107 | testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__") |
| 108 | d = {1:2,3:4} |
| 109 | l1 = [] |
| 110 | for i in d.keys(): l1.append(i) |
| 111 | l = [] |
| 112 | for i in iter(d): l.append(i) |
| 113 | verify(l == l1) |
| 114 | l = [] |
| 115 | for i in d.__iter__(): l.append(i) |
| 116 | verify(l == l1) |
| 117 | l = [] |
| 118 | for i in dictionary.__iter__(d): l.append(i) |
| 119 | verify(l == l1) |
| 120 | d = {1:2, 3:4} |
| 121 | testunop(d, 2, "len(a)", "__len__") |
| 122 | verify(eval(repr(d), {}) == d) |
| 123 | verify(eval(d.__repr__(), {}) == d) |
| 124 | testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__") |
| 125 | |
Tim Peters | 25786c0 | 2001-09-02 08:22:48 +0000 | [diff] [blame] | 126 | def dict_constructor(): |
| 127 | if verbose: |
| 128 | print "Testing dictionary constructor ..." |
| 129 | d = dictionary() |
| 130 | verify(d == {}) |
| 131 | d = dictionary({}) |
| 132 | verify(d == {}) |
| 133 | d = dictionary(mapping={}) |
| 134 | verify(d == {}) |
| 135 | d = dictionary({1: 2, 'a': 'b'}) |
| 136 | verify(d == {1: 2, 'a': 'b'}) |
| 137 | for badarg in 0, 0L, 0j, "0", [0], (0,): |
| 138 | try: |
| 139 | dictionary(badarg) |
| 140 | except TypeError: |
| 141 | pass |
| 142 | else: |
| 143 | raise TestFailed("no TypeError from dictionary(%r)" % badarg) |
| 144 | try: |
| 145 | dictionary(senseless={}) |
| 146 | except TypeError: |
| 147 | pass |
| 148 | else: |
| 149 | raise TestFailed("no TypeError from dictionary(senseless={}") |
| 150 | |
| 151 | try: |
| 152 | dictionary({}, {}) |
| 153 | except TypeError: |
| 154 | pass |
| 155 | else: |
| 156 | raise TestFailed("no TypeError from dictionary({}, {})") |
| 157 | |
| 158 | class Mapping: |
| 159 | dict = {1:2, 3:4, 'a':1j} |
| 160 | |
| 161 | def __getitem__(self, i): |
| 162 | return self.dict[i] |
| 163 | |
| 164 | try: |
| 165 | dictionary(Mapping()) |
| 166 | except TypeError: |
| 167 | pass |
| 168 | else: |
| 169 | raise TestFailed("no TypeError from dictionary(incomplete mapping)") |
| 170 | |
| 171 | Mapping.keys = lambda self: self.dict.keys() |
| 172 | d = dictionary(mapping=Mapping()) |
| 173 | verify(d == Mapping.dict) |
| 174 | |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 175 | def test_dir(): |
| 176 | if verbose: |
| 177 | print "Testing dir() ..." |
| 178 | junk = 12 |
| 179 | verify(dir() == ['junk']) |
| 180 | del junk |
| 181 | |
| 182 | # Just make sure these don't blow up! |
| 183 | for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir: |
| 184 | dir(arg) |
| 185 | |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 186 | # Try classic classes. |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 187 | class C: |
| 188 | Cdata = 1 |
| 189 | def Cmethod(self): pass |
| 190 | |
| 191 | cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__'] |
| 192 | verify(dir(C) == cstuff) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 193 | verify('im_self' in dir(C.Cmethod)) |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 194 | |
| 195 | c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__. |
| 196 | verify(dir(c) == cstuff) |
| 197 | |
| 198 | c.cdata = 2 |
| 199 | c.cmethod = lambda self: 0 |
| 200 | verify(dir(c) == cstuff + ['cdata', 'cmethod']) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 201 | verify('im_self' in dir(c.Cmethod)) |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 202 | |
| 203 | class A(C): |
| 204 | Adata = 1 |
| 205 | def Amethod(self): pass |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 206 | |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 207 | astuff = ['Adata', 'Amethod'] + cstuff |
| 208 | verify(dir(A) == astuff) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 209 | verify('im_self' in dir(A.Amethod)) |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 210 | a = A() |
| 211 | verify(dir(a) == astuff) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 212 | verify('im_self' in dir(a.Amethod)) |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 213 | a.adata = 42 |
| 214 | a.amethod = lambda self: 3 |
| 215 | verify(dir(a) == astuff + ['adata', 'amethod']) |
| 216 | |
| 217 | # The same, but with new-style classes. Since these have object as a |
| 218 | # base class, a lot more gets sucked in. |
| 219 | def interesting(strings): |
| 220 | return [s for s in strings if not s.startswith('_')] |
| 221 | |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 222 | class C(object): |
| 223 | Cdata = 1 |
| 224 | def Cmethod(self): pass |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 225 | |
| 226 | cstuff = ['Cdata', 'Cmethod'] |
| 227 | verify(interesting(dir(C)) == cstuff) |
| 228 | |
| 229 | c = C() |
| 230 | verify(interesting(dir(c)) == cstuff) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 231 | verify('im_self' in dir(C.Cmethod)) |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 232 | |
| 233 | c.cdata = 2 |
| 234 | c.cmethod = lambda self: 0 |
| 235 | verify(interesting(dir(c)) == cstuff + ['cdata', 'cmethod']) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 236 | verify('im_self' in dir(c.Cmethod)) |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 237 | |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 238 | class A(C): |
| 239 | Adata = 1 |
| 240 | def Amethod(self): pass |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 241 | |
| 242 | astuff = ['Adata', 'Amethod'] + cstuff |
| 243 | verify(interesting(dir(A)) == astuff) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 244 | verify('im_self' in dir(A.Amethod)) |
Tim Peters | 37a309d | 2001-09-04 01:20:04 +0000 | [diff] [blame] | 245 | a = A() |
| 246 | verify(interesting(dir(a)) == astuff) |
| 247 | a.adata = 42 |
| 248 | a.amethod = lambda self: 3 |
| 249 | verify(interesting(dir(a)) == astuff + ['adata', 'amethod']) |
Tim Peters | 305b585 | 2001-09-17 02:38:46 +0000 | [diff] [blame] | 250 | verify('im_self' in dir(a.Amethod)) |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 251 | |
Tim Peters | caaff8d | 2001-09-10 23:12:14 +0000 | [diff] [blame] | 252 | # Try a module subclass. |
| 253 | import sys |
| 254 | class M(type(sys)): |
| 255 | pass |
| 256 | minstance = M() |
| 257 | minstance.b = 2 |
| 258 | minstance.a = 1 |
| 259 | verify(dir(minstance) == ['a', 'b']) |
| 260 | |
| 261 | class M2(M): |
| 262 | def getdict(self): |
| 263 | return "Not a dict!" |
| 264 | __dict__ = property(getdict) |
| 265 | |
| 266 | m2instance = M2() |
| 267 | m2instance.b = 2 |
| 268 | m2instance.a = 1 |
| 269 | verify(m2instance.__dict__ == "Not a dict!") |
| 270 | try: |
| 271 | dir(m2instance) |
| 272 | except TypeError: |
| 273 | pass |
| 274 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 275 | binops = { |
| 276 | 'add': '+', |
| 277 | 'sub': '-', |
| 278 | 'mul': '*', |
| 279 | 'div': '/', |
| 280 | 'mod': '%', |
| 281 | 'divmod': 'divmod', |
| 282 | 'pow': '**', |
| 283 | 'lshift': '<<', |
| 284 | 'rshift': '>>', |
| 285 | 'and': '&', |
| 286 | 'xor': '^', |
| 287 | 'or': '|', |
| 288 | 'cmp': 'cmp', |
| 289 | 'lt': '<', |
| 290 | 'le': '<=', |
| 291 | 'eq': '==', |
| 292 | 'ne': '!=', |
| 293 | 'gt': '>', |
| 294 | 'ge': '>=', |
| 295 | } |
| 296 | |
| 297 | for name, expr in binops.items(): |
| 298 | if expr.islower(): |
| 299 | expr = expr + "(a, b)" |
| 300 | else: |
| 301 | expr = 'a %s b' % expr |
| 302 | binops[name] = expr |
| 303 | |
| 304 | unops = { |
| 305 | 'pos': '+', |
| 306 | 'neg': '-', |
| 307 | 'abs': 'abs', |
| 308 | 'invert': '~', |
| 309 | 'int': 'int', |
| 310 | 'long': 'long', |
| 311 | 'float': 'float', |
| 312 | 'oct': 'oct', |
| 313 | 'hex': 'hex', |
| 314 | } |
| 315 | |
| 316 | for name, expr in unops.items(): |
| 317 | if expr.islower(): |
| 318 | expr = expr + "(a)" |
| 319 | else: |
| 320 | expr = '%s a' % expr |
| 321 | unops[name] = expr |
| 322 | |
| 323 | def numops(a, b, skip=[]): |
| 324 | dict = {'a': a, 'b': b} |
| 325 | for name, expr in binops.items(): |
| 326 | if name not in skip: |
| 327 | name = "__%s__" % name |
| 328 | if hasattr(a, name): |
| 329 | res = eval(expr, dict) |
| 330 | testbinop(a, b, res, expr, name) |
| 331 | for name, expr in unops.items(): |
| 332 | name = "__%s__" % name |
| 333 | if hasattr(a, name): |
| 334 | res = eval(expr, dict) |
| 335 | testunop(a, res, expr, name) |
| 336 | |
| 337 | def ints(): |
| 338 | if verbose: print "Testing int operations..." |
| 339 | numops(100, 3) |
| 340 | |
| 341 | def longs(): |
| 342 | if verbose: print "Testing long operations..." |
| 343 | numops(100L, 3L) |
| 344 | |
| 345 | def floats(): |
| 346 | if verbose: print "Testing float operations..." |
| 347 | numops(100.0, 3.0) |
| 348 | |
| 349 | def complexes(): |
| 350 | if verbose: print "Testing complex operations..." |
| 351 | numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge']) |
| 352 | class Number(complex): |
| 353 | __slots__ = ['prec'] |
Tim Peters | 3f996e7 | 2001-09-13 19:18:27 +0000 | [diff] [blame] | 354 | def __new__(cls, *args, **kwds): |
| 355 | result = complex.__new__(cls, *args) |
| 356 | result.prec = kwds.get('prec', 12) |
| 357 | return result |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 358 | def __repr__(self): |
| 359 | prec = self.prec |
| 360 | if self.imag == 0.0: |
| 361 | return "%.*g" % (prec, self.real) |
| 362 | if self.real == 0.0: |
| 363 | return "%.*gj" % (prec, self.imag) |
| 364 | return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) |
| 365 | __str__ = __repr__ |
Tim Peters | 3f996e7 | 2001-09-13 19:18:27 +0000 | [diff] [blame] | 366 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 367 | a = Number(3.14, prec=6) |
| 368 | verify(`a` == "3.14") |
| 369 | verify(a.prec == 6) |
| 370 | |
Tim Peters | 3f996e7 | 2001-09-13 19:18:27 +0000 | [diff] [blame] | 371 | a = Number(a, prec=2) |
| 372 | verify(`a` == "3.1") |
| 373 | verify(a.prec == 2) |
| 374 | |
| 375 | a = Number(234.5) |
| 376 | verify(`a` == "234.5") |
| 377 | verify(a.prec == 12) |
| 378 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 379 | def spamlists(): |
| 380 | if verbose: print "Testing spamlist operations..." |
| 381 | import copy, xxsubtype as spam |
| 382 | def spamlist(l, memo=None): |
| 383 | import xxsubtype as spam |
| 384 | return spam.spamlist(l) |
| 385 | # This is an ugly hack: |
| 386 | copy._deepcopy_dispatch[spam.spamlist] = spamlist |
| 387 | |
| 388 | testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__") |
| 389 | testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") |
| 390 | testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") |
| 391 | testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") |
| 392 | testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]), |
| 393 | "a[b:c]", "__getslice__") |
| 394 | testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]), |
| 395 | "a+=b", "__iadd__") |
| 396 | testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__") |
| 397 | testunop(spamlist([1,2,3]), 3, "len(a)", "__len__") |
| 398 | testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__") |
| 399 | testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__") |
| 400 | testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__") |
| 401 | testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), |
| 402 | spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__") |
| 403 | # Test subclassing |
| 404 | class C(spam.spamlist): |
| 405 | def foo(self): return 1 |
| 406 | a = C() |
| 407 | verify(a == []) |
| 408 | verify(a.foo() == 1) |
| 409 | a.append(100) |
| 410 | verify(a == [100]) |
| 411 | verify(a.getstate() == 0) |
| 412 | a.setstate(42) |
| 413 | verify(a.getstate() == 42) |
| 414 | |
| 415 | def spamdicts(): |
| 416 | if verbose: print "Testing spamdict operations..." |
| 417 | import copy, xxsubtype as spam |
| 418 | def spamdict(d, memo=None): |
| 419 | import xxsubtype as spam |
| 420 | sd = spam.spamdict() |
| 421 | for k, v in d.items(): sd[k] = v |
| 422 | return sd |
| 423 | # This is an ugly hack: |
| 424 | copy._deepcopy_dispatch[spam.spamdict] = spamdict |
| 425 | |
| 426 | testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") |
| 427 | testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") |
| 428 | testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") |
| 429 | testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") |
| 430 | d = spamdict({1:2,3:4}) |
| 431 | l1 = [] |
| 432 | for i in d.keys(): l1.append(i) |
| 433 | l = [] |
| 434 | for i in iter(d): l.append(i) |
| 435 | verify(l == l1) |
| 436 | l = [] |
| 437 | for i in d.__iter__(): l.append(i) |
| 438 | verify(l == l1) |
| 439 | l = [] |
| 440 | for i in type(spamdict({})).__iter__(d): l.append(i) |
| 441 | verify(l == l1) |
| 442 | straightd = {1:2, 3:4} |
| 443 | spamd = spamdict(straightd) |
| 444 | testunop(spamd, 2, "len(a)", "__len__") |
| 445 | testunop(spamd, repr(straightd), "repr(a)", "__repr__") |
| 446 | testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), |
| 447 | "a[b]=c", "__setitem__") |
| 448 | # Test subclassing |
| 449 | class C(spam.spamdict): |
| 450 | def foo(self): return 1 |
| 451 | a = C() |
| 452 | verify(a.items() == []) |
| 453 | verify(a.foo() == 1) |
| 454 | a['foo'] = 'bar' |
| 455 | verify(a.items() == [('foo', 'bar')]) |
| 456 | verify(a.getstate() == 0) |
| 457 | a.setstate(100) |
| 458 | verify(a.getstate() == 100) |
| 459 | |
| 460 | def pydicts(): |
| 461 | if verbose: print "Testing Python subclass of dict..." |
| 462 | verify(issubclass(dictionary, dictionary)) |
| 463 | verify(isinstance({}, dictionary)) |
| 464 | d = dictionary() |
| 465 | verify(d == {}) |
| 466 | verify(d.__class__ is dictionary) |
| 467 | verify(isinstance(d, dictionary)) |
| 468 | class C(dictionary): |
| 469 | state = -1 |
| 470 | def __init__(self, *a, **kw): |
| 471 | if a: |
| 472 | assert len(a) == 1 |
| 473 | self.state = a[0] |
| 474 | if kw: |
| 475 | for k, v in kw.items(): self[v] = k |
| 476 | def __getitem__(self, key): |
| 477 | return self.get(key, 0) |
| 478 | def __setitem__(self, key, value): |
| 479 | assert isinstance(key, type(0)) |
| 480 | dictionary.__setitem__(self, key, value) |
| 481 | def setstate(self, state): |
| 482 | self.state = state |
| 483 | def getstate(self): |
| 484 | return self.state |
| 485 | verify(issubclass(C, dictionary)) |
| 486 | a1 = C(12) |
| 487 | verify(a1.state == 12) |
| 488 | a2 = C(foo=1, bar=2) |
| 489 | verify(a2[1] == 'foo' and a2[2] == 'bar') |
| 490 | a = C() |
| 491 | verify(a.state == -1) |
| 492 | verify(a.getstate() == -1) |
| 493 | a.setstate(0) |
| 494 | verify(a.state == 0) |
| 495 | verify(a.getstate() == 0) |
| 496 | a.setstate(10) |
| 497 | verify(a.state == 10) |
| 498 | verify(a.getstate() == 10) |
| 499 | verify(a[42] == 0) |
| 500 | a[42] = 24 |
| 501 | verify(a[42] == 24) |
| 502 | if verbose: print "pydict stress test ..." |
| 503 | N = 50 |
| 504 | for i in range(N): |
| 505 | a[i] = C() |
| 506 | for j in range(N): |
| 507 | a[i][j] = i*j |
| 508 | for i in range(N): |
| 509 | for j in range(N): |
| 510 | verify(a[i][j] == i*j) |
| 511 | |
| 512 | def pylists(): |
| 513 | if verbose: print "Testing Python subclass of list..." |
| 514 | class C(list): |
| 515 | def __getitem__(self, i): |
| 516 | return list.__getitem__(self, i) + 100 |
| 517 | def __getslice__(self, i, j): |
| 518 | return (i, j) |
| 519 | a = C() |
| 520 | a.extend([0,1,2]) |
| 521 | verify(a[0] == 100) |
| 522 | verify(a[1] == 101) |
| 523 | verify(a[2] == 102) |
| 524 | verify(a[100:200] == (100,200)) |
| 525 | |
| 526 | def metaclass(): |
| 527 | if verbose: print "Testing __metaclass__..." |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 528 | class C: |
| 529 | __metaclass__ = type |
| 530 | def __init__(self): |
| 531 | self.__state = 0 |
| 532 | def getstate(self): |
| 533 | return self.__state |
| 534 | def setstate(self, state): |
| 535 | self.__state = state |
| 536 | a = C() |
| 537 | verify(a.getstate() == 0) |
| 538 | a.setstate(10) |
| 539 | verify(a.getstate() == 10) |
| 540 | class D: |
| 541 | class __metaclass__(type): |
| 542 | def myself(cls): return cls |
| 543 | verify(D.myself() == D) |
Guido van Rossum | 309b566 | 2001-08-17 11:43:17 +0000 | [diff] [blame] | 544 | d = D() |
| 545 | verify(d.__class__ is D) |
| 546 | class M1(type): |
| 547 | def __new__(cls, name, bases, dict): |
| 548 | dict['__spam__'] = 1 |
| 549 | return type.__new__(cls, name, bases, dict) |
| 550 | class C: |
| 551 | __metaclass__ = M1 |
| 552 | verify(C.__spam__ == 1) |
| 553 | c = C() |
| 554 | verify(c.__spam__ == 1) |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 555 | |
Guido van Rossum | 309b566 | 2001-08-17 11:43:17 +0000 | [diff] [blame] | 556 | class _instance(object): |
| 557 | pass |
| 558 | class M2(object): |
| 559 | def __new__(cls, name, bases, dict): |
| 560 | self = object.__new__(cls) |
| 561 | self.name = name |
| 562 | self.bases = bases |
| 563 | self.dict = dict |
| 564 | return self |
| 565 | __new__ = staticmethod(__new__) |
| 566 | def __call__(self): |
| 567 | it = _instance() |
Guido van Rossum | 7e1ff69 | 2001-08-17 11:55:58 +0000 | [diff] [blame] | 568 | # Early binding of methods |
| 569 | for key in self.dict: |
| 570 | if key.startswith("__"): |
| 571 | continue |
| 572 | setattr(it, key, self.dict[key].__get__(it, self)) |
Guido van Rossum | 309b566 | 2001-08-17 11:43:17 +0000 | [diff] [blame] | 573 | return it |
| 574 | class C: |
| 575 | __metaclass__ = M2 |
| 576 | def spam(self): |
| 577 | return 42 |
| 578 | verify(C.name == 'C') |
| 579 | verify(C.bases == ()) |
| 580 | verify('spam' in C.dict) |
| 581 | c = C() |
Guido van Rossum | 7e1ff69 | 2001-08-17 11:55:58 +0000 | [diff] [blame] | 582 | verify(c.spam() == 42) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 583 | |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 584 | # More metaclass examples |
| 585 | |
| 586 | class autosuper(type): |
| 587 | # Automatically add __super to the class |
| 588 | # This trick only works for dynamic classes |
| 589 | # so we force __dynamic__ = 1 |
| 590 | def __new__(metaclass, name, bases, dict): |
| 591 | # XXX Should check that name isn't already a base class name |
| 592 | dict["__dynamic__"] = 1 |
| 593 | cls = super(autosuper, metaclass).__new__(metaclass, |
| 594 | name, bases, dict) |
Guido van Rossum | bfa47b0 | 2001-08-31 04:35:14 +0000 | [diff] [blame] | 595 | # Name mangling for __super removes leading underscores |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 596 | while name[:1] == "_": |
| 597 | name = name[1:] |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 598 | if name: |
| 599 | name = "_%s__super" % name |
| 600 | else: |
| 601 | name = "__super" |
| 602 | setattr(cls, name, super(cls)) |
| 603 | return cls |
| 604 | class A: |
| 605 | __metaclass__ = autosuper |
| 606 | def meth(self): |
| 607 | return "A" |
| 608 | class B(A): |
| 609 | def meth(self): |
| 610 | return "B" + self.__super.meth() |
| 611 | class C(A): |
| 612 | def meth(self): |
| 613 | return "C" + self.__super.meth() |
| 614 | class D(C, B): |
| 615 | def meth(self): |
| 616 | return "D" + self.__super.meth() |
| 617 | verify(D().meth() == "DCBA") |
| 618 | class E(B, C): |
| 619 | def meth(self): |
| 620 | return "E" + self.__super.meth() |
| 621 | verify(E().meth() == "EBCA") |
| 622 | |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 623 | class autoproperty(type): |
| 624 | # Automatically create property attributes when methods |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 625 | # named _get_x and/or _set_x are found |
| 626 | def __new__(metaclass, name, bases, dict): |
| 627 | hits = {} |
| 628 | for key, val in dict.iteritems(): |
| 629 | if key.startswith("_get_"): |
| 630 | key = key[5:] |
| 631 | get, set = hits.get(key, (None, None)) |
| 632 | get = val |
| 633 | hits[key] = get, set |
| 634 | elif key.startswith("_set_"): |
| 635 | key = key[5:] |
| 636 | get, set = hits.get(key, (None, None)) |
| 637 | set = val |
| 638 | hits[key] = get, set |
| 639 | for key, (get, set) in hits.iteritems(): |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 640 | dict[key] = property(get, set) |
| 641 | return super(autoproperty, metaclass).__new__(metaclass, |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 642 | name, bases, dict) |
| 643 | class A: |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 644 | __metaclass__ = autoproperty |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 645 | def _get_x(self): |
| 646 | return -self.__x |
| 647 | def _set_x(self, x): |
| 648 | self.__x = -x |
| 649 | a = A() |
| 650 | verify(not hasattr(a, "x")) |
| 651 | a.x = 12 |
| 652 | verify(a.x == 12) |
| 653 | verify(a._A__x == -12) |
| 654 | |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 655 | class multimetaclass(autoproperty, autosuper): |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 656 | # Merge of multiple cooperating metaclasses |
| 657 | pass |
| 658 | class A: |
| 659 | __metaclass__ = multimetaclass |
| 660 | def _get_x(self): |
| 661 | return "A" |
| 662 | class B(A): |
| 663 | def _get_x(self): |
| 664 | return "B" + self.__super._get_x() |
| 665 | class C(A): |
| 666 | def _get_x(self): |
| 667 | return "C" + self.__super._get_x() |
| 668 | class D(C, B): |
| 669 | def _get_x(self): |
| 670 | return "D" + self.__super._get_x() |
| 671 | verify(D().x == "DCBA") |
| 672 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 673 | def pymods(): |
| 674 | if verbose: print "Testing Python subclass of module..." |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 675 | log = [] |
Guido van Rossum | d307740 | 2001-08-12 05:24:18 +0000 | [diff] [blame] | 676 | import sys |
| 677 | MT = type(sys) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 678 | class MM(MT): |
| 679 | def __init__(self): |
| 680 | MT.__init__(self) |
Guido van Rossum | 867a8d2 | 2001-09-21 19:29:08 +0000 | [diff] [blame] | 681 | def __getattribute__(self, name): |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 682 | log.append(("getattr", name)) |
Guido van Rossum | 867a8d2 | 2001-09-21 19:29:08 +0000 | [diff] [blame] | 683 | return MT.__getattribute__(self, name) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 684 | def __setattr__(self, name, value): |
| 685 | log.append(("setattr", name, value)) |
| 686 | MT.__setattr__(self, name, value) |
| 687 | def __delattr__(self, name): |
| 688 | log.append(("delattr", name)) |
| 689 | MT.__delattr__(self, name) |
| 690 | a = MM() |
| 691 | a.foo = 12 |
| 692 | x = a.foo |
| 693 | del a.foo |
Guido van Rossum | ce129a5 | 2001-08-28 18:23:24 +0000 | [diff] [blame] | 694 | verify(log == [("setattr", "foo", 12), |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 695 | ("getattr", "foo"), |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 696 | ("delattr", "foo")], log) |
| 697 | |
| 698 | def multi(): |
| 699 | if verbose: print "Testing multiple inheritance..." |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 700 | class C(object): |
| 701 | def __init__(self): |
| 702 | self.__state = 0 |
| 703 | def getstate(self): |
| 704 | return self.__state |
| 705 | def setstate(self, state): |
| 706 | self.__state = state |
| 707 | a = C() |
| 708 | verify(a.getstate() == 0) |
| 709 | a.setstate(10) |
| 710 | verify(a.getstate() == 10) |
| 711 | class D(dictionary, C): |
| 712 | def __init__(self): |
| 713 | type({}).__init__(self) |
| 714 | C.__init__(self) |
| 715 | d = D() |
| 716 | verify(d.keys() == []) |
| 717 | d["hello"] = "world" |
| 718 | verify(d.items() == [("hello", "world")]) |
| 719 | verify(d["hello"] == "world") |
| 720 | verify(d.getstate() == 0) |
| 721 | d.setstate(10) |
| 722 | verify(d.getstate() == 10) |
| 723 | verify(D.__mro__ == (D, dictionary, C, object)) |
| 724 | |
Guido van Rossum | e45763a | 2001-08-10 21:28:46 +0000 | [diff] [blame] | 725 | # SF bug #442833 |
| 726 | class Node(object): |
| 727 | def __int__(self): |
| 728 | return int(self.foo()) |
| 729 | def foo(self): |
| 730 | return "23" |
| 731 | class Frag(Node, list): |
| 732 | def foo(self): |
| 733 | return "42" |
| 734 | verify(Node().__int__() == 23) |
| 735 | verify(int(Node()) == 23) |
| 736 | verify(Frag().__int__() == 42) |
| 737 | verify(int(Frag()) == 42) |
| 738 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 739 | def diamond(): |
| 740 | if verbose: print "Testing multiple inheritance special cases..." |
| 741 | class A(object): |
| 742 | def spam(self): return "A" |
| 743 | verify(A().spam() == "A") |
| 744 | class B(A): |
| 745 | def boo(self): return "B" |
| 746 | def spam(self): return "B" |
| 747 | verify(B().spam() == "B") |
| 748 | verify(B().boo() == "B") |
| 749 | class C(A): |
| 750 | def boo(self): return "C" |
| 751 | verify(C().spam() == "A") |
| 752 | verify(C().boo() == "C") |
| 753 | class D(B, C): pass |
| 754 | verify(D().spam() == "B") |
| 755 | verify(D().boo() == "B") |
| 756 | verify(D.__mro__ == (D, B, C, A, object)) |
| 757 | class E(C, B): pass |
| 758 | verify(E().spam() == "B") |
| 759 | verify(E().boo() == "C") |
| 760 | verify(E.__mro__ == (E, C, B, A, object)) |
| 761 | class F(D, E): pass |
| 762 | verify(F().spam() == "B") |
| 763 | verify(F().boo() == "B") |
| 764 | verify(F.__mro__ == (F, D, E, B, C, A, object)) |
| 765 | class G(E, D): pass |
| 766 | verify(G().spam() == "B") |
| 767 | verify(G().boo() == "C") |
| 768 | verify(G.__mro__ == (G, E, D, C, B, A, object)) |
| 769 | |
Guido van Rossum | 3720261 | 2001-08-09 19:45:21 +0000 | [diff] [blame] | 770 | def objects(): |
| 771 | if verbose: print "Testing object class..." |
| 772 | a = object() |
| 773 | verify(a.__class__ == object == type(a)) |
| 774 | b = object() |
| 775 | verify(a is not b) |
| 776 | verify(not hasattr(a, "foo")) |
| 777 | try: |
| 778 | a.foo = 12 |
Guido van Rossum | 6d94627 | 2001-08-10 19:42:38 +0000 | [diff] [blame] | 779 | except (AttributeError, TypeError): |
Guido van Rossum | 3720261 | 2001-08-09 19:45:21 +0000 | [diff] [blame] | 780 | pass |
| 781 | else: |
| 782 | verify(0, "object() should not allow setting a foo attribute") |
| 783 | verify(not hasattr(object(), "__dict__")) |
| 784 | |
| 785 | class Cdict(object): |
| 786 | pass |
| 787 | x = Cdict() |
| 788 | verify(x.__dict__ is None) |
| 789 | x.foo = 1 |
| 790 | verify(x.foo == 1) |
| 791 | verify(x.__dict__ == {'foo': 1}) |
| 792 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 793 | def slots(): |
| 794 | if verbose: print "Testing __slots__..." |
| 795 | class C0(object): |
| 796 | __slots__ = [] |
| 797 | x = C0() |
| 798 | verify(not hasattr(x, "__dict__")) |
| 799 | verify(not hasattr(x, "foo")) |
| 800 | |
| 801 | class C1(object): |
| 802 | __slots__ = ['a'] |
| 803 | x = C1() |
| 804 | verify(not hasattr(x, "__dict__")) |
| 805 | verify(x.a == None) |
| 806 | x.a = 1 |
| 807 | verify(x.a == 1) |
| 808 | del x.a |
| 809 | verify(x.a == None) |
| 810 | |
| 811 | class C3(object): |
| 812 | __slots__ = ['a', 'b', 'c'] |
| 813 | x = C3() |
| 814 | verify(not hasattr(x, "__dict__")) |
| 815 | verify(x.a is None) |
| 816 | verify(x.b is None) |
| 817 | verify(x.c is None) |
| 818 | x.a = 1 |
| 819 | x.b = 2 |
| 820 | x.c = 3 |
| 821 | verify(x.a == 1) |
| 822 | verify(x.b == 2) |
| 823 | verify(x.c == 3) |
| 824 | |
| 825 | def dynamics(): |
| 826 | if verbose: print "Testing __dynamic__..." |
| 827 | verify(object.__dynamic__ == 0) |
| 828 | verify(list.__dynamic__ == 0) |
| 829 | class S1: |
| 830 | __metaclass__ = type |
| 831 | verify(S1.__dynamic__ == 0) |
| 832 | class S(object): |
| 833 | pass |
Guido van Rossum | 9d4fe42 | 2001-08-12 03:38:18 +0000 | [diff] [blame] | 834 | verify(S.__dynamic__ == 0) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 835 | class D(object): |
| 836 | __dynamic__ = 1 |
| 837 | verify(D.__dynamic__ == 1) |
| 838 | class E(D, S): |
| 839 | pass |
| 840 | verify(E.__dynamic__ == 1) |
| 841 | class F(S, D): |
| 842 | pass |
| 843 | verify(F.__dynamic__ == 1) |
| 844 | try: |
| 845 | S.foo = 1 |
| 846 | except (AttributeError, TypeError): |
| 847 | pass |
| 848 | else: |
| 849 | verify(0, "assignment to a static class attribute should be illegal") |
| 850 | D.foo = 1 |
| 851 | verify(D.foo == 1) |
| 852 | # Test that dynamic attributes are inherited |
| 853 | verify(E.foo == 1) |
| 854 | verify(F.foo == 1) |
| 855 | class SS(D): |
| 856 | __dynamic__ = 0 |
| 857 | verify(SS.__dynamic__ == 0) |
| 858 | verify(SS.foo == 1) |
| 859 | try: |
| 860 | SS.foo = 1 |
| 861 | except (AttributeError, TypeError): |
| 862 | pass |
| 863 | else: |
| 864 | verify(0, "assignment to SS.foo should be illegal") |
Guido van Rossum | 9d4fe42 | 2001-08-12 03:38:18 +0000 | [diff] [blame] | 865 | # Test dynamic instances |
| 866 | class C(object): |
| 867 | __dynamic__ = 1 |
Guido van Rossum | 9d4fe42 | 2001-08-12 03:38:18 +0000 | [diff] [blame] | 868 | a = C() |
Guido van Rossum | d307740 | 2001-08-12 05:24:18 +0000 | [diff] [blame] | 869 | verify(not hasattr(a, "foobar")) |
Guido van Rossum | 9d4fe42 | 2001-08-12 03:38:18 +0000 | [diff] [blame] | 870 | C.foobar = 2 |
| 871 | verify(a.foobar == 2) |
| 872 | C.method = lambda self: 42 |
| 873 | verify(a.method() == 42) |
Guido van Rossum | 9d4fe42 | 2001-08-12 03:38:18 +0000 | [diff] [blame] | 874 | C.__repr__ = lambda self: "C()" |
| 875 | verify(repr(a) == "C()") |
Guido van Rossum | d307740 | 2001-08-12 05:24:18 +0000 | [diff] [blame] | 876 | C.__int__ = lambda self: 100 |
| 877 | verify(int(a) == 100) |
| 878 | verify(a.foobar == 2) |
| 879 | verify(not hasattr(a, "spam")) |
| 880 | def mygetattr(self, name): |
| 881 | if name == "spam": |
| 882 | return "spam" |
Guido van Rossum | 19c1cd5 | 2001-09-21 21:24:49 +0000 | [diff] [blame] | 883 | raise AttributeError |
| 884 | C.__getattr__ = mygetattr |
Guido van Rossum | d307740 | 2001-08-12 05:24:18 +0000 | [diff] [blame] | 885 | verify(a.spam == "spam") |
| 886 | a.new = 12 |
| 887 | verify(a.new == 12) |
| 888 | def mysetattr(self, name, value): |
| 889 | if name == "spam": |
| 890 | raise AttributeError |
| 891 | return object.__setattr__(self, name, value) |
| 892 | C.__setattr__ = mysetattr |
| 893 | try: |
| 894 | a.spam = "not spam" |
| 895 | except AttributeError: |
| 896 | pass |
| 897 | else: |
| 898 | verify(0, "expected AttributeError") |
| 899 | verify(a.spam == "spam") |
Guido van Rossum | 80e3675 | 2001-08-14 20:00:33 +0000 | [diff] [blame] | 900 | class D(C): |
| 901 | pass |
| 902 | d = D() |
| 903 | d.foo = 1 |
| 904 | verify(d.foo == 1) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 905 | |
Guido van Rossum | 7e35d57 | 2001-09-15 03:14:32 +0000 | [diff] [blame] | 906 | # Test handling of int*seq and seq*int |
| 907 | class I(int): |
| 908 | __dynamic__ = 1 |
| 909 | verify("a"*I(2) == "aa") |
| 910 | verify(I(2)*"a" == "aa") |
Tim Peters | e000782 | 2001-09-15 06:35:55 +0000 | [diff] [blame] | 911 | verify(2*I(3) == 6) |
| 912 | verify(I(3)*2 == 6) |
| 913 | verify(I(3)*I(2) == 6) |
Guido van Rossum | 7e35d57 | 2001-09-15 03:14:32 +0000 | [diff] [blame] | 914 | |
| 915 | # Test handling of long*seq and seq*long |
| 916 | class L(long): |
| 917 | __dynamic__ = 1 |
| 918 | verify("a"*L(2L) == "aa") |
| 919 | verify(L(2L)*"a" == "aa") |
Tim Peters | e000782 | 2001-09-15 06:35:55 +0000 | [diff] [blame] | 920 | verify(2*L(3) == 6) |
| 921 | verify(L(3)*2 == 6) |
| 922 | verify(L(3)*L(2) == 6) |
Guido van Rossum | 7e35d57 | 2001-09-15 03:14:32 +0000 | [diff] [blame] | 923 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 924 | def errors(): |
| 925 | if verbose: print "Testing errors..." |
| 926 | |
| 927 | try: |
| 928 | class C(list, dictionary): |
| 929 | pass |
| 930 | except TypeError: |
| 931 | pass |
| 932 | else: |
| 933 | verify(0, "inheritance from both list and dict should be illegal") |
| 934 | |
| 935 | try: |
| 936 | class C(object, None): |
| 937 | pass |
| 938 | except TypeError: |
| 939 | pass |
| 940 | else: |
| 941 | verify(0, "inheritance from non-type should be illegal") |
| 942 | class Classic: |
| 943 | pass |
| 944 | |
| 945 | try: |
| 946 | class C(object, Classic): |
| 947 | pass |
| 948 | except TypeError: |
| 949 | pass |
| 950 | else: |
| 951 | verify(0, "inheritance from object and Classic should be illegal") |
| 952 | |
| 953 | try: |
Guido van Rossum | 8aea0cc | 2001-08-29 15:48:43 +0000 | [diff] [blame] | 954 | class C(type(len)): |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 955 | pass |
| 956 | except TypeError: |
| 957 | pass |
| 958 | else: |
Guido van Rossum | 8aea0cc | 2001-08-29 15:48:43 +0000 | [diff] [blame] | 959 | verify(0, "inheritance from CFunction should be illegal") |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 960 | |
| 961 | try: |
| 962 | class C(object): |
| 963 | __slots__ = 1 |
| 964 | except TypeError: |
| 965 | pass |
| 966 | else: |
| 967 | verify(0, "__slots__ = 1 should be illegal") |
| 968 | |
| 969 | try: |
| 970 | class C(object): |
| 971 | __slots__ = [1] |
| 972 | except TypeError: |
| 973 | pass |
| 974 | else: |
| 975 | verify(0, "__slots__ = [1] should be illegal") |
| 976 | |
| 977 | def classmethods(): |
| 978 | if verbose: print "Testing class methods..." |
| 979 | class C(object): |
| 980 | def foo(*a): return a |
| 981 | goo = classmethod(foo) |
| 982 | c = C() |
| 983 | verify(C.goo(1) == (C, 1)) |
| 984 | verify(c.goo(1) == (C, 1)) |
| 985 | verify(c.foo(1) == (c, 1)) |
| 986 | class D(C): |
| 987 | pass |
| 988 | d = D() |
| 989 | verify(D.goo(1) == (D, 1)) |
| 990 | verify(d.goo(1) == (D, 1)) |
| 991 | verify(d.foo(1) == (d, 1)) |
| 992 | verify(D.foo(d, 1) == (d, 1)) |
| 993 | |
| 994 | def staticmethods(): |
| 995 | if verbose: print "Testing static methods..." |
| 996 | class C(object): |
| 997 | def foo(*a): return a |
| 998 | goo = staticmethod(foo) |
| 999 | c = C() |
| 1000 | verify(C.goo(1) == (1,)) |
| 1001 | verify(c.goo(1) == (1,)) |
| 1002 | verify(c.foo(1) == (c, 1,)) |
| 1003 | class D(C): |
| 1004 | pass |
| 1005 | d = D() |
| 1006 | verify(D.goo(1) == (1,)) |
| 1007 | verify(d.goo(1) == (1,)) |
| 1008 | verify(d.foo(1) == (d, 1)) |
| 1009 | verify(D.foo(d, 1) == (d, 1)) |
| 1010 | |
| 1011 | def classic(): |
| 1012 | if verbose: print "Testing classic classes..." |
| 1013 | class C: |
| 1014 | def foo(*a): return a |
| 1015 | goo = classmethod(foo) |
| 1016 | c = C() |
| 1017 | verify(C.goo(1) == (C, 1)) |
| 1018 | verify(c.goo(1) == (C, 1)) |
| 1019 | verify(c.foo(1) == (c, 1)) |
| 1020 | class D(C): |
| 1021 | pass |
| 1022 | d = D() |
| 1023 | verify(D.goo(1) == (D, 1)) |
| 1024 | verify(d.goo(1) == (D, 1)) |
| 1025 | verify(d.foo(1) == (d, 1)) |
| 1026 | verify(D.foo(d, 1) == (d, 1)) |
Guido van Rossum | 9301876 | 2001-08-17 13:40:47 +0000 | [diff] [blame] | 1027 | class E: # *not* subclassing from C |
| 1028 | foo = C.foo |
| 1029 | verify(E().foo == C.foo) # i.e., unbound |
Guido van Rossum | 84a79a8 | 2001-08-17 13:58:31 +0000 | [diff] [blame] | 1030 | verify(repr(C.foo.__get__(C())).startswith("<bound method ")) |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1031 | |
| 1032 | def compattr(): |
| 1033 | if verbose: print "Testing computed attributes..." |
| 1034 | class C(object): |
| 1035 | class computed_attribute(object): |
| 1036 | def __init__(self, get, set=None): |
| 1037 | self.__get = get |
| 1038 | self.__set = set |
| 1039 | def __get__(self, obj, type=None): |
| 1040 | return self.__get(obj) |
| 1041 | def __set__(self, obj, value): |
| 1042 | return self.__set(obj, value) |
| 1043 | def __init__(self): |
| 1044 | self.__x = 0 |
| 1045 | def __get_x(self): |
| 1046 | x = self.__x |
| 1047 | self.__x = x+1 |
| 1048 | return x |
| 1049 | def __set_x(self, x): |
| 1050 | self.__x = x |
| 1051 | x = computed_attribute(__get_x, __set_x) |
| 1052 | a = C() |
| 1053 | verify(a.x == 0) |
| 1054 | verify(a.x == 1) |
| 1055 | a.x = 10 |
| 1056 | verify(a.x == 10) |
| 1057 | verify(a.x == 11) |
| 1058 | |
| 1059 | def newslot(): |
| 1060 | if verbose: print "Testing __new__ slot override..." |
| 1061 | class C(list): |
| 1062 | def __new__(cls): |
| 1063 | self = list.__new__(cls) |
| 1064 | self.foo = 1 |
| 1065 | return self |
| 1066 | def __init__(self): |
| 1067 | self.foo = self.foo + 2 |
| 1068 | a = C() |
| 1069 | verify(a.foo == 3) |
| 1070 | verify(a.__class__ is C) |
| 1071 | class D(C): |
| 1072 | pass |
| 1073 | b = D() |
| 1074 | verify(b.foo == 3) |
| 1075 | verify(b.__class__ is D) |
| 1076 | |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1077 | def altmro(): |
| 1078 | if verbose: print "Testing mro() and overriding it..." |
| 1079 | class A(object): |
| 1080 | def f(self): return "A" |
| 1081 | class B(A): |
| 1082 | pass |
| 1083 | class C(A): |
| 1084 | def f(self): return "C" |
| 1085 | class D(B, C): |
| 1086 | pass |
| 1087 | verify(D.mro() == [D, B, C, A, object] == list(D.__mro__)) |
| 1088 | verify(D().f() == "C") |
Guido van Rossum | d307740 | 2001-08-12 05:24:18 +0000 | [diff] [blame] | 1089 | class PerverseMetaType(type): |
| 1090 | def mro(cls): |
| 1091 | L = type.mro(cls) |
| 1092 | L.reverse() |
| 1093 | return L |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1094 | class X(A,B,C,D): |
| 1095 | __metaclass__ = PerverseMetaType |
| 1096 | verify(X.__mro__ == (object, A, C, B, D, X)) |
| 1097 | verify(X().f() == "A") |
| 1098 | |
| 1099 | def overloading(): |
Guido van Rossum | 65d5d7f | 2001-08-17 21:27:53 +0000 | [diff] [blame] | 1100 | if verbose: print "Testing operator overloading..." |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1101 | |
| 1102 | class B(object): |
| 1103 | "Intermediate class because object doesn't have a __setattr__" |
| 1104 | |
| 1105 | class C(B): |
| 1106 | |
Guido van Rossum | 19c1cd5 | 2001-09-21 21:24:49 +0000 | [diff] [blame] | 1107 | def __getattr__(self, name): |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1108 | if name == "foo": |
| 1109 | return ("getattr", name) |
| 1110 | else: |
Guido van Rossum | 19c1cd5 | 2001-09-21 21:24:49 +0000 | [diff] [blame] | 1111 | raise AttributeError |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1112 | def __setattr__(self, name, value): |
| 1113 | if name == "foo": |
| 1114 | self.setattr = (name, value) |
| 1115 | else: |
| 1116 | return B.__setattr__(self, name, value) |
| 1117 | def __delattr__(self, name): |
| 1118 | if name == "foo": |
| 1119 | self.delattr = name |
| 1120 | else: |
| 1121 | return B.__delattr__(self, name) |
| 1122 | |
| 1123 | def __getitem__(self, key): |
| 1124 | return ("getitem", key) |
| 1125 | def __setitem__(self, key, value): |
| 1126 | self.setitem = (key, value) |
| 1127 | def __delitem__(self, key): |
| 1128 | self.delitem = key |
| 1129 | |
| 1130 | def __getslice__(self, i, j): |
| 1131 | return ("getslice", i, j) |
| 1132 | def __setslice__(self, i, j, value): |
| 1133 | self.setslice = (i, j, value) |
| 1134 | def __delslice__(self, i, j): |
| 1135 | self.delslice = (i, j) |
| 1136 | |
| 1137 | a = C() |
| 1138 | verify(a.foo == ("getattr", "foo")) |
| 1139 | a.foo = 12 |
| 1140 | verify(a.setattr == ("foo", 12)) |
| 1141 | del a.foo |
| 1142 | verify(a.delattr == "foo") |
| 1143 | |
| 1144 | verify(a[12] == ("getitem", 12)) |
| 1145 | a[12] = 21 |
| 1146 | verify(a.setitem == (12, 21)) |
| 1147 | del a[12] |
| 1148 | verify(a.delitem == 12) |
| 1149 | |
| 1150 | verify(a[0:10] == ("getslice", 0, 10)) |
| 1151 | a[0:10] = "foo" |
| 1152 | verify(a.setslice == (0, 10, "foo")) |
| 1153 | del a[0:10] |
| 1154 | verify(a.delslice == (0, 10)) |
| 1155 | |
Guido van Rossum | b5a136b | 2001-08-15 17:51:17 +0000 | [diff] [blame] | 1156 | def methods(): |
Guido van Rossum | 65d5d7f | 2001-08-17 21:27:53 +0000 | [diff] [blame] | 1157 | if verbose: print "Testing methods..." |
Guido van Rossum | b5a136b | 2001-08-15 17:51:17 +0000 | [diff] [blame] | 1158 | class C(object): |
| 1159 | def __init__(self, x): |
| 1160 | self.x = x |
| 1161 | def foo(self): |
| 1162 | return self.x |
| 1163 | c1 = C(1) |
| 1164 | verify(c1.foo() == 1) |
| 1165 | class D(C): |
| 1166 | boo = C.foo |
| 1167 | goo = c1.foo |
| 1168 | d2 = D(2) |
| 1169 | verify(d2.foo() == 2) |
| 1170 | verify(d2.boo() == 2) |
Guido van Rossum | 501c7c7 | 2001-08-16 20:41:56 +0000 | [diff] [blame] | 1171 | verify(d2.goo() == 1) |
Guido van Rossum | 9301876 | 2001-08-17 13:40:47 +0000 | [diff] [blame] | 1172 | class E(object): |
| 1173 | foo = C.foo |
| 1174 | verify(E().foo == C.foo) # i.e., unbound |
Guido van Rossum | 84a79a8 | 2001-08-17 13:58:31 +0000 | [diff] [blame] | 1175 | verify(repr(C.foo.__get__(C(1))).startswith("<bound method ")) |
Guido van Rossum | b5a136b | 2001-08-15 17:51:17 +0000 | [diff] [blame] | 1176 | |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1177 | def specials(): |
| 1178 | # Test operators like __hash__ for which a built-in default exists |
Guido van Rossum | 65d5d7f | 2001-08-17 21:27:53 +0000 | [diff] [blame] | 1179 | if verbose: print "Testing special operators..." |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1180 | # Test the default behavior for static classes |
| 1181 | class C(object): |
| 1182 | def __getitem__(self, i): |
| 1183 | if 0 <= i < 10: return i |
| 1184 | raise IndexError |
| 1185 | c1 = C() |
| 1186 | c2 = C() |
| 1187 | verify(not not c1) |
| 1188 | verify(hash(c1) == id(c1)) |
| 1189 | verify(cmp(c1, c2) == cmp(id(c1), id(c2))) |
| 1190 | verify(c1 == c1) |
| 1191 | verify(c1 != c2) |
| 1192 | verify(not c1 != c1) |
| 1193 | verify(not c1 == c2) |
Tim Peters | 4d2dded | 2001-08-16 19:50:51 +0000 | [diff] [blame] | 1194 | # Note that the module name appears in str/repr, and that varies |
| 1195 | # depending on whether this test is run standalone or from a framework. |
Guido van Rossum | ff0e6d6 | 2001-09-24 16:03:59 +0000 | [diff] [blame^] | 1196 | verify(str(c1).find('C object at ') >= 0) |
Tim Peters | 63a8d69 | 2001-08-16 16:56:16 +0000 | [diff] [blame] | 1197 | verify(str(c1) == repr(c1)) |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1198 | verify(-1 not in c1) |
| 1199 | for i in range(10): |
| 1200 | verify(i in c1) |
| 1201 | verify(10 not in c1) |
| 1202 | # Test the default behavior for dynamic classes |
| 1203 | class D(object): |
| 1204 | __dynamic__ = 1 |
| 1205 | def __getitem__(self, i): |
| 1206 | if 0 <= i < 10: return i |
| 1207 | raise IndexError |
| 1208 | d1 = D() |
| 1209 | d2 = D() |
| 1210 | verify(not not d1) |
| 1211 | verify(hash(d1) == id(d1)) |
| 1212 | verify(cmp(d1, d2) == cmp(id(d1), id(d2))) |
| 1213 | verify(d1 == d1) |
| 1214 | verify(d1 != d2) |
| 1215 | verify(not d1 != d1) |
| 1216 | verify(not d1 == d2) |
Tim Peters | 4d2dded | 2001-08-16 19:50:51 +0000 | [diff] [blame] | 1217 | # Note that the module name appears in str/repr, and that varies |
| 1218 | # depending on whether this test is run standalone or from a framework. |
Guido van Rossum | ff0e6d6 | 2001-09-24 16:03:59 +0000 | [diff] [blame^] | 1219 | verify(str(d1).find('D object at ') >= 0) |
Tim Peters | 63a8d69 | 2001-08-16 16:56:16 +0000 | [diff] [blame] | 1220 | verify(str(d1) == repr(d1)) |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1221 | verify(-1 not in d1) |
| 1222 | for i in range(10): |
| 1223 | verify(i in d1) |
| 1224 | verify(10 not in d1) |
| 1225 | # Test overridden behavior for static classes |
| 1226 | class Proxy(object): |
| 1227 | def __init__(self, x): |
| 1228 | self.x = x |
| 1229 | def __nonzero__(self): |
| 1230 | return not not self.x |
| 1231 | def __hash__(self): |
| 1232 | return hash(self.x) |
| 1233 | def __eq__(self, other): |
| 1234 | return self.x == other |
| 1235 | def __ne__(self, other): |
| 1236 | return self.x != other |
| 1237 | def __cmp__(self, other): |
| 1238 | return cmp(self.x, other.x) |
| 1239 | def __str__(self): |
| 1240 | return "Proxy:%s" % self.x |
| 1241 | def __repr__(self): |
| 1242 | return "Proxy(%r)" % self.x |
| 1243 | def __contains__(self, value): |
| 1244 | return value in self.x |
| 1245 | p0 = Proxy(0) |
| 1246 | p1 = Proxy(1) |
| 1247 | p_1 = Proxy(-1) |
| 1248 | verify(not p0) |
| 1249 | verify(not not p1) |
| 1250 | verify(hash(p0) == hash(0)) |
| 1251 | verify(p0 == p0) |
| 1252 | verify(p0 != p1) |
| 1253 | verify(not p0 != p0) |
| 1254 | verify(not p0 == p1) |
| 1255 | verify(cmp(p0, p1) == -1) |
| 1256 | verify(cmp(p0, p0) == 0) |
| 1257 | verify(cmp(p0, p_1) == 1) |
| 1258 | verify(str(p0) == "Proxy:0") |
| 1259 | verify(repr(p0) == "Proxy(0)") |
| 1260 | p10 = Proxy(range(10)) |
| 1261 | verify(-1 not in p10) |
| 1262 | for i in range(10): |
| 1263 | verify(i in p10) |
| 1264 | verify(10 not in p10) |
| 1265 | # Test overridden behavior for dynamic classes |
| 1266 | class DProxy(object): |
| 1267 | __dynamic__ = 1 |
| 1268 | def __init__(self, x): |
| 1269 | self.x = x |
| 1270 | def __nonzero__(self): |
| 1271 | return not not self.x |
| 1272 | def __hash__(self): |
| 1273 | return hash(self.x) |
| 1274 | def __eq__(self, other): |
| 1275 | return self.x == other |
| 1276 | def __ne__(self, other): |
| 1277 | return self.x != other |
| 1278 | def __cmp__(self, other): |
| 1279 | return cmp(self.x, other.x) |
| 1280 | def __str__(self): |
| 1281 | return "DProxy:%s" % self.x |
| 1282 | def __repr__(self): |
| 1283 | return "DProxy(%r)" % self.x |
| 1284 | def __contains__(self, value): |
| 1285 | return value in self.x |
| 1286 | p0 = DProxy(0) |
| 1287 | p1 = DProxy(1) |
| 1288 | p_1 = DProxy(-1) |
| 1289 | verify(not p0) |
| 1290 | verify(not not p1) |
| 1291 | verify(hash(p0) == hash(0)) |
| 1292 | verify(p0 == p0) |
| 1293 | verify(p0 != p1) |
| 1294 | verify(not p0 != p0) |
| 1295 | verify(not p0 == p1) |
| 1296 | verify(cmp(p0, p1) == -1) |
| 1297 | verify(cmp(p0, p0) == 0) |
| 1298 | verify(cmp(p0, p_1) == 1) |
| 1299 | verify(str(p0) == "DProxy:0") |
| 1300 | verify(repr(p0) == "DProxy(0)") |
| 1301 | p10 = DProxy(range(10)) |
| 1302 | verify(-1 not in p10) |
| 1303 | for i in range(10): |
| 1304 | verify(i in p10) |
| 1305 | verify(10 not in p10) |
Guido van Rossum | 843daa8 | 2001-09-18 20:04:26 +0000 | [diff] [blame] | 1306 | # Safety test for __cmp__ |
| 1307 | def unsafecmp(a, b): |
| 1308 | try: |
| 1309 | a.__class__.__cmp__(a, b) |
| 1310 | except TypeError: |
| 1311 | pass |
| 1312 | else: |
| 1313 | raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( |
| 1314 | a.__class__, a, b) |
| 1315 | unsafecmp(u"123", "123") |
| 1316 | unsafecmp("123", u"123") |
| 1317 | unsafecmp(1, 1.0) |
| 1318 | unsafecmp(1.0, 1) |
| 1319 | unsafecmp(1, 1L) |
| 1320 | unsafecmp(1L, 1) |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1321 | |
Guido van Rossum | 65d5d7f | 2001-08-17 21:27:53 +0000 | [diff] [blame] | 1322 | def weakrefs(): |
| 1323 | if verbose: print "Testing weak references..." |
| 1324 | import weakref |
| 1325 | class C(object): |
| 1326 | pass |
| 1327 | c = C() |
| 1328 | r = weakref.ref(c) |
| 1329 | verify(r() is c) |
| 1330 | del c |
| 1331 | verify(r() is None) |
| 1332 | del r |
| 1333 | class NoWeak(object): |
| 1334 | __slots__ = ['foo'] |
| 1335 | no = NoWeak() |
| 1336 | try: |
| 1337 | weakref.ref(no) |
| 1338 | except TypeError, msg: |
| 1339 | verify(str(msg).find("weakly") >= 0) |
| 1340 | else: |
| 1341 | verify(0, "weakref.ref(no) should be illegal") |
| 1342 | class Weak(object): |
| 1343 | __slots__ = ['foo', '__weakref__'] |
| 1344 | yes = Weak() |
| 1345 | r = weakref.ref(yes) |
| 1346 | verify(r() is yes) |
| 1347 | del yes |
| 1348 | verify(r() is None) |
| 1349 | del r |
| 1350 | |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 1351 | def properties(): |
| 1352 | if verbose: print "Testing property..." |
Guido van Rossum | 76f0cb8 | 2001-08-24 15:24:24 +0000 | [diff] [blame] | 1353 | class C(object): |
| 1354 | def getx(self): |
| 1355 | return self.__x |
| 1356 | def setx(self, value): |
| 1357 | self.__x = value |
| 1358 | def delx(self): |
| 1359 | del self.__x |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 1360 | x = property(getx, setx, delx) |
Guido van Rossum | 76f0cb8 | 2001-08-24 15:24:24 +0000 | [diff] [blame] | 1361 | a = C() |
| 1362 | verify(not hasattr(a, "x")) |
| 1363 | a.x = 42 |
| 1364 | verify(a._C__x == 42) |
| 1365 | verify(a.x == 42) |
| 1366 | del a.x |
| 1367 | verify(not hasattr(a, "x")) |
| 1368 | verify(not hasattr(a, "_C__x")) |
| 1369 | C.x.__set__(a, 100) |
| 1370 | verify(C.x.__get__(a) == 100) |
| 1371 | ## C.x.__set__(a) |
| 1372 | ## verify(not hasattr(a, "x")) |
| 1373 | |
Guido van Rossum | c4a1880 | 2001-08-24 16:55:27 +0000 | [diff] [blame] | 1374 | def supers(): |
Guido van Rossum | 9881fc1 | 2001-08-24 17:07:20 +0000 | [diff] [blame] | 1375 | if verbose: print "Testing super..." |
Guido van Rossum | c4a1880 | 2001-08-24 16:55:27 +0000 | [diff] [blame] | 1376 | |
| 1377 | class A(object): |
| 1378 | def meth(self, a): |
| 1379 | return "A(%r)" % a |
| 1380 | |
| 1381 | verify(A().meth(1) == "A(1)") |
| 1382 | |
| 1383 | class B(A): |
| 1384 | def __init__(self): |
| 1385 | self.__super = super(B, self) |
| 1386 | def meth(self, a): |
| 1387 | return "B(%r)" % a + self.__super.meth(a) |
| 1388 | |
| 1389 | verify(B().meth(2) == "B(2)A(2)") |
| 1390 | |
| 1391 | class C(A): |
| 1392 | __dynamic__ = 1 |
| 1393 | def meth(self, a): |
| 1394 | return "C(%r)" % a + self.__super.meth(a) |
| 1395 | C._C__super = super(C) |
| 1396 | |
| 1397 | verify(C().meth(3) == "C(3)A(3)") |
| 1398 | |
| 1399 | class D(C, B): |
| 1400 | def meth(self, a): |
| 1401 | return "D(%r)" % a + super(D, self).meth(a) |
| 1402 | |
| 1403 | verify (D().meth(4) == "D(4)C(4)B(4)A(4)") |
| 1404 | |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1405 | def inherits(): |
| 1406 | if verbose: print "Testing inheritance from basic types..." |
| 1407 | |
| 1408 | class hexint(int): |
| 1409 | def __repr__(self): |
| 1410 | return hex(self) |
| 1411 | def __add__(self, other): |
| 1412 | return hexint(int.__add__(self, other)) |
| 1413 | # (Note that overriding __radd__ doesn't work, |
| 1414 | # because the int type gets first dibs.) |
| 1415 | verify(repr(hexint(7) + 9) == "0x10") |
| 1416 | verify(repr(hexint(1000) + 7) == "0x3ef") |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1417 | a = hexint(12345) |
Tim Peters | 50fda6c | 2001-09-18 21:24:18 +0000 | [diff] [blame] | 1418 | verify(a == 12345) |
Guido van Rossum | 779ce4a | 2001-09-11 14:02:22 +0000 | [diff] [blame] | 1419 | verify(int(a) == 12345) |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1420 | verify(int(a).__class__ is int) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1421 | verify(hash(a) == hash(12345)) |
Tim Peters | 73a1dfe | 2001-09-11 21:44:14 +0000 | [diff] [blame] | 1422 | verify((+a).__class__ is int) |
| 1423 | verify((a >> 0).__class__ is int) |
| 1424 | verify((a << 0).__class__ is int) |
| 1425 | verify((hexint(0) << 12).__class__ is int) |
| 1426 | verify((hexint(0) >> 12).__class__ is int) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1427 | |
| 1428 | class octlong(long): |
| 1429 | __slots__ = [] |
| 1430 | def __str__(self): |
| 1431 | s = oct(self) |
| 1432 | if s[-1] == 'L': |
| 1433 | s = s[:-1] |
| 1434 | return s |
| 1435 | def __add__(self, other): |
| 1436 | return self.__class__(super(octlong, self).__add__(other)) |
| 1437 | __radd__ = __add__ |
| 1438 | verify(str(octlong(3) + 5) == "010") |
| 1439 | # (Note that overriding __radd__ here only seems to work |
| 1440 | # because the example uses a short int left argument.) |
| 1441 | verify(str(5 + octlong(3000)) == "05675") |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1442 | a = octlong(12345) |
Tim Peters | 50fda6c | 2001-09-18 21:24:18 +0000 | [diff] [blame] | 1443 | verify(a == 12345L) |
Guido van Rossum | 779ce4a | 2001-09-11 14:02:22 +0000 | [diff] [blame] | 1444 | verify(long(a) == 12345L) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1445 | verify(hash(a) == hash(12345L)) |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1446 | verify(long(a).__class__ is long) |
Tim Peters | 69c2de3 | 2001-09-11 22:31:33 +0000 | [diff] [blame] | 1447 | verify((+a).__class__ is long) |
| 1448 | verify((-a).__class__ is long) |
| 1449 | verify((-octlong(0)).__class__ is long) |
| 1450 | verify((a >> 0).__class__ is long) |
| 1451 | verify((a << 0).__class__ is long) |
| 1452 | verify((a - 0).__class__ is long) |
| 1453 | verify((a * 1).__class__ is long) |
| 1454 | verify((a ** 1).__class__ is long) |
| 1455 | verify((a // 1).__class__ is long) |
| 1456 | verify((1 * a).__class__ is long) |
| 1457 | verify((a | 0).__class__ is long) |
| 1458 | verify((a ^ 0).__class__ is long) |
| 1459 | verify((a & -1L).__class__ is long) |
| 1460 | verify((octlong(0) << 12).__class__ is long) |
| 1461 | verify((octlong(0) >> 12).__class__ is long) |
| 1462 | verify(abs(octlong(0)).__class__ is long) |
| 1463 | |
| 1464 | # Because octlong overrides __add__, we can't check the absence of +0 |
| 1465 | # optimizations using octlong. |
| 1466 | class longclone(long): |
| 1467 | pass |
| 1468 | a = longclone(1) |
| 1469 | verify((a + 0).__class__ is long) |
| 1470 | verify((0 + a).__class__ is long) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1471 | |
| 1472 | class precfloat(float): |
| 1473 | __slots__ = ['prec'] |
| 1474 | def __init__(self, value=0.0, prec=12): |
| 1475 | self.prec = int(prec) |
| 1476 | float.__init__(value) |
| 1477 | def __repr__(self): |
| 1478 | return "%.*g" % (self.prec, self) |
| 1479 | verify(repr(precfloat(1.1)) == "1.1") |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1480 | a = precfloat(12345) |
Tim Peters | 50fda6c | 2001-09-18 21:24:18 +0000 | [diff] [blame] | 1481 | verify(a == 12345.0) |
Guido van Rossum | 779ce4a | 2001-09-11 14:02:22 +0000 | [diff] [blame] | 1482 | verify(float(a) == 12345.0) |
Tim Peters | 7a50f25 | 2001-09-10 21:28:20 +0000 | [diff] [blame] | 1483 | verify(float(a).__class__ is float) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1484 | verify(hash(a) == hash(12345.0)) |
Tim Peters | 0280cf7 | 2001-09-11 21:53:35 +0000 | [diff] [blame] | 1485 | verify((+a).__class__ is float) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1486 | |
Tim Peters | 2400fa4 | 2001-09-12 19:12:49 +0000 | [diff] [blame] | 1487 | class madcomplex(complex): |
| 1488 | def __repr__(self): |
| 1489 | return "%.17gj%+.17g" % (self.imag, self.real) |
| 1490 | a = madcomplex(-3, 4) |
| 1491 | verify(repr(a) == "4j-3") |
| 1492 | base = complex(-3, 4) |
| 1493 | verify(base.__class__ is complex) |
Guido van Rossum | d5d8e4a | 2001-09-19 01:16:16 +0000 | [diff] [blame] | 1494 | verify(a == base) |
Tim Peters | 2400fa4 | 2001-09-12 19:12:49 +0000 | [diff] [blame] | 1495 | verify(complex(a) == base) |
| 1496 | verify(complex(a).__class__ is complex) |
| 1497 | a = madcomplex(a) # just trying another form of the constructor |
| 1498 | verify(repr(a) == "4j-3") |
Guido van Rossum | d5d8e4a | 2001-09-19 01:16:16 +0000 | [diff] [blame] | 1499 | verify(a == base) |
Tim Peters | 2400fa4 | 2001-09-12 19:12:49 +0000 | [diff] [blame] | 1500 | verify(complex(a) == base) |
| 1501 | verify(complex(a).__class__ is complex) |
| 1502 | verify(hash(a) == hash(base)) |
| 1503 | verify((+a).__class__ is complex) |
| 1504 | verify((a + 0).__class__ is complex) |
| 1505 | verify(a + 0 == base) |
| 1506 | verify((a - 0).__class__ is complex) |
| 1507 | verify(a - 0 == base) |
| 1508 | verify((a * 1).__class__ is complex) |
| 1509 | verify(a * 1 == base) |
| 1510 | verify((a / 1).__class__ is complex) |
| 1511 | verify(a / 1 == base) |
| 1512 | |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1513 | class madtuple(tuple): |
| 1514 | _rev = None |
| 1515 | def rev(self): |
| 1516 | if self._rev is not None: |
| 1517 | return self._rev |
| 1518 | L = list(self) |
| 1519 | L.reverse() |
| 1520 | self._rev = self.__class__(L) |
| 1521 | return self._rev |
| 1522 | a = madtuple((1,2,3,4,5,6,7,8,9,0)) |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1523 | verify(a == (1,2,3,4,5,6,7,8,9,0)) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1524 | verify(a.rev() == madtuple((0,9,8,7,6,5,4,3,2,1))) |
| 1525 | verify(a.rev().rev() == madtuple((1,2,3,4,5,6,7,8,9,0))) |
| 1526 | for i in range(512): |
| 1527 | t = madtuple(range(i)) |
| 1528 | u = t.rev() |
| 1529 | v = u.rev() |
| 1530 | verify(v == t) |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1531 | a = madtuple((1,2,3,4,5)) |
| 1532 | verify(tuple(a) == (1,2,3,4,5)) |
Tim Peters | 4c3a0a3 | 2001-09-10 23:37:46 +0000 | [diff] [blame] | 1533 | verify(tuple(a).__class__ is tuple) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1534 | verify(hash(a) == hash((1,2,3,4,5))) |
Tim Peters | 7b07a41 | 2001-09-11 19:48:03 +0000 | [diff] [blame] | 1535 | verify(a[:].__class__ is tuple) |
| 1536 | verify((a * 1).__class__ is tuple) |
| 1537 | verify((a * 0).__class__ is tuple) |
| 1538 | verify((a + ()).__class__ is tuple) |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1539 | a = madtuple(()) |
| 1540 | verify(tuple(a) == ()) |
Guido van Rossum | 779ce4a | 2001-09-11 14:02:22 +0000 | [diff] [blame] | 1541 | verify(tuple(a).__class__ is tuple) |
Tim Peters | 7b07a41 | 2001-09-11 19:48:03 +0000 | [diff] [blame] | 1542 | verify((a + a).__class__ is tuple) |
| 1543 | verify((a * 0).__class__ is tuple) |
| 1544 | verify((a * 1).__class__ is tuple) |
| 1545 | verify((a * 2).__class__ is tuple) |
| 1546 | verify(a[:].__class__ is tuple) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1547 | |
| 1548 | class madstring(str): |
| 1549 | _rev = None |
| 1550 | def rev(self): |
| 1551 | if self._rev is not None: |
| 1552 | return self._rev |
| 1553 | L = list(self) |
| 1554 | L.reverse() |
| 1555 | self._rev = self.__class__("".join(L)) |
| 1556 | return self._rev |
| 1557 | s = madstring("abcdefghijklmnopqrstuvwxyz") |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1558 | #XXX verify(s == "abcdefghijklmnopqrstuvwxyz") |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1559 | verify(s.rev() == madstring("zyxwvutsrqponmlkjihgfedcba")) |
| 1560 | verify(s.rev().rev() == madstring("abcdefghijklmnopqrstuvwxyz")) |
| 1561 | for i in range(256): |
| 1562 | s = madstring("".join(map(chr, range(i)))) |
| 1563 | t = s.rev() |
| 1564 | u = t.rev() |
| 1565 | verify(u == s) |
Tim Peters | 64b5ce3 | 2001-09-10 20:52:51 +0000 | [diff] [blame] | 1566 | s = madstring("12345") |
Guido van Rossum | 779ce4a | 2001-09-11 14:02:22 +0000 | [diff] [blame] | 1567 | verify(str(s) == "12345") |
Tim Peters | 5a49ade | 2001-09-11 01:41:59 +0000 | [diff] [blame] | 1568 | verify(str(s).__class__ is str) |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1569 | |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1570 | base = "\x00" * 5 |
| 1571 | s = madstring(base) |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1572 | #XXX verify(s == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1573 | verify(str(s) == base) |
Tim Peters | c636f56 | 2001-09-11 01:52:02 +0000 | [diff] [blame] | 1574 | verify(str(s).__class__ is str) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1575 | verify(hash(s) == hash(base)) |
Tim Peters | 0ab085c | 2001-09-14 00:25:33 +0000 | [diff] [blame] | 1576 | #XXX verify({s: 1}[base] == 1) |
| 1577 | #XXX verify({base: 1}[s] == 1) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1578 | verify((s + "").__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1579 | verify(s + "" == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1580 | verify(("" + s).__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1581 | verify("" + s == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1582 | verify((s * 0).__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1583 | verify(s * 0 == "") |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1584 | verify((s * 1).__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1585 | verify(s * 1 == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1586 | verify((s * 2).__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1587 | verify(s * 2 == base + base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1588 | verify(s[:].__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1589 | verify(s[:] == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1590 | verify(s[0:0].__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1591 | verify(s[0:0] == "") |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1592 | verify(s.strip().__class__ is str) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1593 | verify(s.strip() == base) |
| 1594 | verify(s.lstrip().__class__ is str) |
| 1595 | verify(s.lstrip() == base) |
| 1596 | verify(s.rstrip().__class__ is str) |
| 1597 | verify(s.rstrip() == base) |
Tim Peters | 8fa5dd0 | 2001-09-12 02:18:30 +0000 | [diff] [blame] | 1598 | identitytab = ''.join([chr(i) for i in range(256)]) |
| 1599 | verify(s.translate(identitytab).__class__ is str) |
| 1600 | verify(s.translate(identitytab) == base) |
| 1601 | verify(s.translate(identitytab, "x").__class__ is str) |
| 1602 | verify(s.translate(identitytab, "x") == base) |
| 1603 | verify(s.translate(identitytab, "\x00") == "") |
| 1604 | verify(s.replace("x", "x").__class__ is str) |
| 1605 | verify(s.replace("x", "x") == base) |
| 1606 | verify(s.ljust(len(s)).__class__ is str) |
| 1607 | verify(s.ljust(len(s)) == base) |
| 1608 | verify(s.rjust(len(s)).__class__ is str) |
| 1609 | verify(s.rjust(len(s)) == base) |
| 1610 | verify(s.center(len(s)).__class__ is str) |
| 1611 | verify(s.center(len(s)) == base) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1612 | verify(s.lower().__class__ is str) |
| 1613 | verify(s.lower() == base) |
Tim Peters | c636f56 | 2001-09-11 01:52:02 +0000 | [diff] [blame] | 1614 | |
Tim Peters | 111f609 | 2001-09-12 07:54:51 +0000 | [diff] [blame] | 1615 | s = madstring("x y") |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1616 | #XXX verify(s == "x y") |
Tim Peters | 111f609 | 2001-09-12 07:54:51 +0000 | [diff] [blame] | 1617 | verify(intern(s).__class__ is str) |
| 1618 | verify(intern(s) is intern("x y")) |
| 1619 | verify(intern(s) == "x y") |
| 1620 | |
| 1621 | i = intern("y x") |
| 1622 | s = madstring("y x") |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1623 | #XXX verify(s == i) |
Tim Peters | 111f609 | 2001-09-12 07:54:51 +0000 | [diff] [blame] | 1624 | verify(intern(s).__class__ is str) |
| 1625 | verify(intern(s) is i) |
| 1626 | |
| 1627 | s = madstring(i) |
| 1628 | verify(intern(s).__class__ is str) |
| 1629 | verify(intern(s) is i) |
| 1630 | |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 1631 | class madunicode(unicode): |
| 1632 | _rev = None |
| 1633 | def rev(self): |
| 1634 | if self._rev is not None: |
| 1635 | return self._rev |
| 1636 | L = list(self) |
| 1637 | L.reverse() |
| 1638 | self._rev = self.__class__(u"".join(L)) |
| 1639 | return self._rev |
| 1640 | u = madunicode("ABCDEF") |
Tim Peters | 4f467e8 | 2001-09-12 19:53:15 +0000 | [diff] [blame] | 1641 | verify(u == u"ABCDEF") |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 1642 | verify(u.rev() == madunicode(u"FEDCBA")) |
| 1643 | verify(u.rev().rev() == madunicode(u"ABCDEF")) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1644 | base = u"12345" |
| 1645 | u = madunicode(base) |
| 1646 | verify(unicode(u) == base) |
Tim Peters | 78e0fc7 | 2001-09-11 03:07:38 +0000 | [diff] [blame] | 1647 | verify(unicode(u).__class__ is unicode) |
Tim Peters | af90b3e | 2001-09-12 05:18:58 +0000 | [diff] [blame] | 1648 | verify(hash(u) == hash(base)) |
| 1649 | verify({u: 1}[base] == 1) |
| 1650 | verify({base: 1}[u] == 1) |
Tim Peters | 7a29bd5 | 2001-09-12 03:03:31 +0000 | [diff] [blame] | 1651 | verify(u.strip().__class__ is unicode) |
| 1652 | verify(u.strip() == base) |
| 1653 | verify(u.lstrip().__class__ is unicode) |
| 1654 | verify(u.lstrip() == base) |
| 1655 | verify(u.rstrip().__class__ is unicode) |
| 1656 | verify(u.rstrip() == base) |
| 1657 | verify(u.replace(u"x", u"x").__class__ is unicode) |
| 1658 | verify(u.replace(u"x", u"x") == base) |
| 1659 | verify(u.replace(u"xy", u"xy").__class__ is unicode) |
| 1660 | verify(u.replace(u"xy", u"xy") == base) |
| 1661 | verify(u.center(len(u)).__class__ is unicode) |
| 1662 | verify(u.center(len(u)) == base) |
| 1663 | verify(u.ljust(len(u)).__class__ is unicode) |
| 1664 | verify(u.ljust(len(u)) == base) |
| 1665 | verify(u.rjust(len(u)).__class__ is unicode) |
| 1666 | verify(u.rjust(len(u)) == base) |
| 1667 | verify(u.lower().__class__ is unicode) |
| 1668 | verify(u.lower() == base) |
| 1669 | verify(u.upper().__class__ is unicode) |
| 1670 | verify(u.upper() == base) |
| 1671 | verify(u.capitalize().__class__ is unicode) |
| 1672 | verify(u.capitalize() == base) |
| 1673 | verify(u.title().__class__ is unicode) |
| 1674 | verify(u.title() == base) |
| 1675 | verify((u + u"").__class__ is unicode) |
| 1676 | verify(u + u"" == base) |
| 1677 | verify((u"" + u).__class__ is unicode) |
| 1678 | verify(u"" + u == base) |
| 1679 | verify((u * 0).__class__ is unicode) |
| 1680 | verify(u * 0 == u"") |
| 1681 | verify((u * 1).__class__ is unicode) |
| 1682 | verify(u * 1 == base) |
| 1683 | verify((u * 2).__class__ is unicode) |
| 1684 | verify(u * 2 == base + base) |
| 1685 | verify(u[:].__class__ is unicode) |
| 1686 | verify(u[:] == base) |
| 1687 | verify(u[0:0].__class__ is unicode) |
| 1688 | verify(u[0:0] == u"") |
Guido van Rossum | 91ee798 | 2001-08-30 20:52:40 +0000 | [diff] [blame] | 1689 | |
Tim Peters | 59c9a64 | 2001-09-13 05:38:56 +0000 | [diff] [blame] | 1690 | class CountedInput(file): |
| 1691 | """Counts lines read by self.readline(). |
| 1692 | |
| 1693 | self.lineno is the 0-based ordinal of the last line read, up to |
| 1694 | a maximum of one greater than the number of lines in the file. |
| 1695 | |
| 1696 | self.ateof is true if and only if the final "" line has been read, |
| 1697 | at which point self.lineno stops incrementing, and further calls |
| 1698 | to readline() continue to return "". |
| 1699 | """ |
| 1700 | |
| 1701 | lineno = 0 |
| 1702 | ateof = 0 |
| 1703 | def readline(self): |
| 1704 | if self.ateof: |
| 1705 | return "" |
| 1706 | s = file.readline(self) |
| 1707 | # Next line works too. |
| 1708 | # s = super(CountedInput, self).readline() |
| 1709 | self.lineno += 1 |
| 1710 | if s == "": |
| 1711 | self.ateof = 1 |
| 1712 | return s |
| 1713 | |
Tim Peters | 561f899 | 2001-09-13 19:36:36 +0000 | [diff] [blame] | 1714 | f = file(name=TESTFN, mode='w') |
Tim Peters | 59c9a64 | 2001-09-13 05:38:56 +0000 | [diff] [blame] | 1715 | lines = ['a\n', 'b\n', 'c\n'] |
| 1716 | try: |
| 1717 | f.writelines(lines) |
| 1718 | f.close() |
| 1719 | f = CountedInput(TESTFN) |
| 1720 | for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): |
| 1721 | got = f.readline() |
| 1722 | verify(expected == got) |
| 1723 | verify(f.lineno == i) |
| 1724 | verify(f.ateof == (i > len(lines))) |
| 1725 | f.close() |
| 1726 | finally: |
| 1727 | try: |
| 1728 | f.close() |
| 1729 | except: |
| 1730 | pass |
| 1731 | try: |
| 1732 | import os |
| 1733 | os.unlink(TESTFN) |
| 1734 | except: |
| 1735 | pass |
| 1736 | |
Tim Peters | 808b94e | 2001-09-13 19:33:07 +0000 | [diff] [blame] | 1737 | def keywords(): |
| 1738 | if verbose: |
| 1739 | print "Testing keyword args to basic type constructors ..." |
| 1740 | verify(int(x=1) == 1) |
| 1741 | verify(float(x=2) == 2.0) |
| 1742 | verify(long(x=3) == 3L) |
| 1743 | verify(complex(imag=42, real=666) == complex(666, 42)) |
| 1744 | verify(str(object=500) == '500') |
| 1745 | verify(unicode(string='abc', errors='strict') == u'abc') |
| 1746 | verify(tuple(sequence=range(3)) == (0, 1, 2)) |
| 1747 | verify(list(sequence=(0, 1, 2)) == range(3)) |
| 1748 | verify(dictionary(mapping={1: 2}) == {1: 2}) |
| 1749 | |
| 1750 | for constructor in (int, float, long, complex, str, unicode, |
| 1751 | tuple, list, dictionary, file): |
| 1752 | try: |
| 1753 | constructor(bogus_keyword_arg=1) |
| 1754 | except TypeError: |
| 1755 | pass |
| 1756 | else: |
| 1757 | raise TestFailed("expected TypeError from bogus keyword " |
| 1758 | "argument to %r" % constructor) |
Tim Peters | 561f899 | 2001-09-13 19:36:36 +0000 | [diff] [blame] | 1759 | |
Tim Peters | 8fa4567 | 2001-09-13 21:01:29 +0000 | [diff] [blame] | 1760 | def restricted(): |
| 1761 | import rexec |
| 1762 | if verbose: |
| 1763 | print "Testing interaction with restricted execution ..." |
| 1764 | |
| 1765 | sandbox = rexec.RExec() |
| 1766 | |
| 1767 | code1 = """f = open(%r, 'w')""" % TESTFN |
| 1768 | code2 = """f = file(%r, 'w')""" % TESTFN |
| 1769 | code3 = """\ |
| 1770 | f = open(%r) |
| 1771 | t = type(f) # a sneaky way to get the file() constructor |
| 1772 | f.close() |
| 1773 | f = t(%r, 'w') # rexec can't catch this by itself |
| 1774 | """ % (TESTFN, TESTFN) |
| 1775 | |
| 1776 | f = open(TESTFN, 'w') # Create the file so code3 can find it. |
| 1777 | f.close() |
| 1778 | |
| 1779 | try: |
| 1780 | for code in code1, code2, code3: |
| 1781 | try: |
| 1782 | sandbox.r_exec(code) |
| 1783 | except IOError, msg: |
| 1784 | if str(msg).find("restricted") >= 0: |
| 1785 | outcome = "OK" |
| 1786 | else: |
| 1787 | outcome = "got an exception, but not an expected one" |
| 1788 | else: |
| 1789 | outcome = "expected a restricted-execution exception" |
| 1790 | |
| 1791 | if outcome != "OK": |
| 1792 | raise TestFailed("%s, in %r" % (outcome, code)) |
| 1793 | |
| 1794 | finally: |
| 1795 | try: |
| 1796 | import os |
| 1797 | os.unlink(TESTFN) |
| 1798 | except: |
| 1799 | pass |
| 1800 | |
Tim Peters | 0ab085c | 2001-09-14 00:25:33 +0000 | [diff] [blame] | 1801 | def str_subclass_as_dict_key(): |
| 1802 | if verbose: |
| 1803 | print "Testing a str subclass used as dict key .." |
| 1804 | |
| 1805 | class cistr(str): |
| 1806 | """Sublcass of str that computes __eq__ case-insensitively. |
| 1807 | |
| 1808 | Also computes a hash code of the string in canonical form. |
| 1809 | """ |
| 1810 | |
| 1811 | def __init__(self, value): |
| 1812 | self.canonical = value.lower() |
| 1813 | self.hashcode = hash(self.canonical) |
| 1814 | |
| 1815 | def __eq__(self, other): |
| 1816 | if not isinstance(other, cistr): |
| 1817 | other = cistr(other) |
| 1818 | return self.canonical == other.canonical |
| 1819 | |
| 1820 | def __hash__(self): |
| 1821 | return self.hashcode |
| 1822 | |
Guido van Rossum | d5d8e4a | 2001-09-19 01:16:16 +0000 | [diff] [blame] | 1823 | verify(cistr('ABC') == 'abc') |
| 1824 | verify('aBc' == cistr('ABC')) |
Tim Peters | 0ab085c | 2001-09-14 00:25:33 +0000 | [diff] [blame] | 1825 | verify(str(cistr('ABC')) == 'ABC') |
| 1826 | |
| 1827 | d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} |
| 1828 | verify(d[cistr('one')] == 1) |
| 1829 | verify(d[cistr('tWo')] == 2) |
| 1830 | verify(d[cistr('THrEE')] == 3) |
| 1831 | verify(cistr('ONe') in d) |
| 1832 | verify(d.get(cistr('thrEE')) == 3) |
| 1833 | |
Guido van Rossum | ab3b034 | 2001-09-18 20:38:53 +0000 | [diff] [blame] | 1834 | def classic_comparisons(): |
| 1835 | if verbose: print "Testing classic comparisons..." |
Guido van Rossum | 0639f59 | 2001-09-18 21:06:04 +0000 | [diff] [blame] | 1836 | class classic: |
| 1837 | pass |
| 1838 | for base in (classic, int, object): |
Guido van Rossum | ab3b034 | 2001-09-18 20:38:53 +0000 | [diff] [blame] | 1839 | if verbose: print " (base = %s)" % base |
| 1840 | class C(base): |
| 1841 | def __init__(self, value): |
| 1842 | self.value = int(value) |
| 1843 | def __cmp__(self, other): |
| 1844 | if isinstance(other, C): |
| 1845 | return cmp(self.value, other.value) |
| 1846 | if isinstance(other, int) or isinstance(other, long): |
| 1847 | return cmp(self.value, other) |
| 1848 | return NotImplemented |
| 1849 | c1 = C(1) |
| 1850 | c2 = C(2) |
| 1851 | c3 = C(3) |
| 1852 | verify(c1 == 1) |
| 1853 | c = {1: c1, 2: c2, 3: c3} |
| 1854 | for x in 1, 2, 3: |
| 1855 | for y in 1, 2, 3: |
| 1856 | verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) |
| 1857 | for op in "<", "<=", "==", "!=", ">", ">=": |
| 1858 | verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), |
| 1859 | "x=%d, y=%d" % (x, y)) |
| 1860 | verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) |
| 1861 | verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) |
| 1862 | |
Guido van Rossum | 0639f59 | 2001-09-18 21:06:04 +0000 | [diff] [blame] | 1863 | def rich_comparisons(): |
| 1864 | if verbose: |
| 1865 | print "Testing rich comparisons..." |
| 1866 | class classic: |
| 1867 | pass |
| 1868 | for base in (classic, int, object, list): |
| 1869 | if verbose: print " (base = %s)" % base |
| 1870 | class C(base): |
| 1871 | def __init__(self, value): |
| 1872 | self.value = int(value) |
| 1873 | def __cmp__(self, other): |
| 1874 | raise TestFailed, "shouldn't call __cmp__" |
| 1875 | def __eq__(self, other): |
| 1876 | if isinstance(other, C): |
| 1877 | return self.value == other.value |
| 1878 | if isinstance(other, int) or isinstance(other, long): |
| 1879 | return self.value == other |
| 1880 | return NotImplemented |
| 1881 | def __ne__(self, other): |
| 1882 | if isinstance(other, C): |
| 1883 | return self.value != other.value |
| 1884 | if isinstance(other, int) or isinstance(other, long): |
| 1885 | return self.value != other |
| 1886 | return NotImplemented |
| 1887 | def __lt__(self, other): |
| 1888 | if isinstance(other, C): |
| 1889 | return self.value < other.value |
| 1890 | if isinstance(other, int) or isinstance(other, long): |
| 1891 | return self.value < other |
| 1892 | return NotImplemented |
| 1893 | def __le__(self, other): |
| 1894 | if isinstance(other, C): |
| 1895 | return self.value <= other.value |
| 1896 | if isinstance(other, int) or isinstance(other, long): |
| 1897 | return self.value <= other |
| 1898 | return NotImplemented |
| 1899 | def __gt__(self, other): |
| 1900 | if isinstance(other, C): |
| 1901 | return self.value > other.value |
| 1902 | if isinstance(other, int) or isinstance(other, long): |
| 1903 | return self.value > other |
| 1904 | return NotImplemented |
| 1905 | def __ge__(self, other): |
| 1906 | if isinstance(other, C): |
| 1907 | return self.value >= other.value |
| 1908 | if isinstance(other, int) or isinstance(other, long): |
| 1909 | return self.value >= other |
| 1910 | return NotImplemented |
| 1911 | c1 = C(1) |
| 1912 | c2 = C(2) |
| 1913 | c3 = C(3) |
| 1914 | verify(c1 == 1) |
| 1915 | c = {1: c1, 2: c2, 3: c3} |
| 1916 | for x in 1, 2, 3: |
| 1917 | for y in 1, 2, 3: |
| 1918 | for op in "<", "<=", "==", "!=", ">", ">=": |
| 1919 | verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), |
| 1920 | "x=%d, y=%d" % (x, y)) |
| 1921 | verify(eval("c[x] %s y" % op) == eval("x %s y" % op), |
| 1922 | "x=%d, y=%d" % (x, y)) |
| 1923 | verify(eval("x %s c[y]" % op) == eval("x %s y" % op), |
| 1924 | "x=%d, y=%d" % (x, y)) |
| 1925 | |
Guido van Rossum | 1952e38 | 2001-09-19 01:25:16 +0000 | [diff] [blame] | 1926 | def coercions(): |
| 1927 | if verbose: print "Testing coercions..." |
| 1928 | class I(int): pass |
| 1929 | coerce(I(0), 0) |
| 1930 | coerce(0, I(0)) |
| 1931 | class L(long): pass |
| 1932 | coerce(L(0), 0) |
| 1933 | coerce(L(0), 0L) |
| 1934 | coerce(0, L(0)) |
| 1935 | coerce(0L, L(0)) |
| 1936 | class F(float): pass |
| 1937 | coerce(F(0), 0) |
| 1938 | coerce(F(0), 0L) |
| 1939 | coerce(F(0), 0.) |
| 1940 | coerce(0, F(0)) |
| 1941 | coerce(0L, F(0)) |
| 1942 | coerce(0., F(0)) |
| 1943 | class C(complex): pass |
| 1944 | coerce(C(0), 0) |
| 1945 | coerce(C(0), 0L) |
| 1946 | coerce(C(0), 0.) |
| 1947 | coerce(C(0), 0j) |
| 1948 | coerce(0, C(0)) |
| 1949 | coerce(0L, C(0)) |
| 1950 | coerce(0., C(0)) |
| 1951 | coerce(0j, C(0)) |
| 1952 | |
Guido van Rossum | 8b9cc7e | 2001-09-20 21:49:53 +0000 | [diff] [blame] | 1953 | def descrdoc(): |
| 1954 | if verbose: print "Testing descriptor doc strings..." |
| 1955 | def check(descr, what): |
| 1956 | verify(descr.__doc__ == what, repr(descr.__doc__)) |
| 1957 | check(file.closed, "flag set if the file is closed") # getset descriptor |
| 1958 | check(file.name, "file name") # member descriptor |
| 1959 | |
Tim Peters | 0ab085c | 2001-09-14 00:25:33 +0000 | [diff] [blame] | 1960 | |
Guido van Rossum | a56b42b | 2001-09-20 21:39:07 +0000 | [diff] [blame] | 1961 | def test_main(): |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1962 | lists() |
| 1963 | dicts() |
Tim Peters | 25786c0 | 2001-09-02 08:22:48 +0000 | [diff] [blame] | 1964 | dict_constructor() |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 1965 | test_dir() |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1966 | ints() |
| 1967 | longs() |
| 1968 | floats() |
| 1969 | complexes() |
| 1970 | spamlists() |
| 1971 | spamdicts() |
| 1972 | pydicts() |
| 1973 | pylists() |
| 1974 | metaclass() |
| 1975 | pymods() |
| 1976 | multi() |
| 1977 | diamond() |
Guido van Rossum | 3720261 | 2001-08-09 19:45:21 +0000 | [diff] [blame] | 1978 | objects() |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 1979 | slots() |
| 1980 | dynamics() |
| 1981 | errors() |
| 1982 | classmethods() |
| 1983 | staticmethods() |
| 1984 | classic() |
| 1985 | compattr() |
| 1986 | newslot() |
| 1987 | altmro() |
| 1988 | overloading() |
Guido van Rossum | b5a136b | 2001-08-15 17:51:17 +0000 | [diff] [blame] | 1989 | methods() |
Guido van Rossum | a4ff6ab | 2001-08-15 23:57:59 +0000 | [diff] [blame] | 1990 | specials() |
Guido van Rossum | 65d5d7f | 2001-08-17 21:27:53 +0000 | [diff] [blame] | 1991 | weakrefs() |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 1992 | properties() |
Guido van Rossum | c4a1880 | 2001-08-24 16:55:27 +0000 | [diff] [blame] | 1993 | supers() |
Guido van Rossum | caa9f43 | 2001-08-30 20:06:08 +0000 | [diff] [blame] | 1994 | inherits() |
Tim Peters | 808b94e | 2001-09-13 19:33:07 +0000 | [diff] [blame] | 1995 | keywords() |
Tim Peters | 8fa4567 | 2001-09-13 21:01:29 +0000 | [diff] [blame] | 1996 | restricted() |
Tim Peters | 0ab085c | 2001-09-14 00:25:33 +0000 | [diff] [blame] | 1997 | str_subclass_as_dict_key() |
Guido van Rossum | ab3b034 | 2001-09-18 20:38:53 +0000 | [diff] [blame] | 1998 | classic_comparisons() |
Guido van Rossum | 0639f59 | 2001-09-18 21:06:04 +0000 | [diff] [blame] | 1999 | rich_comparisons() |
Guido van Rossum | 1952e38 | 2001-09-19 01:25:16 +0000 | [diff] [blame] | 2000 | coercions() |
Guido van Rossum | 8b9cc7e | 2001-09-20 21:49:53 +0000 | [diff] [blame] | 2001 | descrdoc() |
Guido van Rossum | a56b42b | 2001-09-20 21:39:07 +0000 | [diff] [blame] | 2002 | if verbose: print "All OK" |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 2003 | |
Guido van Rossum | a56b42b | 2001-09-20 21:39:07 +0000 | [diff] [blame] | 2004 | if __name__ == "__main__": |
| 2005 | test_main() |