PageRenderTime 90ms CodeModel.GetById 22ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file