PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/Tests/test_cliclass.py

http://github.com/IronLanguages/main
Python | 2020 lines | 1950 code | 39 blank | 31 comment | 16 complexity | f9851ddf2ec63de837aced53d51875bc 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. """Test cases for class-related features specific to CLI"""
  16. # this needs to run before we add ref to Microsoft.Scripting where we'll get the
  17. # non-generic version of Action[T]. Therefore it also can't run in test_interpret_sanity.
  18. import sys
  19. if sys.platform=="win32":
  20. print "Will not run this test on CPython. Goodbye."
  21. sys.exit(0)
  22. import System
  23. if __name__ == '__main__':
  24. def f(): print 'hello'
  25. try:
  26. System.Action(f)
  27. if not System.Environment.Version.Major>3:
  28. raise Exception('action[t] test failed')
  29. except TypeError, e:
  30. if e.message!="cannot create instances of Action[T] because it is a generic type definition":
  31. raise Exception(e.message)
  32. import clr
  33. if not clr.IsNetStandard:
  34. clr.AddReference("System.Core")
  35. System.Action(f)
  36. from iptest.assert_util import *
  37. from iptest.warning_util import warning_trapper
  38. skiptest("win32")
  39. load_iron_python_test()
  40. from IronPythonTest import *
  41. def test_inheritance():
  42. class MyList(System.Collections.Generic.List[int]):
  43. def get0(self):
  44. return self[0]
  45. l = MyList()
  46. index = l.Add(22)
  47. Assert(l.get0() == 22)
  48. def test_interface_inheritance():
  49. #
  50. # Verify we can inherit from a class that inherits from an interface
  51. #
  52. class MyComparer(System.Collections.IComparer):
  53. def Compare(self, x, y): return 0
  54. class MyDerivedComparer(MyComparer): pass
  55. class MyFurtherDerivedComparer(MyDerivedComparer): pass
  56. # Check that MyDerivedComparer and MyFurtherDerivedComparer can be used as an IComparer
  57. array = System.Array[int](range(10))
  58. System.Array.Sort(array, 0, 10, MyComparer())
  59. System.Array.Sort(array, 0, 10, MyDerivedComparer())
  60. System.Array.Sort(array, 0, 10, MyFurtherDerivedComparer())
  61. def test_inheritance_generic_method():
  62. #
  63. # Verify we can inherit from an interface containing a generic method
  64. #
  65. class MyGenericMethods(IGenericMethods):
  66. def Factory0(self, TParam = None):
  67. self.type = clr.GetClrType(TParam).FullName
  68. return TParam("123")
  69. def Factory1(self, x, T):
  70. self.type = clr.GetClrType(T).FullName
  71. return T("456") + x
  72. def OutParam(self, x, T):
  73. x.Value = T("2")
  74. return True
  75. def RefParam(self, x, T):
  76. x.Value = x.Value + T("10")
  77. def Wild(self, *args, **kwargs):
  78. self.args = args
  79. self.kwargs = kwargs
  80. self.args[2].Value = kwargs['T2']('1.5')
  81. return self.args[3][0]
  82. c = MyGenericMethods()
  83. AreEqual(GenericMethodTester.TestIntFactory0(c), 123)
  84. AreEqual(c.type, 'System.Int32')
  85. AreEqual(GenericMethodTester.TestStringFactory1(c, "789"), "456789")
  86. AreEqual(c.type, 'System.String')
  87. AreEqual(GenericMethodTester.TestIntFactory1(c, 321), 777)
  88. AreEqual(c.type, 'System.Int32')
  89. AreEqual(GenericMethodTester.TestStringFactory0(c), '123')
  90. AreEqual(c.type, 'System.String')
  91. AreEqual(GenericMethodTester.TestOutParamString(c), '2')
  92. AreEqual(GenericMethodTester.TestOutParamInt(c), 2)
  93. AreEqual(GenericMethodTester.TestRefParamString(c, '10'), '1010')
  94. AreEqual(GenericMethodTester.TestRefParamInt(c, 10), 20)
  95. x = System.Collections.Generic.List[int]((2, 3, 4))
  96. r = GenericMethodTester.GoWild(c, True, 'second', x)
  97. AreEqual(r.Length, 2)
  98. AreEqual(r[0], 1.5)
  99. def test_bases():
  100. #
  101. # Verify that changing __bases__ works
  102. #
  103. class MyExceptionComparer(System.Exception, System.Collections.IComparer):
  104. def Compare(self, x, y): return 0
  105. class MyDerivedExceptionComparer(MyExceptionComparer): pass
  106. e = MyExceptionComparer()
  107. MyDerivedExceptionComparer.__bases__ = (System.Exception, System.Collections.IComparer)
  108. MyDerivedExceptionComparer.__bases__ = (MyExceptionComparer,)
  109. class OldType:
  110. def OldTypeMethod(self): return "OldTypeMethod"
  111. class NewType:
  112. def NewTypeMethod(self): return "NewTypeMethod"
  113. class MyOtherExceptionComparer(System.Exception, System.Collections.IComparer, OldType, NewType):
  114. def Compare(self, x, y): return 0
  115. MyExceptionComparer.__bases__ = MyOtherExceptionComparer.__bases__
  116. AreEqual(e.OldTypeMethod(), "OldTypeMethod")
  117. AreEqual(e.NewTypeMethod(), "NewTypeMethod")
  118. Assert(isinstance(e, System.Exception))
  119. Assert(isinstance(e, System.Collections.IComparer))
  120. Assert(isinstance(e, MyExceptionComparer))
  121. class MyIncompatibleExceptionComparer(System.Exception, System.Collections.IComparer, System.IDisposable):
  122. def Compare(self, x, y): return 0
  123. def Displose(self): pass
  124. if not is_silverlight:
  125. AssertErrorWithMatch(TypeError, "__bases__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_*",
  126. setattr, MyExceptionComparer, "__bases__", MyIncompatibleExceptionComparer.__bases__)
  127. AssertErrorWithMatch(TypeError, "__class__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_*",
  128. setattr, MyExceptionComparer(), "__class__", MyIncompatibleExceptionComparer().__class__)
  129. else:
  130. try:
  131. setattr(MyExceptionComparer, "__bases__", MyIncompatibleExceptionComparer.__bases__)
  132. except TypeError, e:
  133. Assert(e.args[0].startswith("__bases__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_"))
  134. try:
  135. setattr(MyExceptionComparer(), "__class__", MyIncompatibleExceptionComparer().__class__)
  136. except TypeError, e:
  137. Assert(e.args[0].startswith("__class__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_"))
  138. def test_open_generic():
  139. # Inherting from an open generic instantiation should fail with a good error message
  140. try:
  141. class Foo(System.Collections.Generic.IEnumerable): pass
  142. except TypeError:
  143. (exc_type, exc_value, exc_traceback) = sys.exc_info()
  144. Assert(exc_value.message.__contains__("cannot inhert from open generic instantiation"))
  145. def test_interface_slots():
  146. # slots & interfaces
  147. class foo(object):
  148. __slots__ = ['abc']
  149. class bar(foo, System.IComparable):
  150. def CompareTo(self, other):
  151. return 23
  152. class baz(bar): pass
  153. def test_op_Implicit_inheritance():
  154. """should inherit op_Implicit from base classes"""
  155. a = NewClass()
  156. AreEqual(int(a), 1002)
  157. AreEqual(long(a), 1002)
  158. AreEqual(NewClass.op_Implicit(a), 1002)
  159. def test_symbol_dict():
  160. """tests to verify that Symbol dictionaries do the right thing in dynamic scenarios
  161. same as the tests in test_class, but we run this in a module that has imported clr"""
  162. def CheckDictionary(C):
  163. # add a new attribute to the type...
  164. C.newClassAttr = 'xyz'
  165. AreEqual(C.newClassAttr, 'xyz')
  166. # add non-string index into the class and instance dictionary
  167. a = C()
  168. try:
  169. a.__dict__[1] = '1'
  170. C.__dict__[2] = '2'
  171. AreEqual(a.__dict__.has_key(1), True)
  172. AreEqual(C.__dict__.has_key(2), True)
  173. AreEqual(dir(a).__contains__(1), True)
  174. AreEqual(dir(a).__contains__(2), True)
  175. AreEqual(dir(C).__contains__(2), True)
  176. AreEqual(repr(a.__dict__), "{1: '1'}")
  177. AreEqual(repr(C.__dict__).__contains__("2: '2'"), True)
  178. except TypeError:
  179. # new-style classes have dict-proxy, can't do the assignment
  180. pass
  181. # replace a class dictionary (containing non-string keys) w/ a normal dictionary
  182. C.newTypeAttr = 1
  183. AreEqual(hasattr(C, 'newTypeAttr'), True)
  184. class OldClass: pass
  185. if isinstance(C, type(OldClass)):
  186. C.__dict__ = dict(C.__dict__)
  187. AreEqual(hasattr(C, 'newTypeAttr'), True)
  188. else:
  189. try:
  190. C.__dict__ = {}
  191. AssertUnreachable()
  192. except AttributeError:
  193. pass
  194. # replace an instance dictionary (containing non-string keys) w/ a new one.
  195. a.newInstanceAttr = 1
  196. AreEqual(hasattr(a, 'newInstanceAttr'), True)
  197. a.__dict__ = dict(a.__dict__)
  198. AreEqual(hasattr(a, 'newInstanceAttr'), True)
  199. a.abc = 'xyz'
  200. AreEqual(hasattr(a, 'abc'), True)
  201. AreEqual(getattr(a, 'abc'), 'xyz')
  202. class OldClass:
  203. def __init__(self): pass
  204. class NewClass(object):
  205. def __init__(self): pass
  206. CheckDictionary(OldClass)
  207. CheckDictionary(NewClass)
  208. def test_generic_TypeGroup():
  209. # TypeGroup is used to expose "System.IComparable" and "System.IComparable`1" as "System.IComparable"
  210. # repr
  211. AreEqual(repr(System.IComparable), "<types 'IComparable', 'IComparable[T]'>")
  212. # Test member access
  213. AreEqual(System.IComparable.CompareTo(1,1), 0)
  214. AreEqual(System.IComparable.CompareTo(1,2), -1)
  215. AreEqual(System.IComparable[int].CompareTo(1,1), 0)
  216. AreEqual(System.IComparable[int].CompareTo(1,2), -1)
  217. Assert(dir(System.IComparable).__contains__("CompareTo"))
  218. Assert(vars(System.IComparable).keys().__contains__("CompareTo"))
  219. import IronPythonTest
  220. genericTypes = IronPythonTest.NestedClass.InnerGenericClass
  221. # IsAssignableFrom is SecurityCritical and thus cannot be called via reflection in silverlight,
  222. # so disable this in interpreted mode.
  223. if not (is_silverlight):
  224. # converstion to Type
  225. Assert(System.Type.IsAssignableFrom(System.IComparable, int))
  226. AssertError(TypeError, System.Type.IsAssignableFrom, object, genericTypes)
  227. # Test illegal type instantiation
  228. try:
  229. System.IComparable[int, int]
  230. except ValueError: pass
  231. else: AssertUnreachable()
  232. try:
  233. System.EventHandler(None)
  234. except TypeError: pass
  235. else: AssertUnreachable()
  236. def handler():
  237. pass
  238. try:
  239. System.EventHandler(handler)("sender", None)
  240. except TypeError: pass
  241. else: AssertUnreachable()
  242. def handler(s,a):
  243. pass
  244. # Test constructor
  245. if not is_silverlight:
  246. # GetType is SecurityCritical; can't call via reflection on silverlight
  247. AreEqual(System.EventHandler(handler).GetType(), System.Type.GetType("System.EventHandler"))
  248. # GetGenericTypeDefinition is SecuritySafe, can't call on Silverlight.
  249. AreEqual(System.EventHandler[System.EventArgs](handler).GetType().GetGenericTypeDefinition(), System.Type.GetType("System.EventHandler`1"))
  250. # Test inheritance
  251. class MyComparable(System.IComparable):
  252. def CompareTo(self, other):
  253. return self.Equals(other)
  254. myComparable = MyComparable()
  255. Assert(myComparable.CompareTo(myComparable))
  256. try:
  257. class MyDerivedClass(genericTypes): pass
  258. except TypeError: pass
  259. else: AssertUnreachable()
  260. # Use a TypeGroup to index a TypeGroup
  261. t = genericTypes[System.IComparable]
  262. t = genericTypes[System.IComparable, int]
  263. try:
  264. System.IComparable[genericTypes]
  265. except TypeError: pass
  266. else: AssertUnreachable()
  267. def test_generic_only_TypeGroup():
  268. try:
  269. BinderTest.GenericOnlyConflict()
  270. except System.TypeLoadException, e:
  271. Assert(str(e).find('requires a non-generic type') != -1)
  272. Assert(str(e).find('GenericOnlyConflict') != -1)
  273. def test_autodoc():
  274. from System.Threading import Thread, ThreadStart
  275. Assert(Thread.__doc__.find('Thread(start: ThreadStart)') != -1)
  276. #Assert(Thread.__new__.__doc__.find('__new__(cls, ThreadStart start)') != -1)
  277. #AreEqual(Thread.__new__.Overloads[ThreadStart].__doc__, '__new__(cls, ThreadStart start)' + newline)
  278. #IronPythonTest.TypeDescTests is not available for silverlight
  279. @skip("silverlight")
  280. def test_type_descs():
  281. if is_netstandard:
  282. clr.AddReference("System.ComponentModel.Primitives")
  283. test = TypeDescTests()
  284. # new style tests
  285. class bar(int): pass
  286. b = bar(2)
  287. class foo(object): pass
  288. c = foo()
  289. #test.TestProperties(...)
  290. res = test.GetClassName(test)
  291. Assert(res == 'IronPythonTest.TypeDescTests')
  292. #res = test.GetClassName(a)
  293. #Assert(res == 'list')
  294. res = test.GetClassName(c)
  295. Assert(res == 'foo')
  296. res = test.GetClassName(b)
  297. Assert(res == 'bar')
  298. res = test.GetConverter(b)
  299. x = res.ConvertTo(None, None, b, int)
  300. Assert(x == 2)
  301. Assert(type(x) == int)
  302. x = test.GetDefaultEvent(b)
  303. Assert(x == None)
  304. x = test.GetDefaultProperty(b)
  305. Assert(x == None)
  306. x = test.GetEditor(b, object)
  307. Assert(x == None)
  308. x = test.GetEvents(b)
  309. Assert(x.Count == 0)
  310. x = test.GetEvents(b, None)
  311. Assert(x.Count == 0)
  312. x = test.GetProperties(b)
  313. Assert(x.Count > 0)
  314. Assert(test.TestProperties(b, [], []))
  315. bar.foobar = property(lambda x: 42)
  316. Assert(test.TestProperties(b, ['foobar'], []))
  317. bar.baz = property(lambda x:42)
  318. Assert(test.TestProperties(b, ['foobar', 'baz'], []))
  319. delattr(bar, 'baz')
  320. Assert(test.TestProperties(b, ['foobar'], ['baz']))
  321. # Check that adding a non-string entry in the dictionary does not cause any grief.
  322. b.__dict__[1] = 1;
  323. Assert(test.TestProperties(b, ['foobar'], ['baz']))
  324. #Assert(test.TestProperties(test, ['GetConverter', 'GetEditor', 'GetEvents', 'GetHashCode'] , []))
  325. # old style tests
  326. class foo: pass
  327. a = foo()
  328. Assert(test.TestProperties(a, [], []))
  329. res = test.GetClassName(a)
  330. Assert(res == 'foo')
  331. x = test.CallCanConvertToForInt(a)
  332. Assert(x == False)
  333. x = test.GetDefaultEvent(a)
  334. Assert(x == None)
  335. x = test.GetDefaultProperty(a)
  336. Assert(x == None)
  337. x = test.GetEditor(a, object)
  338. Assert(x == None)
  339. x = test.GetEvents(a)
  340. Assert(x.Count == 0)
  341. x = test.GetEvents(a, None)
  342. Assert(x.Count == 0)
  343. x = test.GetProperties(a, (System.ComponentModel.BrowsableAttribute(True), ))
  344. Assert(x.Count == 0)
  345. foo.bar = property(lambda x:'hello')
  346. Assert(test.TestProperties(a, ['bar'], []))
  347. delattr(foo, 'bar')
  348. Assert(test.TestProperties(a, [], ['bar']))
  349. a = a.__class__
  350. Assert(test.TestProperties(a, [], []))
  351. foo.bar = property(lambda x:'hello')
  352. Assert(test.TestProperties(a, [], []))
  353. delattr(a, 'bar')
  354. Assert(test.TestProperties(a, [], ['bar']))
  355. x = test.GetClassName(a)
  356. AreEqual(x, 'classobj')
  357. x = test.CallCanConvertToForInt(a)
  358. AreEqual(x, False)
  359. x = test.GetDefaultEvent(a)
  360. AreEqual(x, None)
  361. x = test.GetDefaultProperty(a)
  362. AreEqual(x, None)
  363. x = test.GetEditor(a, object)
  364. AreEqual(x, None)
  365. x = test.GetEvents(a)
  366. AreEqual(x.Count, 0)
  367. x = test.GetEvents(a, None)
  368. AreEqual(x.Count, 0)
  369. x = test.GetProperties(a)
  370. Assert(x.Count > 0)
  371. # Ensure GetProperties checks the attribute dictionary
  372. a = foo()
  373. a.abc = 42
  374. x = test.GetProperties(a)
  375. for prop in x:
  376. if prop.Name == 'abc':
  377. break
  378. else:
  379. AssertUnreachable()
  380. #silverlight does not support System.Char.Parse
  381. @skip("silverlight")
  382. def test_char():
  383. for x in range(256):
  384. c = System.Char.Parse(chr(x))
  385. AreEqual(c, chr(x))
  386. AreEqual(chr(x), c)
  387. if c == chr(x): pass
  388. else: Assert(False)
  389. if not c == chr(x): Assert(False)
  390. if chr(x) == c: pass
  391. else: Assert(False)
  392. if not chr(x) == c: Assert(False)
  393. def test_repr():
  394. if not is_silverlight:
  395. if is_netstandard:
  396. clr.AddReference('System.Drawing.Primitives')
  397. else:
  398. clr.AddReference('System.Drawing')
  399. from System.Drawing import Point
  400. AreEqual(repr(Point(1,2)).startswith('<System.Drawing.Point object'), True)
  401. AreEqual(repr(Point(1,2)).endswith('[{X=1,Y=2}]>'),True)
  402. # these 3 classes define the same repr w/ different \r, \r\n, \n versions
  403. a = UnaryClass(3)
  404. b = BaseClass()
  405. c = BaseClassStaticConstructor()
  406. ra = repr(a)
  407. rb = repr(b)
  408. rc = repr(c)
  409. sa = ra.find('HelloWorld')
  410. sb = rb.find('HelloWorld')
  411. sc = rc.find('HelloWorld')
  412. AreEqual(ra[sa:sa+13], rb[sb:sb+13])
  413. AreEqual(rb[sb:sb+13], rc[sc:sc+13])
  414. AreEqual(ra[sa:sa+13], 'HelloWorld...') # \r\n should be removed, replaced with ...
  415. def test_explicit_interfaces():
  416. otdc = OverrideTestDerivedClass()
  417. AreEqual(otdc.MethodOverridden(), "OverrideTestDerivedClass.MethodOverridden() invoked")
  418. AreEqual(IOverrideTestInterface.MethodOverridden(otdc), 'IOverrideTestInterface.MethodOverridden() invoked')
  419. AreEqual(IOverrideTestInterface.x.GetValue(otdc), 'IOverrideTestInterface.x invoked')
  420. AreEqual(IOverrideTestInterface.y.GetValue(otdc), 'IOverrideTestInterface.y invoked')
  421. IOverrideTestInterface.x.SetValue(otdc, 'abc')
  422. AreEqual(OverrideTestDerivedClass.Value, 'abcx')
  423. IOverrideTestInterface.y.SetValue(otdc, 'abc')
  424. AreEqual(OverrideTestDerivedClass.Value, 'abcy')
  425. AreEqual(otdc.y, 'OverrideTestDerivedClass.y invoked')
  426. AreEqual(IOverrideTestInterface.Method(otdc), "IOverrideTestInterface.method() invoked")
  427. AreEqual(hasattr(otdc, 'IronPythonTest_IOverrideTestInterface_x'), False)
  428. # we can also do this the ugly way:
  429. AreEqual(IOverrideTestInterface.x.__get__(otdc, OverrideTestDerivedClass), 'IOverrideTestInterface.x invoked')
  430. AreEqual(IOverrideTestInterface.y.__get__(otdc, OverrideTestDerivedClass), 'IOverrideTestInterface.y invoked')
  431. AreEqual(IOverrideTestInterface.__getitem__(otdc, 2), 'abc')
  432. AreEqual(IOverrideTestInterface.__getitem__(otdc, 2), 'abc')
  433. AssertError(NotImplementedError, IOverrideTestInterface.__setitem__, otdc, 2, 3)
  434. try:
  435. IOverrideTestInterface.__setitem__(otdc, 2, 3)
  436. except NotImplementedError: pass
  437. else: AssertUnreachable()
  438. def test_field_helpers():
  439. otdc = OverrideTestDerivedClass()
  440. OverrideTestDerivedClass.z.SetValue(otdc, 'abc')
  441. AreEqual(otdc.z, 'abc')
  442. AreEqual(OverrideTestDerivedClass.z.GetValue(otdc), 'abc')
  443. def test_field_descriptor():
  444. AreEqual(MySize.width.__get__(MySize()), 0)
  445. AreEqual(MySize.width.__get__(MySize(), MySize), 0)
  446. def test_field_const_write():
  447. try:
  448. MySize.MaxSize = 23
  449. except AttributeError, e:
  450. Assert(str(e).find('MaxSize') != -1)
  451. Assert(str(e).find('MySize') != -1)
  452. try:
  453. ClassWithLiteral.Literal = 23
  454. except AttributeError, e:
  455. Assert(str(e).find('Literal') != -1)
  456. Assert(str(e).find('ClassWithLiteral') != -1)
  457. try:
  458. ClassWithLiteral.__dict__['Literal'].__set__(None, 23)
  459. except AttributeError, e:
  460. Assert(str(e).find('int') != -1)
  461. try:
  462. ClassWithLiteral.__dict__['Literal'].__set__(ClassWithLiteral(), 23)
  463. except AttributeError, e:
  464. Assert(str(e).find('int') != -1)
  465. try:
  466. MySize().MaxSize = 23
  467. except AttributeError, e:
  468. Assert(str(e).find('MaxSize') != -1)
  469. Assert(str(e).find('MySize') != -1)
  470. try:
  471. ClassWithLiteral().Literal = 23
  472. except AttributeError, e:
  473. Assert(str(e).find('Literal') != -1)
  474. Assert(str(e).find('ClassWithLiteral') != -1)
  475. def test_field_const_access():
  476. AreEqual(MySize().MaxSize, System.Int32.MaxValue)
  477. AreEqual(MySize.MaxSize, System.Int32.MaxValue)
  478. AreEqual(ClassWithLiteral.Literal, 5)
  479. AreEqual(ClassWithLiteral().Literal, 5)
  480. def test_array():
  481. arr = System.Array[int]([0])
  482. AreEqual(repr(arr), str(arr))
  483. AreEqual(repr(System.Array[int]([0, 1])), 'Array[int]((0, 1))')
  484. def test_strange_inheritance():
  485. """verify that overriding strange methods (such as those that take caller context) doesn't
  486. flow caller context through"""
  487. class m(StrangeOverrides):
  488. def SomeMethodWithContext(self, arg):
  489. AreEqual(arg, 'abc')
  490. def ParamsMethodWithContext(self, *arg):
  491. AreEqual(arg, ('abc', 'def'))
  492. def ParamsIntMethodWithContext(self, *arg):
  493. AreEqual(arg, (2,3))
  494. a = m()
  495. a.CallWithContext('abc')
  496. a.CallParamsWithContext('abc', 'def')
  497. a.CallIntParamsWithContext(2, 3)
  498. #lib.process_util, file, etc are not available in silverlight
  499. @skip("silverlight")
  500. def test_nondefault_indexers():
  501. from iptest.process_util import *
  502. if not has_vbc(): return
  503. import os
  504. import _random
  505. r = _random.Random()
  506. r.seed()
  507. f = file('vbproptest1.vb', 'w')
  508. try:
  509. f.write("""
  510. Public Class VbPropertyTest
  511. private Indexes(23) as Integer
  512. private IndexesTwo(23,23) as Integer
  513. private shared SharedIndexes(5,5) as Integer
  514. Public Property IndexOne(ByVal index as Integer) As Integer
  515. Get
  516. return Indexes(index)
  517. End Get
  518. Set
  519. Indexes(index) = Value
  520. End Set
  521. End Property
  522. Public Property IndexTwo(ByVal index as Integer, ByVal index2 as Integer) As Integer
  523. Get
  524. return IndexesTwo(index, index2)
  525. End Get
  526. Set
  527. IndexesTwo(index, index2) = Value
  528. End Set
  529. End Property
  530. Public Shared Property SharedIndex(ByVal index as Integer, ByVal index2 as Integer) As Integer
  531. Get
  532. return SharedIndexes(index, index2)
  533. End Get
  534. Set
  535. SharedIndexes(index, index2) = Value
  536. End Set
  537. End Property
  538. End Class
  539. """)
  540. f.close()
  541. name = path_combine(testpath.temporary_dir, 'vbproptest%f.dll' % (r.random()))
  542. x = run_vbc('/target:library vbproptest1.vb "/out:%s"' % name)
  543. AreEqual(x, 0)
  544. clr.AddReferenceToFileAndPath(name)
  545. import VbPropertyTest
  546. x = VbPropertyTest()
  547. AreEqual(x.IndexOne[0], 0)
  548. x.IndexOne[1] = 23
  549. AreEqual(x.IndexOne[1], 23)
  550. AreEqual(x.IndexTwo[0,0], 0)
  551. x.IndexTwo[1,2] = 5
  552. AreEqual(x.IndexTwo[1,2], 5)
  553. AreEqual(VbPropertyTest.SharedIndex[0,0], 0)
  554. VbPropertyTest.SharedIndex[3,4] = 42
  555. AreEqual(VbPropertyTest.SharedIndex[3,4], 42)
  556. finally:
  557. if not f.closed: f.close()
  558. os.unlink('vbproptest1.vb')
  559. @skip("silverlight")
  560. def test_nondefault_indexers_overloaded():
  561. from iptest.process_util import *
  562. if not has_vbc(): return
  563. import os
  564. import _random
  565. r = _random.Random()
  566. r.seed()
  567. f = file('vbproptest1.vb', 'w')
  568. try:
  569. f.write("""
  570. Public Class VbPropertyTest
  571. private Indexes(23) as Integer
  572. private IndexesTwo(23,23) as Integer
  573. private shared SharedIndexes(5,5) as Integer
  574. Public Property IndexOne(ByVal index as Integer) As Integer
  575. Get
  576. return Indexes(index)
  577. End Get
  578. Set
  579. Indexes(index) = Value
  580. End Set
  581. End Property
  582. Public Property IndexTwo(ByVal index as Integer, ByVal index2 as Integer) As Integer
  583. Get
  584. return IndexesTwo(index, index2)
  585. End Get
  586. Set
  587. IndexesTwo(index, index2) = Value
  588. End Set
  589. End Property
  590. Public Shared Property SharedIndex(ByVal index as Integer, ByVal index2 as Integer) As Integer
  591. Get
  592. return SharedIndexes(index, index2)
  593. End Get
  594. Set
  595. SharedIndexes(index, index2) = Value
  596. End Set
  597. End Property
  598. End Class
  599. Public Class VbPropertyTest2
  600. Public ReadOnly Property Prop() As string
  601. get
  602. return "test"
  603. end get
  604. end property
  605. Public ReadOnly Property Prop(ByVal name As String) As string
  606. get
  607. return name
  608. end get
  609. end property
  610. End Class
  611. """)
  612. f.close()
  613. name = path_combine(testpath.temporary_dir, 'vbproptest%f.dll' % (r.random()))
  614. AreEqual(run_vbc('/target:library vbproptest1.vb /out:"%s"' % name), 0)
  615. clr.AddReferenceToFileAndPath(name)
  616. import VbPropertyTest, VbPropertyTest2
  617. x = VbPropertyTest()
  618. AreEqual(x.IndexOne[0], 0)
  619. x.IndexOne[1] = 23
  620. AreEqual(x.IndexOne[1], 23)
  621. AreEqual(x.IndexTwo[0,0], 0)
  622. x.IndexTwo[1,2] = 5
  623. AreEqual(x.IndexTwo[1,2], 5)
  624. AreEqual(VbPropertyTest.SharedIndex[0,0], 0)
  625. VbPropertyTest.SharedIndex[3,4] = 42
  626. AreEqual(VbPropertyTest.SharedIndex[3,4], 42)
  627. AreEqual(VbPropertyTest2().Prop, 'test')
  628. AreEqual(VbPropertyTest2().get_Prop('foo'), 'foo')
  629. finally:
  630. if not f.closed: f.close()
  631. os.unlink('vbproptest1.vb')
  632. def test_interface_abstract_events():
  633. # inherit from an interface or abstract event, and define the event
  634. for baseType in [IEventInterface, AbstractEvent]:
  635. class foo(baseType):
  636. def __init__(self):
  637. self._events = []
  638. def add_MyEvent(self, value):
  639. AreEqual(type(value), SimpleDelegate)
  640. self._events.append(value)
  641. def remove_MyEvent(self, value):
  642. AreEqual(type(value), SimpleDelegate)
  643. self._events.remove(value)
  644. def MyRaise(self):
  645. for x in self._events: x()
  646. global called
  647. called = False
  648. def bar(*args):
  649. global called
  650. called = True
  651. a = foo()
  652. a.MyEvent += bar
  653. a.MyRaise()
  654. AreEqual(called, True)
  655. a.MyEvent -= bar
  656. called = False
  657. a.MyRaise()
  658. AreEqual(called, False)
  659. # hook the event from the CLI side, and make sure that raising
  660. # it causes the CLI side to see the event being fired.
  661. UseEvent.Hook(a)
  662. a.MyRaise()
  663. AreEqual(UseEvent.Called, True)
  664. UseEvent.Called = False
  665. UseEvent.Unhook(a)
  666. a.MyRaise()
  667. AreEqual(UseEvent.Called, False)
  668. @disabled("Merlin 177188: Fail in Orcas")
  669. def test_dynamic_assembly_ref():
  670. # verify we can add a reference to a dynamic assembly, and
  671. # then create an instance of that type
  672. class foo(object): pass
  673. clr.AddReference(foo().GetType().Assembly)
  674. import IronPython.NewTypes.System
  675. for x in dir(IronPython.NewTypes.System):
  676. if x.startswith('Object_'):
  677. t = getattr(IronPython.NewTypes.System, x)
  678. x = t(foo)
  679. break
  680. else:
  681. # we should have found our type
  682. AssertUnreachable()
  683. def test_nonzero():
  684. from System import Single, Byte, SByte, Int16, UInt16, Int64, UInt64
  685. for t in [Single, Byte, SByte, Int16, UInt16, Int64, UInt64]:
  686. Assert(hasattr(t, '__nonzero__'))
  687. if t(0): AssertUnreachable()
  688. if not t(1): AssertUnreachable()
  689. def test_virtual_event():
  690. # inherit from a class w/ a virtual event and a
  691. # virtual event that's been overridden. Check both
  692. # overriding it and not overriding it.
  693. for baseType in [VirtualEvent, OverrideVirtualEvent]:
  694. for override in [True, False]:
  695. class foo(baseType):
  696. def __init__(self):
  697. self._events = []
  698. if override:
  699. def add_MyEvent(self, value):
  700. AreEqual(type(value), SimpleDelegate)
  701. self._events.append(value)
  702. def remove_MyEvent(self, value):
  703. AreEqual(type(value), SimpleDelegate)
  704. self._events.remove(value)
  705. def add_MyCustomEvent(self, value): pass
  706. def remove_MyCustomEvent(self, value): pass
  707. def MyRaise(self):
  708. for x in self._events: x()
  709. else:
  710. def MyRaise(self):
  711. self.FireEvent()
  712. # normal event
  713. global called
  714. called = False
  715. def bar(*args):
  716. global called
  717. called = True
  718. a = foo()
  719. a.MyEvent += bar
  720. a.MyRaise()
  721. AreEqual(called, True)
  722. a.MyEvent -= bar
  723. called = False
  724. a.MyRaise()
  725. AreEqual(called, False)
  726. # custom event
  727. a.LastCall = None
  728. a = foo()
  729. a.MyCustomEvent += bar
  730. if override: AreEqual(a.LastCall, None)
  731. else: Assert(a.LastCall.endswith('Add'))
  732. a.Lastcall = None
  733. a.MyCustomEvent -= bar
  734. if override: AreEqual(a.LastCall, None)
  735. else: Assert(a.LastCall.endswith('Remove'))
  736. # hook the event from the CLI side, and make sure that raising
  737. # it causes the CLI side to see the event being fired.
  738. UseEvent.Hook(a)
  739. a.MyRaise()
  740. AreEqual(UseEvent.Called, True)
  741. UseEvent.Called = False
  742. UseEvent.Unhook(a)
  743. a.MyRaise()
  744. AreEqual(UseEvent.Called, False)
  745. @skip("silverlight")
  746. def test_property_get_set():
  747. if is_netstandard:
  748. clr.AddReference("System.Drawing.Primitives")
  749. else:
  750. clr.AddReference("System.Drawing")
  751. from System.Drawing import Size
  752. temp = Size()
  753. AreEqual(temp.Width, 0)
  754. temp.Width = 5
  755. AreEqual(temp.Width, 5)
  756. for i in xrange(5):
  757. temp.Width = i
  758. AreEqual(temp.Width, i)
  759. def test_write_only_property_set():
  760. from IronPythonTest import WriteOnly
  761. obj = WriteOnly()
  762. AssertError(AttributeError, getattr, obj, 'Writer')
  763. def test_isinstance_interface():
  764. Assert(isinstance('abc', System.Collections.IEnumerable))
  765. def test_constructor_function():
  766. '''
  767. Test to hit IronPython.Runtime.Operations.ConstructionFunctionOps.
  768. '''
  769. AreEqual(System.DateTime.__new__.__name__, '__new__')
  770. Assert(System.DateTime.__new__.__doc__.find('__new__(cls: type, year: int, month: int, day: int)') != -1)
  771. if not is_silverlight and not is_netstandard: # no System.AssemblyLoadEventArgs in netstandard
  772. Assert(System.AssemblyLoadEventArgs.__new__.__doc__.find('__new__(cls: type, loadedAssembly: Assembly)') != -1)
  773. def test_class_property():
  774. """__class__ should work on standard .NET types and should return the type object associated with that class"""
  775. AreEqual(System.Environment.Version.__class__, System.Version)
  776. def test_null_str():
  777. """if a .NET type has a bad ToString() implementation that returns null always return String.Empty in Python"""
  778. AreEqual(str(RudeObjectOverride()), '')
  779. AreEqual(RudeObjectOverride().__str__(), '')
  780. AreEqual(RudeObjectOverride().ToString(), None)
  781. Assert(repr(RudeObjectOverride()).startswith('<IronPythonTest.RudeObjectOverride object at '))
  782. def test_keyword_construction_readonly():
  783. # Build is read-only property
  784. AssertError(AttributeError, System.Version, 1, 0, Build=100)
  785. AssertError(AttributeError, ClassWithLiteral, Literal=3)
  786. @skip("silverlight") # no FileSystemWatcher in Silverlight
  787. def test_kw_construction_types():
  788. if is_netstandard:
  789. clr.AddReference("System.IO.FileSystem.Watcher")
  790. for val in [True, False]:
  791. x = System.IO.FileSystemWatcher('.', EnableRaisingEvents = val)
  792. AreEqual(x.EnableRaisingEvents, val)
  793. def test_as_bool():
  794. """verify using expressions in if statements works correctly. This generates an
  795. site whose return type is bool so it's important this works for various ways we can
  796. generate the body of the site, and use the site both w/ the initial & generated targets"""
  797. if is_netstandard:
  798. clr.AddReference("System.Runtime")
  799. else:
  800. clr.AddReference('System') # ensure test passes in ipt
  801. # instance property
  802. x = System.Uri('http://foo')
  803. for i in xrange(2):
  804. if x.AbsolutePath: pass
  805. else: AssertUnreachable()
  806. # instance property on type
  807. for i in xrange(2):
  808. if System.Uri.AbsolutePath: pass
  809. else: AssertUnreachable()
  810. # static property
  811. for i in xrange(2):
  812. if System.Threading.Thread.CurrentThread: pass
  813. else: AssertUnreachable()
  814. # static field
  815. for i in xrange(2):
  816. if System.String.Empty: AssertUnreachable()
  817. # instance field
  818. x = NestedClass()
  819. for i in xrange(2):
  820. if x.Field: AssertUnreachable()
  821. # instance field on type
  822. for i in xrange(2):
  823. if NestedClass.Field: pass
  824. else: AssertUnreachable()
  825. # math
  826. for i in xrange(2):
  827. if System.Int64(1) + System.Int64(1): pass
  828. else: AssertUnreachable()
  829. for i in xrange(2):
  830. if System.Int64(1) + System.Int64(1): pass
  831. else: AssertUnreachable()
  832. # GetItem
  833. x = System.Collections.Generic.List[str]()
  834. x.Add('abc')
  835. for i in xrange(2):
  836. if x[0]: pass
  837. else: AssertUnreachable()
  838. @skip("silverlight") # no Stack on Silverlight
  839. def test_generic_getitem():
  840. if is_netstandard:
  841. clr.AddReference("System.Collections")
  842. # calling __getitem__ is the same as indexing
  843. AreEqual(System.Collections.Generic.Stack.__getitem__(int), System.Collections.Generic.Stack[int])
  844. # but __getitem__ on a type takes precedence
  845. AssertError(TypeError, System.Collections.Generic.List.__getitem__, int)
  846. x = System.Collections.Generic.List[int]()
  847. x.Add(0)
  848. AreEqual(System.Collections.Generic.List[int].__getitem__(x, 0), 0)
  849. # but we can call type.__getitem__ with the instance
  850. AreEqual(type.__getitem__(System.Collections.Generic.List, int), System.Collections.Generic.List[int])
  851. @skip("silverlight") # no WinForms on Silverlight
  852. @skip("netstandard") # no System.Windows.Forms in netstandard
  853. def test_multiple_inheritance():
  854. """multiple inheritance from two types in the same hierarchy should work, this is similar to class foo(int, object)"""
  855. clr.AddReference("System.Windows.Forms")
  856. class foo(System.Windows.Forms.Form, System.Windows.Forms.Control): pass
  857. def test_struct_no_ctor_kw_args():
  858. for x in range(2):
  859. s = Structure(a=3)
  860. AreEqual(s.a, 3)
  861. def test_nullable_new():
  862. from System import Nullable
  863. AreEqual(clr.GetClrType(Nullable[()]).IsGenericType, False)
  864. def test_ctor_keyword_args_newslot():
  865. """ctor keyword arg assignment contruction w/ new slot properties"""
  866. x = BinderTest.KeywordDerived(SomeProperty = 'abc')
  867. AreEqual(x.SomeProperty, 'abc')
  868. x = BinderTest.KeywordDerived(SomeField = 'abc')
  869. AreEqual(x.SomeField, 'abc')
  870. def test_enum_truth():
  871. # zero enums are false, non-zero enums are true
  872. Assert(not System.StringSplitOptions.None)
  873. Assert(System.StringSplitOptions.RemoveEmptyEntries)
  874. AreEqual(System.StringSplitOptions.None.__nonzero__(), False)
  875. AreEqual(System.StringSplitOptions.RemoveEmptyEntries.__nonzero__(), True)
  876. def test_enum_repr():
  877. clr.AddReference('IronPython')
  878. from IronPython.Runtime import ModuleOptions
  879. AreEqual(repr(ModuleOptions.WithStatement), 'IronPython.Runtime.ModuleOptions.WithStatement')
  880. AreEqual(repr(ModuleOptions.WithStatement | ModuleOptions.TrueDivision),
  881. '<enum IronPython.Runtime.ModuleOptions: TrueDivision, WithStatement>')
  882. def test_bad_inheritance():
  883. """verify a bad inheritance reports the type name you're inheriting from"""
  884. def f():
  885. class x(System.Single): pass
  886. def g():
  887. class x(System.Version): pass
  888. AssertErrorWithPartialMessage(TypeError, 'System.Single', f)
  889. AssertErrorWithPartialMessage(TypeError, 'System.Version', g)
  890. def test_disposable():
  891. """classes implementing IDisposable should automatically support the with statement"""
  892. x = DisposableTest()
  893. with x:
  894. pass
  895. AreEqual(x.Called, True)
  896. Assert(hasattr(x, '__enter__'))
  897. Assert(hasattr(x, '__exit__'))
  898. x = DisposableTest()
  899. x.__enter__()
  900. try:
  901. pass
  902. finally:
  903. AreEqual(x.__exit__(None, None, None), None)
  904. AreEqual(x.Called, True)
  905. Assert('__enter__' in dir(x))
  906. Assert('__exit__' in dir(x))
  907. Assert('__enter__' in dir(DisposableTest))
  908. Assert('__exit__' in dir(DisposableTest))
  909. def test_dbnull():
  910. """DBNull should not be true"""
  911. if is_netstandard:
  912. clr.AddReference("System.Data.Common")
  913. if System.DBNull.Value:
  914. AssertUnreachable()
  915. def test_special_repr():
  916. list = System.Collections.Generic.List[object]()
  917. AreEqual(repr(list), 'List[object]()')
  918. list.Add('abc')
  919. AreEqual(repr(list), "List[object](['abc'])")
  920. list.Add(2)
  921. AreEqual(repr(list), "List[object](['abc', 2])")
  922. list.Add(list)
  923. AreEqual(repr(list), "List[object](['abc', 2, [...]])")
  924. dict = System.Collections.Generic.Dictionary[object, object]()
  925. AreEqual(repr(dict), "Dictionary[object, object]()")
  926. dict["abc"] = "def"
  927. AreEqual(repr(dict), "Dictionary[object, object]({'abc' : 'def'})")
  928. dict["two"] = "def"
  929. Assert(repr(dict) == "Dictionary[object, object]({'abc' : 'def', 'two' : 'def'})" or
  930. repr(dict) == "Dictionary[object, object]({'two' : 'def', 'def' : 'def'})")
  931. dict = System.Collections.Generic.Dictionary[object, object]()
  932. dict['abc'] = dict
  933. AreEqual(repr(dict), "Dictionary[object, object]({'abc' : {...}})")
  934. dict = System.Collections.Generic.Dictionary[object, object]()
  935. dict[dict] = 'abc'
  936. AreEqual(repr(dict), "Dictionary[object, object]({{...} : 'abc'})")
  937. def test_issubclass():
  938. Assert(issubclass(int, clr.GetClrType(int)))
  939. def test_explicit_interface_impl():
  940. noConflict = ExplicitTestNoConflict()
  941. oneConflict = ExplicitTestOneConflict()
  942. AreEqual(noConflict.A(), "A")
  943. AreEqual(noConflict.B(), "B")
  944. Assert(hasattr(noConflict, "A"))
  945. Assert(hasattr(noConflict, "B"))
  946. AssertError(AttributeError, lambda : oneConflict.A())
  947. AreEqual(oneConflict.B(), "B")
  948. Assert(not hasattr(oneConflict, "A"))
  949. Assert(hasattr(oneConflict, "B"))
  950. @skip("silverlight") # no ArrayList on Silverlight
  951. def test_interface_isinstance():
  952. if is_netstandard:
  953. clr.AddReference("System.Collections.NonGeneric")
  954. l = System.Collections.ArrayList()
  955. AreEqual(isinstance(l, System.Collections.IList), True)
  956. @skip("silverlight") # no serialization support in Silverlight
  957. @skip("netstandard") # no ClrModule.Serialize/Deserialize in netstandard
  958. def test_serialization():
  959. """
  960. TODO:
  961. - this should become a test module in and of itself
  962. - way more to test here..
  963. """
  964. import cPickle
  965. # test the primitive data types...
  966. data = [1, 1.0, 2j, 2L, System.Int64(1), System.UInt64(1),
  967. System.UInt32(1), System.Int16(1), System.UInt16(1),
  968. System.Byte(1), System.SByte(1), System.Decimal(1),
  969. System.Char.MaxValue, System.DBNull.Value, System.Single(1.0),
  970. System.DateTime.Now, None, {}, (), [], {'a': 2}, (42, ), [42, ],
  971. System.StringSplitOptions.RemoveEmptyEntries,
  972. ]
  973. data.append(list(data)) # list of all the data..
  974. data.append(tuple(data)) # tuple of all the data...
  975. class X:
  976. def __init__(self):
  977. self.abc = 3
  978. class Y(object):
  979. def __init__(self):
  980. self.abc = 3
  981. # instance dictionaries...
  982. data.append(X().__dict__)
  983. data.append(Y().__dict__)
  984. # recursive list
  985. l = []
  986. l.append(l)
  987. data.append(l)
  988. # dict of all the data
  989. d = {}
  990. cnt = 100
  991. for x in data:
  992. d[cnt] = x
  993. cnt += 1
  994. data.append(d)
  995. # recursive dict...
  996. d1 = {}
  997. d2 = {}
  998. d1['abc'] = d2
  999. d1['foo'] = 'baz'
  1000. d2['abc'] = d1
  1001. data.append(d1)
  1002. data.append(d2)
  1003. for value in data:
  1004. # use cPickle & clr.Serialize/Deserialize directly
  1005. for newVal in (cPickle.loads(cPickle.dumps(value)), clr.Deserialize(*clr.Serialize(value))):
  1006. AreEqual(type(newVal), type(value))
  1007. try:
  1008. AreEqual(newVal, value)
  1009. except RuntimeError, e:
  1010. # we hit one of our recursive structures...
  1011. AreEqual(e.message, "maximum recursion depth exceeded in cmp")
  1012. Assert(type(newVal) is list or type(newVal) is dict)
  1013. # passing an unknown format raises...
  1014. AssertError(ValueError, clr.Deserialize, "unknown", "foo")
  1015. al = System.Collections.ArrayList()
  1016. al.Add(2)
  1017. gl = System.Collections.Generic.List[int]()
  1018. gl.Add(2)
  1019. # lists...
  1020. for value in (al, gl):
  1021. for newX in (cPickle.loads(cPickle.dumps(value)), clr.Deserialize(*clr.Serialize(value))):
  1022. AreEqual(value.Count, newX.Count)
  1023. for i in xrange(value.Count):
  1024. AreEqual(value[i], newX[i])
  1025. ht = System.Collections.Hashtable()
  1026. ht['foo'] = 'bar'
  1027. gd = System.Collections.Generic.Dictionary[str, str]()
  1028. gd['foo'] = 'bar'
  1029. # dictionaries
  1030. for value in (ht, gd):
  1031. for newX in (cPickle.loads(cPickle.dumps(value)), clr.Deserialize(*clr.Serialize(value))):
  1032. AreEqual(value.Count, newX.Count)
  1033. for key in value.Keys:
  1034. AreEqual(value[key], newX[key])
  1035. # interesting cases
  1036. for tempX in [System.Exception("some message")]:
  1037. for newX in (cPickle.loads(cPickle.dumps(tempX)), clr.Deserialize(*clr.Serialize(tempX))):
  1038. AreEqual(newX.Message, tempX.Message)
  1039. try:
  1040. exec " print 1"
  1041. except Exception, tempX:
  1042. pass
  1043. newX = cPickle.loads(cPickle.dumps(tempX))
  1044. for attr in ['args', 'filename', 'text', 'lineno', 'msg', 'offset', 'print_file_and_line',
  1045. 'message',
  1046. ]:
  1047. AreEqual(eval("newX.%s" % attr),
  1048. eval("tempX.%s" % attr))
  1049. class K(System.Exception):
  1050. other = "something else"
  1051. tempX = K()
  1052. #CodePlex 16415
  1053. #for newX in (cPickle.loads(cPickle.dumps(tempX)), clr.Deserialize(*clr.Serialize(tempX))):
  1054. # AreEqual(newX.Message, tempX.Message)
  1055. # AreEqual(newX.other, tempX.other)
  1056. #CodePlex 16415
  1057. tempX = System.Exception
  1058. #for newX in (cPickle.loads(cPickle.dumps(System.Exception)), clr.Deserialize(*clr.Serialize(System.Exception))):
  1059. # temp_except = newX("another message")
  1060. # AreEqual(temp_except.Message, "another message")
  1061. def test_generic_method_error():
  1062. if is_netstandard:
  1063. clr.AddReference("System.Linq.Queryable")
  1064. else:
  1065. clr.AddReference('System.Core')
  1066. from System.Linq import Queryable
  1067. AssertErrorWithMessage(TypeError, "The type arguments for method 'First' cannot be inferred from the usage. Try specifying the type arguments explicitly.", Queryable.First, [])
  1068. def test_collection_length():
  1069. a = GenericCollection()
  1070. AreEqual(len(a), 0)
  1071. a.Add(1)
  1072. AreEqual(len(a), 1)
  1073. Assert(hasattr(a, '__len__'))
  1074. def test_dict_copy():
  1075. Assert(int.__dict__.copy().has_key('MaxValue'))
  1076. def test_decimal_bool():
  1077. AreEqual(bool(System.Decimal(0)), False)
  1078. AreEqual(bool(System.Decimal(1)), True)
  1079. @skip("silverlight") # no Char.Parse
  1080. def test_add_str_char():
  1081. AreEqual('bc' + System.Char.Parse('a'), 'bca')
  1082. AreEqual(System.Char.Parse('a') + 'bc', 'abc')
  1083. def test_import_star_enum():
  1084. from System.AttributeTargets import *
  1085. Assert('ReturnValue' in dir())
  1086. @skip("silverlight")
  1087. def test_cp11971():
  1088. old_syspath = [x for x in sys.path]
  1089. try:
  1090. sys.path.append(testpath.temporary_dir)
  1091. #Module using System
  1092. write_to_file(path_combine(testpath.temporary_dir, "cp11971_module.py"),
  1093. """def a():
  1094. from System import Array
  1095. return Array.CreateInstance(int, 2, 2)""")
  1096. #Module which doesn't use System directly
  1097. write_to_file(path_combine(testpath.temporary_dir, "cp11971_caller.py"),
  1098. """import cp11971_module
  1099. A = cp11971_module.a()
  1100. if not hasattr(A, 'Rank'):
  1101. raise 'CodePlex 11971'
  1102. """)
  1103. #Validations
  1104. import cp11971_caller
  1105. Assert(hasattr(cp11971_caller.A, 'Rank'))
  1106. Assert(hasattr(cp11971_caller.cp11971_module.a(), 'Rank'))
  1107. finally:
  1108. sys.path = old_syspath
  1109. @skip("silverlight") # no Stack on Silverlight
  1110. def test_ienumerable__getiter__():
  1111. #--empty list
  1112. called = 0
  1113. x = System.Collections.Generic.List[int]()
  1114. Assert(hasattr(x, "__iter__"))
  1115. for stuff in x:
  1116. called +=1
  1117. AreEqual(called, 0)
  1118. #--add one element to the list
  1119. called = 0
  1120. x.Add(1)
  1121. for stuff in x:
  1122. AreEqual(stuff, 1)
  1123. called +=1
  1124. AreEqual(called, 1)
  1125. #--one element list before __iter__ is called
  1126. called = 0
  1127. x = System.Collections.Generic.List[int]()
  1128. x.Add(1)
  1129. for stuff in x:
  1130. AreEqual(stuff, 1)
  1131. called +=1
  1132. AreEqual(called, 1)
  1133. #--two elements in the list
  1134. called = 0
  1135. x.Add(2)
  1136. for stuff in x:
  1137. AreEqual(stuff-1, called)
  1138. called +=1
  1139. AreEqual(called, 2)
  1140. def test_overload_functions():
  1141. for x in min.Overloads.Functions:
  1142. Assert(x.__doc__.startswith('min('))
  1143. Assert(x.__doc__.find('CodeContext') == -1)
  1144. # multiple accesses should return the same object
  1145. AreEqual(
  1146. id(min.Overloads[object, object]),
  1147. id(min.Overloads[object, object])
  1148. )
  1149. def test_clr_dir():
  1150. Assert('IndexOf' not in clr.Dir('abc'))
  1151. Assert('IndexOf' in clr.DirClr('abc'))
  1152. @skip("posix")
  1153. def test_array_contains():
  1154. AssertError(KeyError, lambda : System.Array[str].__dict__['__contains__'])
  1155. def test_a_override_patching():
  1156. if System.Environment.Version.Major >=4:
  1157. if is_netstandard:
  1158. clr.AddReference("System.Dynamic.Runtime")
  1159. else:
  1160. clr.AddReference("System.Core")
  1161. else:
  1162. clr.AddReference("Microsoft.Scripting.Core")
  1163. # derive from object
  1164. class x(object):
  1165. pass
  1166. # force creation of GetHashCode built-in function
  1167. TestHelpers.HashObject(x())
  1168. # derive from a type which overrides GetHashCode
  1169. from System.Dynamic import InvokeBinder
  1170. from System.Dynamic import CallInfo
  1171. class y(InvokeBinder):
  1172. def GetHashCode(self): return super(InvokeBinder, self).GetHashCode()
  1173. # now the super call should work & should include the InvokeBinder new type
  1174. TestHelpers.HashObject(y(CallInfo(0)))
  1175. def test_inherited_interface_impl():
  1176. BinderTest.InterfaceTestHelper.Flag = False
  1177. BinderTest.InterfaceTestHelper.GetObject().M()
  1178. AreEqual(BinderTest.InterfaceTestHelper.Flag, True)
  1179. BinderTest.InterfaceTestHelper.Flag = False
  1180. BinderTest.InterfaceTestHelper.GetObject2().M()
  1181. AreEqual(BinderTest.InterfaceTestHelper.Flag, True)
  1182. def test_dir():
  1183. # make sure you can do dir on everything in System which
  1184. # includes special types like ArgIterator and Func
  1185. for attr in dir(System):
  1186. dir(getattr(System, attr))
  1187. if not is_silverlight:
  1188. if is_netstandard:
  1189. clr.AddReference("System.Collections")
  1190. for x in [System.Collections.Generic.SortedList,
  1191. System.Collections.Generic.Dictionary,
  1192. ]:
  1193. temp = dir(x)
  1194. def test_family_or_assembly():
  1195. class my(FamilyOrAssembly): pass
  1196. obj = my()
  1197. AreEqual(obj.Method(), 42)
  1198. obj.Property = 'abc'
  1199. AreEqual(obj.Property, 'abc')
  1200. def test_valuetype_iter():
  1201. from System.Collections.Generic import Dictionary
  1202. d = Dictionary[str, str]()
  1203. d["a"] = "foo"
  1204. d["b"] = "bar"
  1205. it = iter(d)
  1206. AreEqual(it.next().Key, 'a')
  1207. AreEqual(it.next().Key, 'b')
  1208. @skip("silverlight", "posix")
  1209. def test_abstract_class_no_interface_impl():
  1210. # this can't be defined in C# or VB, it's a class which is
  1211. # abstract and therefore doesn't implement the interface method
  1212. ilcode = """
  1213. // Microsoft (R) .NET Framework IL Disassembler. Version 3.5.30729.1
  1214. // Copyright (c) Microsoft Corporation. All rights reserved.
  1215. // Metadata version: v2.0.50727
  1216. .assembly extern mscorlib
  1217. {
  1218. .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
  1219. .ver 2:0:0:0
  1220. }
  1221. .assembly test
  1222. {
  1223. .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 )
  1224. .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx

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