-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathPackagingTest.cs
More file actions
1003 lines (902 loc) · 39.2 KB
/
PackagingTest.cs
File metadata and controls
1003 lines (902 loc) · 39.2 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.IO;
using NUnit.Framework;
using Xamarin.ProjectTools;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Xml.Linq;
using Xamarin.Tools.Zip;
using Xamarin.Android.Tasks;
using Xamarin.Android.Tools;
using Microsoft.Build.Framework;
namespace Xamarin.Android.Build.Tests
{
[Parallelizable (ParallelScope.Children)]
public class PackagingTest : BaseTest
{
[Test]
public void CheckProguardMappingFileExists ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8");
// Projects must set $(AndroidCreateProguardMappingFile) to true to opt in
proj.SetProperty (proj.ReleaseProperties, "AndroidCreateProguardMappingFile", true);
using (var b = CreateApkBuilder ()) {
string mappingFile = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, "mapping.txt");
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
FileAssert.Exists (mappingFile, $"'{mappingFile}' should have been generated.");
}
}
[Test]
public void CheckR8InfoMessagesToNotBreakTheBuild ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8");
proj.SetProperty (proj.ReleaseProperties, "AndroidCreateProguardMappingFile", true);
var packages = proj.PackageReferences;
packages.Add (KnownPackages.Xamarin_KotlinX_Coroutines_Android);
proj.OtherBuildItems.Add (new BuildItem ("ProguardConfiguration", "proguard.cfg") {
TextContent = () => @"-keepattributes Signature
-keep class kotlinx.coroutines.channels.** { *; }
"
});
using (var b = CreateApkBuilder ()) {
string mappingFile = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, "mapping.txt");
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
FileAssert.Exists (mappingFile, $"'{mappingFile}' should have been generated.");
}
}
[Test]
public void CheckDebugModeWithTrimming ([Values (AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR)] AndroidRuntime runtime)
{
bool usesAssemblyStores = runtime == AndroidRuntime.CoreCLR;
var proj = new XamarinAndroidApplicationProject {
ProjectName = "MyApp",
IsRelease = false,
EmbedAssembliesIntoApk = true,
};
proj.SetRuntime (runtime);
proj.SetProperty ("PublishTrimmed", "true");
proj.SetProperty ("AndroidUseAssemblyStore", usesAssemblyStores.ToString ());
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
var helper = new ArchiveAssemblyHelper (apk, usesAssemblyStores);
helper.Contains (["Mono.Android.dll", $"{proj.ProjectName}.dll"], out _, out var missingFiles, out _, [AndroidTargetArch.Arm64, AndroidTargetArch.X86_64]);
Assert.IsTrue (missingFiles == null || missingFiles.Count == 0,
string.Format ("The following Expected files are missing. {0}",
string.Join (Environment.NewLine, missingFiles)));
}
[Test]
[NonParallelizable] // Commonly fails NuGet restore
public void CheckIncludedAssemblies ([Values (false, true)] bool usesAssemblyStores, [Values (AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR)] AndroidRuntime runtime)
{
if (!usesAssemblyStores && runtime == AndroidRuntime.CoreCLR) {
Assert.Ignore ("CoreCLR only supports builds with assembly stores.");
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = true
};
AndroidTargetArch[] supportedArches = new[] {
runtime switch {
AndroidRuntime.MonoVM => AndroidTargetArch.Arm,
AndroidRuntime.CoreCLR => AndroidTargetArch.Arm64,
_ => throw new NotSupportedException ($"Unsupported runtime '{runtime}'")
}
};
proj.SetRuntime (runtime);
proj.SetProperty ("AndroidUseAssemblyStore", usesAssemblyStores.ToString ());
proj.SetRuntimeIdentifiers (supportedArches);
proj.PackageReferences.Add (new Package {
Id = "Humanizer.Core",
Version = "2.14.1",
});
proj.PackageReferences.Add (new Package {
Id = "Humanizer.Core.es",
Version = "2.14.1",
});
proj.MainActivity = proj.DefaultMainActivity
.Replace ("//${USINGS}", @"using System;
using Humanizer;
using System.Globalization;")
.Replace ("//${AFTER_ONCREATE}", @"var c = new CultureInfo (""es-ES"");
Console.WriteLine ($""{DateTime.UtcNow.AddHours(-30).Humanize(culture:c)}"");
//${AFTER_ONCREATE}");
proj.OtherBuildItems.Add (new BuildItem ("Using", "System.Globalization"));
proj.OtherBuildItems.Add (new BuildItem ("Using", "Humanizer"));
var expectedFiles = new HashSet<string> {
"Java.Interop.dll",
"Mono.Android.dll",
"Mono.Android.Runtime.dll",
"System.Console.dll",
"System.Private.CoreLib.dll",
"System.Runtime.dll",
"System.Runtime.InteropServices.dll",
"System.Linq.dll",
"UnnamedProject.dll",
"_Microsoft.Android.Resource.Designer.dll",
"Humanizer.dll",
"es/Humanizer.resources.dll",
"System.Collections.dll",
"System.Text.RegularExpressions.dll",
};
if (runtime == AndroidRuntime.MonoVM) {
expectedFiles.Add ("libarc.bin.so");
}
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
var helper = new ArchiveAssemblyHelper (apk, usesAssemblyStores);
List<string> existingFiles;
List<string> missingFiles;
List<string> additionalFiles;
helper.Contains (expectedFiles, out existingFiles, out missingFiles, out additionalFiles, supportedArches);
Assert.IsTrue (missingFiles == null || missingFiles.Count == 0,
string.Format ("The following Expected files are missing. {0}",
string.Join (Environment.NewLine, missingFiles)));
}
}
static IEnumerable<object[]> Get_CheckProjectWithSpaceInNameWorks_Data ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
AddTestData ("Test Me", runtime);
// testing characters as per https://www.compart.com/en/unicode/category/Zs
AddTestData ("TestUnicodeSpace0020\u0020Me", runtime);
AddTestData ("TestUnicodeSpace2000\u2000Me", runtime);
AddTestData ("TestUnicodeSpace2009\u2009Me", runtime);
AddTestData ("TestUnicodeSpace2002\u2002Me", runtime);
AddTestData ("TestUnicodeSpace2007\u2007Me", runtime);
}
return ret;
void AddTestData (string projectName, AndroidRuntime runtime)
{
ret.Add (new object[] {
projectName,
runtime,
});
}
}
[Test]
[Category ("SmokeTests")]
[TestCaseSource (nameof (Get_CheckProjectWithSpaceInNameWorks_Data))]
public void CheckProjectWithSpaceInNameWorks (string projectName, AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
ProjectName = projectName,
RootNamespace = "Test.Me",
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "build failed");
}
}
[Test]
public void CheckClassesDexIsIncluded ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "build failed");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsTrue (zip.ContainsEntry ("classes.dex"), "Apk should contain classes.dex");
}
}
}
[Test]
[Parallelizable (ParallelScope.Self)]
public void CheckIncludedNativeLibraries ([Values] bool compressNativeLibraries, [Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.PackageReferences.Add(KnownPackages.SQLitePCLRaw_Core);
proj.SetAndroidSupportedAbis ("x86_64");
proj.SetProperty (proj.ReleaseProperties, "AndroidStoreUncompressedFileExtensions", compressNativeLibraries ? "" : "so");
using (var b = CreateApkBuilder ()) {
b.ThrowOnBuildFailure = false;
Assert.IsTrue (b.Build (proj), "build failed");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
CompressionMethod method = compressNativeLibraries ? CompressionMethod.Deflate : CompressionMethod.Store;
using (var zip = ZipHelper.OpenZip (apk)) {
var libFiles = zip.Where (x => x.FullName.StartsWith("lib/", StringComparison.Ordinal) && !x.FullName.Equals("lib/", StringComparison.InvariantCultureIgnoreCase));
var abiPaths = new string[] { "lib/x86_64/" };
foreach (var file in libFiles) {
Assert.IsTrue (abiPaths.Any (x => file.FullName.Contains (x)), $"Apk contains an unnesscary lib file: {file.FullName}");
Assert.IsTrue (file.CompressionMethod == method, $"{file.FullName} should have been CompressionMethod.{method} in the apk, but was CompressionMethod.{file.CompressionMethod}");
}
}
}
}
[Test]
public void EmbeddedDSOs ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.AndroidManifest = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" android:versionCode=""1"" android:versionName=""1.0"" package=""{proj.PackageName}"">
<uses-sdk />
<application android:label=""{proj.ProjectName}"" android:extractNativeLibs=""false"">
</application>
</manifest>";
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "first build should have succeeded");
var manifest = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "AndroidManifest.xml");
AssertExtractNativeLibs (manifest, extractNativeLibs: false);
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
AssertEmbeddedDSOs (apk);
//Delete the apk & build again
File.Delete (apk);
Assert.IsTrue (b.Build (proj), "second build should have succeeded");
AssertEmbeddedDSOs (apk);
}
}
void AssertEmbeddedDSOs (string apk)
{
FileAssert.Exists (apk);
var zipAlignPath = Path.Combine (GetPathToZipAlign (), IsWindows ? "zipalign.exe" : "zipalign");
Assert.That (new FileInfo (zipAlignPath), Does.Exist, $"ZipAlign not found at {zipAlignPath}");
Assert.That (RunCommand (zipAlignPath, $"-c -v -p 4 {apk}"), Is.True, $"{apk} does not contain page-aligned .so files");
using (var zip = ZipHelper.OpenZip (apk)) {
foreach (var entry in zip) {
if (entry.FullName.EndsWith (".so", StringComparison.Ordinal)) {
AssertCompression (entry, compressed: false);
}
}
}
}
void AssertCompression (ZipEntry entry, bool compressed)
{
if (compressed) {
Assert.AreNotEqual (CompressionMethod.Store, entry.CompressionMethod, $"`{entry.FullName}` should be compressed!");
Assert.AreNotEqual (entry.Size, entry.CompressedSize, $"`{entry.FullName}` should be compressed!");
} else {
Assert.AreEqual (CompressionMethod.Store, entry.CompressionMethod, $"`{entry.FullName}` should be uncompressed!");
Assert.AreEqual (entry.Size, entry.CompressedSize, $"`{entry.FullName}` should be uncompressed!");
}
}
[Test]
public void IncrementalCompression ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.OtherBuildItems.Add (new AndroidItem.AndroidAsset ("foo.bar") {
BinaryContent = () => new byte [1024],
});
var manifest_template = proj.AndroidManifest;
proj.AndroidManifest = manifest_template.Replace ("<application ", "<application android:extractNativeLibs=\"true\" ");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "first build should have succeeded");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
using (var zip = ZipHelper.OpenZip (apk)) {
foreach (var entry in zip) {
if (entry.FullName.EndsWith (".so", StringComparison.Ordinal) || entry.FullName.EndsWith (".bar", StringComparison.Ordinal)) {
AssertCompression (entry, compressed: true);
}
}
}
// Change manifest & compressed extensions
proj.AndroidManifest = manifest_template.Replace ("<application ", "<application android:extractNativeLibs=\"false\" ");
proj.Touch ("Properties\\AndroidManifest.xml");
proj.SetProperty ("AndroidStoreUncompressedFileExtensions", ".bar");
b.BuildLogFile = "build2.log";
Assert.IsTrue (b.Build (proj), "second build should have succeeded");
FileAssert.Exists (apk);
using (var zip = ZipHelper.OpenZip (apk)) {
foreach (var entry in zip) {
if (entry.FullName.EndsWith (".so", StringComparison.Ordinal) || entry.FullName.EndsWith (".bar", StringComparison.Ordinal)) {
AssertCompression (entry, compressed: false);
}
}
}
}
}
[Test]
public void ExplicitPackageNamingPolicy ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
// TODO: NativeAOT doesn't create obj/Release/android/src/foo/Bar.java, instead it creates obj/Release/android/src/crc64dca3aed1e0ff8a1a/Bar.java
if (runtime == AndroidRuntime.NativeAOT) {
Assert.Ignore ("NativeAOT doesn't follow the explicit package naming policy");
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.Sources.Add (new BuildItem.Source ("Bar.cs") {
TextContent = () => "namespace Foo { class Bar : Java.Lang.Object { } }"
});
proj.SetProperty (proj.DebugProperties, "AndroidPackageNamingPolicy", "Lowercase");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "build failed");
var text = b.Output.GetIntermediaryAsText (b.Output.IntermediateOutputPath, Path.Combine ("android", "src", "foo", "Bar.java"));
Assert.IsTrue (text.Contains ("package foo;"), "expected package not found in the source.");
}
}
[Test]
public void CheckMetadataSkipItemsAreProcessedCorrectly ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var packages = new List<Package> () {
KnownPackages.Xamarin_Jetbrains_Annotations,
};
string metaDataTemplate = @"<AndroidCustomMetaDataForReferences Include=""%"">
<AndroidSkipAddToPackage>True</AndroidSkipAddToPackage>
<AndroidSkipJavaStubGeneration>True</AndroidSkipJavaStubGeneration>
<AndroidSkipResourceExtraction>True</AndroidSkipResourceExtraction>
</AndroidCustomMetaDataForReferences>";
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
Imports = {
new Import (() => "CustomMetaData.target") {
TextContent = () => @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemGroup>" +
string.Join ("\n", packages.Select (x => metaDataTemplate.Replace ("%", x.Id))) +
@"</ItemGroup>
</Project>"
},
}
};
proj.SetRuntime (runtime);
proj.SetProperty (proj.DebugProperties, "AndroidPackageNamingPolicy", "Lowercase");
foreach (var package in packages)
proj.PackageReferences.Add (package);
using (var b = CreateApkBuilder ()) {
b.ThrowOnBuildFailure = false;
Assert.IsTrue (b.Build (proj), "build failed");
var bin = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath);
var obj = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
var lp = Path.Combine (obj, "lp");
Assert.IsTrue (Directory.Exists (lp), $"{lp} should exists.");
Assert.AreEqual (0, Directory.GetDirectories (lp).Length, $"{lp} should NOT contain any directories.");
var support = Path.Combine (obj, "android", "src", "android", "support");
Assert.IsFalse (Directory.Exists (support), $"{support} should NOT exists.");
Assert.IsFalse (File.Exists (lp), $" should NOT have been generated.");
foreach (var apk in Directory.GetFiles (bin, "*-Signed.apk")) {
using (var zip = ZipHelper.OpenZip (apk)) {
foreach (var package in packages) {
Assert.IsFalse (zip.Any (e => e.FullName == $"assemblies/{package.Id}.dll"), $"APK file `{apk}` should not contain {package.Id}");
}
}
}
}
}
[Test]
public void CheckSignApk ([Values] bool useApkSigner, [Values] bool perAbiApk, [Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
string ext = Environment.OSVersion.Platform != PlatformID.Unix ? ".bat" : "";
var foundApkSigner = Directory.EnumerateDirectories (Path.Combine (AndroidSdkPath, "build-tools")).Any (dir => Directory.EnumerateFiles (dir, "apksigner"+ ext).Any ());
if (useApkSigner && !foundApkSigner) {
Assert.Ignore ("Skipping test. Required build-tools verison which contains apksigner is not installed.");
}
string keyfile = Path.Combine (Root, "temp", TestName, "keystore", "release.keystore");
if (File.Exists (keyfile))
File.Delete (keyfile);
string keyToolPath = Path.Combine (AndroidSdkResolver.GetJavaSdkPath (), "bin");
var engine = new MockBuildEngine (Console.Out);
string pass = "Cy(nBW~j.&@B-!R_aq7/syzFR!S$4]7R%i6)R!";
string alias = "release store";
var task = new AndroidCreateDebugKey {
BuildEngine = engine,
KeyStore = keyfile,
StorePass = pass,
KeyAlias = alias,
KeyPass = pass,
KeyAlgorithm="RSA",
Validity=30,
StoreType="pkcs12",
Command="-genkeypair",
ToolPath = keyToolPath,
};
Assert.IsTrue (task.Execute (), "Task should have succeeded.");
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetProperty (proj.ReleaseProperties, "AndroidUseApkSigner", useApkSigner);
proj.SetProperty (proj.ReleaseProperties, "AndroidKeyStore", "True");
proj.SetProperty (proj.ReleaseProperties, "AndroidSigningKeyStore", keyfile);
proj.SetProperty (proj.ReleaseProperties, "AndroidSigningKeyAlias", alias);
proj.SetProperty (proj.ReleaseProperties, "AndroidSigningKeyPass", Uri.EscapeDataString (pass));
proj.SetProperty (proj.ReleaseProperties, "AndroidSigningStorePass", Uri.EscapeDataString (pass));
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, perAbiApk);
if (perAbiApk) {
if (runtime == AndroidRuntime.MonoVM) {
proj.SetAndroidSupportedAbis ("armeabi-v7a", "x86", "arm64-v8a", "x86_64");
} else {
proj.SetRuntimeIdentifiers (AndroidTargetArch.Arm64, AndroidTargetArch.X86_64);
}
} else {
proj.SetRuntimeIdentifiers (AndroidTargetArch.Arm64, AndroidTargetArch.X86_64);
}
using (var b = CreateApkBuilder (Path.Combine ("temp", TestName, "App"))) {
var bin = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath);
Assert.IsTrue (b.Build (proj), "First build failed");
if (runtime != AndroidRuntime.NativeAOT) {
b.AssertHasNoWarnings ();
} else {
StringAssertEx.Contains ("2 Warning(s)", b.LastBuildOutput, "NativeAOT should produce two IL3053 warnings");
}
//Make sure the APKs are signed
foreach (var apk in Directory.GetFiles (bin, "*-Signed.apk")) {
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsTrue (zip.Any (e => e.FullName == "META-INF/MANIFEST.MF"), $"APK file `{apk}` is not signed! It is missing `META-INF/MANIFEST.MF`.");
}
}
// Make sure the APKs have unique version codes
if (perAbiApk) {
var versionList = new List<int> ();
int armManifestCode = Int32.MinValue;
int x86ManifestCode = Int32.MinValue;
if (runtime == AndroidRuntime.MonoVM) {
armManifestCode = GetVersionCodeFromIntermediateManifest (Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "armeabi-v7a", "AndroidManifest.xml"));
x86ManifestCode = GetVersionCodeFromIntermediateManifest (Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "x86", "AndroidManifest.xml"));
versionList.Add (armManifestCode);
versionList.Add (x86ManifestCode);
}
int arm64ManifestCode = GetVersionCodeFromIntermediateManifest (Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "arm64-v8a", "AndroidManifest.xml"));
int x86_64ManifestCode = GetVersionCodeFromIntermediateManifest (Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "x86_64", "AndroidManifest.xml"));
versionList.Add (arm64ManifestCode);
versionList.Add (x86_64ManifestCode);
Assert.True (versionList.Distinct ().Count () == versionList.Count,
$"APK version codes were not unique - armeabi-v7a: {armManifestCode}, x86: {x86ManifestCode}, arm64-v8a: {arm64ManifestCode}, x86_64: {x86_64ManifestCode}");
}
var item = proj.AndroidResources.First (x => x.Include () == "Resources\\values\\Strings.xml");
item.TextContent = () => proj.StringsXml.Replace ("${PROJECT_NAME}", "Foo");
item.Timestamp = null;
Assert.IsTrue (b.Build (proj), "Second build failed");
// Only Strings.xml changed, so assemblies are unchanged and ILLink
// correctly skips — no IL3053 warnings are expected for any runtime.
b.AssertHasNoWarnings ();
//Make sure the APKs are signed
foreach (var apk in Directory.GetFiles (bin, "*-Signed.apk")) {
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsTrue (zip.Any (e => e.FullName == "META-INF/MANIFEST.MF"), $"APK file `{apk}` is not signed! It is missing `META-INF/MANIFEST.MF`.");
}
}
}
int GetVersionCodeFromIntermediateManifest (string manifestFilePath)
{
var doc = XDocument.Load (manifestFilePath);
var versionCode = doc.Descendants ()
.Where (e => e.Name == "manifest")
.Select (m => m.Attribute ("{http://schemas.android.com/apk/res/android}versionCode")).FirstOrDefault ();
if (!int.TryParse (versionCode?.Value, out int parsedCode))
Assert.Fail ($"Unable to parse 'versionCode' value from manifest content: {File.ReadAllText (manifestFilePath)}.");
return parsedCode;
}
}
[Test]
public void CheckAppBundle ([Values] bool isRelease, [Values] AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetProperty ("AndroidPackageFormat", "aab");
// Disable the fast deployment because it is not currently compatible with aabs and so gives an XA0119 build error.
proj.EmbedAssembliesIntoApk = true;
using (var b = CreateApkBuilder ()) {
var bin = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath);
Assert.IsTrue (b.Build (proj), "first build should have succeeded.");
// Make sure the AAB is signed
var aab = Path.Combine (bin, $"{proj.PackageName}-Signed.aab");
using (var zip = ZipHelper.OpenZip (aab)) {
Assert.IsTrue (zip.Any (e => e.FullName == "META-INF/MANIFEST.MF"), $"AAB file `{aab}` is not signed! It is missing `META-INF/MANIFEST.MF`.");
}
// Build with no changes
Assert.IsTrue (b.Build (proj), "second build should have succeeded.");
foreach (var target in new [] { "_Sign", "_BuildApkEmbed" }) {
Assert.IsTrue (b.Output.IsTargetSkipped (target), $"`{target}` should be skipped!");
}
}
}
[Test]
public void MissingSatelliteAssemblyInLibrary ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
if (runtime == AndroidRuntime.NativeAOT) {
Assert.Ignore ("NativeAOT builds don't package satellite assemblies");
}
var path = Path.Combine ("temp", TestName);
var lib = new XamarinAndroidLibraryProject {
IsRelease = isRelease,
ProjectName = "Localization",
OtherBuildItems = {
new BuildItem ("EmbeddedResource", "Foo.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancel</value></data>")
},
}
};
lib.SetRuntime (runtime);
var languages = new string[] {"es", "de", "fr", "he", "it", "pl", "pt", "ru", "sl" };
foreach (string lang in languages) {
lib.OtherBuildItems.Add (
new BuildItem ("EmbeddedResource", $"Foo.{lang}.resx") {
TextContent = () => InlineData.ResxWithContents ($"<data name=\"CancelButton\"><value>{lang}</value></data>")
}
);
}
var app = new XamarinAndroidApplicationProject {
IsRelease = true,
};
app.SetRuntime (runtime);
app.References.Add (new BuildItem.ProjectReference ($"..\\{lib.ProjectName}\\{lib.ProjectName}.csproj", lib.ProjectName, lib.ProjectGuid));
using (var libBuilder = CreateDllBuilder (Path.Combine (path, lib.ProjectName)))
using (var appBuilder = CreateApkBuilder (Path.Combine (path, app.ProjectName))) {
Assert.IsTrue (libBuilder.Build (lib), "Library Build should have succeeded.");
appBuilder.Target = "Build";
Assert.IsTrue (appBuilder.Build (app), "App Build should have succeeded.");
appBuilder.Target = "SignAndroidPackage";
Assert.IsTrue (appBuilder.Build (app), "App SignAndroidPackage should have succeeded.");
var apk = Path.Combine (Root, appBuilder.ProjectDirectory,
app.OutputPath, $"{app.PackageName}-Signed.apk");
var helper = new ArchiveAssemblyHelper (apk);
foreach (string lang in languages) {
foreach (string abi in app.GetRuntimeIdentifiersAsAbis ()) {
Assert.IsTrue (helper.Exists ($"assemblies/{abi}/{lang}/{lib.ProjectName}.resources.dll"), $"Apk should contain satellite assembly for language '{lang}'!");
}
}
}
}
[Test]
public void MissingSatelliteAssemblyInApp ([Values] bool publishAot, [Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
// PublishAot is NativeAOT but it doesn't support assemblies, so when `publishAot` is `true`, we run only
// the Mono test.
if (publishAot && runtime != AndroidRuntime.MonoVM) {
Assert.Ignore ("NativeAOT and CoreCLR don't support PublishAot with satellite assemblies");
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
OtherBuildItems = {
new BuildItem ("EmbeddedResource", "Foo.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancel</value></data>")
},
new BuildItem ("EmbeddedResource", "Foo.es.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancelar</value></data>")
}
}
};
proj.SetPublishAot (publishAot, AndroidNdkPath);
using (var b = CreateApkBuilder ()) {
b.Verbosity = LoggerVerbosity.Diagnostic; // Needed for --satellite switch to appear in the log
b.Target = "Build";
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
b.Target = "SignAndroidPackage";
Assert.IsTrue (b.Build (proj), "SignAndroidPackage should have succeeded.");
if (publishAot) {
// Best idea thus far is to assert ILC's --satellite switch
var regex = $"--satellite:.+{proj.ProjectName}.resources.dll";
StringAssertEx.ContainsRegex (regex, b.LastBuildOutput, $"Build log should contain the pattern: {regex}");
} else {
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
var helper = new ArchiveAssemblyHelper (apk);
foreach (string abi in proj.GetRuntimeIdentifiersAsAbis ()) {
Assert.IsTrue (helper.Exists ($"assemblies/{abi}/es/{proj.ProjectName}.resources.dll"), "Apk should contain satellite assemblies!");
}
}
}
}
[Test]
public void IgnoreManifestFromJar ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
string java = @"
package com.xamarin.testing;
public class Test
{
}
";
var path = Path.Combine (Root, "temp", TestName);
var javaDir = Path.Combine (path, "java", "com", "xamarin", "testing");
if (Directory.Exists (javaDir))
Directory.Delete (javaDir, true);
Directory.CreateDirectory (javaDir);
File.WriteAllText (Path.Combine (javaDir, "..", "..", "..", "AndroidManifest.xml"), @"<?xml version='1.0' ?><maniest />");
var lib = new XamarinAndroidBindingProject () {
IsRelease = isRelease,
AndroidClassParser = "class-parse",
ProjectName = "Binding1",
};
lib.MetadataXml = "<metadata></metadata>";
lib.Jars.Add (new AndroidItem.EmbeddedJar (Path.Combine ("java", "test.jar")) {
BinaryContent = new JarContentBuilder () {
BaseDirectory = Path.Combine (path, "java"),
JarFileName = "test.jar",
JavaSourceFileName = Path.Combine ("com", "xamarin", "testing", "Test.java"),
JavaSourceText = java,
AdditionalFileExtensions = "*.xml",
}.Build
});
lib.SetRuntime (runtime);
var app = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
};
app.SetRuntime (runtime);
app.References.Add (new BuildItem.ProjectReference ($"..\\{lib.ProjectName}\\{lib.ProjectName}.csproj", lib.ProjectName, lib.ProjectGuid));
using (var builder = CreateDllBuilder (Path.Combine (path, lib.ProjectName))) {
Assert.IsTrue (builder.Build (lib), "Build of jar should have succeeded.");
using (var zip = ZipHelper.OpenZip (Path.Combine (path, "java", "test.jar"))) {
Assert.IsTrue (zip.ContainsEntry ($"AndroidManifest.xml"), "Jar should contain AndroidManifest.xml");
}
using (var b = CreateApkBuilder (Path.Combine (path, app.ProjectName))) {
b.Verbosity = LoggerVerbosity.Detailed;
Assert.IsTrue (b.Build (app), "Build of jar should have succeeded.");
var jar = "2965D0C9A2D5DB1E.jar";
string expected = $"Ignoring jar entry AndroidManifest.xml from {jar}: the same file already exists in the apk";
Assert.IsTrue (b.LastBuildOutput.ContainsText (expected), $"AndroidManifest.xml for {jar} should have been ignored.");
}
}
}
[Test]
public void CheckExcludedFilesAreMissing ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.PackageReferences.Add (KnownPackages.Xamarin_Kotlin_StdLib_Common);
using (var b = CreateApkBuilder ()) {
b.Verbosity = LoggerVerbosity.Detailed;
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
string expected = $"Ignoring jar entry 'kotlin/Error.kotlin_metadata'";
Assert.IsTrue (b.LastBuildOutput.ContainsText (expected), $"Error.kotlin_metadata should have been ignored.");
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsFalse (zip.ContainsEntry ("kotlin/Error.kotlin_metadata"), "Error.kotlin_metadata should have been ignored.");
}
}
}
[Test]
public void CheckExcludedFilesCanBeModified ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.PackageReferences.Add (KnownPackages.Xamarin_Kotlin_StdLib_Common);
using (var b = CreateApkBuilder ()) {
b.Verbosity = LoggerVerbosity.Detailed;
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
string expected = $"Ignoring jar entry 'kotlin/Error.kotlin_metadata'";
Assert.IsTrue (b.LastBuildOutput.ContainsText (expected), $"Error.kotlin_metadata should have been ignored.");
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsFalse (zip.ContainsEntry ("kotlin/Error.kotlin_metadata"), "Error.kotlin_metadata should have been ignored.");
}
proj.OtherBuildItems.Add (new BuildItem ("AndroidPackagingOptionsExclude") {
Remove = () => "$([MSBuild]::Escape('*.kotlin*'))",
});
Assert.IsTrue (b.Clean (proj), "Clean should have succeeded.");
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsTrue (zip.ContainsEntry ("kotlin/Error.kotlin_metadata"), "Error.kotlin_metadata should have been included.");
}
}
}
[Test]
public void CheckIncludedFilesArePresent ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.PackageReferences.Add (KnownPackages.Xamarin_Kotlin_Reflect);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
using (var zip = ZipHelper.OpenZip (apk)) {
Assert.IsTrue (zip.ContainsEntry ("kotlin/reflect/reflect.kotlin_builtins"), "reflect.kotlin_builtins should have been included.");
}
}
}
static IEnumerable<object[]> Get_BuildApkWithZipFlushLimits_Data ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
AddTestData (1, -1, runtime);
AddTestData (5, -1, runtime);
AddTestData (50, -1, runtime);
AddTestData (100, -1, runtime);
AddTestData (512, -1, runtime);
AddTestData (1024, -1, runtime);
AddTestData (-1, 1, runtime);
AddTestData (-1, 5, runtime);
AddTestData (-1, 10, runtime);
AddTestData (-1, 100, runtime);
AddTestData (-1, 200, runtime);
}
return ret;
void AddTestData (int filesLimit, int sizeLimit, AndroidRuntime runtime)
{
ret.Add (new object[] {
filesLimit,
sizeLimit,
runtime,
});
}
}
[Test]
[TestCaseSource (nameof (Get_BuildApkWithZipFlushLimits_Data))]
public void BuildApkWithZipFlushLimits (int filesLimit, int sizeLimit, AndroidRuntime runtime)
{
const bool isRelease = false;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinFormsAndroidApplicationProject {
IsRelease = isRelease,
};
proj.SetRuntime (runtime);
proj.SetProperty ("EmbedAssembliesIntoApk", "true");
if (filesLimit > 0)
proj.SetProperty ("_ZipFlushFilesLimit", filesLimit.ToString ());
if (sizeLimit > 0)
proj.SetProperty ("_ZipFlushSizeLimit", (sizeLimit * 1024 * 1024).ToString ());
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
}
}
[Test]
public void ExtractNativeLibsTrue ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
// This combination produces android:extractNativeLibs="false" by default
SupportedOSPlatformVersion = "23",
ManifestMerger = "manifestmerger.jar",
};
proj.SetRuntime (runtime);
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
// We should find extractNativeLibs="true"
var manifest = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "AndroidManifest.xml");
AssertExtractNativeLibs (manifest, extractNativeLibs: true);
// All .so files should be compressed
var apk = Path.Combine (Root, b.ProjectDirectory,
proj.OutputPath, $"{proj.PackageName}-Signed.apk");
using (var zip = ZipHelper.OpenZip (apk)) {
foreach (var entry in zip) {
if (entry.FullName.EndsWith (".so", StringComparison.Ordinal)) {
AssertCompression (entry, compressed: true);
}
}
}
}
}
[Test]
public void DefaultItems ([Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
void CreateEmptyFile (string path)
{
Directory.CreateDirectory (Path.GetDirectoryName (path));
File.WriteAllText (path, contents: "");
}
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
EnableDefaultItems = true,
};
proj.SetRuntime (runtime);
var builder = CreateApkBuilder ();
builder.Save (proj);
proj.ShouldPopulate = false;
// Build error -> no nested sub-directories in Resources
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Resources", "drawable", "foo", "bar.png"));
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Resources", "raw", "foo", "bar.png"));
// Build error -> no files/directories that start with .
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Resources", "raw", ".DS_Store"));
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Assets", ".DS_Store"));
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Assets", ".svn", "foo.txt"));
// Files that should work
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Resources", "raw", "foo.txt"));
CreateEmptyFile (Path.Combine (Root, builder.ProjectDirectory, "Assets", "foo", "bar.txt"));
Assert.IsTrue (builder.Build (proj), "`dotnet build` should succeed");
var apkPath = Path.Combine (Root, builder.ProjectDirectory, proj.OutputPath, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apkPath);
using (var apk = ZipHelper.OpenZip (apkPath)) {
apk.AssertContainsEntry (apkPath, "res/raw/foo.txt");
apk.AssertContainsEntry (apkPath, "assets/foo/bar.txt");
}
}