-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathtest_cliclass.py
1961 lines (1544 loc) · 70.2 KB
/
test_cliclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import sys
import unittest
from iptest import IronPythonTestCase, skipUnlessIronPython, is_cli, is_debug, is_netcoreapp, is_posix, run_test
if is_cli:
import clr
import System
@skipUnlessIronPython()
class CliClassTestCase(IronPythonTestCase):
def setUp(self):
super(CliClassTestCase, self).setUp()
self.load_iron_python_test()
def test_inheritance(self):
import System
class MyList(System.Collections.Generic.List[int]):
def get0(self):
return self[0]
l = MyList()
index = l.Add(22)
self.assertTrue(l.get0() == 22)
def test_interface_inheritance(self):
"""Verify we can inherit from a class that inherits from an interface"""
class MyComparer(System.Collections.IComparer):
def Compare(self, x, y): return 0
class MyDerivedComparer(MyComparer): pass
class MyFurtherDerivedComparer(MyDerivedComparer): pass
# Check that MyDerivedComparer and MyFurtherDerivedComparer can be used as an IComparer
array = System.Array[int](range(10))
System.Array.Sort(array, 0, 10, MyComparer())
System.Array.Sort(array, 0, 10, MyDerivedComparer())
System.Array.Sort(array, 0, 10, MyFurtherDerivedComparer())
def test_inheritance_generic_method(self):
"""Verify we can inherit from an interface containing a generic method"""
from IronPythonTest import IGenericMethods, GenericMethodTester
class MyGenericMethods(IGenericMethods):
def Factory0(self, TParam = None):
self.type = clr.GetClrType(TParam).FullName
return TParam("123")
def Factory1(self, x, T):
self.type = clr.GetClrType(T).FullName
return T("456") + x
def OutParam(self, x, T):
x.Value = T("2")
return True
def RefParam(self, x, T):
x.Value = x.Value + T("10")
def Wild(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.args[2].Value = kwargs['T2']('1.5')
return self.args[3][0]
c = MyGenericMethods()
self.assertEqual(GenericMethodTester.TestIntFactory0(c), 123)
self.assertEqual(c.type, 'System.Int32')
self.assertEqual(GenericMethodTester.TestStringFactory1(c, "789"), "456789")
self.assertEqual(c.type, 'System.String')
self.assertEqual(GenericMethodTester.TestIntFactory1(c, 321), 777)
self.assertEqual(c.type, 'System.Int32')
self.assertEqual(GenericMethodTester.TestStringFactory0(c), '123')
self.assertEqual(c.type, 'System.String')
self.assertEqual(GenericMethodTester.TestOutParamString(c), '2')
self.assertEqual(GenericMethodTester.TestOutParamInt(c), 2)
self.assertEqual(GenericMethodTester.TestRefParamString(c, '10'), '1010')
self.assertEqual(GenericMethodTester.TestRefParamInt(c, 10), 20)
x = System.Collections.Generic.List[int]((2, 3, 4))
r = GenericMethodTester.GoWild(c, True, 'second', x)
self.assertEqual(r.Length, 2)
self.assertEqual(r[0], 1.5)
def test_bases(self):
#
# Verify that changing __bases__ works
#
class MyExceptionComparer(System.Exception, System.Collections.IComparer):
def Compare(self, x, y): return 0
class MyDerivedExceptionComparer(MyExceptionComparer): pass
e = MyExceptionComparer()
MyDerivedExceptionComparer.__bases__ = (System.Exception, System.Collections.IComparer)
MyDerivedExceptionComparer.__bases__ = (MyExceptionComparer,)
class OldType:
def OldTypeMethod(self): return "OldTypeMethod"
class NewType:
def NewTypeMethod(self): return "NewTypeMethod"
class MyOtherExceptionComparer(System.Exception, System.Collections.IComparer, OldType, NewType):
def Compare(self, x, y): return 0
MyExceptionComparer.__bases__ = MyOtherExceptionComparer.__bases__
self.assertEqual(e.OldTypeMethod(), "OldTypeMethod")
self.assertEqual(e.NewTypeMethod(), "NewTypeMethod")
self.assertTrue(isinstance(e, System.Exception))
self.assertTrue(isinstance(e, System.Collections.IComparer))
self.assertTrue(isinstance(e, MyExceptionComparer))
class MyIncompatibleExceptionComparer(System.Exception, System.Collections.IComparer, System.IDisposable):
def Compare(self, x, y): return 0
def Displose(self): pass
self.assertRaisesRegexp(TypeError, "__bases__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_*",
setattr, MyExceptionComparer, "__bases__", MyIncompatibleExceptionComparer.__bases__)
self.assertRaisesRegexp(TypeError, "__class__ assignment: 'MyExceptionComparer' object layout differs from 'IronPython.NewTypes.System.Exception#IComparer#IDisposable_*",
setattr, MyExceptionComparer(), "__class__", MyIncompatibleExceptionComparer().__class__)
def test_open_generic(self):
# Inherting from an open generic instantiation should fail with a good error message
try:
class Foo(System.Collections.Generic.IEnumerable): pass
except TypeError:
(exc_type, exc_value, exc_traceback) = sys.exc_info()
self.assertTrue(exc_value.message.__contains__("cannot inhert from open generic instantiation"))
def test_interface_slots(self):
# slots & interfaces
class foo(object):
__slots__ = ['abc']
class bar(foo, System.IComparable):
def CompareTo(self, other):
return 23
class baz(bar): pass
def test_op_Implicit_inheritance(self):
"""should inherit op_Implicit from base classes"""
from IronPythonTest import NewClass
a = NewClass()
self.assertEqual(int(a), 1002)
self.assertEqual(long(a), 1002)
self.assertEqual(NewClass.op_Implicit(a), 1002)
def test_symbol_dict(self):
"""tests to verify that Symbol dictionaries do the right thing in dynamic scenarios
same as the tests in test_class, but we run this in a module that has imported clr"""
def CheckDictionary(C):
# add a new attribute to the type...
C.newClassAttr = 'xyz'
self.assertEqual(C.newClassAttr, 'xyz')
# add non-string index into the class and instance dictionary
a = C()
try:
a.__dict__[1] = '1'
C.__dict__[2] = '2'
self.assertEqual(a.__dict__.has_key(1), True)
self.assertEqual(C.__dict__.has_key(2), True)
self.assertEqual(dir(a).__contains__(1), True)
self.assertEqual(dir(a).__contains__(2), True)
self.assertEqual(dir(C).__contains__(2), True)
self.assertEqual(repr(a.__dict__), "{1: '1'}")
self.assertEqual(repr(C.__dict__).__contains__("2: '2'"), True)
except TypeError:
# new-style classes have dict-proxy, can't do the assignment
pass
# replace a class dictionary (containing non-string keys) w/ a normal dictionary
C.newTypeAttr = 1
self.assertEqual(hasattr(C, 'newTypeAttr'), True)
class OldClass: pass
if isinstance(C, type(OldClass)):
C.__dict__ = dict(C.__dict__)
self.assertEqual(hasattr(C, 'newTypeAttr'), True)
else:
try:
C.__dict__ = {}
self.assertUnreachable()
except AttributeError:
pass
# replace an instance dictionary (containing non-string keys) w/ a new one.
a.newInstanceAttr = 1
self.assertEqual(hasattr(a, 'newInstanceAttr'), True)
a.__dict__ = dict(a.__dict__)
self.assertEqual(hasattr(a, 'newInstanceAttr'), True)
a.abc = 'xyz'
self.assertEqual(hasattr(a, 'abc'), True)
self.assertEqual(getattr(a, 'abc'), 'xyz')
class OldClass:
def __init__(self): pass
class NewClass(object):
def __init__(self): pass
CheckDictionary(OldClass)
CheckDictionary(NewClass)
def test_generic_TypeGroup(self):
# TypeGroup is used to expose "System.IComparable" and "System.IComparable`1" as "System.IComparable"
# repr
self.assertEqual(repr(System.IComparable), "<types 'IComparable', 'IComparable[T]'>")
# Test member access
self.assertEqual(System.IComparable.CompareTo(1,1), 0)
self.assertEqual(System.IComparable.CompareTo(1,2), -1)
self.assertEqual(System.IComparable[int].CompareTo(1,1), 0)
self.assertEqual(System.IComparable[int].CompareTo(1,2), -1)
self.assertTrue(dir(System.IComparable).__contains__("CompareTo"))
self.assertTrue(vars(System.IComparable).keys().__contains__("CompareTo"))
import IronPythonTest
genericTypes = IronPythonTest.NestedClass.InnerGenericClass
# converstion to Type
self.assertTrue(System.Type.IsAssignableFrom(System.IComparable, int))
self.assertRaises(TypeError, System.Type.IsAssignableFrom, object, genericTypes)
# Test illegal type instantiation
try:
System.IComparable[int, int]
except ValueError: pass
else: self.assertUnreachable()
try:
System.EventHandler(None)
except TypeError: pass
else: self.assertUnreachable()
def handler():
pass
try:
System.EventHandler(handler)("sender", None)
except TypeError: pass
else: self.assertUnreachable()
def handler(s,a):
pass
# Test constructor
self.assertEqual(System.EventHandler(handler).GetType(), System.Type.GetType("System.EventHandler"))
self.assertEqual(System.EventHandler[System.EventArgs](handler).GetType().GetGenericTypeDefinition(), System.Type.GetType("System.EventHandler`1"))
# Test inheritance
class MyComparable(System.IComparable):
def CompareTo(self, other):
return self.Equals(other)
myComparable = MyComparable()
self.assertTrue(myComparable.CompareTo(myComparable))
try:
class MyDerivedClass(genericTypes): pass
except TypeError: pass
else: self.assertUnreachable()
# Use a TypeGroup to index a TypeGroup
t = genericTypes[System.IComparable]
t = genericTypes[System.IComparable, int]
try:
System.IComparable[genericTypes]
except TypeError: pass
else: self.assertUnreachable()
def test_generic_only_TypeGroup(self):
from IronPythonTest import BinderTest
try:
BinderTest.GenericOnlyConflict()
except System.TypeLoadException, e:
self.assertTrue(str(e).find('requires a non-generic type') != -1)
self.assertTrue(str(e).find('GenericOnlyConflict') != -1)
def test_autodoc(self):
import os
from System.Threading import Thread, ThreadStart
self.assertTrue(Thread.__doc__.find('Thread(start: ThreadStart)') != -1)
self.assertTrue(Thread.__new__.__doc__.find('__new__(cls: type, start: ThreadStart)') != -1)
# self.assertEqual(Thread.__new__.Overloads[ThreadStart].__doc__, '__new__(cls : type, start: ThreadStart)' + os.linesep)
def test_type_descs(self):
from IronPythonTest import TypeDescTests
if is_netcoreapp:
clr.AddReference("System.ComponentModel.Primitives")
test = TypeDescTests()
# new style tests
class bar(int): pass
b = bar(2)
class foo(object): pass
c = foo()
#test.TestProperties(...)
res = test.GetClassName(test)
self.assertTrue(res == 'IronPythonTest.TypeDescTests')
#res = test.GetClassName(a)
#self.assertTrue(res == 'list')
res = test.GetClassName(c)
self.assertTrue(res == 'foo')
res = test.GetClassName(b)
self.assertTrue(res == 'bar')
res = test.GetConverter(b)
x = res.ConvertTo(None, None, b, int)
self.assertTrue(x == 2)
self.assertTrue(type(x) == int)
x = test.GetDefaultEvent(b)
self.assertTrue(x == None)
x = test.GetDefaultProperty(b)
self.assertTrue(x == None)
x = test.GetEditor(b, object)
self.assertTrue(x == None)
x = test.GetEvents(b)
self.assertTrue(x.Count == 0)
x = test.GetEvents(b, None)
self.assertTrue(x.Count == 0)
x = test.GetProperties(b)
self.assertTrue(x.Count > 0)
self.assertTrue(test.TestProperties(b, [], []))
bar.foobar = property(lambda x: 42)
self.assertTrue(test.TestProperties(b, ['foobar'], []))
bar.baz = property(lambda x:42)
self.assertTrue(test.TestProperties(b, ['foobar', 'baz'], []))
delattr(bar, 'baz')
self.assertTrue(test.TestProperties(b, ['foobar'], ['baz']))
# Check that adding a non-string entry in the dictionary does not cause any grief.
b.__dict__[1] = 1
self.assertTrue(test.TestProperties(b, ['foobar'], ['baz']))
#self.assertTrue(test.TestProperties(test, ['GetConverter', 'GetEditor', 'GetEvents', 'GetHashCode'] , []))
# old style tests
class foo: pass
a = foo()
self.assertTrue(test.TestProperties(a, [], []))
res = test.GetClassName(a)
self.assertTrue(res == 'foo')
x = test.CallCanConvertToForInt(a)
self.assertTrue(x == False)
x = test.GetDefaultEvent(a)
self.assertTrue(x == None)
x = test.GetDefaultProperty(a)
self.assertTrue(x == None)
x = test.GetEditor(a, object)
self.assertTrue(x == None)
x = test.GetEvents(a)
self.assertTrue(x.Count == 0)
x = test.GetEvents(a, None)
self.assertTrue(x.Count == 0)
x = test.GetProperties(a, (System.ComponentModel.BrowsableAttribute(True), ))
self.assertTrue(x.Count == 0)
foo.bar = property(lambda x:'hello')
self.assertTrue(test.TestProperties(a, ['bar'], []))
delattr(foo, 'bar')
self.assertTrue(test.TestProperties(a, [], ['bar']))
a = a.__class__
self.assertTrue(test.TestProperties(a, [], []))
foo.bar = property(lambda x:'hello')
self.assertTrue(test.TestProperties(a, [], []))
delattr(a, 'bar')
self.assertTrue(test.TestProperties(a, [], ['bar']))
x = test.GetClassName(a)
self.assertEqual(x, 'classobj')
x = test.CallCanConvertToForInt(a)
self.assertEqual(x, False)
x = test.GetDefaultEvent(a)
self.assertEqual(x, None)
x = test.GetDefaultProperty(a)
self.assertEqual(x, None)
x = test.GetEditor(a, object)
self.assertEqual(x, None)
x = test.GetEvents(a)
self.assertEqual(x.Count, 0)
x = test.GetEvents(a, None)
self.assertEqual(x.Count, 0)
x = test.GetProperties(a)
self.assertTrue(x.Count > 0)
# Ensure GetProperties checks the attribute dictionary
a = foo()
a.abc = 42
x = test.GetProperties(a)
for prop in x:
if prop.Name == 'abc':
break
else:
self.assertUnreachable()
def test_char(self):
for x in range(256):
c = System.Char.Parse(chr(x))
self.assertEqual(c, chr(x))
self.assertEqual(chr(x), c)
if c == chr(x): pass
else: self.assertTrue(False)
if not c == chr(x): self.assertTrue(False)
if chr(x) == c: pass
else: self.assertTrue(False)
if not chr(x) == c: self.assertTrue(False)
def test_repr(self):
from IronPythonTest import UnaryClass, BaseClass, BaseClassStaticConstructor
if is_netcoreapp:
clr.AddReference('System.Drawing.Primitives')
else:
clr.AddReference('System.Drawing')
from System.Drawing import Point
self.assertEqual(repr(Point(1,2)).startswith('<System.Drawing.Point object'), True)
self.assertEqual(repr(Point(1,2)).endswith('[{X=1,Y=2}]>'),True)
# these 3 classes define the same repr w/ different \r, \r\n, \n versions
a = UnaryClass(3)
b = BaseClass()
c = BaseClassStaticConstructor()
ra = repr(a)
rb = repr(b)
rc = repr(c)
sa = ra.find('HelloWorld')
sb = rb.find('HelloWorld')
sc = rc.find('HelloWorld')
self.assertEqual(ra[sa:sa+13], rb[sb:sb+13])
self.assertEqual(rb[sb:sb+13], rc[sc:sc+13])
self.assertEqual(ra[sa:sa+13], 'HelloWorld...') # \r\n should be removed, replaced with ...
def test_explicit_interfaces(self):
from IronPythonTest import OverrideTestDerivedClass, IOverrideTestInterface
otdc = OverrideTestDerivedClass()
self.assertEqual(otdc.MethodOverridden(), "OverrideTestDerivedClass.MethodOverridden() invoked")
self.assertEqual(IOverrideTestInterface.MethodOverridden(otdc), 'IOverrideTestInterface.MethodOverridden() invoked')
self.assertEqual(IOverrideTestInterface.x.GetValue(otdc), 'IOverrideTestInterface.x invoked')
self.assertEqual(IOverrideTestInterface.y.GetValue(otdc), 'IOverrideTestInterface.y invoked')
IOverrideTestInterface.x.SetValue(otdc, 'abc')
self.assertEqual(OverrideTestDerivedClass.Value, 'abcx')
IOverrideTestInterface.y.SetValue(otdc, 'abc')
self.assertEqual(OverrideTestDerivedClass.Value, 'abcy')
self.assertEqual(otdc.y, 'OverrideTestDerivedClass.y invoked')
self.assertEqual(IOverrideTestInterface.Method(otdc), "IOverrideTestInterface.method() invoked")
self.assertEqual(hasattr(otdc, 'IronPythonTest_IOverrideTestInterface_x'), False)
# we can also do this the ugly way:
self.assertEqual(IOverrideTestInterface.x.__get__(otdc, OverrideTestDerivedClass), 'IOverrideTestInterface.x invoked')
self.assertEqual(IOverrideTestInterface.y.__get__(otdc, OverrideTestDerivedClass), 'IOverrideTestInterface.y invoked')
self.assertEqual(IOverrideTestInterface.__getitem__(otdc, 2), 'abc')
self.assertEqual(IOverrideTestInterface.__getitem__(otdc, 2), 'abc')
self.assertRaises(NotImplementedError, IOverrideTestInterface.__setitem__, otdc, 2, 3)
try:
IOverrideTestInterface.__setitem__(otdc, 2, 3)
except NotImplementedError: pass
else: self.assertUnreachable()
def test_field_helpers(self):
from IronPythonTest import OverrideTestDerivedClass
otdc = OverrideTestDerivedClass()
OverrideTestDerivedClass.z.SetValue(otdc, 'abc')
self.assertEqual(otdc.z, 'abc')
self.assertEqual(OverrideTestDerivedClass.z.GetValue(otdc), 'abc')
def test_field_descriptor(self):
from IronPythonTest import MySize
self.assertEqual(MySize.width.__get__(MySize()), 0)
self.assertEqual(MySize.width.__get__(MySize(), MySize), 0)
def test_field_const_write(self):
from IronPythonTest import MySize, ClassWithLiteral
try:
MySize.MaxSize = 23
except AttributeError, e:
self.assertTrue(str(e).find('MaxSize') != -1)
self.assertTrue(str(e).find('MySize') != -1)
try:
ClassWithLiteral.Literal = 23
except AttributeError, e:
self.assertTrue(str(e).find('Literal') != -1)
self.assertTrue(str(e).find('ClassWithLiteral') != -1)
try:
ClassWithLiteral.__dict__['Literal'].__set__(None, 23)
except AttributeError, e:
self.assertTrue(str(e).find('int') != -1)
try:
ClassWithLiteral.__dict__['Literal'].__set__(ClassWithLiteral(), 23)
except AttributeError, e:
self.assertTrue(str(e).find('int') != -1)
try:
MySize().MaxSize = 23
except AttributeError, e:
self.assertTrue(str(e).find('MaxSize') != -1)
self.assertTrue(str(e).find('MySize') != -1)
try:
ClassWithLiteral().Literal = 23
except AttributeError, e:
self.assertTrue(str(e).find('Literal') != -1)
self.assertTrue(str(e).find('ClassWithLiteral') != -1)
def test_field_const_access(self):
from IronPythonTest import MySize, ClassWithLiteral
self.assertEqual(MySize().MaxSize, System.Int32.MaxValue)
self.assertEqual(MySize.MaxSize, System.Int32.MaxValue)
self.assertEqual(ClassWithLiteral.Literal, 5)
self.assertEqual(ClassWithLiteral().Literal, 5)
def test_array(self):
arr = System.Array[int]([0])
self.assertEqual(repr(arr), str(arr))
self.assertEqual(repr(System.Array[int]([0, 1])), 'Array[int]((0, 1))')
def test_strange_inheritance(self):
"""verify that overriding strange methods (such as those that take caller context) doesn't
flow caller context through"""
from IronPythonTest import StrangeOverrides
s = self
class m(StrangeOverrides):
def SomeMethodWithContext(self, arg):
s.assertEqual(arg, 'abc')
def ParamsMethodWithContext(self, *arg):
s.assertEqual(arg, ('abc', 'def'))
def ParamsIntMethodWithContext(self, *arg):
s.assertEqual(arg, (2,3))
a = m()
a.CallWithContext('abc')
a.CallParamsWithContext('abc', 'def')
a.CallIntParamsWithContext(2, 3)
def test_nondefault_indexers(self):
if not self.has_vbc(): return
import os
import _random
r = _random.Random()
r.seed()
self.write_to_file('vbproptest1.vb', """
Public Class VbPropertyTest
private Indexes(23) as Integer
private IndexesTwo(23,23) as Integer
private shared SharedIndexes(5,5) as Integer
Public Property IndexOne(ByVal index as Integer) As Integer
Get
return Indexes(index)
End Get
Set
Indexes(index) = Value
End Set
End Property
Public Property IndexTwo(ByVal index as Integer, ByVal index2 as Integer) As Integer
Get
return IndexesTwo(index, index2)
End Get
Set
IndexesTwo(index, index2) = Value
End Set
End Property
Public Shared Property SharedIndex(ByVal index as Integer, ByVal index2 as Integer) As Integer
Get
return SharedIndexes(index, index2)
End Get
Set
SharedIndexes(index, index2) = Value
End Set
End Property
End Class""")
try:
name = os.path.join(self.temporary_dir, 'vbproptest%f.dll' % (r.random()))
x = self.run_vbc('/target:library vbproptest1.vb "/out:%s"' % name)
self.assertEqual(x, 0)
clr.AddReferenceToFileAndPath(name)
import VbPropertyTest
x = VbPropertyTest()
self.assertEqual(x.IndexOne[0], 0)
x.IndexOne[1] = 23
self.assertEqual(x.IndexOne[1], 23)
self.assertEqual(x.IndexTwo[0,0], 0)
x.IndexTwo[1,2] = 5
self.assertEqual(x.IndexTwo[1,2], 5)
self.assertEqual(VbPropertyTest.SharedIndex[0,0], 0)
VbPropertyTest.SharedIndex[3,4] = 42
self.assertEqual(VbPropertyTest.SharedIndex[3,4], 42)
finally:
os.unlink('vbproptest1.vb')
def test_nondefault_indexers_overloaded(self):
if not self.has_vbc(): return
import os
import _random
r = _random.Random()
r.seed()
self.write_to_file('vbproptest1.vb', """
Public Class VbPropertyTest
private Indexes(23) as Integer
private IndexesTwo(23,23) as Integer
private shared SharedIndexes(5,5) as Integer
Public Property IndexOne(ByVal index as Integer) As Integer
Get
return Indexes(index)
End Get
Set
Indexes(index) = Value
End Set
End Property
Public Property IndexTwo(ByVal index as Integer, ByVal index2 as Integer) As Integer
Get
return IndexesTwo(index, index2)
End Get
Set
IndexesTwo(index, index2) = Value
End Set
End Property
Public Shared Property SharedIndex(ByVal index as Integer, ByVal index2 as Integer) As Integer
Get
return SharedIndexes(index, index2)
End Get
Set
SharedIndexes(index, index2) = Value
End Set
End Property
End Class
Public Class VbPropertyTest2
Public ReadOnly Property Prop() As string
get
return "test"
end get
end property
Public ReadOnly Property Prop(ByVal name As String) As string
get
return name
end get
end property
End Class""")
try:
name = os.path.join(self.temporary_dir, 'vbproptest%f.dll' % (r.random()))
self.assertEqual(self.run_vbc('/target:library vbproptest1.vb /out:"%s"' % name), 0)
clr.AddReferenceToFileAndPath(name)
import VbPropertyTest, VbPropertyTest2
x = VbPropertyTest()
self.assertEqual(x.IndexOne[0], 0)
x.IndexOne[1] = 23
self.assertEqual(x.IndexOne[1], 23)
self.assertEqual(x.IndexTwo[0,0], 0)
x.IndexTwo[1,2] = 5
self.assertEqual(x.IndexTwo[1,2], 5)
self.assertEqual(VbPropertyTest.SharedIndex[0,0], 0)
VbPropertyTest.SharedIndex[3,4] = 42
self.assertEqual(VbPropertyTest.SharedIndex[3,4], 42)
self.assertEqual(VbPropertyTest2().Prop, 'test')
self.assertEqual(VbPropertyTest2().get_Prop('foo'), 'foo')
finally:
os.unlink('vbproptest1.vb')
def test_interface_abstract_events(self):
from IronPythonTest import IEventInterface, AbstractEvent, SimpleDelegate, UseEvent
s = self
# inherit from an interface or abstract event, and define the event
for baseType in [IEventInterface, AbstractEvent]:
class foo(baseType):
def __init__(self):
self._events = []
def add_MyEvent(self, value):
s.assertIsInstance(value, SimpleDelegate)
self._events.append(value)
def remove_MyEvent(self, value):
s.assertIsInstance(value, SimpleDelegate)
self._events.remove(value)
def MyRaise(self):
for x in self._events: x()
global called
called = False
def bar(*args):
global called
called = True
a = foo()
a.MyEvent += bar
a.MyRaise()
self.assertEqual(called, True)
a.MyEvent -= bar
called = False
a.MyRaise()
self.assertEqual(called, False)
# hook the event from the CLI side, and make sure that raising
# it causes the CLI side to see the event being fired.
UseEvent.Hook(a)
a.MyRaise()
self.assertEqual(UseEvent.Called, True)
UseEvent.Called = False
UseEvent.Unhook(a)
a.MyRaise()
self.assertEqual(UseEvent.Called, False)
@unittest.skipIf(is_debug, "assertion failure")
def test_dynamic_assembly_ref(self):
# verify we can add a reference to a dynamic assembly, and
# then create an instance of that type
class foo(object): pass
clr.AddReference(foo().GetType().Assembly)
import IronPython.NewTypes.System
for x in dir(IronPython.NewTypes.System):
if x.startswith('Object_'):
t = getattr(IronPython.NewTypes.System, x)
x = t(foo)
break
else:
# we should have found our type
self.fail('No type found!')
def test_nonzero(self):
from System import Single, Byte, SByte, Int16, UInt16, Int64, UInt64
for t in [Single, Byte, SByte, Int16, UInt16, Int64, UInt64]:
self.assertTrue(hasattr(t, '__nonzero__'))
if t(0): self.assertUnreachable()
if not t(1): self.assertUnreachable()
def test_virtual_event(self):
from IronPythonTest import VirtualEvent, OverrideVirtualEvent, SimpleDelegate, UseEvent
s = self
# inherit from a class w/ a virtual event and a
# virtual event that's been overridden. Check both
# overriding it and not overriding it.
for baseType in [VirtualEvent, OverrideVirtualEvent]:
for override in [True, False]:
class foo(baseType):
def __init__(self):
self._events = []
if override:
def add_MyEvent(self, value):
s.assertIsInstance(value, SimpleDelegate)
self._events.append(value)
def remove_MyEvent(self, value):
s.assertIsInstance(value, SimpleDelegate)
self._events.remove(value)
def add_MyCustomEvent(self, value): pass
def remove_MyCustomEvent(self, value): pass
def MyRaise(self):
for x in self._events: x()
else:
def MyRaise(self):
self.FireEvent()
# normal event
global called
called = False
def bar(*args):
global called
called = True
a = foo()
a.MyEvent += bar
a.MyRaise()
self.assertTrue(called)
a.MyEvent -= bar
called = False
a.MyRaise()
self.assertFalse(called)
# custom event
a.LastCall = None
a = foo()
a.MyCustomEvent += bar
if override: self.assertEqual(a.LastCall, None)
else: self.assertTrue(a.LastCall.endswith('Add'))
a.Lastcall = None
a.MyCustomEvent -= bar
if override: self.assertEqual(a.LastCall, None)
else: self.assertTrue(a.LastCall.endswith('Remove'))
# hook the event from the CLI side, and make sure that raising
# it causes the CLI side to see the event being fired.
UseEvent.Hook(a)
a.MyRaise()
self.assertTrue(UseEvent.Called)
UseEvent.Called = False
UseEvent.Unhook(a)
a.MyRaise()
self.assertFalse(UseEvent.Called)
def test_property_get_set(self):
if is_netcoreapp:
clr.AddReference("System.Drawing.Primitives")
else:
clr.AddReference("System.Drawing")
from System.Drawing import Size
temp = Size()
self.assertEqual(temp.Width, 0)
temp.Width = 5
self.assertEqual(temp.Width, 5)
for i in xrange(5):
temp.Width = i
self.assertEqual(temp.Width, i)
def test_write_only_property_set(self):
from IronPythonTest import WriteOnly
obj = WriteOnly()
self.assertRaises(AttributeError, getattr, obj, 'Writer')
def test_isinstance_interface(self):
self.assertTrue(isinstance('abc', System.Collections.IEnumerable))
def test_constructor_function(self):
'''
Test to hit IronPython.Runtime.Operations.ConstructionFunctionOps.
'''
self.assertEqual(System.DateTime.__new__.__name__, '__new__')
self.assertTrue(System.DateTime.__new__.__doc__.find('__new__(cls: type, year: int, month: int, day: int)') != -1)
self.assertTrue(System.AssemblyLoadEventArgs.__new__.__doc__.find('__new__(cls: type, loadedAssembly: Assembly)') != -1)
def test_class_property(self):
"""__class__ should work on standard .NET types and should return the type object associated with that class"""
self.assertEqual(System.Environment.Version.__class__, System.Version)
def test_null_str(self):
"""if a .NET type has a bad ToString() implementation that returns null always return String.Empty in Python"""
from IronPythonTest import RudeObjectOverride
self.assertEqual(str(RudeObjectOverride()), '')
self.assertEqual(RudeObjectOverride().__str__(), '')
self.assertEqual(RudeObjectOverride().ToString(), None)
self.assertTrue(repr(RudeObjectOverride()).startswith('<IronPythonTest.RudeObjectOverride object at '))
def test_keyword_construction_readonly(self):
from IronPythonTest import ClassWithLiteral
self.assertRaises(AttributeError, System.Version, 1, 0, Build=100)
self.assertRaises(AttributeError, ClassWithLiteral, Literal=3)
def test_kw_construction_types(self):
if is_netcoreapp:
clr.AddReference("System.IO.FileSystem.Watcher")
for val in [True, False]:
x = System.IO.FileSystemWatcher('.', EnableRaisingEvents = val)
self.assertEqual(x.EnableRaisingEvents, val)
def test_as_bool(self):
"""verify using expressions in if statements works correctly. This generates an
site whose return type is bool so it's important this works for various ways we can
generate the body of the site, and use the site both w/ the initial & generated targets"""
from IronPythonTest import NestedClass
if is_netcoreapp:
clr.AddReference("System.Runtime")
clr.AddReference("System.Threading.Thread")
else:
clr.AddReference('System') # ensure test passes in ipy
# instance property
x = System.Uri('http://foo')
for i in xrange(2):
if x.AbsolutePath: pass
else: self.fail('instance property')
# instance property on type
for i in xrange(2):
if System.Uri.AbsolutePath: pass
else: self.fail('instance property on type')
# static property
for i in xrange(2):
if System.Threading.Thread.CurrentThread: pass
else: self.fail('static property')
# static field
for i in xrange(2):
if System.String.Empty: self.fail('static field')
# instance field
x = NestedClass()
for i in xrange(2):
if x.Field: self.fail('instance field')
# instance field on type
for i in xrange(2):
if NestedClass.Field: pass
else: self.fail('instance field on type')