-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathBuildTest2.cs
More file actions
2223 lines (1986 loc) · 85.6 KB
/
BuildTest2.cs
File metadata and controls
2223 lines (1986 loc) · 85.6 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Build.Framework;
using Mono.Cecil;
using NUnit.Framework;
using Xamarin.Android.Tasks;
using Xamarin.Android.Tools;
using Xamarin.ProjectTools;
using Microsoft.Android.Build.Tasks;
namespace Xamarin.Android.Build.Tests
{
[Parallelizable (ParallelScope.Children)]
public partial class BuildTest2 : BaseTest
{
static object [] MarshalMethodsDefaultStatusSource = new object [] {
new object[] {
/* isRelease */ true,
/* marshalMethodsEnabled */ false,
},
new object[] {
/* isRelease */ true,
/* marshalMethodsEnabled */ true,
},
new object[] {
/* isRelease */ false,
/* marshalMethodsEnabled */ true,
},
};
// TODO: at some point it should work for CoreCLR, after its managed marshal methods are fixed
[Test]
[TestCaseSource (nameof (MarshalMethodsDefaultStatusSource))]
public void MarshalMethodsDefaultEnabledStatus (bool isRelease, bool marshalMethodsEnabled)
{
var abis = new [] { "armeabi-v7a", "x86" };
AndroidTargetArch[] supportedArches = new [] {
AndroidTargetArch.Arm,
AndroidTargetArch.X86,
};
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
EnableMarshalMethods = marshalMethodsEnabled,
};
// MonoVM-only test
proj.SetRuntime (Android.Tasks.AndroidRuntime.MonoVM);
proj.SetRuntimeIdentifiers (abis);
bool shouldMarshalMethodsBeEnabled = isRelease && marshalMethodsEnabled;
using (var b = CreateApkBuilder ()) {
b.Verbosity = LoggerVerbosity.Diagnostic;
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
Assert.IsTrue (
StringAssertEx.ContainsText (b.LastBuildOutput, $"_AndroidUseMarshalMethods = {shouldMarshalMethodsBeEnabled}"),
$"The '_AndroidUseMarshalMethods' MSBuild property should have had the value of '{shouldMarshalMethodsBeEnabled}'"
);
string objPath = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
List<EnvironmentHelper.EnvironmentFile> envFiles = EnvironmentHelper.GatherEnvironmentFiles (
objPath,
String.Join (";", supportedArches.Select (arch => MonoAndroidHelper.ArchToAbi (arch))),
true
);
var app_config = (EnvironmentHelper.ApplicationConfig_MonoVM)EnvironmentHelper.ReadApplicationConfig (envFiles, Android.Tasks.AndroidRuntime.MonoVM);
Assert.That (app_config, Is.Not.Null, "application_config must be present in the environment files");
Assert.AreEqual (app_config.marshal_methods_enabled, shouldMarshalMethodsBeEnabled, $"Marshal methods enabled status should be '{shouldMarshalMethodsBeEnabled}', but it was '{app_config.marshal_methods_enabled}'");
}
}
// TODO: fix for CoreCLR
// Currently it fails with:
//
// Microsoft.Android.Sdk.AssemblyResolution.targets(198,5): error MSB4096: The item "obj/Release/UnnamedProject.pdb" in item list "ResolvedSymbols" does not define a value for metadata "DestinationSubPath". In order to use this metadata, either qualify it by specifying %(ResolvedSymbols.DestinationSubPath), or ensure that all items in this list define a value for this metadata.
[Test]
public void CompressedWithoutLinker ()
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true
};
// Mono-only test, at least for now
proj.SetRuntime (AndroidRuntime.MonoVM);
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkMode, AndroidLinkMode.None.ToString ());
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
}
}
[Test]
public void BuildBasicApplication ([Values] bool isRelease, [Values ("", "en_US.UTF-8", "sv_SE.UTF-8")] string langEnvironmentVariable, [Values] AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
Dictionary<string, string>? envvar = null;
if (!String.IsNullOrEmpty (langEnvironmentVariable)) {
envvar = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase) {
{"LANG", langEnvironmentVariable},
};
}
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj, environmentVariables: envvar), "Build should have succeeded.");
}
}
[Test]
public void BasicApplicationPublishReadyToRun ([Values] bool isComposite, [Values ("android-x64", "android-arm64")] string rid)
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true, // Enables R2R by default
};
proj.SetRuntime (AndroidRuntime.CoreCLR);
proj.SetProperty ("RuntimeIdentifier", rid);
proj.SetProperty ("AndroidEnableAssemblyCompression", "false");
proj.SetProperty ("PublishReadyToRunComposite", isComposite.ToString ());
var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var assemblyName = proj.ProjectName;
var apk = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, rid, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
var helper = new ArchiveAssemblyHelper (apk, true);
var abi = MonoAndroidHelper.RidToAbi (rid);
Assert.IsTrue (helper.Exists ($"assemblies/{abi}/{assemblyName}.dll"), $"{assemblyName}.dll should exist in apk!");
using var stream = helper.ReadEntry ($"assemblies/{assemblyName}.dll");
stream.Position = 0;
using var peReader = new System.Reflection.PortableExecutable.PEReader (stream);
Assert.IsTrue (peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size > 0,
$"ReadyToRun image not found in {assemblyName}.dll! ManagedNativeHeaderDirectory should not be empty!");
}
[Test]
public void NativeAOT ()
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
ProjectName = "Hello",
};
proj.SetRuntime (AndroidRuntime.NativeAOT);
proj.SetProperty ("_ExtraTrimmerArgs", "--verbose");
// Required for java/util/ArrayList assertion below
proj.MainActivity = proj.DefaultMainActivity
.Replace ("//${AFTER_ONCREATE}", "new Android.Runtime.JavaList (); new Android.Runtime.JavaList<int> ();");
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
b.Output.AssertTargetIsNotSkipped ("_PrepareLinking");
string [] mono_classes = [
"Lmono/MonoRuntimeProvider;",
];
string[] mono_files = [
"lib/arm64-v8a/libmonosgen-2.0.so",
"lib/x86_64/libmonosgen-2.0.so",
];
string [] nativeaot_files = [
$"lib/arm64-v8a/lib{proj.ProjectName}.so",
$"lib/x86_64/lib{proj.ProjectName}.so",
];
var intermediate = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
var output = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath);
var linkedMonoAndroidAssembly = Path.Combine (intermediate, "android-arm64", "linked", "Mono.Android.dll");
FileAssert.Exists (linkedMonoAndroidAssembly);
var javaClassNames = new List<string> ();
var types = new List<TypeReference> ();
using (var assembly = AssemblyDefinition.ReadAssembly (linkedMonoAndroidAssembly)) {
var typeName = "Android.App.Activity";
var methodName = "GetOnCreate_Landroid_os_Bundle_Handler";
var type = assembly.MainModule.GetType (typeName);
Assert.IsNotNull (type, $"{linkedMonoAndroidAssembly} should contain {typeName}");
var method = type.Methods.FirstOrDefault (m => m.Name == methodName);
Assert.IsNotNull (method, $"{linkedMonoAndroidAssembly} should contain {typeName}.{methodName}");
type = assembly.MainModule.Types.FirstOrDefault (t => t.Name == "ManagedTypeMapping");
Assert.IsNotNull (type, $"{linkedMonoAndroidAssembly} should contain ManagedTypeMapping");
method = type.Methods.FirstOrDefault (m => m.Name == "GetJniNameByTypeNameHashIndex");
Assert.IsNotNull (method, $"{type.Name} should contain GetJniNameByTypeNameHashIndex");
foreach (var i in method.Body.Instructions) {
if (i.OpCode != Mono.Cecil.Cil.OpCodes.Ldstr)
continue;
if (i.Operand is not string javaName)
continue;
if (i.Next.OpCode != Mono.Cecil.Cil.OpCodes.Ret)
continue;
javaClassNames.Add (javaName);
}
method = type.Methods.FirstOrDefault (m => m.Name == "GetTypeByJniNameHashIndex");
Assert.IsNotNull (method, $"{type.Name} should contain GetTypeByJniNameHashIndex");
foreach (var i in method.Body.Instructions) {
if (i.OpCode != Mono.Cecil.Cil.OpCodes.Ldtoken)
continue;
if (i.Operand is not TypeReference typeReference)
continue;
if (i.Next?.OpCode != Mono.Cecil.Cil.OpCodes.Call)
continue;
if (i.Next.Next?.OpCode != Mono.Cecil.Cil.OpCodes.Ret)
continue;
types.Add (typeReference);
}
// Basic types
AssertTypeMap ("java/lang/Object", "Java.Lang.Object");
AssertTypeMap ("java/lang/String", "Java.Lang.String");
AssertTypeMap ("[Ljava/lang/Object;", "Java.Interop.JavaArray`1");
AssertTypeMap ("java/util/ArrayList", "Android.Runtime.JavaList");
AssertTypeMap ("android/app/Activity", "Android.App.Activity");
AssertTypeMap ("android/widget/Button", "Android.Widget.Button");
Assert.IsFalse (StringAssertEx.ContainsText (b.LastBuildOutput,
"Duplicate typemap entry for java/util/ArrayList => Android.Runtime.JavaList`1"),
"Should get log message about duplicate Android.Runtime.JavaList`1!");
// Special *Invoker case
AssertTypeMap ("android/view/View$OnClickListener", "Android.Views.View/IOnClickListener");
Assert.IsFalse (StringAssertEx.ContainsText (b.LastBuildOutput,
"Duplicate typemap entry for android/view/View$OnClickListener => Android.Views.View/IOnClickListenerInvoker"),
"Should get log message about duplicate IOnClickListenerInvoker!");
}
// Verify that Java stubs for Mono.Android.dll were generated, instead of using mono.android.jar/dex
var onLayoutChangeListenerImplementor = Path.Combine (intermediate, "android", "src", "mono", "android", "view", "View_OnClickListenerImplementor.java");
FileAssert.Exists (onLayoutChangeListenerImplementor);
var dexFile = Path.Combine (intermediate, "android", "bin", "classes.dex");
FileAssert.Exists (dexFile);
foreach (var className in mono_classes) {
Assert.IsFalse (DexUtils.ContainsClassWithMethod (className, "<init>", "()V", dexFile, AndroidSdkPath), $"`{dexFile}` should *not* include `{className}`!");
}
var apkFile = Path.Combine (output, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apkFile);
using var zip = ZipHelper.OpenZip (apkFile);
foreach (var mono_file in mono_files) {
Assert.IsFalse (zip.ContainsEntry (mono_file, caseSensitive: true), $"APK must *not* contain `{mono_file}`.");
}
foreach (var nativeaot_file in nativeaot_files) {
Assert.IsTrue (zip.ContainsEntry (nativeaot_file, caseSensitive: true), $"APK must contain `{nativeaot_file}`.");
}
void AssertTypeMap(string javaName, string managedName)
{
var javaNameIndex = javaClassNames.FindIndex (name => name == javaName);
var typeIndex = types.FindIndex (td => td.ToString() == managedName);
if (javaNameIndex < 0) {
Assert.Fail ($"TypeMapping should contain \"{javaName}\"!");
} else if (typeIndex < 0) {
Assert.Fail ($"TypeMapping should contain \"{managedName}\"!");
}
}
}
[Test]
public void BuildBasicApplicationThenMoveIt ([Values] bool isRelease, [Values] AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
string path = Path.Combine (Root, "temp", TestName, "App1");
var proj = new XamarinAndroidApplicationProject {
ProjectName = "App",
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder (path)) {
b.Target = "Build";
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
b.Target = "SignAndroidPackage";
Assert.IsTrue (b.Build (proj), "SignAndroidPackage should have succeeded.");
string path2 = Path.Combine (Root, "temp", TestName, "App2");
if (Directory.Exists (path2))
Directory.Delete (path2, recursive: true);
Directory.Move (path, path2);
b.ProjectDirectory = path2;
foreach (var r in proj.AndroidResources)
r.Timestamp = DateTime.UtcNow;
b.Target = "Build";
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "Build should have succeeded.");
Assert.IsTrue (!b.Output.IsTargetSkipped ("_CleanIntermediateIfNeeded"), "_CleanIntermediateIfNeeded should be built.");
Assert.IsTrue (!b.Output.IsTargetSkipped ("_CompileResources"), "_CompileResources Should have built.");
b.Target = "SignAndroidPackage";
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "SignAndroidPackage should have succeeded.");
}
}
public static string GetLinkedPath (ProjectBuilder builder, bool isRelease, string filename)
{
return isRelease ?
builder.Output.GetIntermediaryPath (Path.Combine ("android-arm64", "linked", filename)) :
builder.Output.GetIntermediaryPath (Path.Combine ("android", "assets", filename));
}
[Test]
public void BuildReleaseArm64 ([Values] bool forms, [Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = forms ?
new XamarinFormsAndroidApplicationProject () :
new XamarinAndroidApplicationProject ();
proj.SetRuntime (runtime);
proj.IsRelease = isRelease;
proj.AotAssemblies = false; // Release defaults to Profiled AOT for .NET 6
proj.SetAndroidSupportedAbis ("arm64-v8a");
proj.SetProperty ("LinkerDumpDependencies", "True");
proj.SetProperty ("AndroidUseAssemblyStore", "False");
var flavor = (forms ? "XForms" : "Simple") + "DotNet" + "." + runtime.ToString ();
var apkDescFilename = $"BuildReleaseArm64{flavor}.apkdesc";
var apkDescReference = "reference.apkdesc";
byte [] apkDescData = XamarinAndroidCommonProject.GetResourceContents ($"Xamarin.ProjectTools.Resources.Base.{apkDescFilename}");
proj.OtherBuildItems.Add (new BuildItem ("ApkDescFile", apkDescReference) { BinaryContent = () => apkDescData });
// use BuildHelper.CreateApkBuilder so that the test directory is not removed in tearup
using (var b = BuildHelper.CreateApkBuilder (Path.Combine ("temp", TestName))) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var depsFile = GetLinkedPath (b, true, "linker-dependencies.xml");
FileAssert.Exists (depsFile);
const int ApkSizeThreshold = 5 * 1024;
const int AssemblySizeThreshold = 5 * 1024;
const int ApkPercentChangeThreshold = 3;
const int FilePercentChangeThreshold = 5;
var regressionCheckArgs = $"--test-apk-size-regression={ApkSizeThreshold} --test-assembly-size-regression={AssemblySizeThreshold}";
//TODO Only make these checks more lenient during early previews. Report if any files increase by more than 5% or if the package size increases by more than 3%
regressionCheckArgs = $"--test-apk-percentage-regression=\"{ApkPercentChangeThreshold}\" --test-content-percentage-regression=\"{FilePercentChangeThreshold}\"";
var apkFile = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, proj.PackageName + "-Signed.apk");
var apkDescPath = Path.Combine (Root, apkDescFilename);
var apkDescReferencePath = Path.Combine (Root, b.ProjectDirectory, apkDescReference);
var (code, stdOut, stdErr) = RunApkDiffCommand ($"-s --save-description-2={apkDescPath} --descrease-is-regression {regressionCheckArgs} {apkDescReferencePath} {apkFile}", Path.Combine (Root, b.ProjectDirectory, "apkdiff.log"));
Assert.IsTrue (code == 0, $"apkdiff regression test failed with exit code: {code}. See test attachments.");
}
}
static IEnumerable<object[]> Get_BuildHasNoWarningsData ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
AddTestData (
isRelease: false,
xamarinForms: false,
multidex: false,
packageFormat: "apk",
runtime
);
AddTestData (
isRelease: false,
xamarinForms: true,
multidex: false,
packageFormat: "apk",
runtime
);
AddTestData (
isRelease: false,
xamarinForms: true,
multidex: true,
packageFormat: "apk",
runtime
);
AddTestData (
isRelease: true,
xamarinForms: false,
multidex: false,
packageFormat: "apk",
runtime
);
AddTestData (
isRelease: true,
xamarinForms: true,
multidex: false,
packageFormat: "apk",
runtime
);
AddTestData (
isRelease: false,
xamarinForms: false,
multidex: false,
packageFormat: "aab",
runtime
);
AddTestData (
isRelease: true,
xamarinForms: false,
multidex: false,
packageFormat: "aab",
runtime
);
}
return ret;
void AddTestData (bool isRelease, bool xamarinForms, bool multidex, string packageFormat, AndroidRuntime runtime)
{
ret.Add (new object[] {
isRelease,
xamarinForms,
multidex,
packageFormat,
runtime
});
}
}
[Test]
[TestCaseSource (nameof (Get_BuildHasNoWarningsData))]
public void BuildHasNoWarnings (bool isRelease, bool xamarinForms, bool multidex, string packageFormat, AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = xamarinForms ?
new XamarinFormsAndroidApplicationProject () :
new XamarinAndroidApplicationProject ();
proj.IsRelease = isRelease;
proj.SetRuntime (runtime);
// Enable full trimming
if (!xamarinForms && isRelease) {
proj.TrimModeRelease = TrimMode.Full;
}
if (multidex) {
proj.SetProperty ("AndroidEnableMultiDex", "True");
}
if (packageFormat == "aab") {
// Disable fast deployment for aabs, because we give:
// XA0119: Using Fast Deployment and Android App Bundles at the same time is not recommended.
proj.EmbedAssembliesIntoApk = true;
}
// FIXME: Precompiling failed for TraceReloggerLib.dll, Dia2Lib.dll with exit code 1
if (!isRelease)
proj.PackageReferences.Add (new Package { Id = "BenchmarkDotNet", Version = "0.13.1" });
proj.SetProperty ("XamarinAndroidSupportSkipVerifyVersions", "True"); // Disables API 29 warning in Xamarin.Build.Download
proj.SetProperty ("AndroidPackageFormat", packageFormat);
proj.SetProperty ("TrimmerSingleWarn", "false");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
if (runtime == AndroidRuntime.NativeAOT) {
int numberOfExpectedWarnings;
bool validateWarnings;
if (xamarinForms && !multidex && packageFormat == "apk") {
// NativeAOT goes nuts here (Nov 2025) with 120 different ILC warnings, too many to verify them here in a way that makes sense
numberOfExpectedWarnings = 120;
validateWarnings = false;
} else {
// NativeAOT currently (Nov 2025) produces 6 `ILC : AOT analysis warning IL3050` warnings for various
// bits of code. Even though this test expects no warnings and the above likely make the app not work
// correctly at run time, it is still worth running this test under NativeAOT to test for the absence
// of other warnings.
numberOfExpectedWarnings = 6;
validateWarnings = true;
}
Assert.IsTrue (
StringAssertEx.ContainsText (
b.LastBuildOutput,
$" {numberOfExpectedWarnings} Warning(s)"
),
$"{b.BuildLogFile} should have exactly {numberOfExpectedWarnings} MSBuild warnings for NativeAOT."
);
if (validateWarnings) {
const string expectedWarningIL3050 = "ILC : AOT analysis warning IL3050:";
var warnings = b.LastBuildOutput.SkipWhile (x => !x.StartsWith ("Build succeeded.", StringComparison.Ordinal)).Where (x => x.Contains (expectedWarningIL3050, StringComparison.Ordinal));
Assert.IsTrue (warnings.Count () == numberOfExpectedWarnings, $"Expected {numberOfExpectedWarnings} 'IL3050' warnings, found {warnings.Count ()}");
}
} else {
b.AssertHasNoWarnings ();
}
Assert.IsFalse (StringAssertEx.ContainsText (b.LastBuildOutput, "Warning: end of file not at end of a line"),
"Should not get a warning from the <CompileNativeAssembly/> task.");
var lockFile = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, ".__lock");
FileAssert.DoesNotExist (lockFile);
}
}
static IEnumerable<object[]> Get_BuildHasTrimmerWarningsData ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
AddTestData (runtime, "", new string [0], false);
if (runtime == AndroidRuntime.NativeAOT) {
AddTestData (runtime, "", new [] { "IL2055", "IL3050" }, true, 2);
} else {
AddTestData (runtime, "", new string [0], true);
}
AddTestData (runtime, "SuppressTrimAnalysisWarnings=false", new string [] { "IL2055" }, true, 2);
AddTestData (runtime, "TrimMode=full", new string [] { "IL2055" }, false, 1);
AddTestData (runtime, "TrimMode=full", new string [] { "IL2055" }, true, 2);
AddTestData (runtime, "IsAotCompatible=true", new string [] { "IL2055", "IL3050" }, false);
if (runtime == AndroidRuntime.NativeAOT) {
AddTestData (runtime, "IsAotCompatible=true", new string [] { "IL2055", "IL3050" }, true, 2);
} else {
AddTestData (runtime, "IsAotCompatible=true", new string [] { "IL2055", "IL3050" }, true, 3);
}
}
return ret;
void AddTestData (AndroidRuntime runtime, string properties, string [] codes, bool isRelease, int? totalWarnings = null)
{
ret.Add (new object[] {
runtime,
properties,
codes,
isRelease,
totalWarnings,
});
}
}
[Test]
[TestCaseSource (nameof (Get_BuildHasTrimmerWarningsData))]
public void BuildHasTrimmerWarnings (AndroidRuntime runtime, string properties, string [] codes, bool isRelease, int? totalWarnings = null)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
if (runtime == AndroidRuntime.NativeAOT) {
// We're not interested in ILC warnings here, just the trimmer warnings before ILC runs
var ignoreIlcWarnings = new List<BuildItem> {
new ("IlcArg", "--notrimwarn"),
new ("IlcArg", "--noaotwarn"),
};
proj.ItemGroupList.Add (ignoreIlcWarnings);
}
proj.SetRuntimeIdentifier ("arm64-v8a");
proj.MainActivity = proj.DefaultMainActivity
.Replace ("//${FIELDS}", "Type type = typeof (List<>);")
.Replace ("//${AFTER_ONCREATE}", "Console.WriteLine (type.MakeGenericType (typeof (object)));");
proj.SetProperty ("TrimmerSingleWarn", "false");
if (!string.IsNullOrEmpty (properties)) {
foreach (var property in properties.Split (';')) {
int index = property.IndexOf ('=');
if (index != -1) {
proj.SetProperty (property [..index], property [(index + 1)..]);
}
}
}
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
if (codes.Length == 0) {
b.AssertHasNoWarnings ();
} else {
totalWarnings ??= codes.Length;
Assert.True (StringAssertEx.ContainsText (b.LastBuildOutput, $"{totalWarnings} Warning(s)"), $"Should receive {totalWarnings} warnings");
foreach (var code in codes) {
Assert.True (StringAssertEx.ContainsText (b.LastBuildOutput, code), $"Should receive {code} warning");
}
}
}
[Test]
public void XA0141ErrorIsRaised ([Values] bool isRelease, [Values] AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
PackageReferences = {
KnownPackages.SkiaSharp,
KnownPackages.AndroidXAppCompat,
KnownPackages.AndroidXAppCompatResources,
},
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
Assert.IsTrue (StringAssertEx.ContainsText (b.LastBuildOutput, "XA0141"),
"Error XA0141 should have been raised.");
Assert.IsTrue (StringAssertEx.ContainsText (b.LastBuildOutput, $"NuGet package 'SkiaSharp.NativeAssets.Android' version '{KnownPackages.SkiaSharp.Version}' "), "Warning does not have the correct Nuget package information.");
}
}
static IEnumerable<object[]> Get_XA1037PropertyDeprecatedWarningData ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
AddTestData ("AndroidFastDeploymentType", "Assemblies", true, false, runtime);
AddTestData ("AndroidFastDeploymentType", "Assemblies", false, false, runtime);
AddTestData ("_AndroidUseJavaLegacyResolver", "true", false, true, runtime);
AddTestData ("_AndroidUseJavaLegacyResolver", "true", true, true, runtime);
AddTestData ("_AndroidEmitLegacyInterfaceInvokers", "true", false, true, runtime);
AddTestData ("_AndroidEmitLegacyInterfaceInvokers", "true", true, true, runtime);
}
return ret;
void AddTestData (string property, string value, bool isRelease, bool isBindingProject, AndroidRuntime runtime)
{
ret.Add (new object[] {
property,
value,
isRelease,
isBindingProject,
runtime,
});
}
}
[Test]
[TestCaseSource (nameof (Get_XA1037PropertyDeprecatedWarningData))]
public void XA1037PropertyDeprecatedWarning (string property, string value, bool isRelease, bool isBindingProject, AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
XamarinAndroidProject proj = isBindingProject ? new XamarinAndroidBindingProject () : new XamarinAndroidApplicationProject ();
proj.IsRelease = isRelease;
proj.SetProperty (property, value);
proj.SetRuntime (runtime);
using (ProjectBuilder b = isBindingProject ? CreateDllBuilder () : CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
Assert.IsTrue (StringAssertEx.ContainsText (b.LastBuildOutput, $"The '{property}' MSBuild property is deprecated and will be removed"),
$"Should not get a warning about the {property} property");
}
}
[Test]
public void ClassLibraryHasNoWarnings ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidLibraryProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
//NOTE: these properties should not affect class libraries at all
proj.SetProperty ("AndroidPackageFormat", "aab");
proj.SetProperty ("AotAssemblies", "true");
proj.SetProperty ("AndroidEnableMultiDex", "true");
using (var b = CreateDllBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
b.AssertHasNoWarnings ();
// $(AndroidEnableMultiDex) should not add android-support-multidex.jar!
var aarPath = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, $"{proj.ProjectName}.aar");
using var zip = Xamarin.Tools.Zip.ZipArchive.Open (aarPath, FileMode.Open);
Assert.IsFalse (zip.Any (e => e.FullName.EndsWith (".jar", StringComparison.OrdinalIgnoreCase)),
$"{aarPath} should not contain a .jar file!");
}
}
[Test]
public void BuildBasicApplicationWithNuGetPackageConflicts ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
PackageReferences = {
new Package () {
Id = "System.Buffers",
Version = "4.4.0",
TargetFramework = "monoandroid90",
},
new Package () {
Id = "System.Memory",
Version = "4.5.1",
TargetFramework = "monoandroid90",
},
}
};
proj.SetRuntime (runtime);
proj.Sources.Add (new BuildItem ("Compile", "IsAndroidDefined.fs") {
TextContent = () => @"
using System;
class MemTest {
static void Test ()
{
var x = new Memory<int> ().Length;
Console.WriteLine (x);
var array = new byte [100];
var arraySpan = new Span<byte> (array);
Console.WriteLine (arraySpan.IsEmpty);
}
}"
});
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
}
}
static IEnumerable<object[]> Get_BuildBasicApplicationFSharpData ()
{
var ret = new List<object[]> ();
// TODO: AndroidRuntime.NativeAOT doesn't work yet. Fails with
//
// Microsoft.Android.Sdk.Aot.targets(123,5): error : Runtime critical type System.RuntimeMethodHandle not found
foreach (AndroidRuntime runtime in new[] { AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR }) {
AddTestData (isRelease: false, aot: false, runtime);
AddTestData (isRelease: true, aot: false, runtime);
AddTestData (isRelease: true, aot: true, runtime);
}
return ret;
void AddTestData (bool isRelease, bool aot, AndroidRuntime runtime)
{
ret.Add (new object[] {
isRelease,
aot,
runtime,
});
}
}
[Test]
[TestCaseSource (nameof (Get_BuildBasicApplicationFSharpData))]
[Category ("Minor"), Category ("FSharp")]
[NonParallelizable] // parallel NuGet restore causes failures
public void BuildBasicApplicationFSharp (bool isRelease, bool aot, AndroidRuntime runtime)
{
if (runtime == AndroidRuntime.NativeAOT) {
if (!aot) {
Assert.Ignore ("NativeAOT disabled for !aot");
return;
}
} else if (runtime == AndroidRuntime.CoreCLR) {
if (aot) {
Assert.Ignore ("CoreCLR + AOT == NativeAOT");
return;
}
}
var proj = new XamarinAndroidApplicationProject {
Language = XamarinAndroidProjectLanguage.FSharp,
IsRelease = isRelease,
AotAssemblies = aot,
};
proj.SetRuntime (runtime);
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
}
[Test]
[NonParallelizable]
public void BuildBasicApplicationAppCompat ([Values] bool publishAot, [Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease, aot: publishAot)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetPublishAot (true, AndroidNdkPath);
var packages = proj.PackageReferences;
packages.Add (KnownPackages.AndroidXAppCompat);
proj.MainActivity = proj.DefaultMainActivity.Replace ("public class MainActivity : Activity", "public class MainActivity : AndroidX.AppCompat.App.AppCompatActivity");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
}
}
[Test]
public void DuplicateRJavaOutput ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
PackageReferences = {
new Package { Id = "Xamarin.GooglePlayServices.Base", Version = "118.2.0.5" },
new Package { Id = "Xamarin.GooglePlayServices.Basement", Version = "118.2.0.5" },
new Package { Id = "Xamarin.GooglePlayServices.Tasks", Version = "118.0.2.6" },
}
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
var lines = b.LastBuildOutput.Where (l => l.Contains ("Writing:") && l.Contains ("R.java"));
var hash = new HashSet<string> (StringComparer.Ordinal);
foreach (var duplicate in lines.Where (i => !hash.Add (i))) {
Assert.Fail ($"Duplicate: {duplicate}");
}
}
}
[Test]
[Category ("XamarinBuildDownload")]
[NonParallelizable] // parallel NuGet restore causes failures
public void BuildXamarinFormsMapsApplication ([Values] bool multidex, [Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinFormsMapsApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
if (multidex)
proj.SetProperty ("AndroidEnableMultiDex", "True");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "first should have succeeded.");
b.BuildLogFile = "build2.log";
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "second should have succeeded.");
var targets = new [] {
"_CompileResources",
"_UpdateAndroidResgen",
};
foreach (var target in targets) {
b.Output.AssertTargetIsSkipped (target);
}
proj.Touch ("MainPage.xaml");
b.BuildLogFile = "build3.log";
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "third should have succeeded.");
foreach (var target in targets) {
b.Output.AssertTargetIsSkipped (target);
}
b.Output.AssertTargetIsNotSkipped ("CoreCompile");
b.BuildLogFile = "build4.log";
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "forth should have succeeded.");
foreach (var target in targets) {
b.Output.AssertTargetIsSkipped (target);
}
}
}
[Test]
[NonParallelizable]
public void SkipConvertResourcesCases ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var target = "ConvertResourcesCases";
var proj = new XamarinFormsAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.OtherBuildItems.Add (new BuildItem ("AndroidAarLibrary", "Jars\\material-menu-1.1.0.aar") {
WebContent = "https://repo1.maven.org/maven2/com/balysv/material-menu/1.1.0/material-menu-1.1.0.aar"
});
using (var b = CreateApkBuilder ()) {
b.Verbosity = LoggerVerbosity.Detailed;
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
Assert.IsFalse (b.Output.IsTargetSkipped (target), $"`{target}` should not be skipped.");
List<string> skipped = new List<string> (), processed = new List<string> ();
bool convertResourcesCases = false;
foreach (var text in b.LastBuildOutput) {
var line = text.Trim ();
if (!convertResourcesCases) {
convertResourcesCases = line.StartsWith ($"Task \"{target}\"", StringComparison.OrdinalIgnoreCase);
} else if (line.StartsWith ($"Done executing task \"{target}\"", StringComparison.OrdinalIgnoreCase)) {
convertResourcesCases = false; //end of target
}
if (convertResourcesCases) {
if (line.IndexOf ("Processing:", StringComparison.OrdinalIgnoreCase) >= 0) {
//Processing: obj\Debug\res\layout\main.xml 10/29/2018 8:19:36 PM > 1/1/0001 12:00:00 AM
processed.Add (line);
} else if (line.IndexOf ("Skipping:", StringComparison.OrdinalIgnoreCase) >= 0) {
//Skipping: `obj\Debug\lp\5\jl\res` via `AndroidSkipResourceProcessing`, original file: `bin\TestDebug\temp\packages\Xamarin.Android.Support.Compat.27.0.2.1\lib\MonoAndroid81\Xamarin.Android.Support.Compat.dll`...
skipped.Add (line);
}
}
}
var resources = new [] {
Path.Combine ("layout", "main.xml"),
Path.Combine ("layout", "tabbar.xml"),
Path.Combine ("layout", "toolbar.xml"),
Path.Combine ("values", "colors.xml"),
Path.Combine ("values", "strings.xml"),
Path.Combine ("values", "styles.xml"),
};
foreach (var resource in resources) {
Assert.IsTrue (processed.ContainsText (resource), $"`{target}` should process `{resource}`.");
}
var files = new List<string> {
"material-menu-1.1.0.aar",
};
files.Add ("androidx.core.core.aar");
files.Add ("androidx.transition.transition.aar");
files.Add ("androidx.recyclerview.recyclerview.aar");
files.Add ("androidx.coordinatorlayout.coordinatorlayout.aar");
files.Add ("androidx.cardview.cardview.aar");
files.Add ("androidx.appcompat.appcompat-resources.aar");
files.Add ("androidx.appcompat.appcompat.aar");
files.Add ("com.google.android.material.material.aar");
foreach (var file in files) {
Assert.IsTrue (StringAssertEx.ContainsText (skipped, file), $"`{target}` should skip `{file}`.");
}
}
}
[Test]
public void BuildInParallel ([Values] AndroidRuntime runtime)
{
if (!IsWindows) {
//TODO: one day we should fix the problems here, various MSBuild tasks step on each other when built in parallel
Assert.Ignore ("Currently ignoring this test on non-Windows platforms.");
}
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinFormsAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
//We don't want these things stepping on each other
b.BuildLogFile = null;
b.Save (proj, saveProject: true);
Parallel.For (0, 5, i => {
try {
//NOTE: things are going to break here
b.Build (proj);
} catch (Exception exc) {