PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Languages/IronPython/Tests/test_isinstance.py

http://github.com/IronLanguages/main
Python | 1089 lines | 1047 code | 26 blank | 16 comment | 10 complexity | 29f0e7bb6055618de1ce91f800b69855 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. from iptest.assert_util import *
  16. import sys
  17. @skip("silverlight")
  18. def test_file_io():
  19. def verify_file(ff):
  20. cnt = 0
  21. for i in ff:
  22. Assert(i[0:5] == "Hello")
  23. cnt += 1
  24. ff.close()
  25. Assert(cnt == 10)
  26. f = file("testfile.tmp", "w")
  27. for i in range(10):
  28. f.write("Hello " + str(i) + "\n")
  29. f.close()
  30. f = file("testfile.tmp")
  31. verify_file(f)
  32. f = file("testfile.tmp", "r")
  33. verify_file(f)
  34. f = file("testfile.tmp", "r", -1)
  35. verify_file(f)
  36. f = open("testfile.tmp")
  37. verify_file(f)
  38. f = open("testfile.tmp", "r")
  39. verify_file(f)
  40. f = open("testfile.tmp", "r", -1)
  41. verify_file(f)
  42. f = open("testfile.tmp", "r", 0)
  43. verify_file(f)
  44. if is_cli:
  45. import System
  46. if is_netstandard:
  47. import clr
  48. clr.AddReference("System.IO.FileSystem")
  49. clr.AddReference("System.IO.FileSystem.Primitives")
  50. fs = System.IO.FileStream("testfile.tmp", System.IO.FileMode.Open, System.IO.FileAccess.Read)
  51. f = open(fs)
  52. verify_file(f)
  53. ms = System.IO.MemoryStream(30)
  54. f = open(ms)
  55. f.write("hello")
  56. f.flush()
  57. AreEqual(ms.Length, 5)
  58. AreEqual(ms.GetBuffer()[0], ord('h'))
  59. AreEqual(ms.GetBuffer()[4], ord('o'))
  60. ms.Close()
  61. import os
  62. os.remove("testfile.tmp")
  63. # more tests for 'open'
  64. @skip("silverlight")
  65. def test_open():
  66. AssertError(TypeError, open, None) # arg must be string
  67. AssertError(TypeError, open, [])
  68. AssertError(TypeError, open, 1)
  69. def test_compile():
  70. def max(a,b):
  71. if a>b: return a
  72. else: return b
  73. code = compile("max(10, 15)", "<string>", "eval")
  74. Assert(eval(code) == 15)
  75. code = compile("x = [1,2,3,4,5]\nx.reverse()\nAssert(x == [5,4,3,2,1])", "<string>", "exec")
  76. exec(code)
  77. Assert(x == [5,4,3,2,1])
  78. AssertError(ValueError, compile, "2+2", "<string>", "invalid")
  79. AssertError(SyntaxError, compile, "if 1 < 2: pass", "<string>", "eval")
  80. AssertError(SyntaxError, compile, "a=2", "<string>", "eval")
  81. AssertError(SyntaxError, eval, "a=2")
  82. @skip("silverlight")
  83. def test_redirect():
  84. # stdin, stdout redirect and input, raw_input tests
  85. old_stdin = sys.stdin
  86. old_stdout = sys.stdout
  87. sys.stdout = file("testfile.tmp", "w")
  88. print "Into the file"
  89. print "2+2"
  90. sys.stdout.close()
  91. sys.stdout = old_stdout
  92. sys.stdin = file("testfile.tmp", "r")
  93. s = raw_input()
  94. Assert(s == "Into the file")
  95. s = input()
  96. Assert(s == 4)
  97. sys.stdin.close()
  98. sys.stdin = old_stdin
  99. f = file("testfile.tmp", "r")
  100. g = file("testfile.tmp", "r")
  101. s = f.readline()
  102. t = g.readline()
  103. Assert(s == t)
  104. Assert(s == "Into the file\n")
  105. f.close()
  106. g.close()
  107. f = file("testfile.tmp", "w")
  108. f.writelines(["1\n", "2\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "0\n"])
  109. f.close()
  110. f = file("testfile.tmp", "r")
  111. l = f.readlines()
  112. Assert(l == ["1\n", "2\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "0\n"])
  113. f.close()
  114. import os
  115. os.remove("testfile.tmp")
  116. def test_conversions():
  117. success=False
  118. try:
  119. nstr("Hi")
  120. except NameError:
  121. success=True
  122. AreEqual(success, True)
  123. success=False
  124. try:
  125. zip2([1,2,3],[4,5,6])
  126. except NameError:
  127. success=True
  128. AreEqual(success, True)
  129. AreEqual(str(), "")
  130. AreEqual(unicode(), u"")
  131. AreEqual(oct(long(0)), "0L")
  132. AreEqual(hex(12297829382473034410), "0xaaaaaaaaaaaaaaaaL") #10581
  133. AreEqual(hex(-1L), "-0x1L")
  134. AreEqual(long("-01L"), -1L)
  135. AreEqual(int(" 1 "), 1)
  136. AreEqual(int(" - 1 "), -1)
  137. AreEqual(long(" - 1 "), -1L)
  138. for f in [ long, int ]:
  139. AssertError(ValueError, f, 'p')
  140. AssertError(ValueError, f, 't')
  141. AssertError(ValueError, f, 'a')
  142. AssertError(ValueError, f, '3.2')
  143. AssertError(ValueError, f, '0x0R')
  144. AssertError(ValueError, f, '09', 8)
  145. AssertError(ValueError, f, '0A')
  146. AssertError(ValueError, f, '0x0G')
  147. AssertError(ValueError, int, '1l')
  148. AreEqual(int(1e100), 10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104L)
  149. AreEqual(int(-1e100), -10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104L)
  150. AreEqual(pow(2,3), 8)
  151. def test_type_properties():
  152. #################
  153. # Type properties
  154. AreEqual(type(type), type.__class__)
  155. #################
  156. def test_reload_sys():
  157. import sys
  158. (old_copyright, old_byteorder) = (sys.copyright, sys.byteorder)
  159. (sys.copyright, sys.byteorder) = ("foo", "foo")
  160. (old_argv, old_exc_type) = (sys.argv, sys.exc_type)
  161. (sys.argv, sys.exc_type) = ("foo", "foo")
  162. reloaded_sys = reload(sys)
  163. # Most attributes get reset
  164. AreEqual((old_copyright, old_byteorder), (reloaded_sys.copyright, reloaded_sys.byteorder))
  165. # Some attributes are not reset
  166. AreEqual((reloaded_sys.argv, reloaded_sys.exc_type), ("foo", "foo"))
  167. # Put back the original values
  168. (sys.copyright, sys.byteorder) = (old_copyright, old_byteorder)
  169. (sys.argv, sys.exc_type) = (old_argv, old_exc_type)
  170. def test_hijacking_builtins():
  171. # BUG 433: CPython allows hijacking of __builtins__, but IronPython does not
  172. bug_433 = '''
  173. def foo(arg):
  174. return "Foo"
  175. # trying to override an attribute of __builtins__ causes a TypeError
  176. try:
  177. __builtins__.oct = foo
  178. Assert(False, "Cannot override an attribute of __builtins__")
  179. except TypeError:
  180. pass
  181. # assigning to __builtins__ passes, but doesn't actually affect function semantics
  182. import custombuiltins
  183. '''
  184. # /BUG
  185. def test_custom_mapping():
  186. class MyMapping:
  187. def __getitem__(self, index):
  188. if index == 'a': return 2
  189. if index == 'b': return 5
  190. raise IndexError, 'bad index'
  191. AreEqual(eval('a+b', {}, MyMapping()), 7)
  192. def test_eval_dicts():
  193. # eval referencing locals / globals
  194. global global_value
  195. value_a = 13
  196. value_b = 17
  197. global_value = 23
  198. def eval_using_locals():
  199. value_a = 3
  200. value_b = 7
  201. AreEqual(eval("value_a"), 3)
  202. AreEqual(eval("value_b"), 7)
  203. AreEqual(eval("global_value"), 23)
  204. AreEqual(eval("value_a < value_b"), True)
  205. AreEqual(eval("global_value < value_b"), False)
  206. return True
  207. Assert(eval_using_locals())
  208. if is_cli or is_silverlight:
  209. if System.BitConverter.IsLittleEndian == True:
  210. Assert(sys.byteorder == "little")
  211. else:
  212. Assert(sys.byteorder == "big")
  213. sortedDir = 3
  214. sortedDir = dir()
  215. sortedDir.sort()
  216. Assert(dir() == sortedDir)
  217. def test_getattr():
  218. ## getattr/hasattr: hasattr should eat exception, and return True/False
  219. class C1:
  220. def __init__(self):
  221. self.field = C1
  222. def method(self):
  223. return "method"
  224. def __getattr__(self, attrname):
  225. if attrname == "lambda":
  226. return lambda x: len(x)
  227. elif attrname == "myassert":
  228. raise AssertionError
  229. else:
  230. raise AttributeError, attrname
  231. class C2(object):
  232. def __init__(self):
  233. self.field = C1
  234. def method(self):
  235. return "method"
  236. def __getattr__(self, attrname):
  237. if attrname == "lambda":
  238. return lambda x: len(x)
  239. elif attrname == "myassert":
  240. raise AssertionError
  241. else:
  242. raise AttributeError, attrname
  243. def getattrhelper(t):
  244. o = t()
  245. AreEqual(getattr(o, "field"), C1)
  246. AreEqual(getattr(o, "method")(), "method")
  247. AreEqual(getattr(o, "lambda")("a"), 1)
  248. AssertError(AssertionError, getattr, o, "myassert")
  249. AssertError(AttributeError, getattr, o, "anything")
  250. AssertError(AttributeError, getattr, o, "else")
  251. for attrname in ('field', 'method', '__init__', '__getattr__', 'lambda', '__doc__', '__module__'):
  252. AreEqual(hasattr(o, attrname), True)
  253. for attrname in ("myassert", "anything", "else"):
  254. AreEqual(hasattr(o,attrname), False)
  255. getattrhelper(C1)
  256. getattrhelper(C2)
  257. ## derived from python native type, and create instance of them without arg
  258. def test_inheritance_ctor():
  259. global flag
  260. flag = 0
  261. def myinit(self):
  262. global flag
  263. flag = flag + 1
  264. cnt = 0
  265. for bt in (tuple, dict, list, str, set, frozenset, int, float, complex):
  266. nt = type("derived", (bt,), dict())
  267. inst = nt()
  268. AreEqual(type(inst), nt)
  269. nt2 = type("derived2", (nt,), dict())
  270. inst2 = nt2()
  271. AreEqual(type(inst2), nt2)
  272. nt.__init__ = myinit
  273. inst = nt()
  274. cnt += 1
  275. AreEqual(flag, cnt)
  276. AreEqual(type(inst), nt)
  277. # sub classing built-ins works correctly..
  278. @skip("silverlight")
  279. def test_subclassing_builtins():
  280. class MyFile(file):
  281. myfield = 0
  282. f = MyFile('temporary.deleteme','w')
  283. AreEqual(f.myfield, 0)
  284. f.close()
  285. import os
  286. os.unlink('temporary.deleteme')
  287. class C(list):
  288. def __eq__(self, other):
  289. return 'Passed'
  290. AreEqual(C() == 1, 'Passed')
  291. # extensible types should hash the same as non-extensibles, and unary operators
  292. # should work too
  293. def test_extensible_types_hashing():
  294. for x, y in ( (int, 2), (str, 'abc'), (float, 2.0), (long, 2L), (complex, 2+0j) ):
  295. class foo(x): pass
  296. AreEqual(hash(foo(y)), hash(y))
  297. if x != str:
  298. AreEqual(-foo(y), -y)
  299. AreEqual(+foo(y), +y)
  300. if x != complex and x != float:
  301. AreEqual(~foo(y), ~y)
  302. # can use kw-args w/ file
  303. @skip("silverlight")
  304. def test_kwargs_file():
  305. f = file(name='temporary.deleteme', mode='w')
  306. f.close()
  307. os.unlink('temporary.deleteme')
  308. def test_kwargs_primitives():
  309. AreEqual(int(x=1), 1)
  310. AreEqual(float(x=2), 2.0)
  311. AreEqual(long(x=3), 3L)
  312. AreEqual(complex(imag=4, real=3), 3 + 4j)
  313. AreEqual(str(object=5), '5')
  314. AreEqual(unicode(string='a', errors='strict'), 'a')
  315. AreEqual(tuple(sequence=range(3)), (0,1,2))
  316. AreEqual(list(sequence=(0,1)), [0,1])
  317. #####################################################################
  318. def test_issubclass():
  319. for (x, y) in [("2", int), (2, int), ("string", str), (None, int), (str, None), (int, 3), (int, (6, 7))]:
  320. AssertError(TypeError, lambda: issubclass(x, y))
  321. @skip('win32')
  322. def test_cli_subclasses():
  323. import clr
  324. Assert(issubclass(int, int))
  325. Assert(not issubclass(str, int))
  326. Assert(not issubclass(int, (str, str)))
  327. Assert(issubclass(int, (str, int)))
  328. Assert(issubclass(bytes, basestring))
  329. Assert(issubclass(str, basestring))
  330. Assert(issubclass(unicode, basestring))
  331. Assert(issubclass(basestring, basestring))
  332. class basestring_subclass(basestring):
  333. pass
  334. Assert(issubclass(basestring_subclass, basestring))
  335. Assert(str(None) == "None")
  336. Assert(issubclass(type(None),type(None)))
  337. Assert(str(type(None)) == "<type 'NoneType'>")
  338. Assert(str(1) == "1")
  339. Assert('__str__' in dir(None))
  340. def tryAssignToNoneAttr():
  341. None.__doc__ = "Nothing!"
  342. def tryAssignToNoneNotAttr():
  343. None.notanattribute = "";
  344. AssertError(AttributeError, tryAssignToNoneAttr)
  345. AssertError(AttributeError, tryAssignToNoneNotAttr)
  346. v = None.__doc__
  347. v = None.__new__
  348. v = None.__hash__
  349. AreEqual("<type 'NoneType'>", str(type(None)))
  350. import sys
  351. AreEqual(str(sys), "<module 'sys' (built-in)>")
  352. import time
  353. import toimport
  354. m = [type(sys), type(time), type(toimport)]
  355. for i in m:
  356. for j in m:
  357. Assert(issubclass(i,j))
  358. AssertError(TypeError, type, None, None, None) # arg 1 must be string
  359. AssertError(TypeError, type, "NewType", None, None) # arg 2 must be tuple
  360. AssertError(TypeError, type, "NewType", (), None) # arg 3 must be dict
  361. def splitTest():
  362. "string".split('')
  363. AssertError(ValueError, splitTest)
  364. #####################################################################################
  365. # IronPython does not allow extending System.Int64 and System.Boolean. So we have
  366. # some directed tests for this.
  367. @skip('win32')
  368. def test_primitive_inheritance():
  369. import System
  370. def InheritFromType(t):
  371. class InheritedType(t): pass
  372. return InheritedType
  373. AssertError(TypeError, InheritFromType, System.Int64)
  374. AssertError(TypeError, InheritFromType, System.Boolean)
  375. # isinstance
  376. Assert(isinstance(System.Int64(), System.Int64) == True)
  377. Assert(isinstance(System.Boolean(), System.Boolean) == True)
  378. Assert(isinstance(1, System.Int64) == False)
  379. Assert(isinstance(1, System.Boolean) == False)
  380. class userClass(object): pass
  381. Assert(isinstance(userClass(), System.Int64) == False)
  382. Assert(isinstance(userClass(), System.Boolean) == False)
  383. # issubclass
  384. Assert(issubclass(System.Int64, System.Int64) == True)
  385. Assert(issubclass(System.Boolean, System.Boolean) == True)
  386. Assert(issubclass(type(1), System.Int64) == False)
  387. Assert(issubclass(type(1), System.Boolean) == False)
  388. Assert(issubclass(userClass, System.Int64) == False)
  389. Assert(issubclass(userClass, System.Boolean) == False)
  390. #####################################################################################
  391. @skip('win32')
  392. def test_cli_types():
  393. import System
  394. arrayMapping = {'b': System.SByte, 'h': System.Int16, 'H': System.UInt16, 'i': System.Int32,
  395. 'I': System.UInt32, 'l': System.Int64, 'L': System.UInt64, 'f': System.Single, 'd': System.Double }
  396. def tryConstructValues(validate, *args):
  397. for x in arrayMapping.keys():
  398. # construct from DynamicType
  399. y = System.Array[arrayMapping[x]](*args)
  400. if not is_silverlight: #BUG DDB #76340
  401. AreEqual(y.GetType().GetElementType(), arrayMapping[x]().GetType())
  402. validate(y, *args)
  403. # construct from CLR type
  404. if not is_silverlight: #BUG DDB #76340
  405. y = System.Array[y.GetType().GetElementType()](*args)
  406. AreEqual(y.GetType().GetElementType(), arrayMapping[x]().GetType())
  407. validate(y, *args)
  408. def tryConstructSize(validate, *args):
  409. for x in arrayMapping.keys():
  410. # construct from DynamicType
  411. y = System.Array.CreateInstance(arrayMapping[x], *args)
  412. if not is_silverlight: #BUG DDB #76340
  413. AreEqual(y.GetType().GetElementType(), arrayMapping[x]().GetType())
  414. validate(y, *args)
  415. # construct from CLR type
  416. if not is_silverlight: #BUG DDB #76340
  417. y = System.Array.CreateInstance(y.GetType().GetElementType(), *args)
  418. AreEqual(y.GetType().GetElementType(), arrayMapping[x]().GetType())
  419. validate(y, *args)
  420. def validateLen(res, *args):
  421. AreEqual(len(res), *args)
  422. def validateVals(res, *args):
  423. len(res) == len(args)
  424. for x in range(len(args[0])):
  425. try:
  426. lhs = int(res[x])
  427. rhs = int(args[0][x])
  428. except:
  429. lhs = float(res[x])
  430. rhs = float(args[0][x])
  431. AreEqual(lhs, rhs)
  432. def validateValsIter(res, *args):
  433. len(res) == len(args)
  434. for x in range(len(args)):
  435. print int(res[x]), args[0][x]
  436. AreEqual(int(res[x]), int(args[0][x]))
  437. class MyList(object):
  438. def __len__(self):
  439. return 4
  440. def __iter__(self):
  441. yield 3
  442. yield 4
  443. yield 5
  444. yield 6
  445. def validateValsIter(res, *args):
  446. compList = MyList()
  447. len(res) == len(args)
  448. index = 0
  449. for x in compList:
  450. try:
  451. lhs = int(res[index])
  452. rhs = int(x)
  453. except Exception, e:
  454. lhs = float(res[index])
  455. rhs = float(x)
  456. AreEqual(lhs, rhs)
  457. index += 1
  458. tryConstructSize(validateLen, 0)
  459. tryConstructSize(validateLen, 1)
  460. tryConstructSize(validateLen, 20)
  461. tryConstructValues(validateVals, (3,4,5,6))
  462. tryConstructValues(validateVals, [3,4,5,6])
  463. tryConstructValues(validateValsIter, MyList())
  464. #############################################
  465. # metaclass tests
  466. # normal meta class construction & initialization
  467. def test_metaclass_ctor_init():
  468. global metaInit
  469. global instInit
  470. metaInit = False
  471. instInit = False
  472. class MetaType(type):
  473. def someFunction(cls):
  474. return "called someFunction"
  475. def __init__(cls, name, bases, dct):
  476. global metaInit
  477. metaInit = True
  478. super(MetaType, cls).__init__(name, bases,dct)
  479. cls.xyz = 'abc'
  480. class MetaInstance(object):
  481. __metaclass__ = MetaType
  482. def __init__(self):
  483. global instInit
  484. instInit = True
  485. a = MetaInstance()
  486. AreEqual(metaInit, True)
  487. AreEqual(instInit, True)
  488. AreEqual(MetaInstance.xyz, 'abc')
  489. AreEqual(MetaInstance.someFunction(), "called someFunction")
  490. class MetaInstance(object):
  491. __metaclass__ = MetaType
  492. def __init__(self, xyz):
  493. global instInit
  494. instInit = True
  495. self.val = xyz
  496. metaInit = False
  497. instInit = False
  498. a = MetaInstance('def')
  499. AreEqual(instInit, True)
  500. AreEqual(MetaInstance.xyz, 'abc')
  501. AreEqual(a.val, 'def')
  502. AreEqual(MetaInstance.someFunction(), "called someFunction")
  503. # initialization by calling the metaclass type.
  504. Foo = MetaType('foo', (), {})
  505. AreEqual(type(Foo), MetaType)
  506. instInit = False
  507. def newInit(self):
  508. global instInit
  509. instInit = True
  510. Foo = MetaType('foo', (), {'__init__':newInit})
  511. a = Foo()
  512. AreEqual(instInit, True)
  513. # verify two instances of an old class compare differently
  514. def test_oldclass_compare():
  515. class C: pass
  516. a = C()
  517. b = C()
  518. AreEqual(cmp(a,b) == 0, False)
  519. #################################################################
  520. # check that unhashable types cannot be hashed by Python
  521. # However, they should be hashable using System.Object.GetHashCode
  522. @skip('win32', 'silverlight') # TODO: _weakref support in SL
  523. def test_unhashable_types():
  524. import System
  525. class OldUserClass:
  526. def foo(): pass
  527. import _weakref
  528. from _collections import deque
  529. AssertError(TypeError, hash, slice(None))
  530. hashcode = System.Object.GetHashCode(slice(None))
  531. # weakproxy
  532. AssertError(TypeError, hash, _weakref.proxy(OldUserClass()))
  533. hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass()))
  534. # weakcallableproxy
  535. AssertError(TypeError, hash, _weakref.proxy(OldUserClass().foo))
  536. hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass().foo))
  537. AssertError(TypeError, hash, deque())
  538. hashcode = System.Object.GetHashCode(deque())
  539. AssertError(TypeError, hash, dict())
  540. hashcode = System.Object.GetHashCode(dict())
  541. AssertError(TypeError, hash, list())
  542. hashcode = System.Object.GetHashCode(list())
  543. AssertError(TypeError, hash, set())
  544. hashcode = System.Object.GetHashCode(set())
  545. #################################################################
  546. # Check that attributes of built-in types cannot be deleted
  547. @skip('win32')
  548. def test_builtin_attributes():
  549. import System
  550. def AssignMethodOfBuiltin():
  551. def mylen(): pass
  552. l = list()
  553. l.len = mylen
  554. AssertError(AttributeError, AssignMethodOfBuiltin)
  555. def DeleteMethodOfBuiltin():
  556. l = list()
  557. del l.len
  558. AssertError(AttributeError, DeleteMethodOfBuiltin)
  559. def SetAttrOfBuiltin():
  560. l = list()
  561. l.attr = 1
  562. AssertError(AttributeError, SetAttrOfBuiltin)
  563. def SetDictElementOfBuiltin():
  564. l = list()
  565. l.__dict__["attr"] = 1
  566. AssertError(AttributeError, SetDictElementOfBuiltin)
  567. def SetAttrOfCLIType():
  568. d = System.DateTime()
  569. d.attr = 1
  570. AssertError(AttributeError, SetAttrOfCLIType)
  571. def SetDictElementOfCLIType():
  572. d = System.DateTime()
  573. d.__dict__["attr"] = 1
  574. AssertError(AttributeError, SetDictElementOfCLIType)
  575. AssertErrorWithMessage(TypeError, "vars() argument must have __dict__ attribute", vars, list())
  576. AssertErrorWithMessage(TypeError, "vars() argument must have __dict__ attribute", vars, System.DateTime())
  577. #################################################################
  578. # verify a class w/ explicit interface implementation gets
  579. # it's interfaces shown
  580. @skip('win32')
  581. def test_explicit_interface_impl():
  582. import System
  583. AreEqual(System.IConvertible.ToDouble('32', None), 32.0)
  584. @skip('win32')
  585. def test_mutable_Valuetypes():
  586. load_iron_python_test()
  587. from IronPythonTest import MySize, BaseClass
  588. direct_vt = MySize(1, 2)
  589. embedded_vt = BaseClass()
  590. embedded_vt.Width = 3
  591. embedded_vt.Height = 4
  592. # Read access should still succeed.
  593. AreEqual(direct_vt.width, 1)
  594. AreEqual(embedded_vt.size.width, 3)
  595. AreEqual(embedded_vt.Size.width, 3)
  596. # But writes to value type fields should fail with ValueError.
  597. success = 0
  598. try:
  599. direct_vt.width = 5
  600. except ValueError:
  601. success = 1
  602. Assert(success == 0 and direct_vt.width == 1)
  603. success = 0
  604. try:
  605. embedded_vt.size.width = 5
  606. except ValueError:
  607. success = 1
  608. Assert(success == 0 and embedded_vt.size.width == 3)
  609. success = 0
  610. try:
  611. embedded_vt.Size.width = 5
  612. except ValueError:
  613. success = 1
  614. Assert(success == 0 and embedded_vt.Size.width == 3)
  615. import clr
  616. # ensure .GetType() and calling the helper w/ the type work
  617. AreEqual(clr.GetClrType(str), ''.GetType())
  618. # and ensure we're not just auto-converting back on both of them
  619. AreEqual(clr.GetClrType(str), str)
  620. if not is_netstandard: # TODO: figure out why this doesn't work
  621. AreEqual(clr.GetClrType(str) != str, False)
  622. # as well as GetPythonType
  623. import System
  624. AreEqual(clr.GetPythonType(System.Int32), int)
  625. AreEqual(clr.GetPythonType(clr.GetClrType(int)), int)
  626. # verify we can't create *Ops classes
  627. from IronPython.Runtime.Operations import DoubleOps
  628. AssertError(TypeError, DoubleOps)
  629. # setting mro to an invalid value should result in
  630. # bases still being correct
  631. class foo(object): pass
  632. class bar(foo): pass
  633. class baz(foo): pass
  634. def changeBazBase():
  635. baz.__bases__ = (foo, bar) # illegal MRO
  636. AssertError(TypeError, changeBazBase)
  637. AreEqual(baz.__bases__, (foo, ))
  638. AreEqual(baz.__mro__, (baz, foo, object))
  639. d = {}
  640. d[None, 1] = 2
  641. AreEqual(d, {(None, 1): 2})
  642. #######################################################
  643. def test_int_minvalue():
  644. # Test for type of System.Int32.MinValue
  645. AreEqual(type(-2147483648), int)
  646. AreEqual(type(-(2147483648)), long)
  647. AreEqual(type(-2147483648L), long)
  648. AreEqual(type(-0x80000000), int)
  649. AreEqual(type(int('-2147483648')), int)
  650. AreEqual(type(int('-80000000', 16)), int)
  651. AreEqual(type(int('-2147483649')), long)
  652. AreEqual(type(int('-80000001', 16)), long)
  653. if is_cli:
  654. import clr
  655. import System
  656. # verify our str.split doesn't replace CLR's String.Split
  657. chars = System.Array[str]([' '])
  658. res = 'a b c'.Split(chars, System.StringSplitOptions.RemoveEmptyEntries)
  659. AreEqual(res[0], 'a')
  660. AreEqual(res[1], 'b')
  661. AreEqual(res[2], 'c')
  662. #######################################################
  663. # MRO Tests
  664. def test_mro():
  665. # valid
  666. class C(object): pass
  667. class D(object): pass
  668. class E(D): pass
  669. class F(C, E): pass
  670. AreEqual(F.__mro__, (F,C,E,D,object))
  671. # valid
  672. class A(object): pass
  673. class B(object): pass
  674. class C(A,B): pass
  675. class D(A,B): pass
  676. class E(C,D): pass
  677. AreEqual(E.__mro__, (E,C,D,A,B,object))
  678. # invalid
  679. class A(object): pass
  680. class B(object): pass
  681. class C(A,B): pass
  682. class D(B,A): pass
  683. try:
  684. class E(C,D): pass
  685. AssertUnreachable()
  686. except TypeError:
  687. pass
  688. #######################################################
  689. # calling a type w/ kw-args
  690. def test_type_call_kwargs():
  691. AreEqual(complex(real=2), (2+0j))
  692. #######################################################
  693. def test_bad_addition():
  694. try:
  695. 2.0 + "2.0"
  696. AssertUnreachable()
  697. except TypeError: pass
  698. #### (sometype).__class__ should be defined and correct
  699. def test_class_property():
  700. class foo(object): pass
  701. AreEqual(foo.__class__, type)
  702. class foo(type): pass
  703. class bar(object):
  704. __metaclass__ = foo
  705. AreEqual(bar.__class__, foo)
  706. #### metaclass order:
  707. def test_metaclass_order():
  708. global metaCalled
  709. metaCalled = []
  710. class BaseMeta(type):
  711. def __new__(cls, name, bases, dict):
  712. global metaCalled
  713. metaCalled.append(cls)
  714. return type.__new__(cls, name, bases, dict)
  715. class DerivedMeta(BaseMeta): pass
  716. class A:
  717. __metaclass__ = BaseMeta
  718. AreEqual(metaCalled, [BaseMeta])
  719. metaCalled = []
  720. class B:
  721. __metaclass__ = DerivedMeta
  722. AreEqual(metaCalled, [DerivedMeta])
  723. metaCalled = []
  724. class C(A,B): pass
  725. AreEqual(metaCalled, [BaseMeta, DerivedMeta])
  726. AreEqual(type(C).__name__, 'DerivedMeta')
  727. class E(object):
  728. def getbases(self):
  729. raise RuntimeError
  730. __bases__ = property(getbases)
  731. class I(object):
  732. def getclass(self):
  733. return E()
  734. __class__ = property(getclass)
  735. class C(object):
  736. def getbases(self):
  737. return ()
  738. __bases__ = property(getbases)
  739. AssertError(RuntimeError, isinstance, I(), C())
  740. class C1(object): pass
  741. class C2(object): pass
  742. AreEqual(isinstance(C1(), C2), False)
  743. AreEqual(isinstance(C1(), (C2, C2)), False)
  744. AreEqual(isinstance(C1(), (C2, C2, (C2, C2), C2)), False)
  745. AreEqual(isinstance(C1(), (C2, C2, (C2, (C2, C1), C2), C2)), True)
  746. class C1: pass
  747. class C2: pass
  748. AreEqual(isinstance(C1(), C2), False)
  749. AreEqual(isinstance(C1(), (C2, C2)), False)
  750. AreEqual(isinstance(C1(), (C2, C2, (C2, C2), C2)), False)
  751. AreEqual(isinstance(C1(), (C2, C2, (C2, (C2, C1), C2), C2)), True)
  752. class MyInt(int): pass
  753. Assert(isinstance(MyInt(), int))
  754. # __class__ accesses
  755. def test_class_access():
  756. call_tracker = []
  757. class C(object):
  758. def getclass(self):
  759. call_tracker.append("C.getclass")
  760. return C
  761. __class__ = property(getclass)
  762. AreEqual(isinstance(C(), object), True)
  763. AreEqual(call_tracker, [])
  764. AreEqual(isinstance(C(), str), False)
  765. AreEqual(call_tracker, ["C.getclass"])
  766. call_tracker = []
  767. AreEqual(isinstance(C(), (str, (type, str, float))), False)
  768. AreEqual(call_tracker, ['C.getclass', 'C.getclass', 'C.getclass', 'C.getclass'])
  769. # __bases__ access
  770. def test_base_access():
  771. call_tracker = []
  772. class C(object):
  773. def getbases(self):
  774. call_tracker.append("C.getbases")
  775. return (E,)
  776. __bases__ = property(getbases)
  777. class E(object):
  778. def getbases(self):
  779. call_tracker.append("E.getbases")
  780. return ()
  781. __bases__ = property(getbases)
  782. class D(object):
  783. def getclass(self):
  784. call_tracker.append("D.getclass")
  785. return C()
  786. __class__ = property(getclass)
  787. AreEqual(isinstance(D(), E()), False)
  788. AreEqual(call_tracker, ['E.getbases', 'D.getclass', 'C.getbases'])
  789. class I(object):
  790. def getclass(self):
  791. return None
  792. __class__ = property(getclass)
  793. class C(object):
  794. def getbases(self):
  795. return ()
  796. __bases__ = property(getbases)
  797. AssertError(TypeError, isinstance, I(), None)
  798. AssertError(TypeError, isinstance, 3, None)
  799. AssertError(TypeError, issubclass, int, None)
  800. def test_tuple_new():
  801. # TypeError: tuple.__new__(str): str is not a subtype of tuple
  802. #!!!AssertError(TypeError, tuple.__new__, str)
  803. #!!!AssertError(TypeError, tuple.__new__, str, 'abc')
  804. pass
  805. ########################################################################
  806. # stand-alone tests
  807. # override pow, delete it, and it should be gone
  808. import operator
  809. pow = 7
  810. AreEqual(pow, 7)
  811. del pow
  812. AreEqual(operator.isCallable(pow), True)
  813. try:
  814. del pow
  815. AreEqual(True,False)
  816. except NameError:
  817. pass
  818. @skip("silverlight", "Merlin bug #404247: this test doesn't work when the file is executed from non-Python host (thost)" )
  819. def test_file():
  820. AreEqual(file_var_present, 1)
  821. file_var_present = vars().keys().count('__file__')
  822. run_test(__name__)