forked from QuantConnect/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestMethodBinder.cs
More file actions
1787 lines (1458 loc) · 60.7 KB
/
TestMethodBinder.cs
File metadata and controls
1787 lines (1458 loc) · 60.7 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
using System;
using System.Linq;
using Python.Runtime;
using NUnit.Framework;
using System.Collections.Generic;
using System.Diagnostics;
namespace Python.EmbeddingTest
{
public class TestMethodBinder
{
private static dynamic module;
private static string testModule = @"
from datetime import *
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class PythonModel(TestMethodBinder.CSharpModel):
def TestA(self):
return self.OnlyString(TestMethodBinder.TestImplicitConversion())
def TestB(self):
return self.OnlyClass('input string')
def TestC(self):
return self.InvokeModel('input string')
def TestD(self):
return self.InvokeModel(TestMethodBinder.TestImplicitConversion())
def TestE(self, array):
return array.Length == 2
def TestF(self):
model = TestMethodBinder.CSharpModel()
model.TestEnumerable(model.SomeList)
def TestG(self):
model = TestMethodBinder.CSharpModel()
model.TestList(model.SomeList)
def TestH(self):
return self.OnlyString(TestMethodBinder.ErroredImplicitConversion())
def MethodTimeSpanTest(self):
TestMethodBinder.CSharpModel.MethodDateTimeAndTimeSpan(self, timedelta(days = 1), TestMethodBinder.SomeEnu.A, pinocho = 0)
TestMethodBinder.CSharpModel.MethodDateTimeAndTimeSpan(self, date(1, 1, 1), TestMethodBinder.SomeEnu.A, pinocho = 0)
TestMethodBinder.CSharpModel.MethodDateTimeAndTimeSpan(self, datetime(1, 1, 1, 1, 1, 1), TestMethodBinder.SomeEnu.A, pinocho = 0)
def NumericalArgumentMethodInteger(self):
self.NumericalArgumentMethod(1)
def NumericalArgumentMethodDouble(self):
self.NumericalArgumentMethod(0.1)
def NumericalArgumentMethodNumpy64Float(self):
self.NumericalArgumentMethod(TestMethodBinder.Numpy.float64(0.1))
def ListKeyValuePairTest(self):
self.ListKeyValuePair([{'key': 1}])
self.ListKeyValuePair([])
def EnumerableKeyValuePairTest(self):
self.EnumerableKeyValuePair([{'key': 1}])
self.EnumerableKeyValuePair([])
def MethodWithParamsTest(self):
self.MethodWithParams(1, 'pepe')
def TestList(self):
model = TestMethodBinder.CSharpModel()
model.List([TestMethodBinder.CSharpModel])
def TestListReadOnlyCollection(self):
model = TestMethodBinder.CSharpModel()
model.ListReadOnlyCollection([TestMethodBinder.CSharpModel])
def TestEnumerable(self):
model = TestMethodBinder.CSharpModel()
model.ListEnumerable([TestMethodBinder.CSharpModel])";
public static dynamic Numpy;
[OneTimeSetUp]
public void OneTimeSetUp()
{
PythonEngine.Initialize();
using var _ = Py.GIL();
try
{
Numpy = Py.Import("numpy");
}
catch (PythonException)
{
}
module = PyModule.FromString("module", testModule).GetAttr("PythonModel").Invoke();
}
[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}
[SetUp]
public void SetUp()
{
CSharpModel.LastDelegateCalled = null;
CSharpModel.LastFuncCalled = null;
CSharpModel.MethodCalled = null;
CSharpModel.ProvidedArgument = null;
}
[Test]
public void MethodCalledList()
{
using (Py.GIL())
module.TestList();
Assert.AreEqual("List(List<Type> collection)", CSharpModel.MethodCalled);
}
[Test]
public void MethodCalledReadOnlyCollection()
{
using (Py.GIL())
module.TestListReadOnlyCollection();
Assert.AreEqual("List(IReadOnlyCollection<Type> collection)", CSharpModel.MethodCalled);
}
[Test]
public void MethodCalledEnumerable()
{
using (Py.GIL())
module.TestEnumerable();
Assert.AreEqual("List(IEnumerable<Type> collection)", CSharpModel.MethodCalled);
}
[Test]
public void ListToEnumerableExpectingMethod()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.TestF());
}
[Test]
public void ListToListExpectingMethod()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.TestG());
}
[Test]
public void ImplicitConversionToString()
{
using (Py.GIL())
{
var data = (string)module.TestA();
// we assert implicit conversion took place
Assert.AreEqual("OnlyString impl: implicit to string", data);
}
}
[Test]
public void ImplicitConversionToClass()
{
using (Py.GIL())
{
var data = (string)module.TestB();
// we assert implicit conversion took place
Assert.AreEqual("OnlyClass impl", data);
}
}
// Reproduces a bug in which program explodes when implicit conversion fails
// in Linux
[Test]
public void ImplicitConversionErrorHandling()
{
using (Py.GIL())
{
var errorCaught = false;
try
{
var data = (string)module.TestH();
}
catch (Exception e)
{
errorCaught = true;
Assert.AreEqual("Failed to implicitly convert Python.EmbeddingTest.TestMethodBinder+ErroredImplicitConversion to System.String", e.Message);
}
Assert.IsTrue(errorCaught);
}
}
[Test]
public void WillAvoidUsingImplicitConversionIfPossible_String()
{
using (Py.GIL())
{
var data = (string)module.TestC();
// we assert no implicit conversion took place
Assert.AreEqual("string impl: input string", data);
}
}
[Test]
public void WillAvoidUsingImplicitConversionIfPossible_Class()
{
using (Py.GIL())
{
var data = (string)module.TestD();
// we assert no implicit conversion took place
Assert.AreEqual("TestImplicitConversion impl", data);
}
}
[Test]
public void ArrayLength()
{
using (Py.GIL())
{
var array = new[] { "pepe", "pinocho" };
var data = (bool)module.TestE(array);
// Assert it is true
Assert.AreEqual(true, data);
}
}
[Test]
public void MethodDateTimeAndTimeSpan()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.MethodTimeSpanTest());
}
[Test]
public void NumericalArgumentMethod()
{
using (Py.GIL())
{
CSharpModel.ProvidedArgument = 0;
module.NumericalArgumentMethodInteger();
Assert.AreEqual(typeof(int), CSharpModel.ProvidedArgument.GetType());
Assert.AreEqual(1, CSharpModel.ProvidedArgument);
// python float type has double precision
module.NumericalArgumentMethodDouble();
Assert.AreEqual(typeof(double), CSharpModel.ProvidedArgument.GetType());
Assert.AreEqual(0.1d, CSharpModel.ProvidedArgument);
module.NumericalArgumentMethodNumpy64Float();
Assert.AreEqual(typeof(decimal), CSharpModel.ProvidedArgument.GetType());
Assert.AreEqual(0.1, CSharpModel.ProvidedArgument);
}
}
[Test]
// TODO: see GH issue https://github.com/pythonnet/pythonnet/issues/1532 re importing numpy after an engine restart fails
// so moving example test here so we import numpy once
public void TestReadme()
{
using (Py.GIL())
{
Assert.AreEqual("1.0", Numpy.cos(Numpy.pi * 2).ToString());
dynamic sin = Numpy.sin;
StringAssert.StartsWith("-0.95892", sin(5).ToString());
double c = Numpy.cos(5) + sin(5);
Assert.AreEqual(-0.675262, c, 0.01);
dynamic a = Numpy.array(new List<float> { 1, 2, 3 });
Assert.AreEqual("float64", a.dtype.ToString());
dynamic b = Numpy.array(new List<float> { 6, 5, 4 }, Py.kw("dtype", Numpy.int32));
Assert.AreEqual("int32", b.dtype.ToString());
Assert.AreEqual("[ 6. 10. 12.]", (a * b).ToString().Replace(" ", " "));
}
}
[Test]
public void NumpyDateTime64()
{
using (Py.GIL())
{
var number = 10;
var numpyDateTime = Numpy.datetime64("2011-02");
object result;
var converted = Converter.ToManaged(numpyDateTime, typeof(DateTime), out result, false);
Assert.IsTrue(converted);
Assert.AreEqual(new DateTime(2011, 02, 1), result);
}
}
[Test]
public void ListKeyValuePair()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.ListKeyValuePairTest());
}
[Test]
public void EnumerableKeyValuePair()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.EnumerableKeyValuePairTest());
}
[Test]
public void MethodWithParamsPerformance()
{
using (Py.GIL())
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100000; i++)
{
module.MethodWithParamsTest();
}
stopwatch.Stop();
Console.WriteLine($"Took: {stopwatch.ElapsedMilliseconds}");
}
}
[Test]
public void NumericalArgumentMethodNumpy64FloatPerformance()
{
using (Py.GIL())
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100000; i++)
{
module.NumericalArgumentMethodNumpy64Float();
}
stopwatch.Stop();
Console.WriteLine($"Took: {stopwatch.ElapsedMilliseconds}");
}
}
[Test]
public void MethodWithParamsTest()
{
using (Py.GIL())
Assert.DoesNotThrow(() => module.MethodWithParamsTest());
}
[Test]
public void TestNonStaticGenericMethodBinding()
{
using (Py.GIL())
{
// Test matching generic on instance functions
// i.e. function signature is <T>(Generic<T> var1)
// Run in C#
var class1 = new TestGenericClass1();
var class2 = new TestGenericClass2();
class1.TestNonStaticGenericMethod(class1);
class2.TestNonStaticGenericMethod(class2);
Assert.AreEqual(1, class1.Value);
Assert.AreEqual(1, class2.Value);
// Run in Python
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass1()
class2 = TestMethodBinder.TestGenericClass2()
class1.TestNonStaticGenericMethod(class1)
class2.TestNonStaticGenericMethod(class2)
if class1.Value != 1 or class2.Value != 1:
raise AssertionError('Values were not updated')
"));
}
}
[Test]
public void TestGenericMethodBinding()
{
using (Py.GIL())
{
// Test matching generic
// i.e. function signature is <T>(Generic<T> var1)
// Run in C#
var class1 = new TestGenericClass1();
var class2 = new TestGenericClass2();
TestGenericMethod(class1);
TestGenericMethod(class2);
Assert.AreEqual(1, class1.Value);
Assert.AreEqual(1, class2.Value);
// Run in Python
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass1()
class2 = TestMethodBinder.TestGenericClass2()
TestMethodBinder.TestGenericMethod(class1)
TestMethodBinder.TestGenericMethod(class2)
if class1.Value != 1 or class2.Value != 1:
raise AssertionError('Values were not updated')
"));
}
}
[Test]
public void TestMultipleGenericMethodBinding()
{
using (Py.GIL())
{
// Test matching multiple generics
// i.e. function signature is <T,K>(Generic<T,K> var1)
// Run in C#
var class1 = new TestMultipleGenericClass1();
var class2 = new TestMultipleGenericClass2();
TestMultipleGenericMethod(class1);
TestMultipleGenericMethod(class2);
Assert.AreEqual(1, class1.Value);
Assert.AreEqual(1, class2.Value);
// Run in Python
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestMultipleGenericClass1()
class2 = TestMethodBinder.TestMultipleGenericClass2()
TestMethodBinder.TestMultipleGenericMethod(class1)
TestMethodBinder.TestMultipleGenericMethod(class2)
if class1.Value != 1 or class2.Value != 1:
raise AssertionError('Values were not updated')
"));
}
}
[Test]
public void TestMultipleGenericParamMethodBinding()
{
using (Py.GIL())
{
// Test multiple param generics matching
// i.e. function signature is <T,K>(Generic1<T> var1, Generic<T,K> var2)
// Run in C#
var class1a = new TestGenericClass1();
var class1b = new TestMultipleGenericClass1();
TestMultipleGenericParamsMethod(class1a, class1b);
Assert.AreEqual(1, class1a.Value);
Assert.AreEqual(1, class1a.Value);
var class2a = new TestGenericClass2();
var class2b = new TestMultipleGenericClass2();
TestMultipleGenericParamsMethod(class2a, class2b);
Assert.AreEqual(1, class2a.Value);
Assert.AreEqual(1, class2b.Value);
// Run in Python
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1a = TestMethodBinder.TestGenericClass1()
class1b = TestMethodBinder.TestMultipleGenericClass1()
TestMethodBinder.TestMultipleGenericParamsMethod(class1a, class1b)
if class1a.Value != 1 or class1b.Value != 1:
raise AssertionError('Values were not updated')
class2a = TestMethodBinder.TestGenericClass2()
class2b = TestMethodBinder.TestMultipleGenericClass2()
TestMethodBinder.TestMultipleGenericParamsMethod(class2a, class2b)
if class2a.Value != 1 or class2b.Value != 1:
raise AssertionError('Values were not updated')
"));
}
}
[Test]
public void TestMultipleGenericParamMethodBinding_MixedOrder()
{
using (Py.GIL())
{
// Test matching multiple param generics with mixed order
// i.e. function signature is <T,K>(Generic1<K> var1, Generic<T,K> var2)
// Run in C#
var class1a = new TestGenericClass2();
var class1b = new TestMultipleGenericClass1();
TestMultipleGenericParamsMethod2(class1a, class1b);
Assert.AreEqual(1, class1a.Value);
Assert.AreEqual(1, class1a.Value);
var class2a = new TestGenericClass1();
var class2b = new TestMultipleGenericClass2();
TestMultipleGenericParamsMethod2(class2a, class2b);
Assert.AreEqual(1, class2a.Value);
Assert.AreEqual(1, class2b.Value);
// Run in Python
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1a = TestMethodBinder.TestGenericClass2()
class1b = TestMethodBinder.TestMultipleGenericClass1()
TestMethodBinder.TestMultipleGenericParamsMethod2(class1a, class1b)
if class1a.Value != 1 or class1b.Value != 1:
raise AssertionError('Values were not updated')
class2a = TestMethodBinder.TestGenericClass1()
class2b = TestMethodBinder.TestMultipleGenericClass2()
TestMethodBinder.TestMultipleGenericParamsMethod2(class2a, class2b)
if class2a.Value != 1 or class2b.Value != 1:
raise AssertionError('Values were not updated')
"));
}
}
[Test]
public void TestPyClassGenericBinding()
{
using (Py.GIL())
// Overriding our generics in Python we should still match with the generic method
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class PyGenericClass(TestMethodBinder.TestGenericClass1):
pass
class PyMultipleGenericClass(TestMethodBinder.TestMultipleGenericClass1):
pass
singleGenericClass = PyGenericClass()
multiGenericClass = PyMultipleGenericClass()
TestMethodBinder.TestGenericMethod(singleGenericClass)
TestMethodBinder.TestMultipleGenericMethod(multiGenericClass)
TestMethodBinder.TestMultipleGenericParamsMethod(singleGenericClass, multiGenericClass)
if singleGenericClass.Value != 1 or multiGenericClass.Value != 1:
raise AssertionError('Values were not updated')
"));
}
[Test]
public void TestNonGenericIsUsedWhenAvailable()
{
using (Py.GIL())
{// Run in C#
var class1 = new TestGenericClass3();
TestGenericMethod(class1);
Assert.AreEqual(10, class1.Value);
// When available, should select non-generic method over generic method
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass3()
TestMethodBinder.TestGenericMethod(class1)
if class1.Value != 10:
raise AssertionError('Value was not updated')
"));
}
}
[Test]
public void TestMatchTypedGenericOverload()
{
using (Py.GIL())
{// Test to ensure we can match a typed generic overload
// even when there are other matches that would apply.
var class1 = new TestGenericClass4();
TestGenericMethod(class1);
Assert.AreEqual(15, class1.Value);
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass4()
TestMethodBinder.TestGenericMethod(class1)
if class1.Value != 15:
raise AssertionError('Value was not updated')
"));
}
}
[Test]
public void TestGenericBindingSpeed()
{
using (Py.GIL())
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
TestMultipleGenericParamMethodBinding();
}
stopwatch.Stop();
Console.WriteLine($"Took: {stopwatch.ElapsedMilliseconds} ms");
}
}
[Test]
public void TestGenericTypeMatchingWithConvertedPyType()
{
// This test ensures that we can still match and bind a generic method when we
// have a converted pytype in the args (py timedelta -> C# TimeSpan)
using (Py.GIL())
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from datetime import timedelta
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass1()
span = timedelta(hours=5)
TestMethodBinder.TestGenericMethod(class1, span)
if class1.Value != 5:
raise AssertionError('Values were not updated properly')
"));
}
[Test]
public void TestGenericTypeMatchingWithDefaultArgs()
{
// This test ensures that we can still match and bind a generic method when we have default args
using (Py.GIL())
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from datetime import timedelta
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass1()
TestMethodBinder.TestGenericMethodWithDefault(class1)
if class1.Value != 25:
raise AssertionError(f'Value was not 25, was {class1.Value}')
TestMethodBinder.TestGenericMethodWithDefault(class1, 50)
if class1.Value != 50:
raise AssertionError('Value was not 50, was {class1.Value}')
"));
}
[Test]
public void TestGenericTypeMatchingWithNullDefaultArgs()
{
// This test ensures that we can still match and bind a generic method when we have \
// null default args, important because caching by arg types occurs
using (Py.GIL())
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from datetime import timedelta
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class1 = TestMethodBinder.TestGenericClass1()
TestMethodBinder.TestGenericMethodWithNullDefault(class1)
if class1.Value != 10:
raise AssertionError(f'Value was not 25, was {class1.Value}')
TestMethodBinder.TestGenericMethodWithNullDefault(class1, class1)
if class1.Value != 20:
raise AssertionError('Value was not 50, was {class1.Value}')
"));
}
[Test]
public void TestMatchPyDateToDateTime()
{
using (Py.GIL())
// This test ensures that we match py datetime.date object to C# DateTime object
Assert.DoesNotThrow(() => PyModule.FromString("test", @"
from datetime import *
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
test = date(year=2011, month=5, day=1)
result = TestMethodBinder.GetMonth(test)
if result != 5:
raise AssertionError('Failed to return expected value 1')
"));
}
public class OverloadsTestClass
{
public string Method1(string positionalArg, decimal namedArg1 = 1.2m, int namedArg2 = 123)
{
Console.WriteLine("1");
return "Method1 Overload 1";
}
public string Method1(decimal namedArg1 = 1.2m, int namedArg2 = 123)
{
Console.WriteLine("2");
return "Method1 Overload 2";
}
// ----
public string Method2(string arg1, int arg2, decimal arg3, decimal kwarg1 = 1.1m, bool kwarg2 = false, string kwarg3 = "")
{
return "Method2 Overload 1";
}
public string Method2(string arg1, int arg2, decimal kwarg1 = 1.1m, bool kwarg2 = false, string kwarg3 = "")
{
return "Method2 Overload 2";
}
// ----
public string Method3(string arg1, int arg2, float arg3, float kwarg1 = 1.1f, bool kwarg2 = false, string kwarg3 = "")
{
return "Method3 Overload 1";
}
public string Method3(string arg1, int arg2, float kwarg1 = 1.1f, bool kwarg2 = false, string kwarg3 = "")
{
return "Method3 Overload 2";
}
// ----
public string ImplicitConversionSameArgumentCount(string symbol, int quantity, float trailingAmount, bool trailingAsPercentage, string tag = "")
{
return "ImplicitConversionSameArgumentCount 1";
}
public string ImplicitConversionSameArgumentCount(string symbol, decimal quantity, decimal trailingAmount, bool trailingAsPercentage, string tag = "")
{
return "ImplicitConversionSameArgumentCount 2";
}
public string ImplicitConversionSameArgumentCount2(string symbol, int quantity, float trailingAmount, bool trailingAsPercentage, string tag = "")
{
return "ImplicitConversionSameArgumentCount2 1";
}
public string ImplicitConversionSameArgumentCount2(string symbol, float quantity, float trailingAmount, bool trailingAsPercentage, string tag = "")
{
return "ImplicitConversionSameArgumentCount2 2";
}
public string ImplicitConversionSameArgumentCount2(string symbol, decimal quantity, float trailingAmount, bool trailingAsPercentage, string tag = "")
{
return "ImplicitConversionSameArgumentCount2 2";
}
// ----
public string VariableArgumentsMethod(params CSharpModel[] paramsParams)
{
return "VariableArgumentsMethod(CSharpModel[])";
}
public string VariableArgumentsMethod(params PyObject[] paramsParams)
{
return "VariableArgumentsMethod(PyObject[])";
}
// ----
public string MethodWithEnumParam(SomeEnu enumValue, string symbol)
{
return $"MethodWithEnumParam With Enum";
}
public string MethodWithEnumParam(PyObject pyObject, string symbol)
{
return $"MethodWithEnumParam With PyObject";
}
// ----
public string ConstructorMessage { get; set; }
public OverloadsTestClass(params CSharpModel[] paramsParams)
{
ConstructorMessage = "OverloadsTestClass(CSharpModel[])";
}
public OverloadsTestClass(params PyObject[] paramsParams)
{
ConstructorMessage = "OverloadsTestClass(PyObject[])";
}
public OverloadsTestClass()
{
}
}
[TestCase("Method1('abc', namedArg1=10, namedArg2=321)", "Method1 Overload 1")]
[TestCase("Method1('abc', namedArg1=12.34, namedArg2=321)", "Method1 Overload 1")]
[TestCase("Method2(\"SPY\", 10, 123, kwarg1=1, kwarg2=True)", "Method2 Overload 1")]
[TestCase("Method2(\"SPY\", 10, 123.34, kwarg1=1.23, kwarg2=True)", "Method2 Overload 1")]
[TestCase("Method3(\"SPY\", 10, 123.34, kwarg1=1.23, kwarg2=True)", "Method3 Overload 1")]
public void SelectsRightOverloadWithNamedParameters(string methodCallCode, string expectedResult)
{
using var _ = Py.GIL();
dynamic module = PyModule.FromString("SelectsRightOverloadWithNamedParameters", @$"
def call_method(instance):
return instance.{methodCallCode}
");
var instance = new OverloadsTestClass();
var result = module.call_method(instance).As<string>();
Assert.AreEqual(expectedResult, result);
}
[TestCase("ImplicitConversionSameArgumentCount", "10", "ImplicitConversionSameArgumentCount 1")]
[TestCase("ImplicitConversionSameArgumentCount", "10.1", "ImplicitConversionSameArgumentCount 2")]
[TestCase("ImplicitConversionSameArgumentCount2", "10", "ImplicitConversionSameArgumentCount2 1")]
[TestCase("ImplicitConversionSameArgumentCount2", "10.1", "ImplicitConversionSameArgumentCount2 2")]
public void DisambiguatesOverloadWithSameArgumentCountAndImplicitConversion(string methodName, string quantity, string expectedResult)
{
using var _ = Py.GIL();
dynamic module = PyModule.FromString("DisambiguatesOverloadWithSameArgumentCountAndImplicitConversion", @$"
def call_method(instance):
return instance.{methodName}(""SPY"", {quantity}, 123.4, trailingAsPercentage=True)
");
var instance = new OverloadsTestClass();
var result = module.call_method(instance).As<string>();
Assert.AreEqual(expectedResult, result);
}
public class CSharpClass
{
public string CalledMethodMessage { get; private set; }
public void Method()
{
CalledMethodMessage = "Overload 1";
}
public void Method(string stringArgument, decimal decimalArgument = 1.2m)
{
CalledMethodMessage = "Overload 2";
}
public void Method(PyObject typeArgument, decimal decimalArgument = 1.2m)
{
CalledMethodMessage = "Overload 3";
}
}
[Test]
public void CallsCorrectOverloadWithoutErrors()
{
using var _ = Py.GIL();
var module = PyModule.FromString("CallsCorrectOverloadWithoutErrors", @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
class PythonModel(TestMethodBinder.CSharpModel):
pass
def call_method(instance):
instance.Method(PythonModel, decimalArgument=1.234)
");
var instance = new CSharpClass();
using var pyInstance = instance.ToPython();
Assert.DoesNotThrow(() =>
{
module.GetAttr("call_method").Invoke(pyInstance);
});
Assert.AreEqual("Overload 3", instance.CalledMethodMessage);
Assert.IsFalse(Exceptions.ErrorOccurred());
}
public class CSharpClass2
{
public string CalledMethodMessage { get; private set; } = string.Empty;
public void Clear()
{
CalledMethodMessage = string.Empty;
}
public void Method()
{
CalledMethodMessage = "Overload 1";
}
public void Method(CSharpClass csharpClassArgument, decimal decimalArgument = 1.2m, PyObject pyObjectKwArgument = null)
{
CalledMethodMessage = "Overload 2";
}
public void Method(PyObject pyObjectArgument, decimal decimalArgument = 1.2m, object objectArgument = null)
{
CalledMethodMessage = "Overload 3";
}
// This must be matched when passing just a single argument and it's a PyObject,
// event though the PyObject kwarg in the second overload has more precedence.
// But since it will not be passed, this overload must be called.
public void Method(PyObject pyObjectArgument, decimal decimalArgument = 1.2m, int intArgument = 0)
{
CalledMethodMessage = "Overload 4";
}
}
[Test]
public void PyObjectArgsHavePrecedenceOverOtherTypes()
{
using var _ = Py.GIL();
var instance = new CSharpClass2();
using var pyInstance = instance.ToPython();
using var pyArg = new CSharpClass().ToPython();
Assert.DoesNotThrow(() =>
{
// We are passing a PyObject and not using the named arguments,
// that overload must be called without converting the PyObject to CSharpClass
pyInstance.InvokeMethod("Method", pyArg);
});
Assert.AreEqual("Overload 4", instance.CalledMethodMessage);
Assert.IsFalse(Exceptions.ErrorOccurred());
instance.Clear();