-
Notifications
You must be signed in to change notification settings - Fork 541
Expand file tree
/
Copy pathCSharp.Tests.cs
More file actions
2068 lines (1849 loc) · 78.9 KB
/
CSharp.Tests.cs
File metadata and controls
2068 lines (1849 loc) · 78.9 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.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using CSharp;
using NUnit.Framework;
[TestFixture]
public unsafe class CSharpTests
{
public class ExtendsWrapper : TestOverrideFromSecondaryBase
{
public ExtendsWrapper()
{
ProtectedFunction();
}
}
[Test]
public void TestUncompilableCode()
{
#pragma warning disable 0168 // warning CS0168: The variable `foo' is declared but never used
#pragma warning disable 0219 // warning CS0219: The variable `foo' is assigned but its value is never used
ALLCAPS_UNDERSCORES a;
new MultipleInheritance().Dispose();
using (var testRenaming = new TestRenaming())
{
testRenaming.name();
testRenaming.Name();
testRenaming.Property.GetHashCode();
}
new ForceCreationOfInterface().Dispose();
new InheritsProtectedVirtualFromSecondaryBase().Dispose();
new InheritanceBuffer().Dispose();
new HasProtectedVirtual().Dispose();
new Proprietor(5).Dispose();
new HasCtorWithMappedToEnum<TestFlag>(TestFlag.Flag1).Dispose();
new TestAnonymousMemberNameCollision().Dispose();
using (var testOverrideFromSecondaryBase = new TestOverrideFromSecondaryBase())
{
testOverrideFromSecondaryBase.function();
var ok = false;
testOverrideFromSecondaryBase.function(ref ok);
var property = testOverrideFromSecondaryBase.property;
testOverrideFromSecondaryBase.VirtualMember();
}
using (var foo = new Foo())
{
var isNoParams = foo.IsNoParams;
foo.SetNoParams();
foo.Width = 5;
using (var hasSecondaryBaseWithAbstractWithDefaultArg = new HasSecondaryBaseWithAbstractWithDefaultArg())
{
hasSecondaryBaseWithAbstractWithDefaultArg.Abstract();
hasSecondaryBaseWithAbstractWithDefaultArg.AbstractWithNoDefaultArg(foo);
}
Assert.That(foo.PublicFieldMappedToEnum, Is.EqualTo(TestFlag.Flag2));
Assert.That(foo.ReturnConstRef(), Is.EqualTo(5));
}
using (var hasOverride = new HasOverrideOfHasPropertyWithDerivedType())
hasOverride.CauseRenamingError();
using (var qux = new Qux())
{
qux.Type.GetHashCode();
using (Bar bar = new Bar(qux))
{
bar.Type.GetHashCode();
}
}
using (var quux = new Quux())
{
quux.SetterWithDefaultOverload = null;
quux.SetSetterWithDefaultOverload();
}
using (ComplexType complexType = TestFlag.Flag1)
{
}
using (var typeMappedWithOperator = new TypeMappedWithOperator())
{
int i = typeMappedWithOperator | 5;
}
using (Base<int> @base = new DerivedFromSpecializationOfUnsupportedTemplate())
{
}
CSharp.CSharpCool.FunctionInsideInlineNamespace();
CSharp.CSharpCool.TakeMappedEnum(TestFlag.Flag1);
using (CSharpTemplatesCool.SpecialiseReturnOnly())
{
}
using (var t1 = new T1())
using (new IndependentFields<int>(t1))
{
}
using (var t2 = new T2())
using (new IndependentFields<int>(t2))
{
}
#pragma warning restore 0168
#pragma warning restore 0219
}
private class OverriddenInManaged : Baz
{
public override int Type => 10;
}
[Test]
public void TestDer()
{
using (var der = new OverriddenInManaged())
{
using (var hasDer = new HasOverriddenInManaged())
{
hasDer.SetOverriddenInManaged(der);
Assert.That(hasDer.CallOverriddenInManaged(), Is.EqualTo(10));
}
}
}
[Test]
[Ignore("https://github.com/mono/CppSharp/issues/1518")]
public void TestReturnCharPointer()
{
Assert.That(new IntPtr(CSharp.CSharpCool.ReturnCharPointer()), Is.EqualTo(IntPtr.Zero));
const char z = 'z';
Assert.That(*CSharp.CSharpCool.TakeConstCharRef(z), Is.EqualTo(z));
}
[Test]
public void TestTakeCharPointer()
{
char c = 'c';
Assert.That(*CSharp.CSharpCool.TakeCharPointer(&c), Is.EqualTo(c));
}
[Test]
public void TestIndexer()
{
using (var foo = new Foo())
{
Assert.That(foo[0], Is.EqualTo(50));
foo[0] = 250;
Assert.That(foo[0], Is.EqualTo(250));
Assert.That(foo[(uint)0], Is.EqualTo(15));
}
using (var bar = new Bar())
{
Assert.That(bar[0].A, Is.EqualTo(10));
using (Foo foo = new Foo { A = 25 })
{
bar[0] = foo;
Assert.That(bar[0].A, Is.EqualTo(25));
}
}
}
[Test]
public void TestReturnSmallPOD()
{
using (var f = new Foo())
{
foreach (var pod in new[] { f.SmallPodCdecl, f.SmallPodStdcall, f.SmallPodThiscall })
{
Assert.That(pod.A, Is.EqualTo(10000));
Assert.That(pod.B, Is.EqualTo(40000));
}
}
}
[Test]
public void TestPropertyAccessModifier()
{
Assert.That(typeof(Foo).GetProperty("P",
BindingFlags.Instance | BindingFlags.NonPublic), Is.Not.Null);
}
[Test]
public void TestMultipleInheritance()
{
using (var baz = new Baz())
{
Assert.That(baz.Method, Is.EqualTo(1));
var bar = (IBar)baz;
Assert.That(bar.Method, Is.EqualTo(2));
Assert.That(baz[0], Is.EqualTo(50));
using (Foo foo = new Foo { A = 1000 })
{
bar[0] = foo;
Assert.That(bar[0].A, Is.EqualTo(1000));
}
Assert.That(baz.FarAwayFunc, Is.EqualTo(20));
Assert.That(baz.TakesQux(baz), Is.EqualTo(20));
Assert.That(baz.ReturnQux().FarAwayFunc, Is.EqualTo(20));
baz.SetMethod(Bar.ProtectedNestedEnum.Item1);
Assert.That(baz.P, Is.EqualTo(5));
baz.PublicDouble = 1.5;
Assert.That(baz.PublicDouble, Is.EqualTo(1.5));
baz.PublicInt = 15;
Assert.That(baz.PublicInt, Is.EqualTo(15));
}
}
[Test]
public void TestProperties()
{
using (var proprietor = new Proprietor())
{
Assert.That(proprietor.Parent, Is.EqualTo(0));
proprietor.Value = 20;
Assert.That(proprietor.Value, Is.EqualTo(20));
proprietor.Prop = 50;
Assert.That(proprietor.Prop, Is.EqualTo(50));
}
using (var qux = new Qux())
{
using (var p = new P((IQux)qux) { Value = 20 })
{
Assert.That(p.Value, Is.EqualTo(30));
p.Prop = 50;
Assert.That(p.Prop, Is.EqualTo(150));
using (var complexType = new ComplexType())
{
p.ComplexType = complexType;
Assert.That(p.ComplexType.Check(), Is.EqualTo(5));
}
Assert.That(p.Test, Is.True);
Assert.That(p.IsBool, Is.False);
}
}
}
[Test]
public void TestAttributes()
{
Assert.That(typeof(Qux).GetMethod("Obsolete")
.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length,
Is.GreaterThan(0));
}
[Test]
public void TestDestructors()
{
CSharp.TestDestructors.InitMarker();
Assert.AreEqual(0, CSharp.TestDestructors.Marker);
using (var dtors = new TestDestructors())
{
Assert.AreEqual(0xf00d, CSharp.TestDestructors.Marker);
dtors.Dispose();
}
Assert.AreEqual(0xcafe, CSharp.TestDestructors.Marker);
}
[Test]
public unsafe void TestArrayOfPointersToPrimitives()
{
using (var bar = new Bar())
{
var array = new IntPtr[1];
int i = 5;
array[0] = new IntPtr(&i);
bar.ArrayOfPrimitivePointers = array;
Assert.That(i, Is.EqualTo(*(int*)bar.ArrayOfPrimitivePointers[0]));
}
}
[Test]
public void TestCopyConstructorValue()
{
var testCopyConstructorVal = new TestCopyConstructorVal { A = 10, B = 5 };
var copyBar = new TestCopyConstructorVal(testCopyConstructorVal);
Assert.That(testCopyConstructorVal.A, Is.EqualTo(copyBar.A));
Assert.That(testCopyConstructorVal.B, Is.EqualTo(copyBar.B));
}
[Test]
public void TestPropertiesConflictingWithMethod()
{
using (var p = new P((IQux)new Qux()) { Test = true })
{
Assert.That(p.Test, Is.True);
p.GetTest();
}
}
[Test]
public void TestDefaultArguments()
{
using (var methodsWithDefaultValues = new MethodsWithDefaultValues())
{
methodsWithDefaultValues.DefaultPointer();
methodsWithDefaultValues.DefaultVoidStar();
methodsWithDefaultValues.DefaultFunctionPointer();
methodsWithDefaultValues.DefaultValueType();
methodsWithDefaultValues.DefaultChar();
methodsWithDefaultValues.DefaultEmptyChar();
methodsWithDefaultValues.DefaultEmptyEnum();
methodsWithDefaultValues.DefaultRefTypeBeforeOthers();
methodsWithDefaultValues.DefaultRefTypeAfterOthers();
methodsWithDefaultValues.DefaultRefTypeBeforeAndAfterOthers();
methodsWithDefaultValues.DefaultIntAssignedAnEnum();
methodsWithDefaultValues.defaultRefAssignedValue();
methodsWithDefaultValues.DefaultRefAssignedValue();
methodsWithDefaultValues.DefaultEnumAssignedBitwiseOr();
methodsWithDefaultValues.DefaultEnumAssignedBitwiseOrShort();
methodsWithDefaultValues.DefaultNonEmptyCtor();
methodsWithDefaultValues.DefaultNonEmptyCtorWithNullPtr();
Assert.That(methodsWithDefaultValues.DefaultMappedToEnum(), Is.EqualTo(Flags.Flag3));
methodsWithDefaultValues.DefaultMappedToZeroEnum();
methodsWithDefaultValues.DefaultMappedToEnumAssignedWithCtor();
methodsWithDefaultValues.DefaultTypedefMappedToEnumRefAssignedWithCtor();
methodsWithDefaultValues.DefaultZeroMappedToEnumAssignedWithCtor();
Assert.That(methodsWithDefaultValues.DefaultImplicitCtorInt().Priv, Is.EqualTo(0));
methodsWithDefaultValues.DefaultImplicitCtorChar();
methodsWithDefaultValues.DefaultImplicitCtorFoo();
methodsWithDefaultValues.DefaultImplicitCtorEnum();
methodsWithDefaultValues.DefaultIntWithLongExpression();
methodsWithDefaultValues.DefaultRefTypeEnumImplicitCtor();
methodsWithDefaultValues.Rotate4x4Matrix(0, 0, 0);
methodsWithDefaultValues.DefaultPointerToValueType();
methodsWithDefaultValues.DefaultDoubleWithoutF();
methodsWithDefaultValues.DefaultIntExpressionWithEnum();
methodsWithDefaultValues.DefaultCtorWithMoreThanOneArg();
methodsWithDefaultValues.DefaultEmptyBraces();
methodsWithDefaultValues.DefaultWithRefManagedLong();
methodsWithDefaultValues.DefaultWithFunctionCall();
methodsWithDefaultValues.DefaultWithPropertyCall();
methodsWithDefaultValues.DefaultWithGetPropertyCall();
methodsWithDefaultValues.DefaultWithIndirectStringConstant();
methodsWithDefaultValues.DefaultWithDirectIntConstant();
methodsWithDefaultValues.DefaultWithEnumInLowerCasedNameSpace();
methodsWithDefaultValues.DefaultWithCharFromInt();
methodsWithDefaultValues.DefaultWithFreeConstantInNameSpace();
methodsWithDefaultValues.DefaultWithStdNumericLimits(10, 5);
methodsWithDefaultValues.DefaultWithSpecialization();
methodsWithDefaultValues.DefaultOverloadedImplicitCtor();
methodsWithDefaultValues.DefaultWithParamNamedSameAsMethod(5);
Assert.That(methodsWithDefaultValues.DefaultIntAssignedAnEnumWithBinaryOperatorAndFlags(), Is.EqualTo((int)(Bar.Items.Item1 | Bar.Items.Item2)));
Assert.That(methodsWithDefaultValues.DefaultWithConstantFlags(), Is.EqualTo(CSharp.CSharpCool.ConstFlag1 | CSharp.CSharpCool.ConstFlag2 | CSharp.CSharpCool.ConstFlag3));
Assert.IsTrue(methodsWithDefaultValues.DefaultWithPointerToEnum());
Assert.AreEqual(CSharp.CSharpCool.DefaultSmallPODInstance.__Instance, methodsWithDefaultValues.DefaultWithNonPrimitiveType().__Instance);
}
}
[Test]
public void TestGenerationOfAnotherUnitInSameFile()
{
AnotherUnitCool.FunctionInAnotherUnit();
}
[Test]
public void TestPrivateOverride()
{
using (var hasOverridesWithChangedAccess = new HasOverridesWithChangedAccess())
hasOverridesWithChangedAccess.PrivateOverride();
using (var hasOverridesWithIncreasedAccess = new HasOverridesWithIncreasedAccess())
hasOverridesWithIncreasedAccess.PrivateOverride();
}
[Test]
public void TestQFlags()
{
Assert.AreEqual(TestFlag.Flag2, new ComplexType().ReturnsQFlags);
}
[Test]
public void TestCopyCtor()
{
using (Qux q1 = new Qux())
{
for (int i = 0; i < q1.Array.Length; i++)
{
q1.Array[i] = i;
}
using (Qux q2 = new Qux(q1))
{
for (int i = 0; i < q2.Array.Length; i++)
{
Assert.AreEqual(q1.Array[i], q2.Array[i]);
}
}
}
}
[Test]
public void TestBooleanArray()
{
using (Foo foo = new Foo { A = 10 })
{
var new_values = new bool[5];
for (int i = 0; i < new_values.Length; ++i)
{
new_values[i] = i % 2 == 0;
}
foo.Btest = new_values;
Assert.AreEqual(true, foo.Btest[0]);
Assert.AreEqual(false, foo.Btest[1]);
Assert.AreEqual(true, foo.Btest[2]);
Assert.AreEqual(false, foo.Btest[3]);
Assert.AreEqual(true, foo.Btest[4]);
}
}
[Test]
public void TestImplicitCtor()
{
using (Foo foo = new Foo { A = 10 })
{
using (MethodsWithDefaultValues m = foo)
{
Assert.AreEqual(foo.A, m.A);
}
}
using (MethodsWithDefaultValues m1 = 5)
{
Assert.AreEqual(5, m1.A);
}
}
[Test]
public void TestStructWithPrivateFields()
{
var structWithPrivateFields = new StructWithPrivateFields(10, new Foo { A = 5 });
Assert.AreEqual(10, structWithPrivateFields.SimplePrivateField);
Assert.AreEqual(5, structWithPrivateFields.ComplexPrivateField.A);
}
[Test]
public void TestRenamingVariable()
{
Assert.AreEqual(5, Foo.Rename);
}
[Test]
public void TestPrimarySecondaryBase()
{
using (var a = new MI_A0())
{
Assert.That(a.Get(), Is.EqualTo(50));
}
using (var c = new MI_C())
{
Assert.That(c.Get(), Is.EqualTo(50));
}
using (var d = new MI_D())
{
Assert.That(d.Get(), Is.EqualTo(50));
}
}
[Test]
public void TestNativeToManagedMapWithForeignObjects()
{
IntPtr native1;
IntPtr native2;
var hasVirtualDtor1Map = (IDictionary<IntPtr, HasVirtualDtor1>)typeof(
HasVirtualDtor1).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
var hasVirtualDtor2Map = (IDictionary<IntPtr, HasVirtualDtor2>)typeof(
HasVirtualDtor2).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
using (var testNativeToManagedMap = new TestNativeToManagedMap())
{
var hasVirtualDtor2 = testNativeToManagedMap.HasVirtualDtor2;
native2 = hasVirtualDtor2.__Instance;
native1 = hasVirtualDtor2.HasVirtualDtor1.__Instance;
Assert.IsTrue(hasVirtualDtor1Map.ContainsKey(native1));
Assert.IsTrue(hasVirtualDtor2Map.ContainsKey(native2));
Assert.AreSame(hasVirtualDtor2, testNativeToManagedMap.HasVirtualDtor2);
}
Assert.IsFalse(hasVirtualDtor1Map.ContainsKey(native1));
Assert.IsFalse(hasVirtualDtor2Map.ContainsKey(native2));
}
[Test]
public void TestNativeToManagedMapWithOwnObjects()
{
using (var testNativeToManagedMap = new TestNativeToManagedMap())
{
var quxMap = (IDictionary<IntPtr, IQux>)typeof(
Qux).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
var bar = new Bar();
testNativeToManagedMap.PropertyWithNoVirtualDtor = bar;
Assert.AreSame(bar, testNativeToManagedMap.PropertyWithNoVirtualDtor);
Assert.IsTrue(quxMap.ContainsKey(bar.__Instance));
bar.Dispose();
Assert.IsFalse(quxMap.ContainsKey(bar.__Instance));
}
}
[Test]
public void TestCallingVirtualDtor()
{
CallDtorVirtually.Destroyed = false;
using (var callDtorVirtually = new CallDtorVirtually())
{
var hasVirtualDtor1 = CallDtorVirtually.GetHasVirtualDtor1(callDtorVirtually);
hasVirtualDtor1.Dispose();
}
Assert.That(CallDtorVirtually.Destroyed, Is.True);
}
[Test]
public void TestNonOwning()
{
CallDtorVirtually.Destroyed = false;
var nonOwned = CallDtorVirtually.NonOwnedInstance;
nonOwned.Dispose();
Assert.That(CallDtorVirtually.Destroyed, Is.False);
}
// Verify that the finalizer gets called if an instance is not disposed. Note that
// we've arranged to have the generator turn on finalizers for (just) the
// TestFinalizer class.
[Test]
public void TestFinalizerGetsCalledWhenNotDisposed()
{
using var callbackRegistration = new TestFinalizerDisposeCallbackRegistration();
var nativeAddr = CreateAndReleaseTestFinalizerInstance(false);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.That(callbackRegistration.NativeAddr, Is.EqualTo(nativeAddr));
Assert.That(callbackRegistration.IsDisposing, Is.False);
}
// Verify that the finalizer is not called if an instance is disposed. Note that we've
// arranged to have the generator turn on finalizers for (just) the TestFinalizer
// class.
[Test]
public void TestFinalizerNotCalledWhenDisposed()
{
using var callbackRegistration = new TestFinalizerDisposeCallbackRegistration();
var nativeAddr = CreateAndReleaseTestFinalizerInstance(true);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.That(callbackRegistration.NativeAddr, Is.EqualTo(nativeAddr));
Assert.That(callbackRegistration.IsDisposing, Is.True);
}
// Empirically, the finalizer won't release a reference until the stack frame in which
// the reference was created has been released. Use this method to create/release the
// instance.
private Int64 CreateAndReleaseTestFinalizerInstance(bool dispose)
{
var instance = new TestFinalizer();
Assert.That(instance.__Instance, !Is.EqualTo(IntPtr.Zero));
var nativeAddr = instance.__Instance.ToInt64();
if (dispose) instance.Dispose();
return nativeAddr;
}
class TestFinalizerDisposeCallbackRegistration : IDisposable
{
public bool? IsDisposing = null;
public long? NativeAddr = null;
public TestFinalizerDisposeCallbackRegistration()
{
TestFinalizer.DisposeCallback = (isDisposing, intPtr) =>
{
IsDisposing = isDisposing;
NativeAddr = intPtr.ToInt64();
};
}
public void Dispose() => TestFinalizer.DisposeCallback = null;
}
[Test]
public void TestParamTypeToInterfacePass()
{
var baseClass = new TestParamToInterfacePassBaseTwo();
baseClass++;
Assert.AreEqual(baseClass.M, 1);
ITestParamToInterfacePassBaseTwo baseInterface = new TestParamToInterfacePassBaseTwo();
var dervClass = new TestParamToInterfacePass();
dervClass.AddM(baseClass);
Assert.AreEqual(dervClass.M, 1);
dervClass = new TestParamToInterfacePass(dervClass + baseClass);
Assert.AreEqual(dervClass.M, 2);
dervClass = new TestParamToInterfacePass(dervClass + baseInterface);
Assert.AreEqual(dervClass.M, 2);
baseClass.Dispose();
}
[Test]
public unsafe void TestMultiOverLoadPtrToRef()
{
var r = 0;
MultiOverloadPtrToRef m = &r;
m.Dispose();
using (var obj = new MultiOverloadPtrToRef(ref r))
{
var p = obj.ReturnPrimTypePtr();
Assert.AreEqual(0, p[0]);
Assert.AreEqual(0, p[1]);
Assert.AreEqual(0, p[2]);
obj.TakePrimTypePtr(ref *p);
Assert.AreEqual(100, p[0]);
Assert.AreEqual(200, p[1]);
Assert.AreEqual(300, p[2]);
int[] array = { 1, 2, 3 };
fixed (int* p1 = array)
{
obj.TakePrimTypePtr(ref *p1);
Assert.AreEqual(100, p1[0]);
Assert.AreEqual(200, p1[1]);
Assert.AreEqual(300, p1[2]);
}
Assert.AreEqual(100, array[0]);
Assert.AreEqual(200, array[1]);
Assert.AreEqual(300, array[2]);
float pThree = 0;
var refInt = 0;
obj.FuncPrimitivePtrToRef(ref refInt, null, ref pThree);
obj.FuncPrimitivePtrToRefWithDefVal(ref refInt, null, null, ref refInt);
obj.FuncPrimitivePtrToRefWithMultiOverload(ref refInt, null, null, ref refInt);
}
}
[Test]
public void TestFixedArrayRefType()
{
Foo[] foos = new Foo[4];
foos[0] = new Foo { A = 5 };
foos[1] = new Foo { A = 6 };
foos[2] = new Foo { A = 7 };
foos[3] = new Foo { A = 8 };
Bar bar = new Bar { Foos = foos };
Foo[] retFoos = bar.Foos;
Assert.AreEqual(5, retFoos[0].A);
Assert.AreEqual(6, retFoos[1].A);
Assert.AreEqual(7, retFoos[2].A);
Assert.AreEqual(8, retFoos[3].A);
foreach (Foo foo in foos)
{
foo.Dispose();
}
Foo[] foosMore = new Foo[2];
foosMore[0] = new Foo();
foosMore[1] = new Foo();
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => bar.Foos = foosMore);
Assert.AreEqual("value", ex.ParamName);
string[] message = ex.Message.Split(
Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Assert.AreEqual("The dimensions of the provided array don't match the required size. (Parameter 'value')", message[0]);
foreach (Foo foo in foosMore)
{
foo.Dispose();
}
}
[Test]
public void TestOutTypeInterfacePassTry()
{
using (var interfaceClassObj = new TestParamToInterfacePassBaseTwo())
{
ITestParamToInterfacePassBaseTwo interfaceType = interfaceClassObj;
using (var obj = new TestOutTypeInterfaces())
{
obj.FuncTryInterfaceTypeOut(out interfaceType);
ITestParamToInterfacePassBaseTwo interfaceTypePtr;
obj.FuncTryInterfaceTypePtrOut(out interfaceTypePtr);
}
}
}
[Test]
public void TestConversionForCtorWithDefaultParams()
{
using (Foo foo = 15)
{
Assert.That(foo.A, Is.EqualTo(15));
}
}
[Test]
public unsafe void TestSizeOfDerivesFromTemplateInstantiation()
{
Assert.That(sizeof(DerivesFromTemplateInstantiation.__Internal), Is.EqualTo(sizeof(int)));
}
[Test]
public void TestReferenceToArrayWithConstSize()
{
int[] incorrectlySizedArray = { 1 };
Assert.Catch<ArgumentOutOfRangeException>(() => CSharp.CSharpCool.PassConstantArrayRef(incorrectlySizedArray));
int[] array = { 1, 2 };
var result = CSharp.CSharpCool.PassConstantArrayRef(array);
Assert.That(result, Is.EqualTo(array[0]));
}
[Test]
public void TestComparison()
{
var testComparison1 = new TestComparison { A = 5, B = 5.5f };
var testComparison2 = new TestComparison { A = 5, B = 5.5f };
Assert.IsTrue(testComparison1 == testComparison2);
Assert.IsTrue(testComparison1.Equals(testComparison2));
var testHashes = new Dictionary<TestComparison, int>();
testHashes[testComparison1] = 1;
testHashes[testComparison2] = 2;
Assert.That(testHashes[testComparison1], Is.EqualTo(2));
}
[Test]
public void TestOverriddenPropertyFromIndirectBase()
{
using (var overridePropertyFromIndirectPrimaryBase = new OverridePropertyFromIndirectPrimaryBase())
{
Assert.That(overridePropertyFromIndirectPrimaryBase.Property, Is.EqualTo(5));
}
}
[Test]
public void TestCallingVirtualBeforeCtorFinished()
{
using (new QApplication())
{
using (new QWidget())
{
}
}
}
[Test]
public void TestMultipleInheritanceFieldOffsets()
{
using (var multipleInheritanceFieldOffsets = new MultipleInheritanceFieldOffsets())
{
Assert.That(multipleInheritanceFieldOffsets.Primary, Is.EqualTo(1));
Assert.That(multipleInheritanceFieldOffsets.Secondary, Is.EqualTo(2));
Assert.That(multipleInheritanceFieldOffsets.Own, Is.EqualTo(3));
}
}
[Test]
public void TestVirtualDtorAddedInDerived()
{
using (new VirtualDtorAddedInDerived())
{
}
Assert.IsTrue(VirtualDtorAddedInDerived.DtorCalled);
}
[Test]
public void TestGetEnumFromNativePointer()
{
using (var getEnumFromNativePointer = new GetEnumFromNativePointer())
{
Assert.That(UsesPointerToEnumInParamOfVirtual.CallOverrideOfHasPointerToEnumInParam(
getEnumFromNativePointer, Flags.Flag3), Is.EqualTo(Flags.Flag3));
}
}
[Test]
public void TestStdStringConstant()
{
Assert.That(CSharp.HasFreeConstant.AnotherUnitCool.STD_STRING_CONSTANT, Is.EqualTo("test"));
// check a second time to ensure it hasn't been improperly freed
Assert.That(CSharp.HasFreeConstant.AnotherUnitCool.STD_STRING_CONSTANT, Is.EqualTo("test"));
}
[Test]
public void TestZeroAllocatedMemoryOption()
{
// We've arranged in the generator for the ZeroAllocatedMemory option to return true for this one
// class.
var test = new ClassZeroAllocatedMemoryTest();
Assert.That(test.P1, Is.EqualTo(0));
Assert.That(test.p2.P2p1, Is.EqualTo(0));
Assert.That(test.p2.P2p2, Is.EqualTo(0));
Assert.That(test.P3, Is.EqualTo(false));
Assert.That(test.P4, Is.EqualTo('\0'));
}
[Test]
public void TestAlignment()
{
foreach (var internalType in new[]
{
typeof(CSharp.IndependentFields.__Internal),
typeof(CSharp.DependentValueFields.__Internalc__S_DependentValueFields__b),
typeof(CSharp.DependentValueFields.__Internalc__S_DependentValueFields__f),
typeof(CSharp.DependentPointerFields.__Internal),
typeof(CSharp.DependentValueFields.__Internal_Ptr),
typeof(CSharp.HasDefaultTemplateArgument.__Internalc__S_HasDefaultTemplateArgument__I___S_IndependentFields__I)
})
{
var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
var fieldOffset = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffset != null)
Assert.That(fieldOffset.Value, Is.EqualTo(0));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0));
Assert.That(Marshal.SizeOf(internalType), Is.EqualTo(internalType.StructLayoutAttribute.Size));
}
foreach (var internalType in new Type[]
{
typeof(CSharp.TwoTemplateArgs.__Internal_Ptr),
typeof(CSharp.TwoTemplateArgs.__Internalc__S_TwoTemplateArgs___I_I),
typeof(CSharp.TwoTemplateArgs.__Internalc__S_TwoTemplateArgs___I_f)
})
{
var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(independentFields.Length, Is.EqualTo(2));
var fieldOffsetKey = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffsetKey != null)
Assert.That(fieldOffsetKey.Value, Is.EqualTo(0));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0));
var fieldOffsetValue = (FieldOffsetAttribute)independentFields[1].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffsetValue != null)
Assert.That(fieldOffsetValue.Value, Is.EqualTo(Marshal.SizeOf(IntPtr.Zero)));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[1].Name), Is.EqualTo(Marshal.SizeOf(IntPtr.Zero)));
Assert.That(Marshal.SizeOf(internalType), Is.EqualTo(internalType.StructLayoutAttribute.Size));
}
foreach (var (type, offsets) in new (Type, uint[])[] {
(typeof(ClassCustomTypeAlignment), CSharp.CSharpCool.ClassCustomTypeAlignmentOffsets),
(typeof(ClassCustomObjectAlignment), CSharp.CSharpCool.ClassCustomObjectAlignmentOffsets),
(typeof(ClassMicrosoftObjectAlignment), CSharp.CSharpCool.ClassMicrosoftObjectAlignmentOffsets),
(typeof(StructWithEmbeddedArrayOfStructObjectAlignment), CSharp.CSharpCool.StructWithEmbeddedArrayOfStructObjectAlignmentOffsets),
})
{
var internalType = type.GetNestedType("__Internal");
var managedOffsets = internalType
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.SkipWhile(x => x.FieldType == typeof(IntPtr))
.Where(x => !x.Name.EndsWith("Padding"))
.Select(field => (uint)Marshal.OffsetOf(internalType, field.Name));
Assert.That(managedOffsets, Is.EqualTo(offsets));
Assert.That(Marshal.SizeOf(internalType), Is.EqualTo(internalType.StructLayoutAttribute.Size));
}
}
[Test]
public void TestEmbeddedArrayOfStructAccessor()
{
const ulong firstLong = 0xC92EEDE87AAB4FECul;
const ulong secondLong = 0xAD5FB16491935522ul;
var testStruct = new StructWithEmbeddedArrayOfStructObjectAlignment();
testStruct.EmbeddedStruct[0].Ui64 = firstLong;
testStruct.EmbeddedStruct[1].Ui64 = secondLong;
// Since the memory allocated for EmbeddedStruct is generally uninintialized, I suppose it _could_
// just happen to match, but it seems very unlikely.
Assert.That(firstLong, Is.EqualTo(testStruct.EmbeddedStruct[0].Ui64));
Assert.That(secondLong, Is.EqualTo(testStruct.EmbeddedStruct[1].Ui64));
}
public void TestClassSize()
{
Assert.That(Marshal.SizeOf<HasSecondaryBaseWithAbstractWithDefaultArg.__Internal>, Is.EqualTo(Marshal.SizeOf<IntPtr>() * 2));
}
[Test]
public void TestConstantArray()
{
Assert.That(CSharp.CSharpCool.VariableWithFixedPrimitiveArray[0], Is.EqualTo(5));
Assert.That(CSharp.CSharpCool.VariableWithFixedPrimitiveArray[1], Is.EqualTo(10));
Assert.That(CSharp.CSharpCool.VariableWithVariablePrimitiveArray[0], Is.EqualTo(15));
Assert.That(CSharp.CSharpCool.VariableWithVariablePrimitiveArray[1], Is.EqualTo(20));
}
[Test]
public void TestStaticVariables()
{
Assert.That(StaticVariables.Boolean, Is.EqualTo(true));
Assert.That(StaticVariables.Chr, Is.EqualTo('G'));
Assert.That(StaticVariables.UChr, Is.EqualTo('G'));
Assert.That(StaticVariables.Int, Is.EqualTo(1020304050));
Assert.That(StaticVariables.Float, Is.EqualTo(0.5020f));
Assert.That(StaticVariables.String, Is.EqualTo("Str"));
Assert.That(StaticVariables.ChrArray, Is.EqualTo(new[] { 'A', 'B' }));
Assert.That(StaticVariables.IntArray, Is.EqualTo(new[] { 1020304050, 1526374850 }));
Assert.That(StaticVariables.FloatArray, Is.EqualTo(new[] { 0.5020f, 0.6020f }));
Assert.That(StaticVariables.BoolArray, Is.EqualTo(new[] { false, true }));
Assert.That(StaticVariables.VoidPtrArray, Is.EqualTo(new IntPtr[] { new IntPtr(0x10203040), new IntPtr(0x40302010) }));
}
[Test]
public void TestVariableInitializer()
{
Assert.That(VariablesWithInitializer.Boolean, Is.EqualTo(true));
Assert.That(VariablesWithInitializer.Chr, Is.EqualTo('G'));
Assert.That(VariablesWithInitializer.UChr, Is.EqualTo('G'));
Assert.That(VariablesWithInitializer.Int, Is.EqualTo(1020304050));
Assert.That(VariablesWithInitializer.IntSum, Is.EqualTo(VariablesWithInitializer.Int + 500));
Assert.That(VariablesWithInitializer.Float, Is.EqualTo(0.5020f));
Assert.That(VariablesWithInitializer.Double, Is.EqualTo(0.700020235));
Assert.That(VariablesWithInitializer.DoubleSum, Is.EqualTo(0.700020235 + 23.17376));
Assert.That(VariablesWithInitializer.DoubleFromConstexprFunction, Is.EqualTo(0.700020235 + 23.17376));
Assert.That(VariablesWithInitializer.Int64, Is.EqualTo(602030405045));
Assert.That(VariablesWithInitializer.UInt64, Is.EqualTo(9602030405045));
Assert.That(VariablesWithInitializer.String, Is.EqualTo("Str"));
Assert.That(VariablesWithInitializer.WideString, Is.EqualTo("Str"));
Assert.That(VariablesWithInitializer.StringArray1, Is.EqualTo(new[] { "StrF,\"or" }));
Assert.That(VariablesWithInitializer.StringArray3, Is.EqualTo(new[] { "StrF,\"or", "C#", VariablesWithInitializer.String }));
Assert.That(VariablesWithInitializer.StringArray30, Is.EqualTo(new[] {
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str"}));
Assert.That(VariablesWithInitializer.StringArray3EmptyInitList, Is.EqualTo(new[] { "", "", "" }));
Assert.That(VariablesWithInitializer.WideStringArray, Is.EqualTo(new[] { "Str", "C#" }));
Assert.That(VariablesWithInitializer.ChrArray, Is.EqualTo(new[] { 'A', 'B' }));
Assert.That(VariablesWithInitializer.IntArray, Is.EqualTo(new[] { 1020304050, 1526374850 }));
Assert.That(VariablesWithInitializer.IntArray3, Is.EqualTo(new[] { 1020304050, 1526374850, default }));
Assert.That(VariablesWithInitializer.FloatArray, Is.EqualTo(new[] { 0.5020f, 0.6020f }));
Assert.That(VariablesWithInitializer.BoolArray, Is.EqualTo(new[] { false, true }));
}
[Test]
public void TestIndirectVariableInitializer()
{
// The actual test is that the generator doesn't throw when generating
// IndependentStringVariable. If we're running the test, we must have
// generated CSharp.cs without crashing the generator.
Assert.That(MoreVariablesWithInitializer.DependentStringVariable, Is.EqualTo(MoreVariablesWithInitializer.IndependentStringVariable));
}
[Test]
public void TestPointerPassedAsItsSecondaryBase()
{
using (QApplication application = new QApplication())
{
using (QWidget widget = new QWidget())
{
using (QPainter painter = new QPainter(widget))
{
Assert.That(widget.Test, Is.EqualTo(5));
}
}
}
}
[Test]
public void TestUnicode()
{
using (var testString = new TestString())
{
Assert.That(testString.UnicodeConst, Is.EqualTo("ქართული ენა"));
}
}
[Test]
public void TestStringMemManagement()
{
const int instanceCount = 100;
const string otherString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
var batch = new TestString[instanceCount];
for (var i = 0; i < instanceCount; i++)
{
batch[i] = new TestString { UnicodeConst = otherString };
if (batch[i].UnicodeConst != otherString)
{
throw new Exception($"iteration {i}");
}
}
GC.Collect();
for (var i = 0; i < instanceCount; i++)
{
if (batch[i].UnicodeConst != otherString)
{
throw new Exception($"iteration {i}");
}
Assert.That(batch[i].UnicodeConst, Is.EqualTo(otherString));
}
Array.ForEach(batch, ts => ts.Dispose());