-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathtest_regressions.py
More file actions
1772 lines (1432 loc) · 59.1 KB
/
Copy pathtest_regressions.py
File metadata and controls
1772 lines (1432 loc) · 59.1 KB
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.
"""
This module consists of regression tests for CodePlex and Dev10 IronPython bugs
added primarily by IP developers that need to be folded into other test modules
and packages.
Any test case added to this file should be of the form:
def test_cp1234(): ...
where 'cp' refers to the fact that the test case is for a regression on CodePlex
(use 'dev10' for Dev10 bugs). '1234' should refer to the CodePlex or Dev10
Work Item number.
"""
import os
import sys
import unittest
from iptest import IronPythonTestCase, is_32, is_cli, is_mono, is_netcoreapp, is_netcoreapp21, is_windows, is_posix, run_test, skipUnlessIronPython, stdout_trapper
is_long32bit = is_32 or is_windows
class RegressionTest(IronPythonTestCase):
@unittest.skipIf(is_netcoreapp, 'no System.AppDomain.DoCallBack')
@skipUnlessIronPython()
def test_cp18345(self):
import System
import time
class x(object):
def f(self):
global z
z = 100
System.AppDomain.CurrentDomain.DoCallBack(x().f)
time.sleep(10)
self.assertEqual(z, 100)
def test_cp17420(self):
#Create a temporary Python file
test_file_name = os.path.join(self.temporary_dir, "cp17420_%d.py" % os.getpid())
test_log_name = os.path.join(self.temporary_dir, "cp17420_%d.log" % os.getpid())
try:
os.remove(test_log_name)
except:
pass
test_file = '''
output = []
for i in range(0, 100):
output.append(str(i) + "\\n")
with open(r"%s", "w") as f:
f.writelines(output)''' % (test_log_name)
self.write_to_file(test_file_name, test_file)
#Execute the file from a separate process
self.assertEqual(self.launch(sys.executable, test_file_name), 0)
#Verify contents of file
with open(test_log_name, "r") as temp_file:
lines = temp_file.readlines()
self.assertEqual(len(lines), 100)
os.unlink(test_file_name)
os.unlink(test_log_name)
def test_cp17274(self):
class KOld:
def __init__(self):
self.__doc__ = "KOld doc"
class KNew(object):
def __init__(self):
self.__doc__ = "KNew doc"
class KNewDerived(KNew, KOld):
def method(self):
self.__doc__ = "KNewDerived doc"
class KNewDerivedSpecial(int):
def __init__(self):
self.__doc__ = "KNewDerivedSpecial doc"
self.assertEqual(KOld().__doc__, "KOld doc")
self.assertEqual(KNew().__doc__, "KNew doc")
k = KNewDerived()
self.assertEqual(k.__doc__, "KNew doc")
k.method()
self.assertEqual(k.__doc__, "KNewDerived doc")
self.assertEqual(KNewDerivedSpecial().__doc__, "KNewDerivedSpecial doc")
@skipUnlessIronPython()
def test_cp16831(self):
import clr
clr.AddReference("IronPythonTest")
import IronPythonTest
temp = IronPythonTest.NullableTest()
temp.BProperty = True
for i in range(2):
if not temp.BProperty:
self.fail("Nullable Boolean was set to True")
for i in range(2):
if not temp.BProperty==True:
self.fail("Nullable Boolean was set to True")
temp.BProperty = False
for i in range(2):
if temp.BProperty:
self.fail("Nullable Boolean was set to False")
for i in range(2):
if not temp.BProperty==False:
self.fail("Nullable Boolean was set to False")
temp.BProperty = None
for i in range(2):
if temp.BProperty:
self.fail("Nullable Boolean was set to None")
for i in range(2):
if not temp.BProperty==None:
self.fail("Nullable Boolean was set to None")
def test_cp_27434(self):
tests = {
'\d' : 0,
'(\d)' : 1,
'(\d) (\w)' : 2,
'(?:[\d\.]+) (\w)' : 1,
'(hello(\w)*world) [\d\.]?' : 2,
'(hello(\w)*world) ([\d\.]?)' : 3,
'(hello(\w)*world) (?:[\d\.]?)' : 2,
}
import re
for data, groups in tests.items():
regex = re.compile(data)
message = "'%s' should have %d groups, not %d" % (data, groups, regex.groups)
self.assertTrue(regex.groups == groups, message)
@skipUnlessIronPython()
def test_protected_ctor_inheritance_cp20021(self):
self.load_iron_python_test()
from IronPythonTest import (
ProtectedCtorTest, ProtectedCtorTest1, ProtectedCtorTest2,
ProtectedCtorTest3, ProtectedCtorTest4,
ProtectedInternalCtorTest, ProtectedInternalCtorTest1,
ProtectedInternalCtorTest2, ProtectedInternalCtorTest3,
ProtectedInternalCtorTest4
)
# no number:
protected = [ProtectedCtorTest, ProtectedCtorTest1, ProtectedCtorTest2,
ProtectedCtorTest3, ProtectedCtorTest4, ]
protected_internal = [ProtectedInternalCtorTest, ProtectedInternalCtorTest1,
ProtectedInternalCtorTest2, ProtectedInternalCtorTest3,
ProtectedInternalCtorTest4, ]
for zero, one, two, three, four in (protected, protected_internal):
# calling protected ctors shouldn't work
self.assertRaises(TypeError, zero)
self.assertRaises(TypeError, zero.__new__)
self.assertRaises(TypeError, one, object())
self.assertRaises(TypeError, one.__new__, object())
self.assertRaises(TypeError, two, object())
self.assertRaises(TypeError, two.__new__, two, object())
self.assertRaises(TypeError, two, object(), object())
self.assertRaises(TypeError, two.__new__, two, object(), object())
self.assertRaises(TypeError, three)
self.assertRaises(TypeError, three.__new__, three)
three(object())
three.__new__(ProtectedCtorTest3, object())
self.assertRaises(TypeError, four, object())
self.assertRaises(TypeError, four.__new__, four, object())
four()
four.__new__(four)
class myzero(zero):
def __new__(cls): return zero.__new__(cls)
class myone(one):
def __new__(cls): return one.__new__(cls, object())
class mytwo1(two):
def __new__(cls): return two.__new__(cls, object())
class mytwo2(two):
def __new__(cls): return two.__new__(cls, object(), object())
class mythree1(three):
def __new__(cls): return three.__new__(cls)
class mythree2(three):
def __new__(cls): return three.__new__(cls, object())
class myfour1(four):
def __new__(cls): return four.__new__(cls)
class myfour2(four):
def __new__(cls): return four.__new__(cls, object())
for cls in [myzero, myone, mytwo1, mytwo2, mythree1, mythree2, myfour1, myfour2]:
cls()
def test_re_paren_in_char_list_cp20191(self):
import re
format_re = re.compile(r'(?P<order1>[<>|=]?)(?P<repeats> *[(]?[ ,0-9]*[)]? *)(?P<order2>[<>|=]?)(?P<dtype>[A-Za-z0-9.]*)')
self.assertEqual(format_re.match('a3').groups(), ('', '', '', 'a3'))
def test_struct_uint_bad_value_cp20039(self):
'''Also https://github.com/IronLanguages/ironpython3/issues/1381'''
class x(object):
def __init__(self, value):
self.value = value
def __and__(self, other):
global andCalled
andCalled = True
return self.value
def __int__(self):
raise Exception('foo')
import _struct
global andCalled
andCalled = False
for code in ['L', 'I']:
if code != 'L' or is_long32bit:
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, 0x100000000)
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, -1)
for code in ['l', 'i', 'h', 'H', 'B', 'b']:
if code != 'l' or is_long32bit:
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, 0x80000000)
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, -0x80000001)
for code in ['L', 'Q']:
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, 0x10000000000000000)
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, -1)
for code in ['l', 'q']:
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, 0x8000000000000000)
self.assertRaisesRegex(_struct.error, "argument out of range", _struct.Struct(code).pack, -0x8000000000000001)
self.assertRaisesRegex(_struct.error, r"ushort format requires 0 <= number .*", _struct.Struct('H').pack, 0x10000)
self.assertRaisesRegex(_struct.error, r"ushort format requires 0 <= number .*", _struct.Struct('H').pack, -1)
self.assertRaisesRegex(_struct.error, r"short format requires .* <= number .*", _struct.Struct('h').pack, 0x8000)
self.assertRaisesRegex(_struct.error, r"short format requires .* <= number .*", _struct.Struct('h').pack, -0x8001)
self.assertRaisesRegex(_struct.error, r"ubyte format requires 0 <= number .*", _struct.Struct('B').pack, 0x100)
self.assertRaisesRegex(_struct.error, r"ubyte format requires 0 <= number .*", _struct.Struct('B').pack, -1)
self.assertRaisesRegex(_struct.error, r"byte format requires .* <= number .*", _struct.Struct('b').pack, 0x80)
self.assertRaisesRegex(_struct.error, r"byte format requires .* <= number .*", _struct.Struct('b').pack, -0x81)
for code in ['b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'n', 'N', 'P']:
self.assertRaisesRegex(_struct.error, "required argument is not an integer", _struct.Struct(code).pack, x(0))
self.assertRaisesRegex(_struct.error, "required argument is not an integer", _struct.Struct(code).pack, x(-1))
# __and__ was called in Python2.6 check that this is no longer True
self.assertTrue(not andCalled)
def test_reraise_backtrace_cp20051(self):
'''
TODO: this test needs far better verification.
'''
import sys
def foo():
some_exception_raising_code()
try:
try:
foo()
except:
excinfo1 = sys.exc_info()[2]
exc1_list = []
while excinfo1:
exc1_list.append((excinfo1.tb_frame.f_code.co_filename,
excinfo1.tb_frame.f_code.co_name,
excinfo1.tb_frame.f_lineno))
excinfo1 = excinfo1.tb_next
raise
except Exception as e:
excinfo2 = sys.exc_info()[2]
exc2_list = []
while excinfo2:
exc2_list.append((excinfo2.tb_frame.f_code.co_filename,
excinfo2.tb_frame.f_code.co_name,
excinfo2.tb_frame.f_lineno))
excinfo2 = excinfo2.tb_next
# CPython reports 2 frames, IroPython includes the re-raise and reports 3
self.assertTrue(len(exc2_list) >= 2)
@unittest.skipIf(is_posix, 'No _winreg on posix')
def test_winreg_error_cp17050(self):
import winreg
self.assertEqual(winreg.error, WindowsError)
@skipUnlessIronPython()
def test_indexing_value_types_cp20370(self):
import clr
if is_netcoreapp:
clr.AddReference("System.Drawing.Primitives")
else:
clr.AddReference("System.Drawing")
from System.Drawing import Point
p = Point(1,2)
l = [None]
l[0] = p
self.assertEqual(id(l[0]), id(p))
self.assertEqual(id(l[0]), id(p))
x = {}
x[p] = p
self.assertEqual(id(list(x.keys())[0]), id(p))
self.assertEqual(id(list(x.values())[0]), id(p))
self.load_iron_python_test()
from IronPythonTest import StructIndexable
a = StructIndexable()
a[0] = 1
self.assertEqual(a[0], 1)
def test_enumerate_index_increment_cp20016(self):
def f(item):
return item[0] in [0, 1]
self.assertEqual(list(filter(f, enumerate(['a', 'b']))), [(0, 'a'), (1, 'b')])
self.assertEqual(list(filter(lambda x: x[0] in [0, 1], enumerate([10.0, 27.0]))),
[(0, 10.0), (1, 27.0)])
def test_invalid_args_cp20616(self):
test_cases = {
lambda: ''.join() : "join() takes exactly one argument (0 given)",
lambda: ''.join("", "") : "join() takes exactly one argument (2 given)",
lambda: ''.join("", "", "") : "join() takes exactly one argument (3 given)",
lambda: ''.replace("", "", "", "") : "replace() takes at most 3 arguments (4 given)",
}
if is_cli:
import clr
import System
test_cases.update({
lambda: System.String("").PadRight() : "PadRight() takes at least 1 argument (0 given)",
lambda: System.String("").PadRight(1, "a", "") : "PadRight() takes at most 2 arguments (3 given)",
})
#CodePlex 21063
if is_cli:
for key in test_cases:
test_cases[key] = test_cases[key].replace("one", "1")
for key in test_cases:
temp_lambda = key
expected_err_msg = test_cases[key]
self.assertRaisesMessage(TypeError, expected_err_msg, temp_lambda)
def test_cp19678(self):
global iterCalled, getItemCalled
iterCalled = False
getItemCalled = False
class o(object):
def __iter__(self):
global iterCalled
iterCalled = True
return iter([1, 2, 3])
def __getitem__(self, index):
global getItemCalled
getItemCalled = True
return [1, 2, 3][index]
def __len__(self):
return 3
self.assertEqual(1 in o(), True)
self.assertEqual(iterCalled, True)
self.assertEqual(getItemCalled, False)
def test_exception_multiple_inheritance_cp20208(self):
class FTPError(Exception): pass
class FTPOSError(FTPError, OSError): pass
self.assertEqual(FTPOSError, type(FTPOSError()))
def test_conversions_cp19675(self):
class MyFloatType(float):
def __int__(self):
return 42
def __str__(self):
return 'hello'
MyFloat = MyFloatType()
self.assertEqual(int(MyFloat), 42)
self.assertEqual(str(MyFloat), 'hello')
class MyFloatType(float): pass
MyFloat = MyFloatType()
self.assertEqual(int(MyFloat), 0)
self.assertEqual(str(MyFloat), '0.0')
class MyFloatType(float):
def __new__(cls):
return float.__new__(cls, 3.14)
MyFloat = MyFloatType()
self.assertEqual(MyFloat, 3.14)
self.assertEqual(int(MyFloat), 3)
@skipUnlessIronPython()
def test_type_delegate_conversion(self):
import clr
from System import Func
class x(object): pass
ctor = Func[object](x)
self.assertEqual(type(ctor()), x)
def test_module_alias_cp19656(self):
old_path = [x for x in sys.path]
sys.path.append(self.test_dir)
stuff_name = "stuff_%d" % os.getpid()
check_name = "check_%d" % os.getpid()
stuff_mod = os.path.join(self.test_dir, stuff_name + ".py")
check_mod = os.path.join(self.test_dir, check_name + ".py")
try:
self.write_to_file(stuff_mod, "Keys = 3")
self.write_to_file(check_mod, "def check(module):\n return module.Keys")
stuff = __import__(stuff_name)
check = __import__(check_name).check
self.assertEqual(check(stuff), 3)
finally:
os.unlink(stuff_mod)
os.unlink(check_mod)
sys.path = old_path
def test_cp24691(self):
pwd = os.getcwd()
self.assertEqual(os.path.abspath("bad:"),
os.path.join(os.getcwd(), "bad:"))
def test_cp24690(self):
import errno
self.assertEqual(errno.errorcode[2],
"ENOENT")
@unittest.skipIf(is_netcoreapp, 'https://github.com/IronLanguages/ironpython2/issues/349')
@unittest.skipIf(is_posix, 'Test does not work on Mono')
def test_cp24692(self):
import errno, os, stat
dir_name = "cp24692_testdir"
try:
os.mkdir(dir_name)
os.chmod(dir_name, stat.S_IREAD)
try:
os.rmdir(dir_name)
except WindowsError as e:
self.assertEqual(e.errno, errno.EACCES)
else:
self.fail()
finally:
os.chmod(dir_name, stat.S_IWRITE)
os.rmdir(dir_name)
@skipUnlessIronPython()
def test_cp22735(self):
import System
from System import Func
def test_xxsubtype_bench(self):
import xxsubtype
if sys.version_info >= (3,6) or sys.implementation.name == "ironpython":
self.assertEqual(type(xxsubtype.bench(xxsubtype, "bench")), float)
else:
with self.assertRaises(TypeError):
xxsubtype.bench(xxsubtype, "bench")
def test_str_ljust_cp21483(self):
self.assertEqual('abc'.ljust(-2147483648), 'abc')
self.assertEqual('abc'.ljust(-2147483647), 'abc')
if is_cli:
self.assertRaises(OverflowError, #"long int too large to convert to int",
'abc'.ljust, -2147483649)
else:
self.assertEqual('abc'.ljust(-2147483649), 'abc')
@unittest.skipIf(is_mono, "https://github.com/mono/mono/issues/17192")
@skipUnlessIronPython()
def test_help_dir_cp11833(self):
import System
self.assertTrue(dir(System).count('Action') == 1)
from io import StringIO
oldstdout, sys.stdout = sys.stdout, StringIO()
try:
help(System.Action)
finally:
sys.stdout = oldstdout
self.assertTrue(dir(System).count('Action') == 1)
def test_not___len___cp_24129(self):
class C(object):
def __len__(self):
return 3
c = C()
print(bool(c))
self.assertEqual(not c, False)
@skipUnlessIronPython()
def test_cp18912(self):
import __future__
feature = __future__.__dict__['with_statement']
x = compile('x=1', 'ignored', 'exec', feature.compiler_flag)
def test_cp19789(self):
class A:
a = 1
class B(object):
b = 2
class C(A, B):
pass
self.assertTrue('a' in dir(A))
self.assertTrue('b' in dir(B))
self.assertTrue('a' in dir(C) and 'b' in dir(C))
def test_cp24573(self):
def f(a=None):
pass
self.assertRaisesRegex(TypeError, "f\(\) got multiple values for argument 'a'",
lambda: f(1, a=3))
self.assertRaisesRegex(TypeError, "f\(\) got multiple values for argument 'a'",
lambda: f(1, **{"a":3}))
self.assertRaisesRegex(TypeError, "f\(\) got multiple values for keyword argument 'a'",
lambda: f(a=1, **{"a": 3}))
@unittest.skipIf(is_netcoreapp, 'requires System.Drawing.Common dependency')
@skipUnlessIronPython()
def test_cp24802(self):
import clr
clr.AddReference('System.Drawing')
import System
p = System.Drawing.Pen(System.Drawing.Color.Blue)
p.Width = System.Single(3.14)
self.assertEqual(p.Width, System.Single(3.14))
p.Width = 4.0
self.assertEqual(p.Width, 4.0)
def test_cp23822(self):
from copy import deepcopy
def F():
a = 4
class C:
field=7
def G(self):
print(a)
b = 4
return deepcopy(list(locals().keys()))
c = C()
return c.G()
temp_list = F()
temp_list.sort()
self.assertEqual(temp_list, ['a', 'b', 'deepcopy', 'self'])
def test_cp23823(self):
from copy import deepcopy
def f():
a = 10
def g1():
print(a)
return deepcopy(set(locals().keys()))
def g2():
return deepcopy(set(locals().keys()))
return (g1(), g2())
self.assertEqual(f(), ({'a', 'deepcopy'}, {'deepcopy'}))
def cp22692_helper(self, source, flags):
retVal = []
err = err1 = err2 = None
code = code1 = code2 = None
try:
code = compile(source, "dummy", "single", flags, 1)
except SyntaxError as e:
err = e
try:
code1 = compile(source + "\n", "dummy", "single", flags, 1)
except SyntaxError as e:
err1 = e
try:
code2 = compile(source + "\n\n", "dummy", "single", flags, 1)
except SyntaxError as e:
err2 = e
if not code:
retVal.append(type(err1))
retVal.append(type(err2))
return retVal
def test_cp22692(self):
self.assertEqual(self.cp22692_helper("if 1:", 0x200),
[IndentationError if sys.version_info >= (3,9) else SyntaxError, IndentationError if sys.version_info >= (3,9) else SyntaxError])
self.assertEqual(self.cp22692_helper("if 1:", 0),
[IndentationError if sys.version_info >= (3,9) else SyntaxError, IndentationError if sys.version_info >= (3,9) else SyntaxError])
self.assertEqual(self.cp22692_helper("if 1:\n if 1:", 0x200),
[IndentationError if is_cli or sys.version_info >= (3,9) else SyntaxError, IndentationError if is_cli or sys.version_info >= (3,9) else SyntaxError])
self.assertEqual(self.cp22692_helper("if 1:\n if 1:", 0),
[IndentationError if is_cli or sys.version_info >= (3,9) else SyntaxError, IndentationError if is_cli or sys.version_info >= (3,9) else SyntaxError])
@skipUnlessIronPython()
def test_cp23545(self):
import clr
clr.AddReference("rowantest.defaultmemberscs")
from Merlin.Testing.DefaultMemberSample import ClassWithDefaultField
self.assertEqual(repr(ClassWithDefaultField.Field),
"<field# Field on ClassWithDefaultField>")
try:
ClassWithDefaultField.Field = 20
except ValueError as e:
self.assertEqual(e.args[0],
"assignment to instance field w/o instance")
self.assertEqual(ClassWithDefaultField().Field, 10)
def test_cp20174(self):
old_path = [x for x in sys.path]
sys.path.append(self.test_dir)
cp20174_path = os.path.join(self.test_dir, "cp20174")
try:
cp20174_init = os.path.join(cp20174_path, "__init__.py")
self.write_to_file(cp20174_init, "from . import a")
cp20174_a = os.path.join(cp20174_path, "a.py")
self.write_to_file(cp20174_a, """
from .property import x
class C:
def _get_x(self): return x
x = property(_get_x)
""")
cp20174_property = os.path.join(cp20174_path, "property.py")
self.write_to_file(cp20174_property, "x=1")
import cp20174
self.assertEqual(cp20174.property.x, 1)
finally:
self.clean_directory(cp20174_path, remove=True)
sys.path = old_path
@skipUnlessIronPython()
def test_cp20370(self):
import clr
if is_netcoreapp:
clr.AddReference("System.Drawing.Primitives")
else:
clr.AddReference("System.Drawing")
from System.Drawing import Point
p1 = Point(1, 2)
p2 = Point(3, 4)
l = [p1]
self.assertTrue(id(l[-1]) != id(p2))
l[-1] = p2
self.assertEqual(id(l[-1]), id(p2))
@unittest.skipIf(is_netcoreapp, 'throws PlatformNotSupportedException')
@skipUnlessIronPython()
def test_cp23878(self):
import clr
clr.AddReference("rowantest.delegatedefinitions")
clr.AddReference("rowantest.typesamples")
from Merlin.Testing import Delegate, Flag
from time import sleep
cwtm = Delegate.ClassWithTargetMethods()
vi32d = Delegate.VoidInt32Delegate(cwtm.MVoidInt32)
ar = vi32d.BeginInvoke(32, None, None)
is_complete = False
for i in range(100):
sleep(1)
if ar.IsCompleted:
is_complete = True
break
self.assertTrue(is_complete)
self.assertEqual(Flag.Value, 32)
def test_cp23914(self):
class C(object):
def __init__(self,x,y,z):
print(x,y,z)
m = type.__call__
with stdout_trapper() as trapper:
try:
l = m(C,1,2,3)
l = m(C,z=3,y=2,x=1)
except Exception as e:
print(e.args[0])
self.assertEqual(trapper.messages[0:2], ['1 2 3', '1 2 3'])
@unittest.skipIf(is_cli, 'CPython specific test')
def test_cp23992(self):
def f():
x = 3
def g():
return locals()
l1 = locals()
l2 = g()
return (l1, l2)
t1, t2 = f()
self.assertEqual(set(t1.keys()), {'x', 'g'})
self.assertEqual(t2, {})
@unittest.skipUnless(is_cli, "import cp20472 is not failing, regression in CPython? (https://github.com/IronLanguages/ironpython3/issues/909)")
def test_cp24169(self):
import os, sys
orig_syspath = [x for x in sys.path]
try:
sys.path.append(os.path.join(self.test_dir, "encoded_files"))
import cp20472 #no encoding specified and has an invalid UTF-8 sequence
self.fail("Line above should had thrown!")
except SyntaxError as e:
self.assertTrue(e.msg.startswith("Non-UTF-8 code starting with '\\xcf' in file "))
self.assertTrue(e.msg.endswith("on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details"))
self.assertTrue("%sencoded_files%scp20472.py" % (os.sep, os.sep) in e.msg, e.msg)
finally:
sys.path = orig_syspath
def test_cp24484(self):
class DictClass(dict):
def __getattr__(self, name):
return lambda x: x*20
class K(object):
def __init__(self, parent):
self.parent = parent
def __getattr__(self, name):
return getattr(self.parent, name)
dc = DictClass()
k = K(dc)
for i in range(200):
temp = k.test(20)
def test_cp23555(self):
with stdout_trapper() as trapper:
class Base(object):
pass
class Real(Base, float):
def __new__(cls, *args, **kwargs):
print('real new')
result = Stub.__new__(cls, *args, **kwargs)
return result
def __init__(self, *args, **kwargs):
print('real init')
def __del__(self):
print('real del')
class Stub(Real):
def __new__(cls, *args, **kwargs):
print('stub new')
return float.__new__(Stub, args[0])
def __init__(self, *args, **kwargs):
print('stub init')
def __del__(self):
print("this should never happen; it's just here to ensure I get registered for GC")
def ConstructReal(x):
f = Real(x)
f.__class__ = Real
return f
f = ConstructReal(1.0)
del f
# ensure __del__ is called
import gc
gc.collect()
self.assertEqual(trapper.messages,
['real new', 'stub new', 'stub init', 'real del'])
def test_cp24677(self):
class SomeError(Exception):
pass
class SomeOtherError(SomeError, IOError):
pass
soe = SomeOtherError("some message")
try:
raise soe
except Exception:
pass
try:
raise soe
except SomeError:
pass
try:
raise soe
except IOError:
pass
try:
raise soe
except SomeOtherError:
pass
@skipUnlessIronPython()
def test_gh1435(self):
if not self.has_csc(): raise unittest.SkipTest("missing csc")
import clr
code = """
using System;
/// <summary>
/// Some description1.
/// </summary>
public class gh1435
{
/// <summary>
/// Some description2.
/// </summary>
public static String strFoo= "foo";
/// <summary>
/// Some description3.
/// </summary>
public gh1435()
{
}
/// <summary>
/// Some description4.
/// </summary>
public int someMethod1()
{
return 8;
}
/// <summary>
/// Some description5.
/// </summary>
public int someMethod2(string strSome)
{
return 8;
}
/// <summary>
/// Some description6.
/// </summary>
public int someMethod3(out string strSome)
{
strSome = "Some string.";
return 8;
}
/// <summary>
/// Another description1
/// </summary>
public int someMethod4(out string strSome, ref int foo)
{
strSome = "Another string";
foo = 10;
return 5;
}
}
"""
tmp = self.temporary_dir
test_cs, test_dll, test_xml = os.path.join(tmp, 'gh1435.cs'), os.path.join(tmp, 'gh1435.dll'), os.path.join(tmp, 'gh1435.xml')
self.write_to_file(test_cs, code)
self.assertEqual(self.run_csc('/nologo /doc:{0} /target:library /out:{1} {2}'.format(test_xml, test_dll, test_cs)), 0)
expected = """Help on method_descriptor:
someMethod4(...)
someMethod4(self: clsBar, foo: int) -> (int, str, int)
Another description1""".replace('\r', '')
clr.AddReferenceToFileAndPath(test_dll)
import gh1435
with stdout_trapper() as trapper:
help(gh1435.someMethod4)
self.assertTrue('\n'.join(trapper.messages), expected)
def test_gh278(self):
import _random
r = _random.Random()
s1 = r.getstate()
s2 = r.getstate()
self.assertIsNot(s1, s2)
self.assertEqual(s1, s2)
def test_gh1549(self):
import hashlib
m = hashlib.md5()
m.digest()
m.update(b'foo')
m.digest()
def test_gh1284(self):
import math
self.assertEqual(round(math.asinh(4.),12),round(math.log(math.sqrt(17.)+4.),12))
self.assertEqual(round(math.asinh(.4),12),round(math.log(math.sqrt(1.16)+.4),12))
self.assertEqual(round(math.asinh(-.5),12),round(math.log(math.sqrt(1.25)-.5),12))
self.assertEqual(round(math.asinh(-6.),12),round(math.log(math.sqrt(37.)-6.),12))
def test_gh1612(self):
def stack_depth(frame):
i = 0
while frame is not None:
i += 1
frame = frame.f_back
return i
try:
depth = stack_depth(sys._getframe())
except AttributeError:
return
def gen():
while True:
yield stack_depth(sys._getframe())
x = gen()
self.assertEqual(next(x), depth + 1)
def test():
self.assertEqual(next(x), depth + 2)
test()
def test_gh1629(self):
self.assertEqual('Bool is True', 'Bool is {}'.format(True))
self.assertEqual('Bool is 1', 'Bool is {:^}'.format(True))
self.assertEqual('Bool is 1 ', 'Bool is {:^10}'.format(True))
def test_ipy3_gh230(self):
"""https://github.com/IronLanguages/ironpython3/pull/230"""
import inspect
class test(object): pass
self.assertFalse(inspect.ismethoddescriptor(test.__weakref__))
self.assertFalse(inspect.ismethoddescriptor(test.__dict__["__dict__"]))
def test_ipy3_gh219(self):
"""https://github.com/IronLanguages/ironpython3/pull/219"""
with self.assertRaises(SyntaxError):
exec('["a"] = [1]')
with self.assertRaises(SyntaxError):
exec('[a + 1] = [1]')
def test_ipy3_gh215(self):
"""https://github.com/IronLanguages/ironpython3/pull/215"""
import io
class Test(io.IOBase): pass
dir(Test()) # check that this does not StackOverflow
def test_ipy2_gh206(self):
"""https://github.com/IronLanguages/ironpython2/issues/206"""
class x0: pass
class x1(object): pass
class aco(object):
def __init__(self):
self.cnt += 1
super(aco, self).__init__()