PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/Tests/test_class.py

http://github.com/IronLanguages/main
Python | 3764 lines | 3631 code | 82 blank | 51 comment | 36 complexity | 781581b3b4743bfe061622f3b4ddff9a MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Apache License, Version 2.0, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Apache License, Version 2.0.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. #--IMPORTS---------------------------------------------------------------------
  16. from iptest.assert_util import *
  17. from iptest.type_util import *
  18. import sys
  19. #--HELPERS---------------------------------------------------------------------
  20. ############################################################
  21. def test_common_attributes():
  22. builtin_type_instances = [None, object(), 1, "Hello", [0,1], {"a":0}]
  23. builtin_hashable_type_instances = [None, object(), 1, "Hello"]
  24. builtin_types = [type(None), object, int, str, list, dict]
  25. for i in builtin_type_instances:
  26. # Read-only attribute
  27. AssertError(AttributeError, i.__delattr__, "__doc__")
  28. # Non-existent attribute
  29. AssertError(AttributeError, i.__delattr__, "foo")
  30. # Modifying __class__ causes a TypeError
  31. AssertError(TypeError, i.__delattr__, "__class__")
  32. # Read-only attribute
  33. AssertError(TypeError, i.__setattr__, "__doc__")
  34. # Non-existent attribute
  35. AssertError(AttributeError, i.__setattr__, "foo", "foovalue")
  36. # Modifying __class__ causes a TypeError
  37. AssertError(TypeError, i.__setattr__, "__class__")
  38. AreEqual(type(i), i.__getattribute__("__class__"))
  39. # Non-existent attribute
  40. AssertError(AttributeError, i.__getattribute__, "foo")
  41. if (is_cli or is_silverlight) and i == None: # !!! Need to expose __reduce__ on all types
  42. AssertError(TypeError, i.__reduce__)
  43. AssertError(TypeError, i.__reduce_ex__)
  44. for i in builtin_hashable_type_instances:
  45. AreEqual(hash(i), i.__hash__())
  46. for i in builtin_types:
  47. if (is_cli or is_silverlight) and i == type(None):
  48. continue
  49. # __init__ and __new__ are implemented by IronPython.Runtime.Operations.InstanceOps
  50. # We do repr to ensure that we can map back the functions properly
  51. repr(getattr(i, "__init__"))
  52. repr(getattr(i, "__new__"))
  53. ############################################################
  54. def test_set_dict():
  55. class C: pass
  56. setdict = C.__dict__
  57. C.__dict__ = setdict
  58. o1 = C()
  59. class C:
  60. def m(self):
  61. return 42
  62. o2 = C()
  63. Assert(42 == o2.m())
  64. Assert(o2.__class__ is C)
  65. Assert(o2.__class__ is not o1.__class__)
  66. ############################################################
  67. def test_attrs():
  68. class C:pass
  69. C.v = 10
  70. Assert(C.v == 10)
  71. success = 0
  72. try:
  73. x = C.x
  74. except AttributeError:
  75. success = 1
  76. Assert(success == 1)
  77. ############################################################
  78. def test_type_in():
  79. AreEqual(type in (None, True, False, 1, {}, [], (), 1.0, 1L, (1+0j)), False)
  80. ############################################################
  81. def test_init_defaults():
  82. class A:
  83. def __init__(self, height=20, width=30):
  84. self.area = height * width
  85. a = A()
  86. Assert(a.area == 600)
  87. a = A(2,3)
  88. Assert(a.area == 6)
  89. a = A(2)
  90. Assert(a.area == 60)
  91. a = A(width = 2)
  92. Assert(a.area == 40)
  93. ############################################################
  94. def test_getattr():
  95. class C:
  96. def __init__(self, name, flag):
  97. self.f = file(name, flag)
  98. def __getattr__(self, name):
  99. return getattr(self.f, name)
  100. tmpfile = "tmpfile.txt"
  101. if not is_silverlight:
  102. c=C(tmpfile, "w")
  103. c.write("Hello\n")
  104. c.close()
  105. c=C(tmpfile, "r")
  106. Assert(c.readline() == "Hello\n")
  107. c.close()
  108. try:
  109. import os
  110. os.unlink(tmpfile)
  111. except:
  112. pass
  113. # new-style
  114. class C(object):
  115. def __getattr__(self, name):
  116. raise AttributeError(name)
  117. # old-style
  118. class D:
  119. def __getattr__(self, name):
  120. raise AttributeError(name)
  121. # new-style __getattribute__
  122. class E(object):
  123. def __getattribute__(self, name):
  124. if name == 'xyz':
  125. raise AttributeError(name)
  126. if name == 'x':
  127. return 42
  128. return object.__getattribute__(self, name)
  129. # derived new-style type
  130. class F(E):
  131. pass
  132. # verify that base class' __getattribute__ is called.
  133. AreEqual(F().x, 42)
  134. # exception shouldn't propagate out
  135. for cls in [C, D, E, F]:
  136. AreEqual(getattr(cls(), 'xyz', 'DNE'), 'DNE')
  137. AreEqual(hasattr(cls(), 'xyz'), False)
  138. # removing & adding back on __getattribute__ should work
  139. class foo(object):
  140. def __getattribute__(self, name): return 42
  141. x = foo.__getattribute__
  142. del foo.__getattribute__
  143. AssertError(AttributeError, getattr, foo(), 'x')
  144. foo.__getattribute__ = x
  145. AreEqual(foo().x, 42)
  146. del foo.__getattribute__
  147. AssertError(AttributeError, getattr, foo(), 'x')
  148. # check getattr when the property raises
  149. class C(object):
  150. def throw(self):
  151. raise AttributeError
  152. foo = property(throw)
  153. AreEqual(getattr(C(), 'foo', 'abc'), 'abc')
  154. def count_elem(d,n):
  155. count = 0
  156. for e in d:
  157. if e == n:
  158. count += 1
  159. return count
  160. ############################################################
  161. def test_newstyle_oldstyle_dict():
  162. """Dictionary and new style classes"""
  163. class class_n(object):
  164. val1 = "Value"
  165. def __init__(self):
  166. self.val2 = self.val1
  167. inst_n = class_n()
  168. Assert(inst_n.val2 == "Value")
  169. Assert(not 'val2' in dir(class_n))
  170. Assert('val1' in dir(class_n))
  171. Assert('val2' in dir(inst_n))
  172. Assert('val1' in dir(inst_n))
  173. Assert('val2' in inst_n.__dict__)
  174. Assert(inst_n.__dict__['val2'] == "Value")
  175. Assert(count_elem(dir(inst_n), "val1") == 1)
  176. inst_n.val1 = 20
  177. Assert(count_elem(dir(inst_n), "val1") == 1)
  178. # old style classes:
  179. class class_o:
  180. val1 = "Value"
  181. def __init__(self):
  182. self.val2 = self.val1
  183. inst_o = class_o()
  184. Assert('val1' in dir(class_o))
  185. Assert(not 'val2' in dir(class_o))
  186. Assert('val1' in dir(inst_o))
  187. Assert('val2' in dir(inst_o))
  188. Assert('val2' in inst_o.__dict__)
  189. Assert(inst_o.__dict__['val2'] == "Value")
  190. Assert(count_elem(dir(inst_o), "val1") == 1)
  191. inst_n.val1 = 20
  192. Assert(count_elem(dir(inst_o), "val1") == 1)
  193. Assert(isinstance(class_o, object))
  194. Assert(isinstance(inst_o, object))
  195. Assert(isinstance(None, object))
  196. ############################################################
  197. def test_misc():
  198. class C:
  199. def x(self):
  200. return 'C.x'
  201. def y(self):
  202. return 'C.y'
  203. class D:
  204. def z(self):
  205. return 'D.z'
  206. c = C()
  207. AreEqual(c.x(), "C.x")
  208. AreEqual(c.y(), "C.y")
  209. # verify repr and str on old-style class objects have the right format:
  210. # bug# 795
  211. AreEqual(str(C), __name__+'.C')
  212. AreEqual(repr(C).index('<class '+__name__+'.C at 0x'), 0)
  213. success=0
  214. try:
  215. c.z()
  216. except AttributeError:
  217. success=1
  218. Assert(success==1)
  219. C.__bases__+=(D,)
  220. AreEqual(c.z(), "D.z")
  221. class C:
  222. def m(self):
  223. return "IronPython"
  224. def n(self, parm):
  225. return parm
  226. c = C()
  227. y = c.m
  228. y = c.n
  229. y = C.m
  230. y = C.n
  231. Assert('__dict__' not in str.__dict__)
  232. ############################################################
  233. def test_dir_in_init():
  234. # both of these shouldn't throw
  235. class DirInInit(object):
  236. def __init__(self):
  237. dir(self)
  238. a = DirInInit()
  239. ############################################################
  240. def test_priv_class():
  241. class _PrivClass(object):
  242. def __Mangled(self):
  243. pass
  244. def __init__(self):
  245. a = self.__Mangled
  246. a = _PrivClass()
  247. ############################################################
  248. def test_inheritance_attrs_dir():
  249. class foo:
  250. def foofunc(self):
  251. return "foofunc"
  252. class bar(foo):
  253. def barfunc(self):
  254. return "barfunc"
  255. class baz(foo, bar):
  256. def bazfunc(self):
  257. return "bazfunc"
  258. Assert('foofunc' in dir(foo))
  259. Assert(dir(foo).count('__doc__') == 1)
  260. Assert(dir(foo).count('__module__') == 1)
  261. Assert(len(dir(foo)) == 3)
  262. Assert('foofunc' in dir(bar))
  263. Assert('barfunc' in dir(bar))
  264. Assert(dir(bar).count('__doc__') == 1)
  265. Assert(dir(bar).count('__module__') == 1)
  266. Assert(len(dir(bar)) == 4)
  267. Assert('foofunc' in dir(baz))
  268. Assert('barfunc' in dir(baz))
  269. Assert('bazfunc' in dir(baz))
  270. Assert(dir(baz).count('__doc__') == 1)
  271. Assert(dir(baz).count('__module__') == 1)
  272. Assert(len(dir(baz)) == 5)
  273. bz = baz()
  274. Assert('foofunc' in dir(bz))
  275. Assert('barfunc' in dir(bz))
  276. Assert('bazfunc' in dir(bz))
  277. Assert(dir(bz).count('__doc__') == 1)
  278. Assert(dir(bz).count('__module__') == 1)
  279. Assert(len(dir(bz)) == 5)
  280. bz.__module__ = "MODULE"
  281. Assert(bz.__module__ == "MODULE")
  282. bz.__module__ = "SOMEOTHERMODULE"
  283. Assert(bz.__module__ == "SOMEOTHERMODULE")
  284. bz.__module__ = 33
  285. Assert(bz.__module__ == 33)
  286. bz.__module__ = [2, 3, 4]
  287. Assert(bz.__module__ == [2, 3 , 4])
  288. ############################################################
  289. def test_oldstyle_setattr():
  290. global called
  291. class C:
  292. def __setattr__(self, name, value):
  293. global called
  294. called = (self, name, value)
  295. a = C()
  296. a.abc = 'def'
  297. AreEqual(called, (a, 'abc', 'def'))
  298. del C.__setattr__
  299. a.qrt = 'abc'
  300. AreEqual(called, (a, 'abc', 'def'))
  301. def setattr(self, name, value):
  302. global called
  303. called = (self, name, value)
  304. C.__setattr__ = setattr
  305. a.qrt = 'abc'
  306. AreEqual(called, (a, 'qrt', 'abc'))
  307. ############################################################
  308. def test_oldstyle_getattr():
  309. """verify we don't access __getattr__ while creating an old
  310. style class."""
  311. class C:
  312. def __getattr__(self,name):
  313. return globals()[name]
  314. a = C()
  315. def test_oldstyle_eq():
  316. """old style __eq__ shouldn't call __cmp__"""
  317. class x: pass
  318. inst = type(x())
  319. global cmpCalled
  320. cmpCalled = False
  321. class C:
  322. def __init__(self, value):
  323. self.value = value
  324. def __cmp__(self, other):
  325. global cmpCalled
  326. cmpCalled = True
  327. return self.value - other.value
  328. class D:
  329. def __init__(self, value):
  330. self.value = value
  331. def __cmp__(self, other):
  332. global cmpCalled
  333. cmpCalled = True
  334. return self.value - other.value
  335. class C2(C): pass
  336. class D2(D): pass
  337. AreEqual(inst.__eq__(C(3.0), C(4.5)), NotImplemented)
  338. AreEqual(inst.__eq__(C(3.0), C2(4.5)), NotImplemented)
  339. AreEqual(inst.__eq__(C(3.0), D(4.5)), NotImplemented)
  340. AreEqual(cmpCalled, False)
  341. ############################################################
  342. def test_raise_attrerror():
  343. """raising AttributeError from __getattr__ should be ok,
  344. and shouldn't be seen by the user"""
  345. class A:
  346. def __getattr__(self, name):
  347. raise AttributeError, 'get outta here'
  348. def __repr__(self):
  349. return 'foo'
  350. class B:
  351. def __getattr__(self, name):
  352. raise AttributeError, 'get outta here'
  353. def __str__(self):
  354. return 'foo'
  355. AreEqual(str(A()), 'foo')
  356. AreEqual(repr(A()), 'foo')
  357. AreEqual(str(B()), 'foo')
  358. Assert(repr(B()).find('B instance') != -1)
  359. ############################################################
  360. # use exec to define methods on classes:
  361. def test_exec_namespace():
  362. class oldclasswithexec:
  363. exec "def oldexecmethod(self): return 'result of oldexecmethod'"
  364. Assert('oldexecmethod' in dir(oldclasswithexec))
  365. AreEqual(oldclasswithexec().oldexecmethod(), 'result of oldexecmethod')
  366. class newclasswithexec(object):
  367. exec "def newexecmethod(self): return 'result of newexecmethod'"
  368. Assert('newexecmethod' in dir(newclasswithexec))
  369. AreEqual(newclasswithexec().newexecmethod(), 'result of newexecmethod')
  370. ############################################################
  371. def test_module_name():
  372. global __name__
  373. mod = sys.modules[__name__]
  374. name = __name__
  375. mod.__name__ = None
  376. class C: pass
  377. AreEqual(C.__module__, None)
  378. def func1():
  379. __name__ = "wrong"
  380. class C: pass
  381. return C()
  382. def func2():
  383. class C: pass
  384. return C()
  385. def func3():
  386. global __name__
  387. __name__ = "right"
  388. class C: pass
  389. return C()
  390. AreEqual(func1().__module__, func2().__module__)
  391. __name__ = "fake"
  392. AreEqual(func1().__module__, "fake")
  393. AreEqual(func3().__module__, "right")
  394. mod.__name__ = name
  395. def f(x): x.__module__
  396. def g(x): getattr(x, '__module__')
  397. import errno
  398. for thing in "", 1, errno, 1L, 1+2j, (), [], {}:
  399. AreEqual(getattr(thing, '__module__', 'does_not_exist'), 'does_not_exist')
  400. AreEqual(hasattr(thing, '__module__'), False)
  401. AssertError(AttributeError, f, thing)
  402. AssertError(AttributeError, g, thing)
  403. AssertErrorWithMessage(TypeError, "can't set function.__module__", type(type(f)).__dict__['__module__'].__set__, type(f), 42)
  404. class x(object): pass
  405. type(type(x())).__dict__['__module__'].__set__(x, 'fooz')
  406. AreEqual(x.__module__, 'fooz')
  407. AssertErrorWithMessage(TypeError, "can't delete x.__module__", type(type(x())).__dict__['__module__'].__delete__, x)
  408. ############################################################
  409. def test_check_dictionary():
  410. """tests to verify that Symbol dictionaries do the right thing in dynamic scenarios"""
  411. def CheckDictionary(C):
  412. # add a new attribute to the type...
  413. C.newClassAttr = 'xyz'
  414. AreEqual(C.newClassAttr, 'xyz')
  415. # add non-string index into the class and instance dictionary
  416. a = C()
  417. a.__dict__[1] = '1'
  418. if object in C.__bases__:
  419. try:
  420. C.__dict__[2] = '2'
  421. AssertUnreachable()
  422. except TypeError: pass
  423. AreEqual(C.__dict__.has_key(2), False)
  424. AreEqual(a.__dict__.has_key(1), True)
  425. AreEqual(dir(a).__contains__(1), True)
  426. AreEqual(repr(a.__dict__), "{1: '1'}")
  427. # replace a class dictionary (containing non-string keys) w/ a normal dictionary
  428. C.newTypeAttr = 1
  429. AreEqual(hasattr(C, 'newTypeAttr'), True)
  430. class OldClass: pass
  431. if isinstance(C, type(OldClass)):
  432. C.__dict__ = dict(C.__dict__)
  433. AreEqual(hasattr(C, 'newTypeAttr'), True)
  434. else:
  435. try:
  436. C.__dict__ = {}
  437. AssertUnreachable()
  438. except AttributeError:
  439. pass
  440. # replace an instance dictionary (containing non-string keys) w/ a new one.
  441. a.newInstanceAttr = 1
  442. AreEqual(hasattr(a, 'newInstanceAttr'), True)
  443. a.__dict__ = dict(a.__dict__)
  444. AreEqual(hasattr(a, 'newInstanceAttr'), True)
  445. a.abc = 'xyz'
  446. AreEqual(hasattr(a, 'abc'), True)
  447. AreEqual(getattr(a, 'abc'), 'xyz')
  448. class OldClass:
  449. def __init__(self): pass
  450. class NewClass(object):
  451. def __init__(self): pass
  452. CheckDictionary(OldClass)
  453. CheckDictionary(NewClass)
  454. ############################################################
  455. def test_call_type_call():
  456. for stuff in [object, int, str, bool, float]:
  457. AreEqual(type(type.__call__(stuff)), stuff)
  458. AreEqual(type.__call__(int, 5), 5)
  459. AreEqual(type.__call__(int), 0)
  460. AreEqual(type.__call__(bool, True), True)
  461. AreEqual(type.__call__(bool), False)
  462. #User-defined old/new style classes
  463. call_mapper = {}
  464. class KOld0:
  465. def __call__(self):
  466. return 2
  467. call_mapper[KOld0] = lambda: [type(KOld0()).__call__(KOld0())]
  468. class KOld1:
  469. def __call__(self, p):
  470. return 2
  471. call_mapper[KOld1] = lambda: [type(KOld1()).__call__(KOld1(), 3.14),
  472. type(KOld1()).__call__(KOld1(), p=3.14),
  473. type(KOld1()).__call__(KOld1(), **{"p":3.14}),
  474. type(KOld1()).__call__(KOld1(), (1, 2, 3)) ]
  475. class KOldArgs:
  476. def __call__(self, *args):
  477. return 2
  478. call_mapper[KOldArgs] = lambda: [type(KOldArgs()).__call__(KOldArgs())]
  479. class KOldKwargs:
  480. def __call__(self, **kwargs):
  481. return 2
  482. call_mapper[KOldKwargs] = lambda: [type(KOldKwargs()).__call__(KOldKwargs())]
  483. class KOldArgsKwargs:
  484. def __call__(self, *args, **kwargs):
  485. return 2
  486. call_mapper[KOldArgsKwargs] = lambda: [type(KOldArgsKwargs()).__call__(KOldArgsKwargs())]
  487. class KNew0(object):
  488. def __call__(self):
  489. return 2
  490. call_mapper[KNew0] = lambda: [type(KNew0()).__call__(KNew0())]
  491. class KNew1(object):
  492. def __call__(self, p):
  493. return 2
  494. call_mapper[KNew1] = lambda: [type(KNew1()).__call__(KNew1(), 3.14),
  495. type(KNew1()).__call__(KNew1(), p=3.14),
  496. type(KNew1()).__call__(KNew1(), **{"p":3.14}),
  497. type(KNew1()).__call__(KNew1(), []),
  498. ]
  499. class KNewArgs(object):
  500. def __call__(self, *args):
  501. return 2
  502. call_mapper[KNewArgs] = lambda: [type(KNewArgs()).__call__(KNewArgs()) ]
  503. class KNewKwargs(object):
  504. def __call__(self, **kwargs):
  505. return 2
  506. call_mapper[KNewKwargs] = lambda: [type(KNewKwargs()).__call__(KNewKwargs())]
  507. class KNewArgsKwargs(object):
  508. def __call__(self, *args, **kwargs):
  509. return 2
  510. call_mapper[KNewArgsKwargs] = lambda: [type(KNewArgsKwargs()).__call__(KNewArgsKwargs())]
  511. for K in call_mapper.keys():
  512. for ret_val in call_mapper[K]():
  513. AreEqual(ret_val, 2)
  514. def test_cp8246():
  515. #...
  516. class K(object):
  517. def __call__(self):
  518. return ((), {})
  519. AreEqual(K()(), ((), {}))
  520. #...
  521. class K(object):
  522. def __call__(self, **kwargs):
  523. return ((), kwargs)
  524. AreEqual(K()(), ((), {}))
  525. AreEqual(K()(**{}), ((), {}))
  526. AreEqual(K()(**{'a':None}), ((), {'a':None}))
  527. #...
  528. class K(object):
  529. def __call__(self, *args):
  530. return (args, {})
  531. AreEqual(K()(), ((), {}))
  532. AreEqual(K()(*()), ((), {}))
  533. AreEqual(K()(*(None,)), ((None,), {}))
  534. #...
  535. class K(object):
  536. def __call__(self, *args, **kwargs):
  537. return (args, kwargs)
  538. AreEqual(K()(), ((), {}))
  539. AreEqual(K()(*()), ((), {}))
  540. AreEqual(K()(**{}), ((), {}))
  541. AreEqual(K()(*(), **{}), ((), {}))
  542. AreEqual(K()(*(None,)), ((None,), {}))
  543. AreEqual(K()(**{'a':None}), ((), {'a':None}))
  544. AreEqual(K()(*(None,), **{'a':None}), ((None,), {'a':None}))
  545. ############################################################
  546. def test_mixed_inheritance():
  547. """inheritance from both old & new style classes..."""
  548. class foo: pass
  549. class bar(object): pass
  550. class baz1(foo, bar): pass
  551. class baz2(bar, foo): pass
  552. AreEqual(baz1.__bases__, (foo, bar))
  553. AreEqual(baz2.__bases__, (bar, foo))
  554. class foo:
  555. abc = 3
  556. class bar(object):
  557. def get_abc():
  558. return 42
  559. def set_abc():
  560. pass
  561. abc = property(fget=get_abc, fset=set_abc)
  562. class baz(foo, bar): pass
  563. AreEqual(baz().abc, 3)
  564. ############################################################
  565. def test_newstyle_unbound_inheritance():
  566. """verify calling unbound method w/ new-style class on subclass which
  567. new-style also inherits from works."""
  568. class foo:
  569. def func(self): return self
  570. class bar(object, foo):
  571. def barfunc(self):
  572. return foo.func(self)
  573. a = bar()
  574. AreEqual(a.barfunc(), a)
  575. ############################################################
  576. def test_mro():
  577. """mro (method resolution order) support"""
  578. class A(object): pass
  579. AreEqual(A.__mro__, (A, object))
  580. class B(object): pass
  581. AreEqual(B.__mro__, (B, object))
  582. class C(B): pass
  583. AreEqual(C.__mro__, (C, B, object))
  584. class N(C,B,A): pass
  585. AreEqual(N.__mro__, (N, C, B, A, object))
  586. try:
  587. class N(A, B,C): pass
  588. AssertUnreachable("impossible MRO created")
  589. except TypeError:
  590. pass
  591. try:
  592. class N(A, A): pass
  593. AssertUnreachable("can't dervie from the same base type twice")
  594. except TypeError:
  595. pass
  596. ############################################################
  597. def test_mro_bases():
  598. """verify replacing base classes also updates MRO"""
  599. class C(object):
  600. def __getattribute__(self, name):
  601. if(name == 'xyz'): return 'C'
  602. return super(C, self).__getattribute__(name)
  603. class C1(C):
  604. def __getattribute__(self, name):
  605. if(name == 'xyz'): return 'C1'
  606. return super(C1, self).__getattribute__(name)
  607. class A(object): pass
  608. class B(object):
  609. def __getattribute__(self, name):
  610. if(name == 'xyz'): return 'B'
  611. return super(B, self).__getattribute__(name)
  612. a = C1()
  613. AreEqual(a.xyz, 'C1')
  614. C1.__bases__ = (A,B)
  615. AreEqual(a.xyz, 'C1')
  616. del(C1.__getattribute__)
  617. AreEqual(a.xyz, 'B')
  618. ############################################################
  619. def test_dynamic_mro_bases():
  620. class C(object):
  621. pass
  622. def __getattribute__(self, name):
  623. if (name == 'xyz'):
  624. return 'C'
  625. return super(C, self).__getattribute__(name)
  626. C.__getattribute__ = __getattribute__
  627. class C1(C):
  628. pass
  629. def __getattribute__(self, name):
  630. if (name == 'xyz'):
  631. return 'C1'
  632. return super(C1, self).__getattribute__(name)
  633. C1.__getattribute__ = __getattribute__
  634. class B(object):
  635. pass
  636. def __getattribute__(self, name):
  637. if (name == 'xyz'):
  638. return 'B'
  639. return super(B, self).__getattribute__(name)
  640. B.__getattribute__ = __getattribute__
  641. C1.__bases__ = (B, )
  642. AreEqual(C1().xyz, 'C1')
  643. ############################################################
  644. def test_builtin_mro():
  645. """int mro shouldn't include ValueType"""
  646. AreEqual(int.__mro__, (int, object))
  647. ############################################################
  648. def test_mixed_inheritance_mro():
  649. """mixed inheritance from old-style & new-style classes"""
  650. # we should use old-style MRO when inheriting w/ a single old-style class
  651. class A: pass
  652. class B(A): pass
  653. class C(A): pass
  654. class D(B, C):pass
  655. class E(D, object): pass
  656. # old-style MRO of D is D, B, A, C, which should
  657. # be present in E's mro
  658. AreEqual(E.__mro__, (E, D, B, A, C, object))
  659. class F(B, C, object): pass
  660. # but when inheriting from multiple old-style classes we switch
  661. # to new-style MRO, and respect local ordering of classes in the MRO
  662. AreEqual(F.__mro__, (F, B, C, A, object))
  663. class G(B, object, C): pass
  664. AreEqual(G.__mro__, (G, B, object, C, A))
  665. class H(E): pass
  666. AreEqual(H.__mro__, (H, E, D, B, A, C, object))
  667. try:
  668. class H(A,B,E): pass
  669. AssertUnreachable()
  670. except TypeError:
  671. pass
  672. class H(E,B,A): pass
  673. AreEqual(H.__mro__, (H, E, D, B, A, C, object))
  674. ############################################################
  675. def test_depth_first_mro_mixed():
  676. """Verify given two large, independent class hierarchies
  677. that we favor them in the order listed.
  678. w/ old-style
  679. """
  680. class A: pass
  681. class B(A): pass
  682. class C(A): pass
  683. class D(B,C): pass
  684. class E(D, object): pass
  685. class G: pass
  686. class H(G): pass
  687. class I(G): pass
  688. class K(H,I, object): pass
  689. class L(K,E): pass
  690. AreEqual(L.__mro__, (L, K, H, I, G, E, D, B, A, C, object))
  691. ############################################################
  692. def test_depth_first_mro():
  693. """w/o old-style"""
  694. class A(object): pass
  695. class B(A): pass
  696. class C(A): pass
  697. class D(B,C): pass
  698. class E(D, object): pass
  699. class G(object): pass
  700. class H(G): pass
  701. class I(G): pass
  702. class K(H,I, object): pass
  703. class L(K,E): pass
  704. AreEqual(L.__mro__, (L, K, H, I, G, E, D, B, C, A, object))
  705. ############################################################
  706. def test_newstyle_lookup():
  707. """new-style classes should only lookup methods from the class, not from the instance"""
  708. class Strange(object):
  709. def uselessMethod(self): pass
  710. global obj
  711. obj = Strange()
  712. obj.__nonzero__ = lambda: False
  713. AreEqual(bool(obj), True)
  714. def twoargs(self, other):
  715. global twoArgsCalled
  716. twoArgsCalled = True
  717. return self
  718. def onearg(self):
  719. return self
  720. def onearg_str(self):
  721. return 'abc'
  722. # create methods that we can then stick into Strange
  723. twoargs = type(Strange.uselessMethod)(twoargs, None, Strange)
  724. onearg = type(Strange.uselessMethod)(onearg, None, Strange)
  725. class ForwardAndReverseTests:
  726. testCases = [
  727. #forward versions
  728. ('__add__', 'obj + obj'),
  729. ('__sub__', 'obj - obj'),
  730. ('__mul__', 'obj * obj'),
  731. ('__floordiv__', 'obj // obj'),
  732. ('__mod__', 'obj % obj'),
  733. ('__divmod__', 'divmod(obj,obj)'),
  734. ('__pow__', 'pow(obj, obj)'),
  735. ('__lshift__', 'obj << obj'),
  736. ('__rshift__', 'obj >> obj'),
  737. ('__and__', 'obj & obj'),
  738. ('__xor__', 'obj ^ obj'),
  739. ('__or__', 'obj | obj'),
  740. # reverse versions
  741. ('__radd__', '1 + obj'),
  742. ('__rsub__', '1 - obj'),
  743. ('__rmul__', '1 * obj'),
  744. ('__rfloordiv__', '1 // obj'),
  745. ('__rmod__', '1 % obj'),
  746. #('__rdivmod__', '1 % obj'), #bug 975
  747. ('__rpow__', 'pow(1, obj)'),
  748. ('__rlshift__', '1 << obj'),
  749. ('__rrshift__', '1 >> obj'),
  750. ('__rand__', '1 & obj'),
  751. ('__rxor__', '1 ^ obj'),
  752. ('__ror__', '1 | obj'),
  753. ]
  754. @staticmethod
  755. def NegativeTest(method, testCase):
  756. setattr(obj, method, twoargs)
  757. try:
  758. eval(testCase)
  759. AssertUnreachable()
  760. except TypeError, e:
  761. pass
  762. delattr(obj, method)
  763. @staticmethod
  764. def PositiveTest(method, testCase):
  765. setattr(Strange, method, twoargs)
  766. AreEqual(eval(testCase), obj)
  767. delattr(Strange, method)
  768. class InPlaceTests:
  769. # in-place versions require exec instead of eval
  770. testCases = [
  771. # inplace versions
  772. ('__iadd__', 'obj += obj'),
  773. ('__isub__', 'obj -= obj'),
  774. ('__imul__', 'obj *= obj'),
  775. ('__ifloordiv__', 'obj //= obj'),
  776. ('__imod__', 'obj %= obj'),
  777. ('__ipow__', 'obj **= obj'),
  778. ('__ilshift__', 'obj <<= obj'),
  779. ('__irshift__', 'obj >>= obj'),
  780. ('__iand__', 'obj &= obj'),
  781. ('__ixor__', 'obj ^= obj'),
  782. ('__ior__', 'obj |= obj'),
  783. ]
  784. @staticmethod
  785. def NegativeTest(method, testCase):
  786. setattr(obj, method, twoargs)
  787. try:
  788. exec testCase in globals(), locals()
  789. AssertUnreachable()
  790. except TypeError:
  791. pass
  792. delattr(obj, method)
  793. @staticmethod
  794. def PositiveTest(method, testCase):
  795. setattr(Strange, method, twoargs)
  796. global twoArgsCalled
  797. twoArgsCalled = False
  798. exec testCase in globals(), locals()
  799. AreEqual(twoArgsCalled, True)
  800. delattr(Strange, method)
  801. class SingleArgTests:
  802. testCases = [
  803. # one-argument versions
  804. ('__neg__', '-obj'),
  805. ('__pos__', '+obj'),
  806. ('__abs__', 'abs(obj)'),
  807. ('__invert__', '~obj'),
  808. ]
  809. @staticmethod
  810. def NegativeTest(method, testCase):
  811. setattr(obj, method, onearg)
  812. try:
  813. eval(testCase)
  814. AssertUnreachable()
  815. except TypeError:
  816. pass
  817. delattr(obj, method)
  818. @staticmethod
  819. def PositiveTest(method, testCase):
  820. setattr(Strange, method, onearg)
  821. try:
  822. AreEqual(eval(testCase), obj)
  823. except TypeError:
  824. Assert(method == '__oct__' or method == '__hex__')
  825. delattr(Strange, method)
  826. class HexOctTests:
  827. testCases = [
  828. ('__oct__', 'oct(obj)'),
  829. ('__hex__', 'hex(obj)'),
  830. ]
  831. @staticmethod
  832. def NegativeTest(method, testCase):
  833. setattr(obj, method, onearg)
  834. try:
  835. eval(testCase)
  836. AssertUnreachable()
  837. except TypeError:
  838. pass
  839. delattr(obj, method)
  840. @staticmethod
  841. def PositiveTest(method, testCase):
  842. setattr(Strange, method, onearg_str)
  843. AreEqual(eval(testCase), 'abc')
  844. delattr(Strange, method)
  845. class ConversionTests:
  846. testCases = [
  847. (('__complex__', 2+0j), 'complex(obj)'),
  848. (('__int__', 1), 'int(obj)'),
  849. (('__long__', 1L), 'long(obj)'),
  850. (('__float__', 1.0), 'float(obj)'),
  851. ]
  852. @staticmethod
  853. def NegativeTest(method, testCase):
  854. setattr(obj, method[0], onearg)
  855. try:
  856. eval(testCase)
  857. AssertUnreachable()
  858. except (TypeError, ValueError), e:
  859. AreEqual(e.args[0].find('returned') == -1, True) # shouldn't have returned '__complex__ returned ...'
  860. delattr(obj, method[0])
  861. @staticmethod
  862. def PositiveTest(method, testCase):
  863. def testMethod(self):
  864. return method[1]
  865. testMethod = type(Strange.uselessMethod)(testMethod, None, Strange)
  866. setattr(Strange, method[0], testMethod)
  867. AreEqual(eval(testCase), method[1])
  868. delattr(Strange, method[0])
  869. allTests = [ForwardAndReverseTests, InPlaceTests, SingleArgTests, ConversionTests, HexOctTests]
  870. for test in allTests:
  871. for method,testCase in test.testCases:
  872. test.NegativeTest(method, testCase)
  873. for method,testCase in test.testCases:
  874. test.PositiveTest(method, testCase)
  875. #Verify that the base type's defined special operators get picked up.
  876. class DerivedStrange(Strange): pass
  877. obj = DerivedStrange()
  878. for test in allTests:
  879. for method,testCase in test.testCases:
  880. test.NegativeTest(method, testCase)
  881. for method,testCase in test.testCases:
  882. test.PositiveTest(method, testCase)
  883. def test_bad_repr():
  884. # overriding a classes __repr__ and returning a
  885. # non-string should throw
  886. class C:
  887. def __repr__(self):
  888. return None
  889. AssertError(TypeError, repr, C())
  890. class C(object):
  891. def __repr__(self):
  892. return None
  893. AssertError(TypeError, repr, C())
  894. ############################################################
  895. def test_name():
  896. """setting __name__ on a class should work"""
  897. class C(object): pass
  898. C.__name__ = 'abc'
  899. AreEqual(C.__name__, 'abc')
  900. ############################################################
  901. def test_mro_super():
  902. """super for multiple inheritance we should follow the MRO as we go up the super chain"""
  903. class F:
  904. def meth(self):
  905. return 'F'
  906. class G: pass
  907. def gmeth(self): return 'G'
  908. class A(object):
  909. def meth(self):
  910. if hasattr(super(A, self), 'meth'):
  911. return 'A' + super(A, self).meth()
  912. else:
  913. return "A"
  914. class B(A):
  915. def __init__(self):
  916. self.__super = super(B, self)
  917. super(B, self).__init__()
  918. def meth(self):
  919. return "B" + self.__super.meth()
  920. class C(A):
  921. def __init__(self):
  922. self.__super = super(C, self)
  923. super(C, self).__init__()
  924. def meth(self):
  925. return "C" + self.__super.meth()
  926. class D(C, B):
  927. def meth(self):
  928. return "D" + super(D, self).meth()
  929. AreEqual(D().meth(), 'DCBA')
  930. class D(C, F, B):
  931. def meth(self):
  932. return "D" + super(D, self).meth()
  933. AreEqual(D.__mro__, (D,C,F,B,A,object))
  934. AreEqual(D().meth(), 'DCF')
  935. class D(C, B, F):
  936. def meth(self):
  937. return "D" + super(D, self).meth()
  938. AreEqual(D.__mro__, (D,C,B,A,object,F))
  939. AreEqual(D().meth(), 'DCBAF')
  940. class D(C, B, G):
  941. def meth(self):
  942. return "D" + super(D, self).meth()
  943. d = D()
  944. d.meth = type(F.meth)(gmeth, d, G)
  945. AreEqual(d.meth(), 'G')
  946. ############################################################
  947. def test_slots():
  948. """slots tests"""
  949. # simple slots, assign, delete, etc...
  950. class foo(object):
  951. __slots__ = ['abc']
  952. class bar(object):
  953. __slots__ = 'abc'
  954. class baz(object):
  955. __slots__ = ('abc', )
  956. for slotType in [foo, bar, baz]:
  957. a = slotType()
  958. AssertError(AttributeError, lambda: a.abc)
  959. AreEqual(hasattr(a, 'abc'), False)
  960. a.abc = 'xyz'
  961. AreEqual(a.abc, 'xyz')
  962. AreEqual(hasattr(a, 'abc'), True)
  963. del(a.abc)
  964. AreEqual(hasattr(a, 'abc'), False)
  965. AssertError(AttributeError, lambda: a.abc)
  966. # slot classes don't have __dict__
  967. AreEqual(hasattr(a, '__dict__'), False)
  968. AssertError(AttributeError, lambda: a.__dict__)
  969. # sub-class of slots class, has no slots, has a __dict__
  970. class foo(object):
  971. __slots__ = 'abc'
  972. def __init__(self):
  973. self.abc = 23
  974. class bar(foo):
  975. def __init__(self):
  976. super(bar, self).__init__()
  977. a = bar()
  978. AreEqual(a.abc, 23)
  979. del(a.abc)
  980. AreEqual(hasattr(a, 'abc'), False)
  981. a.abc = 42
  982. AreEqual(a.abc, 42)
  983. x = a.__dict__
  984. AreEqual(x.has_key('abc'), False)
  985. a.xyz = 'abc'
  986. AreEqual(a.xyz, 'abc')
  987. # subclass of not-slots class defining slots:
  988. class A(object): pass
  989. class B(A): __slots__ = 'c'
  990. AreEqual(hasattr(B(), '__dict__'), True)
  991. AreEqual(hasattr(B, 'c'), True)
  992. # slots & metaclass
  993. if is_cli or is_silverlight: # INCOMPATBILE: __slots__ not supported for subtype of type
  994. class foo(type):
  995. __slots__ = ['abc']
  996. class bar(object):
  997. __metaclass__ = foo
  998. # complex slots
  999. class foo(object):
  1000. __slots__ = ['abc']
  1001. def __new__(cls, *args, **kw):
  1002. self = object.__new__(cls)
  1003. dict = object.__getattribute__(self, '__dict__')
  1004. return self
  1005. class bar(foo): pass
  1006. a = bar()
  1007. AssertError(AttributeError, foo)
  1008. # slots & name-mangling
  1009. class foo(object):
  1010. __slots__ = '__bar'
  1011. AreEqual(hasattr(foo, '_foo__bar'), True)
  1012. # invalid __slots__ values
  1013. for x in ['', None, '3.5']:
  1014. try:
  1015. class C(object):
  1016. __slots__ = x
  1017. AssertUnreachable()
  1018. except TypeError:
  1019. pass
  1020. # including __dict__ in slots allows accessing __dict__
  1021. class A(object): __slots__ = '__dict__'
  1022. AreEqual(hasattr(A(),"__dict__"), True)
  1023. a = A()
  1024. a.abc = 'xyz'
  1025. AreEqual(a.abc, 'xyz')
  1026. class B(A): pass
  1027. AreEqual(hasattr(B(),"__dict__"), True)
  1028. b = A()
  1029. b.abc = 'xyz'
  1030. AreEqual(b.abc, 'xyz')
  1031. # including __weakref__ explicitly
  1032. class A(object):
  1033. __slots__ = ["__weakref__"]
  1034. hasattr(A(), "__weakref__")
  1035. class B(A): pass
  1036. hasattr(B(), "__weakref__")
  1037. # weird case, including __weakref__ and __dict__ and we allow
  1038. # a subtype to inherit from both
  1039. if is_cli or is_silverlight: types = [object, dict, tuple] # INCOMPATBILE: __slots__ not supported for tuple
  1040. else: types = [object,dict]
  1041. for x in types:
  1042. class A(x):
  1043. __slots__ = ["__dict__"]
  1044. class B(x):
  1045. __slots__ = ["__weakref__"]
  1046. class C(A,B):
  1047. __slots__ = []
  1048. a = C()
  1049. AreEqual(hasattr(a, '__dict__'), True)
  1050. AreEqual(hasattr(a, '__weakref__'), True)
  1051. class C(A,B):
  1052. __slots__ = ['xyz']
  1053. a = C()
  1054. AreEqual(hasattr(a, '__dict__'), True)
  1055. AreEqual(hasattr(a, '__weakref__'), True)
  1056. AreEqual(hasattr(C, 'xyz'), True)
  1057. # calling w/ keyword args
  1058. class foo(object):
  1059. __slots__ = ['a', 'b']
  1060. def __new__(cls, one='a', two='b'):
  1061. self = object.__new__(cls)
  1062. self.a = one
  1063. self.b = two
  1064. return self
  1065. a = foo('x', two='y')
  1066. AreEqual(a.a, 'x')
  1067. AreEqual(a.b, 'y')
  1068. # assign to __dict__
  1069. class C(object): pass
  1070. a = C()
  1071. a.__dict__ = {'b':1}
  1072. AreEqual(a.b, 1)
  1073. # base, child define slots, grand-child doesn't
  1074. class foo(object): __slots__ = ['fooSlot']
  1075. class bar(foo): __slots__ = ['barSlot']
  1076. class baz(bar): pass # shouldn't throw
  1077. a = baz()
  1078. a.barSlot = 'xyz'
  1079. a.fooSlot = 'bar'
  1080. a.dictEntry = 'foo'
  1081. AreEqual(a.barSlot, 'xyz')
  1082. AreEqual(a.fooSlot, 'bar')
  1083. AreEqual(a.dictEntry, 'foo')
  1084. # large number of slots works (nested tuple slots)
  1085. class foo(object):
  1086. __slots__ = [ 'a' + str(x) for x in range(256) ]
  1087. a = foo()
  1088. for x in range(256):
  1089. setattr(a, 'a' + str(x), x)
  1090. for x in range(256):
  1091. AreEqual(x, getattr(a, 'a' + str(x)))
  1092. # new-style / old-style mixed with slots, slots take precedence
  1093. class foo:
  1094. abc = 3
  1095. class bar(object):
  1096. __slots__ = ['abc']
  1097. def __init__(self): self.abc = 5
  1098. class bar2(object):
  1099. abc = 5
  1100. class baz(foo, bar): pass
  1101. class baz2(foo, bar2): pass
  1102. AreEqual(baz().abc, 5)
  1103. # but if it's just a class member we respect MRO
  1104. AreEqual(baz2().abc, 3)
  1105. # getattr and __slots__ should mix well
  1106. class Foo(object):
  1107. __slots__ = ['bar']
  1108. def __getattr__(self, name):
  1109. return name.upper()
  1110. AreEqual(Foo().bar, 'BAR')
  1111. # slot takes precedence over dictionary member
  1112. class Foo(object):
  1113. __slots__ = ['bar', '__dict__']
  1114. a = Foo()
  1115. a.__dict__['bar'] = 'abc'
  1116. AssertError(AttributeError, lambda : a.bar)
  1117. # members defined the class take precedence over slots
  1118. global initCalled
  1119. class Foo(object):
  1120. __slots__ = ["__init__"]
  1121. def __init__(self):
  1122. global initCalled
  1123. initCalled = True
  1124. initCalled = False
  1125. a = Foo()
  1126. AreEqual(initCalled, True)
  1127. # the member is readonly because the member slot is gone.
  1128. def f(): a.__init__ = 'abc'
  1129. AssertError(AttributeError, f)
  1130. # make sure __init__ isn't special
  1131. class Foo(object):
  1132. __slots__ = ["abc"]
  1133. abc = 3
  1134. a = Foo()
  1135. AreEqual(a.abc, 3)
  1136. def f(): a.abc = 'abc'
  1137. AssertError(AttributeError, f)
  1138. class Foo(object): __slots__ = 'abc'
  1139. AreEqual(repr(Foo.abc), "<member 'abc' of 'Foo' objects>")
  1140. AreEqual(str(Foo.abc), "<member 'abc' of 'Foo' objects>")
  1141. AssertErrorWithPartialMessage(AttributeError, 'abc', lambda: Foo().abc)
  1142. # again w/ empty __slots__ in C1 (409720)
  1143. class C1(object):
  1144. __slots__ = []
  1145. class C2(object):
  1146. __slots__ = ['a']
  1147. class D1(C1, C2): pass
  1148. # name mangling, slots, and classes which start with __
  1149. class __NameStartsWithUnderscore(object):
  1150. __slots__ = [ '__a' ]
  1151. def __init__(self): self.__a = 'a'
  1152. def geta(self): return self.__a
  1153. s = __NameStartsWithUnderscore()
  1154. AreEqual(s.geta(), 'a')
  1155. def test_slots11457():
  1156. class COld:
  1157. __slots__ = ['a']
  1158. class CNew(object):
  1159. __slots__ = ['a']
  1160. for C in [COld, CNew]:
  1161. for i in xrange(2):
  1162. setattr(C, 'a', 5)
  1163. AreEqual(C().a, 5)
  1164. setattr(C, 'a', 7)
  1165. AreEqual(C().a, 7)
  1166. ############################################################
  1167. def test_inheritance_cycle():
  1168. """test for inheritance cycle"""
  1169. class CycleA: pass
  1170. class CycleB: pass
  1171. try:
  1172. CycleA.__bases__ = (CycleA,)
  1173. AssertUnreachable()
  1174. except TypeError: pass
  1175. try:
  1176. CycleA.__bases__ = (CycleB,)
  1177. CycleB.__bases__ = (CycleA,)
  1178. AssertUnreachable()
  1179. except TypeError: pass
  1180. ############################################################
  1181. def test_hexoct():
  1182. """returning non-string from hex & oct should throw"""
  1183. class foo(object):
  1184. def __hex__(self): return self
  1185. def __oct__(self): return self
  1186. class bar:
  1187. def __hex__(self): return self
  1188. def __oct__(self): return self
  1189. AssertError(TypeError, hex, foo())
  1190. AssertError(TypeError, oct, foo())
  1191. AssertError(TypeError, hex, bar())
  1192. AssertError(TypeError, oct, bar())
  1193. @skip("multiple_execute")
  1194. def test_no_clr_attributes():
  1195. """verify types have no CLR attributes"""
  1196. # list,
  1197. class x: pass
  1198. for stuff in [object, int, float, bool, str, long, complex, dict, set,
  1199. None, NotImplemented, Ellipsis, type(test_no_clr_attributes),
  1200. classmethod, staticmethod, frozenset, property, sys,
  1201. BaseException, type(zip), slice, buffer, enumerate, file,
  1202. range, xrange, type(x), type(x())]:
  1203. for dir_stuff in dir(stuff):
  1204. if dir_stuff[:1].isalpha():
  1205. Assert(dir_stuff[:1].islower(),
  1206. "%s should not be an attribute of %s" % (dir_stuff, str(stuff)))
  1207. def test_method_correct_name():
  1208. # __str__ is an InstanceOps method (ToStringMethod), but we should
  1209. # report the proper name in __str__
  1210. Assert(repr(BaseException.__str__).find('__str__') != -1)
  1211. @skip("multiple_execute")
  1212. def test_no_clr_attributes_sanity():
  1213. AreEqual(hasattr(int, 'MaxValue'), False)
  1214. AreEqual(hasattr(int, 'MinValue'), False)
  1215. AreEqual(hasattr(int, 'Abs'), False)
  1216. AreEqual(hasattr(int, 'BitwiseOr'), False)
  1217. AreEqual(hasattr(int, 'Equals'), False)
  1218. AreEqual(hasattr(str, 'Empty'), False)
  1219. AreEqual(hasattr(str, 'Compare'), False)
  1220. AreEqual(hasattr(str, 'Equals'), False)
  1221. AreEqual(hasattr(str, 'IndexOf'), False)
  1222. ############################################################
  1223. def test_outer_scope():
  1224. """do not automatically include outer scopes in closure scenarios"""
  1225. def outer_scope_test():
  1226. class Referenced:
  1227. pass
  1228. class C:
  1229. if Referenced: pass
  1230. Assert("Referenced" not in C.__dict__.keys())
  1231. outer_scope_test()
  1232. for x in [None, 'abc', 3]:
  1233. class foo(object): pass
  1234. a = foo()
  1235. try:
  1236. a.__dict__ = x
  1237. AssertUnreachable()
  1238. except TypeError: pass
  1239. def test_default_new_init():
  1240. """test cases to verify we do the right thing for the default new & init
  1241. methods"""
  1242. anyInitList = [
  1243. int,
  1244. long,
  1245. float,
  1246. complex,
  1247. tuple,
  1248. ]
  1249. anyNewList = [list, # classes that take any set of args to __new__
  1250. set,
  1251. ]
  1252. AssertError(TypeError, object().__init__, 1, 2, 3)
  1253. for x in anyInitList:
  1254. x().__init__(1, 2, 3)
  1255. AssertError(TypeError, x.__new__, x, 1, 2, 3)
  1256. AreEqual(isinstance(x.__new__(x), x), True)
  1257. for x in anyNewList:
  1258. AreEqual(len(x.__new__(x, 1, 2, 3)), 0)
  1259. AssertError(TypeError, x.__new__(x).__init__, 1, 2, 3)
  1260. class foo(object): pass
  1261. AssertError(TypeError, foo, 1)
  1262. class foo(list): pass
  1263. AreEqual(list.__new__(list, sequence='abc'), [])
  1264. x = list.__new__(foo, 1, 2, 3)
  1265. AreEqual(len(x), 0)
  1266. AreEqual(type(x), foo)
  1267. # define only __init__. __new__ should be the same object
  1268. # for both types, and calling it w/ different types should have
  1269. # different responses.
  1270. class foo(object):
  1271. def __init__(self): pass
  1272. AreEqual(id(foo.__new__), id(object.__new__))
  1273. AssertError(TypeError, object.__new__, object, 1,2,3)
  1274. AreEqual(type(object.__new__(foo, 1, 2, 3)), foo)
  1275. # inheritance / mutating class hierarchy tests
  1276. # overrides __new__ w/ object.__new__
  1277. class x(object):
  1278. __new__ = object.__new__
  1279. AssertError(TypeError, x().__init__, 2)
  1280. # inherits __new__, overrides w/ default __new__
  1281. class x(object):
  1282. def __new__(cls, *args):
  1283. return object.__new__(cls)
  1284. class y(x):
  1285. __new__ = object.__new__
  1286. AreEqual(y().__init__(2), None)
  1287. # then deletes the base __new__
  1288. del x.__new__
  1289. AreEqual(y().__init__(2), None)
  1290. # then deletes y.__new__
  1291. del y.__new__
  1292. AreEqual(y().__init__(2), None)
  1293. # dynamically add __new__
  1294. class x(object): pass
  1295. x.__new__ = staticmethod(lambda cls : object.__new__(x))
  1296. AreEqual(x().__init__(2), None)
  1297. # __init__ versions
  1298. # overrides __init__ w/ object.__init__
  1299. class x(object):
  1300. __init__ = object.__init__
  1301. AssertError(TypeError, x, 2)
  1302. # inherits __init__, overrides w/ default __init__
  1303. class x(object):
  1304. def __init__(cls, *args):
  1305. return object.__init__(cls)
  1306. class y(x):
  1307. __init__ = object.__init__
  1308. AssertError(TypeError, y, 2)
  1309. # then deletes the base __init__
  1310. del x.__init__
  1311. AssertError(TypeError, y, 2)
  1312. # then deletes y.__init__
  1313. del y.__init__
  1314. AssertError(TypeError, y, 2)
  1315. # dynamically add __init__
  1316. class x(object): pass
  1317. x.__init__ = staticmethod(lambda cls : object.__init__(x))
  1318. x(2)
  1319. # switching bases doesn't change it either
  1320. class x(object):
  1321. def __new__(cls, *args):
  1322. return object.__new__(cls)
  1323. class z(object): pass
  1324. class y(x):
  1325. pass
  1326. AreEqual(y().__init__(2), None)
  1327. y.__bases__ = (z, )
  1328. AreEqual(y().__init__(2), None)
  1329. def test_hash():
  1330. for x in [tuple, str, unicode, object, frozenset]:
  1331. inst = x()
  1332. AreEqual(inst.__hash__(), hash(inst))
  1333. # old style hash can return longs, the result of which is
  1334. # the hash of the long
  1335. class foo:
  1336. def __hash__(self): return 1<<35L
  1337. if not is_net40: #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24550
  1338. AreEqual(hash(foo()), 8)
  1339. def test_NoneSelf():
  1340. try:
  1341. set.add(None)
  1342. AssertUnreachable()
  1343. except TypeError:
  1344. pass
  1345. def test_builtin_classmethod():
  1346. descr = dict.__dict__["fromkeys"]
  1347. AssertError(TypeError, descr.__get__, 42)
  1348. AssertError(TypeError, descr.__get__, None, 42)
  1349. AssertError(TypeError, descr.__get__, None, int)
  1350. def test_classmethod():
  1351. if is_ironpython: #http://ironpython.codeplex.com/workitem/27908
  1352. AssertError(TypeError, classmethod, 1)
  1353. else:
  1354. cm = classmethod(1)
  1355. AssertError(TypeError, cm.__get__, None)
  1356. AssertError(TypeError, cm.__get__, None, None)
  1357. def foo(): pass
  1358. cm = classmethod(foo)
  1359. AssertError(TypeError, cm.__get__, None)
  1360. AssertError(TypeError, cm.__get__, None, None)
  1361. def test_EmptyTypes():
  1362. for x in [None, Ellipsis, NotImplemented]:
  1363. Assert(type(x) != str)
  1364. AreEqual(repr(Ellipsis), 'Ellipsis')
  1365. AreEqual(repr(NotImplemented), 'NotImplemented')
  1366. AreEqual(repr(type(Ellipsis)), "<type 'ellipsis'>")
  1367. AreEqual(repr(type(NotImplemented)), "<type 'NotImplementedType'>")
  1368. def test_property():
  1369. prop = property()
  1370. try: prop.fget = test_classmethod
  1371. except TypeError: pass
  1372. else: AssertUnreachable()
  1373. try: prop.fdel = test_classmethod
  1374. except TypeError: pass
  1375. else: AssertUnreachable()
  1376. try: prop.__doc__ = 'abc'
  1377. except TypeError: pass
  1378. else: AssertUnreachable()
  1379. try: prop.fset = test_classmethod
  1380. except TypeError: pass
  1381. else: AssertUnreachable()
  1382. @skip("win32")
  1383. def test_override_mro():
  1384. try:
  1385. class C(object):
  1386. def __mro__(self): pass
  1387. except NotImplementedError: pass
  1388. else: Fail("Expected NotImplementedError, got none")
  1389. class C(object):
  1390. def mro(self): pass
  1391. try:
  1392. class C(type):
  1393. def mro(self): pass
  1394. except NotImplementedError: pass
  1395. else: Fail("Expected NotImplementedError, got none")
  1396. class D(type): pass
  1397. try:
  1398. class E(D):
  1399. def mro(self): pass
  1400. except NotImplementedError: pass
  1401. else: Fail("Expected NotImplementedError, got none")
  1402. def test_type_mro():
  1403. AssertError(TypeError, type.mro)
  1404. AreEqual(object.mro(), list(object.__mro__))
  1405. AreEqual(type(object.mro()), list)
  1406. AreEqual(type(object.__mro__), tuple)
  1407. def test_derived_tuple_eq():
  1408. # verify overriding __eq__ on tuple still allows us to call the super version
  1409. class bazbar(tuple):
  1410. def __eq__(self,other):
  1411. other = bazbar(other)
  1412. return super(bazbar,self).__eq__(other)
  1413. AreEqual(bazbar('abc'), 'abc')
  1414. def test_new_old_slots():
  1415. class N(object): pass
  1416. class O: pass
  1417. class C(N, O):
  1418. __slots__ = ['a','b']
  1419. def test_slots_counter():
  1420. import gc
  1421. class Counter(object):
  1422. c = 0
  1423. def __init__(self):
  1424. Counter.c += 1
  1425. def __del__(self):
  1426. Counter.c -= 1
  1427. def testit():
  1428. class C(object):
  1429. __slots__ = ['a', 'b', 'c']
  1430. x = C()
  1431. x.a = Counter()
  1432. x.b = Counter()
  1433. x.c = Counter()
  1434. AreEqual(Counter.c, 3)
  1435. del x
  1436. testit()
  1437. #collect not defined for silverlight
  1438. if not is_silverlight:
  1439. gc.collect()
  1440. AreEqual(Counter.c, 0)
  1441. def test_override_container_contains():
  1442. for x in (dict, list, tuple):
  1443. class C(x):
  1444. def __contains__(self, other):
  1445. return other == "abc"
  1446. AreEqual('abc' in C(), True)
  1447. def test_override_container_len():
  1448. for x in (dict, list, tuple):
  1449. class C(x):
  1450. def __len__(self): return 2
  1451. AreEqual(C().__len__(), 2)
  1452. AreEqual(len(C()), 2)
  1453. AreEqual(C(), x())
  1454. if x is dict:
  1455. AreEqual(C({1:1}), {1:1})
  1456. d = {1:1, 2:2, 3:3}
  1457. AreEqual(C(d).__cmp__({0:0, 1:1, 2:2}), 1)
  1458. d[4] = 4
  1459. AreEqual(len(list(C(d).iterkeys())), len(list(d.iterkeys())))
  1460. else:
  1461. AreEqual(C([1]), x([1]))
  1462. a = range(4)
  1463. AreEqual(len(list(iter(C(a)))), len(list(iter(x(a)))))
  1464. @skip("multiple_execute") #http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=17551
  1465. def test_dictproxy_access():
  1466. def f():
  1467. int.__dict__[0] = 0
  1468. AssertError(TypeError, f)
  1469. class KOld: pass
  1470. class KNew(object): pass
  1471. #CodePlex 16001
  1472. AreEqual(int.__dict__.get(0, 'abc'), 'abc')
  1473. AreEqual(int.__dict__.get('__new__'), int.__new__)
  1474. AreEqual(KOld.__dict__.get(0, 'abc'), 'abc')
  1475. AreEqual(KNew.__dict__.get(0, 'abc'), 'abc')
  1476. AreEqual(KNew.__dict__.get('__new__'), None)
  1477. #CodePlex 15702
  1478. AreEqual(int.__dict__.copy(), dict(int.__dict__))
  1479. AreEqual(int.__class__.__dict__.copy(), dict(int.__class__.__dict__))
  1480. AreEqual(KOld.__dict__.copy(), dict(KOld.__dict__))
  1481. AreEqual(KNew.__dict__.copy(), dict(KNew.__dict__))
  1482. #Dev10 4844754
  1483. AreEqual(KNew.__class__.__dict__.copy(), dict(KNew.__class__.__dict__))
  1484. AreEqual(set(KNew.__dict__.iteritems()), set(dict(KNew.__dict__).iteritems()))
  1485. AreEqual(set(KNew.__dict__.iterkeys()), set(dict(KNew.__dict__).iterkeys()))
  1486. AreEqual(set(KNew.__dict__.itervalues()), set(dict(KNew.__dict__).itervalues()))
  1487. for value in [None, 'abc', 1, object(), KNew(), KOld(), KNew, KOld, property(lambda x: x)]:
  1488. class KNew(object):
  1489. abc = value
  1490. AreEqual(KNew.__dict__['abc'], value)
  1491. AreEqual(KNew.__dict__.get('abc'), value)
  1492. AreEqual(KNew.__dict__.get('abc', value), value)
  1493. for items in KNew.__dict__.iteritems(), KNew.__dict__.items(), zip(KNew.__dict__.keys(), KNew.__dict__.values()):
  1494. for k, v in items:
  1495. if k == 'abc':
  1496. AreEqual(v, value)
  1497. # tests w/ special requirements that can't be run in methods..
  1498. #Testing the class attributes backed by globals
  1499. x = 10
  1500. class C:
  1501. x = x
  1502. del x
  1503. x = x
  1504. AreEqual(C.x, 10)
  1505. AreEqual(x, 10)
  1506. try:
  1507. class C:
  1508. x = x
  1509. del x
  1510. del x
  1511. except NameError:
  1512. pass
  1513. else:
  1514. Assert("Expecting name error")
  1515. AreEqual(x, 10)
  1516. class C:
  1517. x = 10
  1518. del x
  1519. b = x
  1520. AreEqual(x, 10)
  1521. AreEqual(C.b, 10)
  1522. AreEqual(x, 10)
  1523. def test_getattribute_getattr():
  1524. # verify object.__getattribute__(name) will call __getattr__
  1525. class Base(object):
  1526. def __getattribute__(self, name):
  1527. return object.__getattribute__(self, name)
  1528. class Derived(Base):
  1529. def __getattr__(self, name):
  1530. if name == "bar": return 23
  1531. raise AttributeError(name)
  1532. def __getattribute__(self, name):
  1533. return Base.__getattribute__(self, name)
  1534. a = Derived()
  1535. AreEqual(a.bar, 23)
  1536. # getattr doesn't get called when calling object.__getattribute__
  1537. class x(object):
  1538. def __getattr__(self, name): return 23
  1539. AssertError(AttributeError, object.__getattribute__, x(), 'abc')
  1540. # verify __getattr__ gets called after __getattribute__ fails, not
  1541. # during the base call to object.
  1542. state = []
  1543. class Derived(object):
  1544. def __getattr__(self, name):
  1545. if name == "bar":
  1546. AreEqual(state, [])
  1547. return 23
  1548. raise AttributeError(name)
  1549. def __getattribute__(self, name):
  1550. try:
  1551. state.append('getattribute')
  1552. return object.__getattribute__(self, name)
  1553. finally:
  1554. AreEqual(state.pop(), 'getattribute')
  1555. a = Derived()
  1556. AreEqual(a.bar, 23)
  1557. def test_dynamic_getattribute_getattr():
  1558. class Base(object):
  1559. pass
  1560. def __getattribute__(self, name):
  1561. return object.__getattribute__(self, name)
  1562. Base.__getattribute__ = __getattribute__
  1563. class Derived(Base):
  1564. pass
  1565. def __getattr__(self, name):
  1566. if name == "bar":
  1567. return 23
  1568. raise AttributeError(name)
  1569. Derived.__getattr__ = __getattr__
  1570. def __getattribute__(self, name):
  1571. return Base.__getattribute__(self, name)
  1572. Derived.__getattribute__ = __getattribute__
  1573. a = Derived()
  1574. AreEqual(a.bar, 23)
  1575. def test_setattr():
  1576. # verify defining __setattr__ works
  1577. global setCalled
  1578. class KNew(object):
  1579. def __setattr__(self, name, value):
  1580. global setCalled
  1581. setCalled = True
  1582. object.__setattr__(self, name, value)
  1583. class KOld:
  1584. def __setattr__(self, name, value):
  1585. global setCalled
  1586. setCalled = True
  1587. self.__dict__[name] = value
  1588. class KNewSub(KNew): pass
  1589. class KOldSub(KOld): pass
  1590. for K in [ KOld,
  1591. KOldSub, #CodePlex 8018
  1592. KNew,
  1593. KNewSub]:
  1594. setCalled = False
  1595. x = K()
  1596. x.abc = 23
  1597. AreEqual(x.abc, 23)
  1598. AreEqual(setCalled, True)
  1599. def test_dynamic_getattribute():
  1600. # verify adding / removing __getattribute__ succeeds
  1601. # remove
  1602. class foo(object):
  1603. def __getattribute__(self, name):
  1604. raise Exception()
  1605. class bar(foo):
  1606. def __getattribute__(self, name):
  1607. return super(bar, self).__getattribute__(name)
  1608. del foo.__getattribute__
  1609. a = bar()
  1610. a.xyz = 'abc'
  1611. AreEqual(a.xyz, 'abc')
  1612. # add
  1613. class foo(object): pass
  1614. def getattr(self, name):
  1615. if name == 'abc': return 42
  1616. foo.__getattribute__ = getattr
  1617. AreEqual(foo().abc, 42)
  1618. def test_nonstring_name():
  1619. global __name__
  1620. name = __name__
  1621. try:
  1622. __name__ = 3
  1623. class C: pass
  1624. AreEqual(C.__module__, 3)
  1625. class C(object): pass
  1626. AreEqual(C.__module__, 3)
  1627. class C(type): pass
  1628. AreEqual(C.__module__, 3)
  1629. class D(object):
  1630. __metaclass__ = C
  1631. AreEqual(D.__module__, 3)
  1632. finally:
  1633. __name__ = name
  1634. def test_dictproxy_descrs():
  1635. # verify that we get the correct descriptors when we access the dictionary proxy directly
  1636. class foo(object):
  1637. xyz = 'abc'
  1638. AreEqual(foo.__dict__['xyz'], 'abc')
  1639. class foo(object):
  1640. def __get__(self, instance, context):
  1641. return 'abc'
  1642. class bar(object):
  1643. xyz = foo()
  1644. AreEqual(bar.__dict__['xyz'].__class__, foo)
  1645. ## __int__
  1646. def test_fastnew_int():
  1647. class C1:
  1648. def __int__(self): return 100
  1649. class C2:
  1650. def __int__(self): return myint(100)
  1651. class C3:
  1652. def __int__(self): return 100L
  1653. class C4:
  1654. def __int__(self): return mylong(100L)
  1655. class C5:
  1656. def __int__(self): return -123456789012345678910
  1657. class C6:
  1658. def __int__(self): return C6()
  1659. class C7:
  1660. def __int__(self): return "100"
  1661. for x in [C1, C2, C3, C4]: AreEqual(int(x()), 100)
  1662. AreEqual(int(C5()), -123456789012345678910)
  1663. for x in [C6, C7]: AssertError(TypeError, int, x())
  1664. class C1(object):
  1665. def __int__(self): return 100
  1666. class C2(object):
  1667. def __int__(self): return myint(100)
  1668. class C3(object):
  1669. def __int__(self): return 100L
  1670. class C4(object):
  1671. def __int__(self): return mylong(100L)
  1672. class C5(object):
  1673. def __int__(self): return -123456789012345678910
  1674. class C6(object):
  1675. def __int__(self): return C6()
  1676. class C7(object):
  1677. def __int__(self): return "100"
  1678. for x in [C1, C2, C3, C4]: AreEqual(int(x()), 100)
  1679. AreEqual(int(C5()), -123456789012345678910)
  1680. for x in [C6, C7]: AssertError(TypeError, int, x())
  1681. def test_type_type_is_type():
  1682. class OS: pass
  1683. class NS(object): pass
  1684. true_values = [type, NS, int, float, tuple, str]
  1685. if is_cli:
  1686. import System
  1687. true_values += [System.Boolean, System.Int32, System.Version, System.Exception]
  1688. for x in true_values:
  1689. Assert(type(x) is type)
  1690. false_values = [OS]
  1691. if is_cli:
  1692. false_values += [ System.Boolean(1), System.Int32(3), System.Version(0, 0), System.Exception() ]
  1693. for x in false_values:
  1694. Assert(type(x) is not type)
  1695. def test_hash_return_values():
  1696. # new-style classes do conversion to int
  1697. for retval in [1, 1.0, 1.1, 1L, 1<<30]:
  1698. for type in [object, int, str, float, long]:
  1699. class foo(object):
  1700. def __hash__(self): return retval
  1701. AreEqual(hash(foo()), int(retval))
  1702. # old-style classes require int or long return value
  1703. for retval in [1.0, 1.1]:
  1704. class foo:
  1705. def __hash__(self): return retval
  1706. AssertError(TypeError, hash, foo())
  1707. tests = { 1L:1,
  1708. 2L:2,
  1709. }
  1710. if not is_net40: #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24550
  1711. tests.update( { 1<<32: 1,
  1712. (1<<32)+1: 2,
  1713. 1<<34: 4,
  1714. 1<<31: -2147483648,
  1715. })
  1716. for retval in tests.keys():
  1717. class foo:
  1718. def __hash__(self): return retval
  1719. AreEqual(hash(foo()), tests[retval])
  1720. def test_cmp_notimplemented():
  1721. class foo(object):
  1722. def __eq__(self, other):
  1723. ran.append('foo.eq')
  1724. return NotImplemented
  1725. def __ne__(self, other):
  1726. ran.append('foo.ne')
  1727. return NotImplemented
  1728. def __le__(self, other):
  1729. ran.append('foo.le')
  1730. return NotImplemented
  1731. def __lt__(self, other):
  1732. ran.append('foo.lt')
  1733. return NotImplemented
  1734. def __gt__(self, other):
  1735. ran.append('foo.gt')
  1736. return NotImplemented
  1737. def __ge__(self, other):
  1738. ran.append('foo.ge')
  1739. return NotImplemented
  1740. def __cmp__(self, other):
  1741. ran.append('foo.cmp')
  1742. return NotImplemented
  1743. class bar:
  1744. def __eq__(self, other):
  1745. ran.append('bar.eq')
  1746. return NotImplemented
  1747. def __ne__(self, other):
  1748. ran.append('bar.ne')
  1749. return NotImplemented
  1750. def __le__(self, other):
  1751. ran.append('bar.le')
  1752. return NotImplemented
  1753. def __lt__(self, other):
  1754. ran.append('bar.lt')
  1755. return NotImplemented
  1756. def __gt__(self, other):
  1757. ran.append('bar.gt')
  1758. return NotImplemented
  1759. def __ge__(self, other):
  1760. ran.append('bar.ge')
  1761. return NotImplemented
  1762. def __cmp__(self, other):
  1763. ran.append('bar.cmp')
  1764. return NotImplemented
  1765. ran = []
  1766. cmp(foo(), bar())
  1767. #AreEqual(ran, ['foo.eq', 'bar.eq', 'foo.lt', 'bar.gt', 'foo.gt', 'bar.lt', 'bar.cmp'])
  1768. ran = []
  1769. cmp(foo(), foo())
  1770. #AreEqual(ran, ['foo.cmp', 'foo.cmp'])
  1771. ran = []
  1772. cmp(bar(), bar())
  1773. #AreEqual(ran, ['bar.cmp', 'bar.cmp', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.lt', 'bat.gt', 'bar.gt', 'bar.lt', 'bar.gt', 'bar.lt', 'bar.lt', 'bar.gt', 'bar.cmp', 'bar.cmp'])
  1774. ran = []
  1775. cmp(foo(), 1)
  1776. #AreEqual(ran, ['foo.eq', 'foo.lt', 'foo.gt', 'foo.cmp'])
  1777. def test_override_repr():
  1778. class KOld:
  1779. def __repr__(self):
  1780. return "old"
  1781. class KNew(object):
  1782. def __repr__(self):
  1783. return "new"
  1784. AreEqual(repr(KOld()), "old")
  1785. AreEqual(str(KOld()), "old")
  1786. AreEqual(repr(KNew()), "new")
  1787. #IP breaks here because __str__ in new style classes does not call __repr__
  1788. AreEqual(str(KNew()), "new")
  1789. def test_mutate_base():
  1790. class basetype(object):
  1791. xyz = 3
  1792. class subtype(basetype): pass
  1793. AreEqual(subtype.xyz, 3)
  1794. AreEqual(subtype().xyz, 3)
  1795. basetype.xyz = 7
  1796. AreEqual(subtype.xyz, 7)
  1797. AreEqual(subtype().xyz, 7)
  1798. def test_mixed_newstyle_oldstyle_init():
  1799. """mixed new-style & old-style class should run init if its defined in the old-style class"""
  1800. class foo:
  1801. def __init__(self):
  1802. self.x = 3
  1803. class bar(foo):
  1804. def __init__(self):
  1805. self.x = 4
  1806. class baz(foo): pass
  1807. class ns(object): pass
  1808. class full(bar, baz, ns): pass
  1809. a = full()
  1810. AreEqual(a.x, 4)
  1811. class full(bar, baz, ns):
  1812. def __init__(self):
  1813. self.x = 5
  1814. a = full()
  1815. AreEqual(a.x, 5)
  1816. class ns(object):
  1817. def __init__(self):
  1818. self.x = 6
  1819. class full(bar, baz, ns): pass
  1820. a = full()
  1821. AreEqual(a.x, 4)
  1822. def test_mixed_newstyle_oldstyle_new():
  1823. class S:
  1824. pass
  1825. class P(S, object):
  1826. def __new__(cls, *a, **kw):
  1827. return object.__new__(cls)
  1828. AreEqual(type(P()), P)
  1829. def test_mixed_newstyle_oldstyle_descriptor():
  1830. class base:
  1831. @classmethod
  1832. def f(cls):
  1833. return cls
  1834. class x(base, object):
  1835. pass
  1836. AreEqual(x.f(), x)
  1837. def test_getattr_exceptions():
  1838. """verify the original exception propagates out"""
  1839. class AttributeTest(object):
  1840. def __getattr__(self, name): raise AttributeError('catch me')
  1841. x = AttributeTest()
  1842. try:
  1843. y = x.throws
  1844. except AttributeError, ex:
  1845. AreEqual(ex.args, ('catch me',))
  1846. else: Fail("should have thrown")
  1847. def test_descriptor_meta_magic():
  1848. class valueDescriptor(object):
  1849. def __init__(self,x=None): self.value = x
  1850. def __get__(self,ob,cls): return self.value
  1851. def __set__(self,ob,x): self.value = x
  1852. class Ameta(type):
  1853. def createShared( cls, nm, initValue=None ):
  1854. o = valueDescriptor(initValue)
  1855. setattr( cls,nm, o )
  1856. setattr( cls.__class__,nm, o )
  1857. class A:
  1858. __metaclass__ = Ameta
  1859. class B( A ):
  1860. A.createShared("cls2",1)
  1861. def test(value):
  1862. AreEqual(o.cls2, value)
  1863. AreEqual(o2.cls2, value)
  1864. AreEqual(A.cls2, value)
  1865. AreEqual(B.cls2, value)
  1866. o = A()
  1867. o2 = B()
  1868. test(1)
  1869. B.cls2 = 2
  1870. test(2)
  1871. A.cls2 = 3
  1872. test(3)
  1873. o.cls2 = 4
  1874. test(4)
  1875. o2.cls2 = 5
  1876. test(5)
  1877. def test_missing_attr():
  1878. class foo(object): pass
  1879. a = foo()
  1880. def f(): a.dne
  1881. AssertErrorWithMessage(AttributeError, "'foo' object has no attribute 'dne'", f)
  1882. def test_method():
  1883. class tst_oc:
  1884. def root(): return 2
  1885. class tst_nc:
  1886. def root(): return 2
  1887. AssertError(TypeError, tst_oc.root)
  1888. AssertError(TypeError, tst_nc.root)
  1889. instancemethod = type(tst_oc.root)
  1890. AssertError(TypeError, instancemethod, lambda x:True, None)
  1891. def test_descriptors_custom_attrs():
  1892. """verifies the interaction between descriptors and custom attribute access works properly"""
  1893. class mydesc(object):
  1894. def __get__(self, instance, ctx):
  1895. raise AttributeError
  1896. class f(object):
  1897. x = mydesc()
  1898. def __getattr__(self, name): return 42
  1899. AreEqual(f().x, 42)
  1900. def test_cp5801():
  1901. class Foo(object):
  1902. __slots__ = ['bar']
  1903. def __getattr__(self, n):
  1904. return n.upper()
  1905. foo = Foo()
  1906. AreEqual(foo.bar, "BAR")
  1907. def test_property_always_set_descriptor():
  1908. """verifies that set descriptors take precedence over dictionary entries and
  1909. properties are always treated as set descriptors, even if they have no
  1910. setter function"""
  1911. class C(object):
  1912. x = property(lambda self: self._x)
  1913. def __init__(self):
  1914. self._x = 42
  1915. c = C()
  1916. c.__dict__['x'] = 43
  1917. AreEqual(c.x, 42)
  1918. # now check a user get descriptor
  1919. class MyDescriptor(object):
  1920. def __get__(self, *args): return 42
  1921. class C(object):
  1922. x = MyDescriptor()
  1923. c = C()
  1924. c.__dict__['x'] = 43
  1925. AreEqual(c.x, 43)
  1926. # now check a user get/set descriptor
  1927. class MyDescriptor(object):
  1928. def __get__(self, *args): return 42
  1929. def __set__(self, *args): pass
  1930. class C(object):
  1931. x = MyDescriptor()
  1932. c = C()
  1933. c.__dict__['x'] = 43
  1934. AreEqual(c.x, 42)
  1935. def test_object_as_condition():
  1936. class C(object):
  1937. def __mod__(self, other): return 1
  1938. o = C()
  1939. flag = 0
  1940. if o % o: flag = 1 # the bug was causing cast error before
  1941. AreEqual(flag, 1)
  1942. def test_unbound_class_method():
  1943. class C(object):
  1944. def f(): return 1
  1945. x = C()
  1946. AssertErrorWithPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f())
  1947. AssertErrorWithPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f(C))
  1948. AssertErrorWithPartialMessage(TypeError, "arguments (1 given)", lambda: C.f(x))
  1949. AssertErrorWithPartialMessage(TypeError, "arguments (1 given)", lambda: x.f())
  1950. def test_oldinstance_operator_exceptions():
  1951. global called
  1952. def fmaker(name, ex = None):
  1953. def f(self, *args):
  1954. global called
  1955. called.append(name)
  1956. if ex:
  1957. raise ex(name)
  1958. def g(*args):
  1959. return NotImplemented
  1960. return g
  1961. return f
  1962. def fthrowingmaker(name, ex):
  1963. def f(self):
  1964. global called
  1965. called.append(name)
  1966. def g(*args):
  1967. raise ex
  1968. return g
  1969. return f
  1970. class OC:
  1971. __eq__ = property(fmaker('oc_eq', AttributeError))
  1972. __ne__ = property(fmaker('oc_ne', AttributeError))
  1973. class OC2:
  1974. __eq__ = property(fthrowingmaker('oc_eq', AttributeError))
  1975. __ne__ = property(fthrowingmaker('oc_ne', AttributeError))
  1976. class OC3:
  1977. def __getattr__(self, name):
  1978. return property(fmaker(name, AttributeError)).__get__(self, OC3)
  1979. called = []
  1980. Assert(not OC() == OC())
  1981. AreEqual(called, ['oc_eq']*4)
  1982. called = []
  1983. type(OC()).__eq__(OC(), OC())
  1984. AreEqual(called, ['oc_eq']*2)
  1985. called =[]
  1986. Assert(OC() != OC())
  1987. AreEqual(called, ['oc_ne']*4)
  1988. called = []
  1989. type(OC()).__ne__(OC(), OC())
  1990. AreEqual(called, ['oc_ne']*2)
  1991. called = []
  1992. AssertError(AttributeError, lambda : not OC2() == OC2())
  1993. AreEqual(called, ['oc_eq'])
  1994. called = []
  1995. AssertError(AttributeError, lambda : type(OC2()).__eq__(OC2(), OC2()))
  1996. AreEqual(called, ['oc_eq'])
  1997. called =[]
  1998. AssertError(AttributeError, lambda : OC2() != OC2())
  1999. AreEqual(called, ['oc_ne'])
  2000. called = []
  2001. AssertError(AttributeError, lambda : type(OC2()).__ne__(OC2(), OC2()))
  2002. AreEqual(called, ['oc_ne'])
  2003. called = []
  2004. AssertError(AttributeError, lambda : type(OC()).__getattribute__(OC(), '__eq__'))
  2005. AreEqual(called, ['oc_eq'])
  2006. Assert(not hasattr(OC(), '__eq__'))
  2007. # IronPython still differs on these from CPython:
  2008. # verify other attributes work correctly
  2009. #for x in ['__abs__', '__float__', '__long__', '__int__', '__hex__', '__oct__', '__pos__', '__neg__', '__invert__']:
  2010. # # unary operators which pass on AttributeError
  2011. # print x
  2012. # AssertError(AttributeError, getattr(type(OC3()), x), OC3())
  2013. for x in ['__hash__', '__nonzero__', '__str__', '__repr__']:
  2014. # unary operators that catch AttributeError
  2015. getattr(type(OC3()), x)(OC3())
  2016. # IronPython still differs on these from CPython:
  2017. #for x in ['__iter__']:
  2018. # # unary operators that call, catch, and report another error
  2019. # called = []
  2020. # AssertError(TypeError, getattr(type(OC3()), x), OC3())
  2021. # Assert(x in called)
  2022. for x in ['__add__', '__iadd__', '__radd__', '__cmp__', '__coerce__']:
  2023. # binary operators catch AttributeError
  2024. getattr(type(OC3()), x)(OC3(), OC3())
  2025. def test_cp10291():
  2026. class K1(object):
  2027. def __call__(self):
  2028. return "K1"
  2029. class K2(K1):
  2030. def __call__(self):
  2031. return "K2" + K1.__call__(self)
  2032. class K1Old:
  2033. def __call__(self):
  2034. return "K1"
  2035. class K2Old(K1Old):
  2036. def __call__(self):
  2037. return "K2" + K1Old.__call__(self)
  2038. for k1, k2 in [ (K1, K2),
  2039. (K1Old, K2Old),
  2040. ]:
  2041. AreEqual(k1()(), "K1")
  2042. AreEqual(k2()(), "K2K1")
  2043. @skip("win32") # should be reenabled against CPython26
  2044. def test_cp11760():
  2045. class KNew(object):
  2046. def __str__(self): return "KNew"
  2047. class KOld:
  2048. def __str__(self): return "KOld"
  2049. for K in [KNew, KOld]:
  2050. dir_str = dir(K().__str__)
  2051. for x in [ '__class__', '__delattr__', '__doc__',
  2052. '__get__', '__getattribute__', '__hash__', '__init__',
  2053. '__new__', '__reduce__', '__reduce_ex__', '__repr__',
  2054. '__setattr__', '__str__', 'im_class',
  2055. 'im_func', '__func__', 'im_self', '__self__',
  2056. #'__call__', '__cmp__',
  2057. ]:
  2058. Assert(x in dir_str, x + " is not in dir(K().__str__)")
  2059. def test_delattr():
  2060. global called
  2061. class X(object):
  2062. def __delattr__(self, name):
  2063. global called
  2064. called = True
  2065. del X().abc
  2066. Assert(called)
  2067. def test_cp10709():
  2068. class KNew(object):
  2069. p1 = property(lambda self: 3.14)
  2070. m1 = lambda self: 3.15
  2071. f1 = lambda: 3.16
  2072. def m2(self, a):
  2073. x = lambda: 3.17
  2074. return x()
  2075. class KOld:
  2076. p1 = property(lambda self: 3.14)
  2077. m1 = lambda self: 3.15
  2078. f1 = lambda: 3.16
  2079. def m2(self, a):
  2080. x = lambda: 3.17
  2081. return x()
  2082. for temp in dir(KNew) + dir(KNew()) + dir(KOld) + dir(KOld()):
  2083. Assert("lambda" not in temp)
  2084. def test_oldstyle_fancycallable():
  2085. class C : pass
  2086. x = C(*())
  2087. Assert(x.__class__ is C)
  2088. x = C(**{})
  2089. Assert(x.__class__ is C)
  2090. x = C(*(), **{})
  2091. Assert(x.__class__ is C)
  2092. class C:
  2093. def __init__(self, a):
  2094. pass
  2095. x = C(*(2,))
  2096. #Merlin 382112
  2097. x = C(*(None,))
  2098. Assert(x.__class__ is C)
  2099. x = C(**{'a': None})
  2100. def test_oldclass_newclass_construction():
  2101. """calling __new__ on and old-class passing in new-classes should result in a new-style type"""
  2102. class nc(object): pass
  2103. class oc: pass
  2104. newType = type(oc).__new__(type(oc), 'foo', (nc, oc), {})
  2105. AreEqual(type(newType), type)
  2106. def test_inherited_getattribute():
  2107. """inherited getattribute should be respected"""
  2108. class x(object):
  2109. def __getattribute__(self, name):
  2110. if name == 'abc': return 42
  2111. return object.__getattribute__(self, name)
  2112. class y(x): pass
  2113. AreEqual(y().abc, 42)
  2114. GETATTRIBUTE_CALLED = False
  2115. def test_cp13820():
  2116. global GETATTRIBUTE_CALLED
  2117. GETATTRIBUTE_CALLED = False
  2118. class KOld:
  2119. def __getattribute__(self, name):
  2120. global GETATTRIBUTE_CALLED
  2121. GETATTRIBUTE_CALLED = True
  2122. print "__getattribute__ was called by:", name
  2123. return 1
  2124. def __init__(self):
  2125. return
  2126. def __del__(self):
  2127. return
  2128. def __str__(self): return ""
  2129. def __cmp__(self, other): return 0
  2130. def __hash__(self): return 1
  2131. def __nonzero__(self): return 1
  2132. def __get__(self, instance, owner): return 3
  2133. def __delete__(self, instance): return
  2134. def __len__(self): return 4
  2135. def __getitem__(self, key): return 5
  2136. def __setitem__(self, key, value): return
  2137. def __getslice__(self, i, j): return 6
  2138. def __contains__(self, obj): return True
  2139. def __add__(self, other): return 7
  2140. def __hex__(self): return hex(9)
  2141. def __coerce__(self, other): return None
  2142. def __lt__(self, other): return True
  2143. class KNew(object):
  2144. def __getattribute__(self, name):
  2145. global GETATTRIBUTE_CALLED
  2146. GETATTRIBUTE_CALLED = True
  2147. print "__getattribute__ was called by:", name
  2148. return 1
  2149. def __init__(self):
  2150. return
  2151. def __del__(self):
  2152. return
  2153. def __str__(self): return ""
  2154. def __cmp__(self, other): return 0
  2155. def __hash__(self): return 1
  2156. def __nonzero__(self): return 1
  2157. def __get__(self, instance, owner): return 3
  2158. def __delete__(self, instance): return
  2159. def __len__(self): return 4
  2160. def __getitem__(self, key): return 5
  2161. def __setitem__(self, key, value): return
  2162. def __getslice__(self, i, j): return 6
  2163. def __contains__(self, obj): return True
  2164. def __add__(self, other): return 7
  2165. def __hex__(self): return hex(9)
  2166. def __coerce__(self, other): return None
  2167. def __lt__(self, other): return True
  2168. for K in [KOld, KNew]:
  2169. obj = K()
  2170. str(obj)
  2171. obj==3
  2172. hash(obj)
  2173. bool(obj)
  2174. obj[3]
  2175. obj[3] = 4
  2176. len(obj)
  2177. obj[1:3]
  2178. if K==KOld: hasattr(obj, "abc")
  2179. obj + 3
  2180. hex(obj)
  2181. obj<9
  2182. del obj
  2183. Assert(not GETATTRIBUTE_CALLED)
  2184. def test_keyword_type_construction():
  2185. """using type.__call__ should accept keyword arguments"""
  2186. class x(object):
  2187. def __new__(cls, *args, **kwargs):
  2188. return object.__new__(cls)
  2189. def __init__(self, *args, **kwargs):
  2190. for x, y in kwargs.iteritems():
  2191. setattr(self, x, y)
  2192. return object.__init__(self)
  2193. obj = type.__call__(x, *(), **{'abc':2})
  2194. AreEqual(obj.abc, 2)
  2195. obj = x.__call__(*(), **{'abc':3})
  2196. AreEqual(obj.abc, 3)
  2197. def test_mixed_mro_respected():
  2198. """creates a class with an mro of "MC, NC, OC2, NC2, object, OC" and verifies that we get NC2 member, not OC"""
  2199. class OC:
  2200. abc = 3
  2201. class OC2(OC):
  2202. pass
  2203. class NC(object):
  2204. pass
  2205. class NC2(object):
  2206. abc = 5
  2207. class MC(NC, OC2, NC2, OC): pass
  2208. AreEqual(MC.abc, 5)
  2209. def test_descriptor_object_getattribute_interactions():
  2210. class nondata_desc(object):
  2211. def __init__(self, value): self.value = value
  2212. def __get__(self, inst, ctx = None):
  2213. return (self.value, inst, ctx)
  2214. class data_desc(object):
  2215. def __init__(self, value): self.value = value
  2216. def __get__(self, inst, ctx = None):
  2217. return (self.value, inst, ctx)
  2218. def __set__(self, inst, value):
  2219. self.value = value
  2220. def __delete__(self, inst):
  2221. del self.value
  2222. class readonly_data_desc(object):
  2223. def __init__(self, value): self.value = value
  2224. def __get__(self, inst, ctx = None):
  2225. return (self.value, inst, ctx)
  2226. def __set__(self, inst, value):
  2227. raise AttributeError()
  2228. def __delete__(self, inst):
  2229. raise AttributeError()
  2230. class meta(type):
  2231. nondata = nondata_desc(1)
  2232. data = data_desc(2)
  2233. nondata_shadowed_class = nondata_desc(3)
  2234. data_shadowed_class = data_desc(4)
  2235. nondata_shadowed_inst = nondata_desc(5)
  2236. data_shadowed_inst = data_desc(6)
  2237. ro_data = readonly_data_desc(7)
  2238. ro_shadowed_class = readonly_data_desc(8)
  2239. ro_shadowed_inst = readonly_data_desc(9)
  2240. class x(object):
  2241. __metaclass__ = meta
  2242. def __init__(self):
  2243. self.nondata_shadowed_inst = "nondata_inst"
  2244. self.data_shadowed_inst = "data_inst"
  2245. self.ro_shadowed_inst = 'ro_inst'
  2246. nondata_shadowed_class = 'nondata_shadowed_class'
  2247. data_shadowed_class = 'data_shadowed_class'
  2248. ro_shadowed_class = 'ro_shadowed_class'
  2249. a = x()
  2250. AssertError(AttributeError, object.__getattribute__, a, 'nondata')
  2251. AssertError(AttributeError, object.__getattribute__, a, 'data')
  2252. AssertError(AttributeError, object.__getattribute__, a, 'ro_data')
  2253. AreEqual(object.__getattribute__(a, 'nondata_shadowed_class'), 'nondata_shadowed_class')
  2254. AreEqual(object.__getattribute__(a, 'data_shadowed_class'), 'data_shadowed_class')
  2255. AreEqual(object.__getattribute__(a, 'ro_shadowed_class'), 'ro_shadowed_class')
  2256. AreEqual(object.__getattribute__(a, 'nondata_shadowed_inst'), 'nondata_inst')
  2257. AreEqual(object.__getattribute__(a, 'data_shadowed_inst'), 'data_inst')
  2258. AreEqual(object.__getattribute__(a, 'ro_shadowed_inst'), 'ro_inst')
  2259. AreEqual(object.__getattribute__(x, 'nondata_shadowed_class'), 'nondata_shadowed_class')
  2260. AreEqual(object.__getattribute__(x, 'data_shadowed_class'), (4, x, meta))
  2261. AreEqual(object.__getattribute__(x, 'ro_shadowed_class'), (8, x, meta))
  2262. AreEqual(object.__getattribute__(x, 'nondata_shadowed_inst'), (5, x, meta))
  2263. AreEqual(object.__getattribute__(x, 'data_shadowed_inst'), (6, x, meta))
  2264. AreEqual(object.__getattribute__(x, 'ro_shadowed_inst'), (9, x, meta))
  2265. AreEqual(object.__getattribute__(x, 'ro_data'), (7, x, meta))
  2266. AreEqual(object.__getattribute__(x, 'nondata'), (1, x, meta))
  2267. AreEqual(object.__getattribute__(x, 'data'), (2, x, meta))
  2268. def test_cp5803():
  2269. #--Simple
  2270. class KSimple(object):
  2271. def __radd__(self, other):
  2272. return
  2273. for x in ["", 1, 3.14, None, u"stuff", object, KSimple]:
  2274. AreEqual(x + KSimple(), None)
  2275. AssertErrorWithPartialMessage(TypeError,
  2276. "unsupported operand type(s) for +: 'KSimple' and 'str'",
  2277. lambda: KSimple() + "")
  2278. #--Addition
  2279. class K(object): pass
  2280. class K0(object):
  2281. def __radd__(self, other):
  2282. return "__radd__:" + str(type(self)) + " " + str(type(other))
  2283. class K1(object):
  2284. def __radd__(self, other):
  2285. return "__radd__:" + str(type(self)) + " " + str(type(other))
  2286. def __add__(self, other):
  2287. return "__add__:" + str(type(self)) + " " + str(type(other))
  2288. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K' and 'K'", lambda: K() + K())
  2289. AreEqual(K() + K0(), "__radd__:<class '" + __name__ + ".K0'> <class '" + __name__ + ".K'>")
  2290. AreEqual(K() + K1(), "__radd__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
  2291. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K'", lambda: K0() + K())
  2292. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K0'", lambda: K0() + K0())
  2293. AreEqual(K0() + K1(), "__radd__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
  2294. AreEqual(K1() + K(), "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
  2295. AreEqual(K1() + K0(), "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
  2296. AreEqual(K1() + K1(), "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K1'>" )
  2297. #--Subtraction
  2298. class K(object): pass
  2299. class K0(object):
  2300. def __rsub__(self, other):
  2301. return "__rsub__:" + str(type(self)) + " " + str(type(other))
  2302. class K1(object):
  2303. def __rsub__(self, other):
  2304. return "__rsub__:" + str(type(self)) + " " + str(type(other))
  2305. def __sub__(self, other):
  2306. return "__sub__:" + str(type(self)) + " " + str(type(other))
  2307. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K' and 'K'", lambda: K() - K())
  2308. AreEqual(K() - K0(), "__rsub__:<class '" + __name__ + ".K0'> <class '" + __name__ + ".K'>")
  2309. AreEqual(K() - K1(), "__rsub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
  2310. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K'", lambda: K0() - K())
  2311. AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K0'", lambda: K0() - K0())
  2312. AreEqual(K0() - K1(), "__rsub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
  2313. AreEqual(K1() - K(), "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
  2314. AreEqual(K1() - K0(), "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
  2315. AreEqual(K1() - K1(), "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K1'>" )
  2316. #--Old style
  2317. class K: pass
  2318. class K0:
  2319. def __radd__(self, other):
  2320. return "__radd__:" + str(type(self)) + " " + str(type(other))
  2321. class K1:
  2322. def __radd__(self, other):
  2323. return "__radd__:" + str(type(self)) + " " + str(type(other))
  2324. def __add__(self, other):
  2325. return "__add__:" + str(type(self)) + " " + str(type(other))
  2326. AssertError(TypeError, lambda: K() + K())
  2327. AreEqual(K() + K0(), "__radd__:<type 'instance'> <type 'instance'>")
  2328. AreEqual(K() + K1(), "__radd__:<type 'instance'> <type 'instance'>")
  2329. AssertError(TypeError, lambda: K0() + K())
  2330. AreEqual(K0() + K0(), "__radd__:<type 'instance'> <type 'instance'>")
  2331. AreEqual(K0() + K1(), "__radd__:<type 'instance'> <type 'instance'>")
  2332. AreEqual(K1() + K(), "__add__:<type 'instance'> <type 'instance'>")
  2333. AreEqual(K1() + K0(), "__add__:<type 'instance'> <type 'instance'>")
  2334. AreEqual(K1() + K1(), "__add__:<type 'instance'> <type 'instance'>")
  2335. def test_special_type_attributes():
  2336. # some attributes on new-style class are alwayed retrieved
  2337. # from the type, not the classes dictionary
  2338. class x(object):
  2339. __dict__ = 'abc'
  2340. __class__ = 'abc'
  2341. __bases__ = 'abc'
  2342. __name__ = 'abc'
  2343. class y(object): pass
  2344. AreEqual(type(x.__dict__), type(y.__dict__))
  2345. AreEqual(x.__class__, type)
  2346. AreEqual(x.__bases__, (object, ))
  2347. AreEqual(x.__name__, 'x')
  2348. def test_issubclass():
  2349. # first argument doesn't need to be new-style or old-style class if it defines __bases__
  2350. class C(object):
  2351. def __getattribute__(self, name):
  2352. if name == "__bases__": return (object, )
  2353. return object.__getattribute__(self, name)
  2354. class S(object):
  2355. def __getattribute__(self, name):
  2356. if name == "__bases__": return (x, )
  2357. return C.__getattribute__(self, name)
  2358. x = C()
  2359. AreEqual(issubclass(S(), x), True)
  2360. AreEqual(issubclass(S(), (x, )), True)
  2361. # if arg 1 doesn't have __bases__ a TypeError is raised
  2362. class S(object):
  2363. pass
  2364. x = C()
  2365. AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), x)
  2366. AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), (x, ))
  2367. # arg 1 __bases__ must be a tuple
  2368. for arg1 in [[2, 3, 4], 23, 'abc']:
  2369. class S(object):
  2370. def __getattribute__(self, name):
  2371. if name == "__bases__": return arg1
  2372. return C.__getattribute__(self, name)
  2373. AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), x)
  2374. AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), (x, ))
  2375. # recursively check members returned from __bases__
  2376. class S(object):
  2377. def __getattribute__(self, name):
  2378. if name == "__bases__": return (y, )
  2379. return C.__getattribute__(self, name)
  2380. class A(object):
  2381. def __getattribute__(self, name):
  2382. if name == "__bases__": return (x, )
  2383. return C.__getattribute__(self, name)
  2384. y = A()
  2385. AreEqual(issubclass(S(), x), True)
  2386. AreEqual(issubclass(S(), (x, )), True)
  2387. # but ignore members that don't have __bases__ themselves, don't raise a TypeError
  2388. class S(object):
  2389. def __getattribute__(self, name):
  2390. if name == "__bases__": return (123, )
  2391. return C.__getattribute__(self, name)
  2392. AreEqual(issubclass(S(), x), False)
  2393. AreEqual(issubclass(S(), (x, )), False)
  2394. # if __bases__ returns a type we should fallback into subclass(type, typeinfo)
  2395. class C(object):
  2396. def __getattribute__(self, name):
  2397. if name == "__bases__": return (int, )
  2398. return object.__getattribute__(self, name)
  2399. AreEqual(issubclass(C(), object), True)
  2400. AreEqual(issubclass(C(), (object, )), True)
  2401. # if __bases__ returns an old-class we should fallback into subclass(oc, typeinfo)
  2402. class OC1: pass
  2403. class OC2(OC1): pass
  2404. class C(object):
  2405. def __getattribute__(self, name):
  2406. if name == "__bases__": return (OC2, )
  2407. return object.__getattribute__(self, name)
  2408. AreEqual(issubclass(C(), OC1), True)
  2409. AreEqual(issubclass(C(), (OC1, )), True)
  2410. # raising an exception from __bases__ propagates out
  2411. class C(object):
  2412. def getbases(self):
  2413. raise RuntimeError
  2414. __bases__ = property(getbases)
  2415. class S(C): pass
  2416. AssertError(RuntimeError, issubclass, C(), S())
  2417. reclimit = sys.getrecursionlimit()
  2418. if reclimit == sys.maxint:
  2419. sys.setrecursionlimit(1001)
  2420. # Make sure that calling isinstance with a deeply nested tuple for its
  2421. # argument will raise RuntimeError eventually.
  2422. def blowstack(fxn, arg, compare_to):
  2423. tuple_arg = (compare_to,)
  2424. for cnt in xrange(sys.getrecursionlimit()+5):
  2425. tuple_arg = (tuple_arg,)
  2426. fxn(arg, tuple_arg)
  2427. AssertError(RuntimeError, blowstack, issubclass, str, str)
  2428. sys.setrecursionlimit(reclimit)
  2429. def test_isinstance_recursion():
  2430. reclimit = sys.getrecursionlimit()
  2431. if reclimit == sys.maxint:
  2432. sys.setrecursionlimit(1001)
  2433. # Make sure that calling isinstance with a deeply nested tuple for its
  2434. # argument will raise RuntimeError eventually.
  2435. def blowstack(fxn, arg, compare_to):
  2436. tuple_arg = (compare_to,)
  2437. for cnt in xrange(sys.getrecursionlimit()+5):
  2438. tuple_arg = (tuple_arg,)
  2439. fxn(arg, tuple_arg)
  2440. AssertError(RuntimeError, blowstack, isinstance, '', str)
  2441. sys.setrecursionlimit(reclimit)
  2442. def test_call_recursion():
  2443. reclimit = sys.getrecursionlimit()
  2444. if reclimit == sys.maxint:
  2445. sys.setrecursionlimit(1001)
  2446. class A(object): pass
  2447. A.__call__ = A()
  2448. AssertError(RuntimeError, A())
  2449. sys.setrecursionlimit(reclimit)
  2450. def test_metaclass_base_search():
  2451. class MetaClass(type):
  2452. def __init__(cls, clsname, bases, dict):
  2453. setattr(cls, "attr_%s" % clsname, "attribute set on %s by MetaClass" % clsname)
  2454. super(MetaClass, cls).__init__(clsname, bases, dict)
  2455. class Mixin(object):
  2456. __metaclass__ = MetaClass
  2457. class Parent(object):
  2458. pass
  2459. class Child(Parent, Mixin):
  2460. pass
  2461. AreEqual(Child.attr_Child, 'attribute set on Child by MetaClass')
  2462. def test_binary_operator_subclass():
  2463. """subclassing but not overriding shouldn't call __radd__"""
  2464. class A(object):
  2465. def __add__(self, other):
  2466. return ('a', self.__class__.__name__)
  2467. __radd__ = __add__
  2468. class B(A):
  2469. def __add__(self, other):
  2470. return ('b', self.__class__.__name__)
  2471. __radd__ = __add__
  2472. class C(A): pass
  2473. a = A()
  2474. b = B()
  2475. c = C()
  2476. AreEqual(a + b, ('b', 'B'))
  2477. AreEqual(a + c, ('a', 'A'))
  2478. def test_cp2021():
  2479. class KOld:
  2480. def __rmul__(self, other):
  2481. return 7
  2482. class KNew(object):
  2483. def __rmul__(self, other):
  2484. return 7
  2485. for testdata in [[], [1], [1,2]]:
  2486. AreEqual(testdata * KOld(), 7)
  2487. AreEqual(testdata * KNew(), 7)
  2488. AssertErrorWithMessage(TypeError, "object cannot be interpreted as an index",
  2489. testdata.__mul__, KOld())
  2490. AssertErrorWithMessage(TypeError, "'KNew' object cannot be interpreted as an index",
  2491. testdata.__mul__, KNew())
  2492. def test_redundant_multiple_bases():
  2493. """specifying an extra base which is implied by a previous one should work ok"""
  2494. class Foo(list, object):
  2495. pass
  2496. class Bar(Foo):
  2497. pass
  2498. AreEqual(Bar(), [])
  2499. def test_metaclass_keyword_args():
  2500. class MetaType(type):
  2501. def __init__(cls, name, bases, dict):
  2502. super(MetaType, cls).__init__(name, bases, dict)
  2503. class Base(object):
  2504. __metaclass__ = MetaType
  2505. class A(Base):
  2506. def __init__(self, a, b='b', c=12, d=None, e=None):
  2507. self.d = d
  2508. self.b = b
  2509. a = A('empty', *(), **{'d': 'boom'})
  2510. AreEqual(a.d, 'boom')
  2511. a = A('empty', *('foo', ), **{'d': 'boom'})
  2512. AreEqual(a.b, 'foo')
  2513. AreEqual(a.d, 'boom')
  2514. def test_oldinstance_creation():
  2515. class C: pass
  2516. inst = type(C())
  2517. d = {'a': 2}
  2518. i = inst(C, d)
  2519. AreEqual(id(d), id(i.__dict__))
  2520. Assert(isinstance(i, C))
  2521. x = inst(C, None)
  2522. AreEqual(x.__dict__, {})
  2523. def test_metaclass_getattribute():
  2524. class mc(type):
  2525. def __getattr__(self, name):
  2526. return 42
  2527. class nc_ga(object):
  2528. __metaclass__ = mc
  2529. AreEqual(nc_ga.x, 42)
  2530. def test_method_call():
  2531. class K(object):
  2532. def m(self, *args, **kwargs):
  2533. return args, kwargs
  2534. AreEqual(K().m.__call__(), ((), {}))
  2535. AreEqual(K().m.__call__(42), ((42, ), {}))
  2536. AreEqual(K().m.__call__(42, x = 23), ((42, ), {'x': 23}))
  2537. Assert('__call__' in dir(K().m))
  2538. def test_metaclass_multiple_bases():
  2539. global log
  2540. log = []
  2541. class C(object): pass
  2542. class MT1(type):
  2543. def __new__(cls, name, bases, dict):
  2544. log.append('MT1')
  2545. return super(MT1, cls).__new__(cls, name, bases, dict)
  2546. class D(object):
  2547. __metaclass__ = MT1
  2548. AreEqual(log, ['MT1'])
  2549. class MT2(type):
  2550. def __new__(cls, name, bases, dict):
  2551. log.append('MT2')
  2552. return super(MT2, cls).__new__(cls, name, bases, dict)
  2553. class E(object):
  2554. __metaclass__ = MT2
  2555. AreEqual(log, ['MT1', 'MT2'])
  2556. class T1(C, D): pass
  2557. AreEqual(log, ['MT1', 'MT2', 'MT1'])
  2558. def f():
  2559. class T2(C, D, E): pass
  2560. AssertError(TypeError, f)
  2561. AreEqual(log, ['MT1', 'MT2', 'MT1'])
  2562. def test_del_getattribute(): # 409747
  2563. class B(object):
  2564. def __getattribute__(self, name): pass
  2565. class D(B): pass
  2566. def f(): del D.__getattribute__ # AttributeError expected.
  2567. AssertError(AttributeError, f)
  2568. def test_metaclass_oldstyle_only_bases():
  2569. class C: pass
  2570. AssertError(TypeError, type, 'foo', (C, ), {})
  2571. def test_bad_mro_error_message():
  2572. class A(object): pass
  2573. class B(A): pass
  2574. AssertErrorWithPartialMessage(TypeError, "Cannot create a consistent method resolution\norder (MRO) for bases A, B",
  2575. type, "X", (A,B), {})
  2576. def test_finalizer():
  2577. """returning the same object from __new__ shouldn't cause it to be finalized"""
  2578. global val, called
  2579. val = None
  2580. called = False
  2581. class X(object):
  2582. def __new__(cls):
  2583. global val
  2584. if val == None:
  2585. val = object.__new__(cls)
  2586. return val
  2587. def __del__(self):
  2588. called = True
  2589. a = X()
  2590. b = X()
  2591. AreEqual(id(a), id(b))
  2592. import gc
  2593. gc.collect()
  2594. AreEqual(called, False)
  2595. def test_metaclass_attribute_lookup():
  2596. class x(type):
  2597. @property
  2598. def Foo(self): return self._foo
  2599. @Foo.setter
  2600. def Foo(self, value): self._foo = value
  2601. class y:
  2602. __metaclass__ = x
  2603. def Foo(self): return 42
  2604. _foo = 0
  2605. # data descriptor should lookup in meta class first.
  2606. AreEqual(y.Foo, 0)
  2607. class x(type):
  2608. Foo = 42
  2609. class y:
  2610. __metaclass__ = x
  2611. Foo = 0
  2612. # non-data descriptors lookup in the normal class first
  2613. AreEqual(y.Foo, 0)
  2614. def test_len():
  2615. class l(object):
  2616. def __int__(self):
  2617. return 42
  2618. vals = (l(), 42L, 42.0)
  2619. if is_cli:
  2620. from iptest.type_util import clr_all_types
  2621. vals += tuple(t(42) for t in clr_all_types)
  2622. for x in vals:
  2623. class C(object):
  2624. def __len__(self):
  2625. return x
  2626. AreEqual(len(C()), 42)
  2627. def test_descriptor_exception():
  2628. class desc(object):
  2629. def __get__(self, value, ctx):
  2630. raise AttributeError, 'foo'
  2631. class x(object):
  2632. a = 42
  2633. class y(x):
  2634. a = desc()
  2635. AssertErrorWithMessage(AttributeError, 'foo', lambda: y().a)
  2636. class y(object):
  2637. a = desc()
  2638. AssertErrorWithMessage(AttributeError, 'foo', lambda: y().a)
  2639. def test_mutate_descriptor():
  2640. class desc(object):
  2641. def __get__(self, value, ctx):
  2642. return 42
  2643. class x(object):
  2644. a = desc()
  2645. AreEqual(x().a, 42)
  2646. desc.__get__ = lambda self, value, ctx: 23
  2647. AreEqual(x().a, 23)
  2648. def test_method_tuple_type():
  2649. """creates a method who's type is declared to be a tuple"""
  2650. class x(object):
  2651. def f(self): pass
  2652. def f(self): return self
  2653. AreEqual(type(x.f)(f, None, (int, str))(42), 42)
  2654. AreEqual(type(x.f)(f, None, (int, str))('abc'), 'abc')
  2655. AssertError(TypeError, type(x.f)(f, None, (int, str)), 1L)
  2656. def test_mutate_class():
  2657. def f(): object.foo = 42
  2658. def g(): type.foo = 42
  2659. def h(): del type.foo
  2660. def i(): del object.foo
  2661. AssertError(TypeError, f)
  2662. AssertError(TypeError, g)
  2663. AssertError(TypeError, h)
  2664. AssertError(TypeError, i)
  2665. def test_wacky_new_init():
  2666. global initCalled
  2667. for base in [object, list]:
  2668. for has_finalizer in [True, False]:
  2669. class CustomInit(object):
  2670. def __get__(self, inst, ctx):
  2671. return self
  2672. def __call__(self, *args):
  2673. global initCalled
  2674. initCalled = 'CustomInit'
  2675. class Base(base):
  2676. def __new__(self, toCreate):
  2677. return base.__new__(toCreate)
  2678. if has_finalizer:
  2679. def __del__(self): pass
  2680. class Sub(Base):
  2681. def __init__(self, *args):
  2682. global initCalled
  2683. initCalled = 'Sub'
  2684. class NotSub(base):
  2685. def __init__(self, *args):
  2686. global initCalled
  2687. initCalled = 'NotSub'
  2688. class OC: pass
  2689. class MixedSub(Base, OC):
  2690. def __init__(self, *args):
  2691. global initCalled
  2692. initCalled = 'MixedSub'
  2693. class CustomSub(Base):
  2694. __init__ = CustomInit()
  2695. Base(MixedSub)
  2696. AreEqual(initCalled, 'MixedSub')
  2697. Base(Sub)
  2698. AreEqual(initCalled, 'Sub')
  2699. initCalled = None
  2700. Base(NotSub)
  2701. AreEqual(initCalled, None)
  2702. Base(CustomSub)
  2703. AreEqual(initCalled, 'CustomInit')
  2704. def test_new_init_error_combinations():
  2705. class X1(object):
  2706. args = ()
  2707. def __init__(self):
  2708. object.__init__(self, *X1.args)
  2709. class X2(object):
  2710. args = ()
  2711. def __new__(cls):
  2712. return object.__new__(cls, *X2.args)
  2713. temp = X1()
  2714. temp = X2()
  2715. for args in [(42,),
  2716. (None,), #CP19585
  2717. (42, 43), ("abc",),
  2718. ]:
  2719. X1.args = args
  2720. X2.args = args
  2721. AssertError(TypeError, X1)
  2722. AssertError(TypeError, X2)
  2723. #--args plus kwargs
  2724. class X3(object):
  2725. args = ()
  2726. kwargs = {}
  2727. def __init__(self):
  2728. object.__init__(self, *X3.args, **X3.kwargs)
  2729. class X4(object):
  2730. args = ()
  2731. kwargs = {}
  2732. def __new__(cls):
  2733. return object.__new__(cls, *X4.args, **X4.kwargs)
  2734. temp = X3()
  2735. temp = X4()
  2736. for args, kwargs in [
  2737. [(42,), {}],
  2738. [(None,), {'a':3}],
  2739. [(42, 43), {'a':3, 'b': 4}],
  2740. [("abc",), {'z':None}],
  2741. [(), {'a':3}],
  2742. ]:
  2743. X3.args = args
  2744. X3.kwargs = kwargs
  2745. X4.args = args
  2746. X4.kwargs = kwargs
  2747. AssertError(TypeError, X3)
  2748. AssertError(TypeError, X4)
  2749. def test_oldstyle_splat_dict():
  2750. class C: pass
  2751. def E(): return {}
  2752. AreEqual(type(C(*E())), type(C()))
  2753. def test_get_dict_once():
  2754. class x(object): pass
  2755. class y(x): pass
  2756. Assert('__dict__' in x.__dict__)
  2757. Assert('__dict__' not in y.__dict__)
  2758. def test_cp22832():
  2759. class KOld:
  2760. KOldStuff = 3
  2761. class KNew(object, KOld):
  2762. pass
  2763. Assert("KOldStuff" in dir(KNew))
  2764. # mono's GC apparently behaves differently...
  2765. @skip("silverlight", "posix")
  2766. def test_cp23564():
  2767. global A
  2768. A = 0
  2769. class K1(object):
  2770. def __del__(self):
  2771. global A
  2772. A = 1
  2773. class K2(K1):
  2774. pass
  2775. k = K2()
  2776. k.__class__ = K1
  2777. del k
  2778. force_gc()
  2779. AreEqual(A, 1)
  2780. def test_object_delattr():
  2781. class A(object):
  2782. def __init__(self):
  2783. self.abc = 42
  2784. x = A()
  2785. object.__delattr__(x, 'abc')
  2786. AreEqual(hasattr(x, 'abc'), False)
  2787. def test_cp33622():
  2788. AreEqual(object.__repr__ in (None,), False)
  2789. AreEqual(object.__repr__ in (None,object.__repr__), True)
  2790. AreEqual(object.__repr__ in (None,object.__cmp__), False)
  2791. AreEqual(object.__repr__ in (None,object.__str__), False)
  2792. def test_cp24649_gh120():
  2793. import copy
  2794. class Descriptor(object):
  2795. def __get__(self, instance, owner):
  2796. return instance.x
  2797. def clone(cls):
  2798. """Create clone of provided class"""
  2799. attrs = vars(cls).copy()
  2800. skipped = ['__dict__', '__weakref__']
  2801. for attr in skipped:
  2802. try:
  2803. del attrs[attr]
  2804. except KeyError:
  2805. pass
  2806. cattrs = copy.deepcopy(attrs)
  2807. return type(cls.__name__, cls.__bases__, cattrs)
  2808. class C(object):
  2809. a = Descriptor()
  2810. def __init__(self, x):
  2811. self.x = x
  2812. # make sure all expected keys are present, and only those
  2813. AreEqual(set(C.__dict__.keys()),
  2814. {'a', '__module__', '__dict__', '__weakref__', '__doc__', '__init__'})
  2815. # make sure .items() is the same as indexing
  2816. for key, value in C.__dict__.items():
  2817. AreEqual(C.__dict__[key], value)
  2818. CC = clone(C)
  2819. cc = CC(1)
  2820. AreEqual(cc.x, 1)
  2821. #--MAIN------------------------------------------------------------------------
  2822. run_test(__name__)