-
Notifications
You must be signed in to change notification settings - Fork 528
/
InstallAndRunTests.cs
1144 lines (1022 loc) · 45.2 KB
/
InstallAndRunTests.cs
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.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.XPath;
using Mono.Cecil;
using NUnit.Framework;
using Xamarin.ProjectTools;
namespace Xamarin.Android.Build.Tests
{
[TestFixture]
[Category ("UsesDevice")]
public class InstallAndRunTests : DeviceTest
{
static ProjectBuilder builder;
static XamarinAndroidApplicationProject proj;
[TearDown]
public void Teardown ()
{
builder?.Dispose ();
builder = null;
proj = null;
}
[Test]
public void NativeAssemblyCacheWithSatelliteAssemblies ([Values (true, false)] bool enableMarshalMethods)
{
// TODO: enable when marshal methods are fixed
if (enableMarshalMethods) {
Assert.Ignore ("Test is skipped when marshal methods are enabled, pending fixes to MM for .NET9");
}
var path = Path.Combine ("temp", TestName);
var lib = new XamarinAndroidLibraryProject {
ProjectName = "Localization",
OtherBuildItems = {
new BuildItem ("EmbeddedResource", "Foo.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancel</value></data>")
},
}
};
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>")
}
);
}
proj = new XamarinAndroidApplicationProject {
IsRelease = true,
EnableMarshalMethods = enableMarshalMethods,
};
proj.References.Add (new BuildItem.ProjectReference ($"..\\{lib.ProjectName}\\{lib.ProjectName}.csproj", lib.ProjectName, lib.ProjectGuid));
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
using (var libBuilder = CreateDllBuilder (Path.Combine (path, lib.ProjectName))) {
builder = CreateApkBuilder (Path.Combine (path, proj.ProjectName));
Assert.IsTrue (libBuilder.Build (lib), "Library Build should have succeeded.");
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
var apk = Path.Combine (Root, builder.ProjectDirectory, proj.OutputPath, $"{proj.PackageName}-Signed.apk");
var helper = new ArchiveAssemblyHelper (apk);
foreach (string lang in languages) {
Assert.IsTrue (helper.Exists ($"assemblies/{lang}/{lib.ProjectName}.resources.dll"), $"Apk should contain satellite assembly for language '{lang}'!");
}
RunProjectAndAssert (proj, builder);
Assert.True (WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "logcat.log"), 30), "Activity should have started.");
}
}
[Test]
public void GlobalLayoutEvent_ShouldRegisterAndFire_OnActivityLaunch ([Values (false, true)] bool isRelease)
{
string expectedLogcatOutput = "Bug 29730: GlobalLayout event handler called!";
proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
SupportedOSPlatformVersion = "23",
};
if (isRelease || !TestEnvironment.CommercialBuildAvailable) {
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
}
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}",
$@"button.ViewTreeObserver.GlobalLayout += Button_ViewTreeObserver_GlobalLayout;
}}
void Button_ViewTreeObserver_GlobalLayout (object sender, EventArgs e)
{{
Android.Util.Log.Debug (""BugzillaTests"", ""{expectedLogcatOutput}"");
");
builder = CreateApkBuilder (Path.Combine ("temp", $"Bug29730-{isRelease}"));
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
AdbStartActivity ($"{proj.PackageName}/{proj.JavaPackageName}.MainActivity");
Assert.IsTrue (MonitorAdbLogcat ((line) => {
return line.Contains (expectedLogcatOutput);
}, Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), 60), $"Output did not contain {expectedLogcatOutput}!");
}
[Test]
public void SubscribeToAppDomainUnhandledException ()
{
proj = new XamarinAndroidApplicationProject () {
IsRelease = true,
};
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}",
@" AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
Console.WriteLine (""# Unhandled Exception: sender={0}; e.IsTerminating={1}; e.ExceptionObject={2}"",
sender, e.IsTerminating, e.ExceptionObject);
};
throw new Exception (""CRASH"");
");
builder = CreateApkBuilder ();
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunProjectAndAssert (proj, builder);
string expectedLogcatOutput = "# Unhandled Exception: sender=System.Object; e.IsTerminating=True; e.ExceptionObject=System.Exception: CRASH";
Assert.IsTrue (
MonitorAdbLogcat (CreateLineChecker (expectedLogcatOutput),
logcatFilePath: Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), timeout: 60),
$"Output did not contain {expectedLogcatOutput}!");
}
public static Func<string, bool> CreateLineChecker (string expectedLogcatOutput)
{
// On .NET 6, `adb logcat` output may be line-wrapped in unexpected ways.
// https://github.com/xamarin/xamarin-android/pull/6119#issuecomment-896246633
// Try to see if *successive* lines match expected output
var remaining = expectedLogcatOutput;
return line => {
if (line.IndexOf (remaining, StringComparison.Ordinal) >= 0) {
Reset ();
return true;
}
int count = Math.Min (line.Length, remaining.Length);
for ( ; count > 0; count--) {
var startMatch = remaining.Substring (0, count);
if (line.IndexOf (startMatch, StringComparison.Ordinal) >= 0) {
remaining = remaining.Substring (count);
return false;
}
}
Reset ();
return false;
};
void Reset ()
{
remaining = expectedLogcatOutput;
}
}
[Test]
[Category ("UsesDevice")]
[TestCase ("テスト")]
[TestCase ("随机生成器")]
[TestCase ("中国")]
public void SmokeTestBuildAndRunWithSpecialCharacters (string testName)
{
var rootPath = Path.Combine (Root, "temp", TestName);
var proj = new XamarinFormsAndroidApplicationProject () {
ProjectName = testName,
IsRelease = true,
};
proj.SetAndroidSupportedAbis (DeviceAbi);
proj.SetDefaultTargetDevice ();
using (var builder = CreateApkBuilder (Path.Combine (rootPath, proj.ProjectName))){
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunProjectAndAssert (proj, builder);
var timeoutInSeconds = 120;
Assert.IsTrue (WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), timeoutInSeconds));
}
}
[Test]
public void CustomLinkDescriptionPreserve ([Values (AndroidLinkMode.SdkOnly, AndroidLinkMode.Full)] AndroidLinkMode linkMode)
{
var lib1 = new XamarinAndroidLibraryProject () {
ProjectName = "Library1",
Sources = {
new BuildItem.Source ("SomeClass.cs") {
TextContent = () => "namespace Library1 { public class SomeClass { } }"
},
new BuildItem.Source ("NonPreserved.cs") {
TextContent = () => "namespace Library1 { public class NonPreserved { } }"
},
new BuildItem.Source ("LinkerClass.cs") {
TextContent = () => @"
namespace Library1 {
public class LinkerClass {
public LinkerClass () { }
public bool IsPreserved { get { return true; } }
public bool ThisMethodShouldBePreserved () { return true; }
public void WasThisMethodPreserved (string arg1) { }
[Android.Runtime.Preserve]
public void PreserveAttribMethod () { }
}
}",
}, new BuildItem.Source ("LinkModeFullClass.cs") {
TextContent = () => @"
namespace Library1 {
public class LinkModeFullClass {
public bool ThisMethodShouldNotBePreserved () { return true; }
}
}",
},
}
};
var lib2 = new DotNetStandard {
ProjectName = "LinkTestLib",
Sdk = "Microsoft.NET.Sdk",
TargetFramework = "netstandard2.0",
PackageReferences = {
new Package {
Id = "sqlite-net-pcl",
Version = "1.7.335",
}
},
Sources = {
new BuildItem.Source ("Bug21578.cs") {
TextContent = () => getResource("Bug21578")
},
new BuildItem.Source ("Bug35195.cs") {
TextContent = () => getResource("Bug35195")
},
new BuildItem.Source ("HttpClientTest.cs") {
TextContent = () => getResource("HttpClientTest")
},
new BuildItem.Source ("PreserveTest.cs") {
TextContent = () => getResource("PreserveTest")
},
},
};
proj = new XamarinFormsAndroidApplicationProject () {
IsRelease = true,
AndroidLinkModeRelease = linkMode,
References = {
new BuildItem ("ProjectReference", "..\\Library1\\Library1.csproj"),
new BuildItem ("ProjectReference", "..\\LinkTestLib\\LinkTestLib.csproj"),
},
PackageReferences = {
KnownPackages.AndroidXMigration,
KnownPackages.AndroidXAppCompat,
KnownPackages.AndroidXAppCompatResources,
KnownPackages.AndroidXBrowser,
KnownPackages.AndroidXMediaRouter,
KnownPackages.AndroidXLegacySupportV4,
KnownPackages.AndroidXLifecycleLiveData,
KnownPackages.XamarinGoogleAndroidMaterial,
},
Sources = {
new BuildItem.Source ("MaterialTextChanged.cs") {
TextContent = () => getResource ("MaterialTextChanged")
},
},
OtherBuildItems = {
new BuildItem ("LinkDescription", "linker.xml") {
TextContent = () => linkMode == AndroidLinkMode.SdkOnly ? "<linker/>" : @"
<linker>
<assembly fullname=""Library1"">
<type fullname=""Library1.LinkerClass"">
<method name="".ctor"" />
<method name=""WasThisMethodPreserved"" />
<method name=""get_IsPreserved"" />
</type>
</assembly>
<assembly fullname=""LinkTestLib"">
<type fullname=""LinkTestLib.TodoTask"" />
</assembly>
</linker>
",
},
},
};
// NOTE: workaround for netcoreapp3.0 dependency being included along with monoandroid8.0
// See: https://www.nuget.org/packages/SQLitePCLRaw.bundle_green/2.0.3
proj.PackageReferences.Add (new Package {
Id = "SQLitePCLRaw.provider.dynamic_cdecl",
Version = "2.0.3",
});
proj.AndroidManifest = proj.AndroidManifest.Replace ("</manifest>", "<uses-permission android:name=\"android.permission.INTERNET\" /></manifest>");
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
using (var sr = new StreamReader (typeof (InstallAndRunTests).Assembly.GetManifestResourceStream ("Xamarin.Android.Build.Tests.Resources.LinkDescTest.MainActivityReplacement.cs")))
proj.MainActivity = sr.ReadToEnd ();
// Set up library projects
var rootPath = Path.Combine (Root, "temp", TestName);
using (var lb1 = CreateDllBuilder (Path.Combine (rootPath, lib1.ProjectName)))
Assert.IsTrue (lb1.Build (lib1), "First library build should have succeeded.");
using (var lb2 = CreateDllBuilder (Path.Combine (rootPath, lib2.ProjectName)))
Assert.IsTrue (lb2.Build (lib2), "Second library build should have succeeded.");
builder = CreateApkBuilder (Path.Combine (rootPath, proj.ProjectName));
Assert.IsTrue (builder.Install (proj), "First install should have succeeded.");
RunProjectAndAssert (proj, builder);
var logcatPath = Path.Combine (Root, builder.ProjectDirectory, "logcat.log");
Assert.IsTrue (MonitorAdbLogcat ((line) => {
return line.Contains ("All regression tests completed.");
}, logcatPath, 90), "Linker test app did not run successfully.");
var logcatOutput = File.ReadAllText (logcatPath);
StringAssert.Contains ("[PASS]", logcatOutput);
StringAssert.DoesNotContain ("[FAIL]", logcatOutput);
if (linkMode == AndroidLinkMode.Full) {
StringAssert.Contains ("[LINKALLPASS]", logcatOutput);
StringAssert.DoesNotContain ("[LINKALLFAIL]", logcatOutput);
}
string getResource (string name)
{
using (var sr = new StreamReader (typeof (InstallAndRunTests).Assembly.GetManifestResourceStream ($"Xamarin.Android.Build.Tests.Resources.LinkDescTest.{name}.cs")))
return sr.ReadToEnd ();
}
}
[Test]
public void JsonDeserializationCreatesJavaHandle ([Values (false, true)] bool isRelease)
{
proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
// error SYSLIB0011: 'BinaryFormatter.Serialize(Stream, object)' is obsolete: 'BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.'
proj.SetProperty ("NoWarn", "SYSLIB0011");
if (isRelease || !TestEnvironment.CommercialBuildAvailable) {
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
}
proj.References.Add (new BuildItem.Reference ("System.Runtime.Serialization"));
proj.References.Add (new BuildItem.Reference ("System.Runtime.Serialization.Json"));
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}",
@"TestJsonDeserializationCreatesJavaHandle();
}
void TestJsonDeserialization (Person p)
{
var stream = new MemoryStream ();
var serializer = new DataContractJsonSerializer (typeof (Person));
serializer.WriteObject (stream, p);
stream.Position = 0;
StreamReader sr = new StreamReader (stream);
Console.WriteLine ($""JSON Person representation: {sr.ReadToEnd ()}"");
stream.Position = 0;
Person p2 = (Person) serializer.ReadObject (stream);
Console.WriteLine ($""JSON Person parsed: Name '{p2.Name}' Age '{p2.Age}' Handle '0x{p2.Handle:X}'"");
if (p2.Name != ""John Smith"")
throw new InvalidOperationException (""JSON deserialization of Name"");
if (p2.Age != 900)
throw new InvalidOperationException (""JSON deserialization of Age"");
if (p2.Handle == IntPtr.Zero)
throw new InvalidOperationException (""Failed to instantiate new Java instance for Person!"");
Console.WriteLine ($""JSON Person deserialized OK"");
}
void TestJsonDeserializationCreatesJavaHandle ()
{
Person p = new Person () {
Name = ""John Smith"",
Age = 900,
};
TestJsonDeserialization (p);").Replace ("//${AFTER_MAINACTIVITY}", @"
[DataContract]
[Serializable]
class Person : Java.Lang.Object {
[DataMember]
public string Name;
[DataMember]
public int Age;
internal sealed class Binder : SerializationBinder
{
public override Type BindToType (string assemblyName, string typeName)
{
if (typeName == ""Person"")
return typeof (Person);
return null;
}
}
}");
string usings =
@"using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
";
proj.MainActivity = usings + proj.MainActivity;
builder = CreateApkBuilder ();
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
AdbStartActivity ($"{proj.PackageName}/{proj.JavaPackageName}.MainActivity");
Assert.IsFalse (MonitorAdbLogcat ((line) => {
return line.Contains ("TestJsonDeserializationCreatesJavaHandle");
}, Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), 60), $"Output did contain TestJsonDeserializationCreatesJavaHandle!");
}
[Test]
public void RunWithInterpreterEnabled ([Values (false, true)] bool isRelease)
{
proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
AotAssemblies = false, // Release defaults to Profiled AOT for .NET 6
};
var abis = new string[] { "armeabi-v7a", "arm64-v8a", "x86", "x86_64" };
proj.SetAndroidSupportedAbis (abis);
proj.SetProperty (proj.CommonProperties, "UseInterpreter", "True");
builder = CreateApkBuilder ();
builder.BuildLogFile = "install.log";
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunAdbCommand ("shell setprop debug.mono.log all");
var logProp = RunAdbCommand ("shell getprop debug.mono.log")?.Trim ();
Assert.AreEqual (logProp, "all", "The debug.mono.log prop was not set correctly.");
RunProjectAndAssert (proj, builder);
Func<string, bool> checkForInterpMessage = line => {
return line.Contains ("Enabling Mono Interpreter");
};
var timeoutInSeconds = 120;
var didPrintInterpMessage = MonitorAdbLogcat (
action: checkForInterpMessage,
logcatFilePath: Path.Combine (Root, builder.ProjectDirectory, "interpreter-logcat.log"),
timeout: timeoutInSeconds);
var didStart = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), timeoutInSeconds);
ClearShellProp ("debug.mono.log");
logProp = RunAdbCommand ("shell getprop debug.mono.log")?.Trim ();
Assert.AreEqual (logProp, string.Empty, "The debug.mono.log prop was not unset correctly.");
Assert.IsTrue (didPrintInterpMessage, "logcat output did not contain 'Enabling Mono Interpreter'.");
Assert.IsTrue (didStart, "Activity should have started.");
}
[Test]
public void RunWithLLVMEnabled ()
{
var proj = new XamarinAndroidApplicationProject () {
IsRelease = true,
};
proj.SetAndroidSupportedAbis ("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
proj.SetProperty ("EnableLLVM", true.ToString ());
builder = CreateApkBuilder ();
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunProjectAndAssert (proj, builder);
var activityNamespace = proj.PackageName;
var activityName = "MainActivity";
var logcatFilePath = Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log");
var failedToLoad = new List<string> ();
bool appLaunched = MonitorAdbLogcat ((line) => {
if (SeenFailedToLoad (line))
failedToLoad.Add (line);
return SeenActivityDisplayed (line);
}, logcatFilePath, timeout: 120);
Assert.IsTrue (appLaunched, "LLVM app did not launch");
Assert.AreEqual (0, failedToLoad.Count, $"LLVM .so files not loaded:\n{string.Join ("\n", failedToLoad)}");
bool SeenActivityDisplayed (string line)
{
var idx1 = line.IndexOf ("ActivityManager: Displayed", StringComparison.OrdinalIgnoreCase);
var idx2 = idx1 > 0 ? 0 : line.IndexOf ("ActivityTaskManager: Displayed", StringComparison.OrdinalIgnoreCase);
return (idx1 > 0 || idx2 > 0) && line.Contains (activityNamespace) && line.Contains (activityName);
}
bool SeenFailedToLoad (string line)
{
return line.Contains ("Failed to load shared library");
}
}
[Test]
public void ResourceDesignerWithNuGetReference ([Values ("net8.0-android")] string dotnetTargetFramework)
{
// Build a NuGet Package
var nuget = new XamarinAndroidLibraryProject () {
Sdk = "Xamarin.Legacy.Sdk/0.2.0-alpha4",
ProjectName = "Test.Nuget.Package",
IsRelease = true,
ExtraNuGetConfigSources = {
"https://api.nuget.org/v3/index.json",
},
};
nuget.Sources.Clear ();
nuget.Sources.Add (new AndroidItem.AndroidResource ("Resources/values/Strings.xml") {
TextContent = () => @"<resources>
<string name='library_resouce_from_nuget'>Library Resource From Nuget</string>
</resources>",
});
nuget.SetProperty ("PackageName", "Test.Nuget.Package");
var legacyTargetFrameworkVersion = "13.0";
var legacyTargetFramework = $"monoandroid{legacyTargetFrameworkVersion}";
nuget.TargetFramework = "";
nuget.TargetFrameworks = $"{dotnetTargetFramework};{legacyTargetFramework}";
var rootPath = Path.Combine (Root, "temp", TestName);
var nugetBuilder = CreateDllBuilder (Path.Combine (rootPath, nuget.ProjectName));
nugetBuilder.Save (nuget);
var dotnet = new DotNetCLI (Path.Combine (rootPath, nuget.ProjectName, nuget.ProjectFilePath));
Assert.IsTrue (dotnet.Pack (parameters: new [] { "Configuration=Release" }), "`dotnet pack` should succeed");
// Build an app which references it.
var proj = new XamarinAndroidApplicationProject () {
ProjectName = "App1",
IsRelease = true,
};
proj.SetAndroidSupportedAbis (DeviceAbi);
proj.OtherBuildItems.Add (new BuildItem ("None", "NuGet.config") {
TextContent = () => @"<?xml version='1.0' encoding='utf-8'?>
<configuration>
<packageSources>
<add key='local' value='" + Path.Combine (Root, nugetBuilder.ProjectDirectory, "bin", "Release") + @"' />
</packageSources>
</configuration>",
});
proj.PackageReferences.Add (new Package {
Id = "Test.Nuget.Package",
Version = "1.0.0",
});
builder = CreateApkBuilder (Path.Combine (rootPath, proj.ProjectName));
Assert.IsTrue (builder.Install (proj, doNotCleanupOnUpdate: true), "Install should have succeeded.");
string resource_designer = GetResourceDesignerPath (builder, proj);
var contents = GetResourceDesignerText (proj, resource_designer);
StringAssert.Contains ("public const int library_resouce_from_nuget =", contents);
}
[Test]
public void SingleProject_ApplicationId ([Values (false, true)] bool testOnly)
{
AssertCommercialBuild ();
proj = new XamarinAndroidApplicationProject ();
proj.SetProperty ("ApplicationId", "com.i.should.get.overridden.by.the.manifest");
if (testOnly)
proj.AndroidManifest = proj.AndroidManifest.Replace ("<application", "<application android:testOnly=\"true\"");
var abis = new string [] { "armeabi-v7a", "arm64-v8a", "x86", "x86_64" };
proj.SetAndroidSupportedAbis (abis);
builder = CreateApkBuilder ();
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunProjectAndAssert (proj, builder);
var didStart = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"));
Assert.IsTrue (didStart, "Activity should have started.");
}
[Test]
public void AppWithStyleableUsageRuns ([Values (true, false)] bool isRelease, [Values (true, false)] bool linkResources)
{
var rootPath = Path.Combine (Root, "temp", TestName);
var lib = new XamarinAndroidLibraryProject () {
ProjectName = "Styleable.Library"
};
lib.AndroidResources.Add (new AndroidItem.AndroidResource ("Resources\\values\\styleables.xml") {
TextContent = () => @"<?xml version='1.0' encoding='utf-8'?>
<resources>
<declare-styleable name='MyLibraryView'>
<attr name='MyBool' format='boolean' />
<attr name='MyInt' format='integer' />
</declare-styleable>
</resources>",
});
lib.AndroidResources.Add (new AndroidItem.AndroidResource ("Resources\\layout\\librarylayout.xml") {
TextContent = () => @"<?xml version='1.0' encoding='utf-8'?>
<Styleable.Library.MyLibraryLayout xmlns:app='http://schemas.android.com/apk/res-auto' app:MyBool='true' app:MyInt='128'/>
",
});
lib.Sources.Add (new BuildItem.Source ("MyLibraryLayout.cs") {
TextContent = () => @"using System;
namespace Styleable.Library {
public class MyLibraryLayout : Android.Widget.LinearLayout
{
public MyLibraryLayout (Android.Content.Context context, Android.Util.IAttributeSet attrs) : base (context, attrs)
{
Android.Content.Res.TypedArray a = context.Theme.ObtainStyledAttributes (attrs, Resource.Styleable.MyLibraryView, 0,0);
try {
bool b = a.GetBoolean (Resource.Styleable.MyLibraryView_MyBool, defValue: false);
if (!b)
throw new Exception (""MyBool was not true."");
int i = a.GetInteger (Resource.Styleable.MyLibraryView_MyInt, defValue: -1);
if (i != 128)
throw new Exception (""MyInt was not 128."");
}
finally {
a.Recycle();
}
}
}
}"
});
proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
};
proj.AddReference (lib);
proj.AndroidResources.Add (new AndroidItem.AndroidResource ("Resources\\values\\styleables.xml") {
TextContent = () => @"<?xml version='1.0' encoding='utf-8'?>
<resources>
<declare-styleable name='MyView'>
<attr name='MyBool' format='boolean' />
<attr name='MyInt' format='integer' />
</declare-styleable>
</resources>",
});
proj.SetProperty ("AndroidLinkResources", linkResources ? "False" : "True");
proj.LayoutMain = proj.LayoutMain.Replace ("<LinearLayout", "<UnnamedProject.MyLayout xmlns:app='http://schemas.android.com/apk/res-auto' app:MyBool='true' app:MyInt='128'")
.Replace ("</LinearLayout>", "</UnnamedProject.MyLayout>");
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_MAINACTIVITY}",
@"public class MyLayout : Android.Widget.LinearLayout
{
public MyLayout (Android.Content.Context context, Android.Util.IAttributeSet attrs) : base (context, attrs)
{
Android.Content.Res.TypedArray a = context.Theme.ObtainStyledAttributes (attrs, Resource.Styleable.MyView, 0,0);
try {
bool b = a.GetBoolean (Resource.Styleable.MyView_MyBool, defValue: false);
if (!b)
throw new Exception (""MyBool was not true."");
int i = a.GetInteger (Resource.Styleable.MyView_MyInt, defValue: -1);
if (i != 128)
throw new Exception (""MyInt was not 128."");
}
finally {
a.Recycle();
}
}
}
");
var abis = new string [] { "armeabi-v7a", "arm64-v8a", "x86", "x86_64" };
proj.SetAndroidSupportedAbis (abis);
var libBuilder = CreateDllBuilder (Path.Combine (rootPath, lib.ProjectName));
Assert.IsTrue (libBuilder.Build (lib), "Library should have built succeeded.");
builder = CreateApkBuilder (Path.Combine (rootPath, proj.ProjectName));
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
RunProjectAndAssert (proj, builder);
var didStart = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"));
Assert.IsTrue (didStart, "Activity should have started.");
}
[Test]
public void CheckXamarinFormsAppDeploysAndAButtonWorks ()
{
var proj = new XamarinFormsAndroidApplicationProject ();
proj.SetAndroidSupportedAbis (DeviceAbi);
var builder = CreateApkBuilder ();
Assert.IsTrue (builder.Build (proj), "Build should have succeeded.");
builder.BuildLogFile = "install.log";
Assert.IsTrue (builder.Install (proj), "Install should have succeeded.");
AdbStartActivity ($"{proj.PackageName}/{proj.JavaPackageName}.MainActivity");
WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "startup-logcat.log"), 15);
ClearAdbLogcat ();
ClearBlockingDialogs ();
ClickButton (proj.PackageName, "myXFButton", "CLICK ME");
Assert.IsTrue (MonitorAdbLogcat ((line) => {
return line.Contains ("Button was Clicked!");
}, Path.Combine (Root, builder.ProjectDirectory, "button-logcat.log")), "Button Should have been Clicked.");
}
[Test]
public void SkiaSharpCanvasBasedAppRuns ([Values (true, false)] bool isRelease, [Values (true, false)] bool addResource)
{
var app = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
PackageName = "Xamarin.SkiaSharpCanvasTest",
PackageReferences = {
KnownPackages.SkiaSharp,
KnownPackages.SkiaSharp_Views,
KnownPackages.AndroidXAppCompat,
KnownPackages.AndroidXAppCompatResources,
},
};
app.AndroidResources.Add (new AndroidItem.AndroidResource ("Resources\\values\\styles.xml") {
TextContent = () => @"<resources><style name='AppTheme' parent='Theme.AppCompat.Light.DarkActionBar'/></resources>",
});
// begin Remove these lines when the new fixed SkiaSharp is released.
if (addResource) {
app.AndroidResources.Add (new AndroidItem.AndroidResource ("Resources\\values\\attrs.xml") {
TextContent = () => @"<resources><declare-styleable name='SKCanvasView'>
<attr name='ignorePixelScaling' format='boolean'/>
</declare-styleable></resources>",
});
}
// end
app.LayoutMain = app.LayoutMain.Replace ("<LinearLayout", @"<FrameLayout
xmlns:android='http://schemas.android.com/apk/res/android'
xmlns:app='http://schemas.android.com/apk/res-auto'
android:layout_width='match_parent'
android:layout_height='match_parent'>
<SkiaSharp.Views.Android.SKCanvasView
android:layout_width='match_parent'
android:layout_height='match_parent'
android:id='@+id/skiaView' />")
.Replace ("</LinearLayout>", "</FrameLayout>");
app.MainActivity = @"using Android.App;
using Android.OS;
using AndroidX.AppCompat.App;
using SkiaSharp;
using SkiaSharp.Views.Android;
namespace UnnamedProject
{
[Activity(MainLauncher = true, Theme = ""@style/AppTheme"")]
public class MainActivity : AppCompatActivity
{
private SKCanvasView skiaView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
skiaView = FindViewById<SKCanvasView>(Resource.Id.skiaView);
}
protected override void OnResume()
{
base.OnResume();
skiaView.PaintSurface += OnPaintSurface;
}
protected override void OnPause()
{
skiaView.PaintSurface -= OnPaintSurface;
base.OnPause();
}
private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
// the the canvas and properties
var canvas = e.Surface.Canvas;
// make sure the canvas is blank
canvas.Clear(SKColors.White);
// draw some text
var paint = new SKPaint
{
Color = SKColors.Black,
IsAntialias = true,
Style = SKPaintStyle.Fill,
TextAlign = SKTextAlign.Center,
TextSize = 24
};
var coord = new SKPoint(e.Info.Width / 2, (e.Info.Height + paint.TextSize) / 2);
canvas.DrawText(""SkiaSharp"", coord, paint);
}
}
}
";
using (var b = CreateApkBuilder (Path.Combine ("temp", TestName, app.ProjectName))) {
b.BuildLogFile = "build1.log";
b.ThrowOnBuildFailure = false;
if (!addResource) {
Assert.IsFalse (b.Build (app, doNotCleanupOnUpdate: true), $"Build of {app.ProjectName} should have failed.");
Assert.IsTrue (b.LastBuildOutput.ContainsText (isRelease ? "IL8000" : "XA8000"));
Assert.IsTrue (b.LastBuildOutput.ContainsText ("@styleable/SKCanvasView"), "Expected '@styleable/SKCanvasView' in build output.");
Assert.IsTrue (b.LastBuildOutput.ContainsText ("@styleable/SKCanvasView_ignorePixelScaling"), "Expected '@styleable/SKCanvasView_ignorePixelScaling' in build output.");
return;
}
Assert.IsTrue (b.Build (app, doNotCleanupOnUpdate: true), $"Build of {app.ProjectName} should have succeeded.");
b.BuildLogFile = "install1.log";
Assert.IsTrue (b.Install (app, doNotCleanupOnUpdate: true), "Install should have suceeded.");
AdbStartActivity ($"{app.PackageName}/{app.JavaPackageName}.MainActivity");
WaitForPermissionActivity (Path.Combine (Root, b.ProjectDirectory, "permission-logcat.log"));
ClearAdbLogcat ();
WaitForActivityToStart (app.PackageName, "MainActivity",
Path.Combine (Root, b.ProjectDirectory, "startup-logcat.log"), 15);
}
}
[Test]
public void CheckResouceIsOverridden ()
{
var library = new XamarinAndroidLibraryProject () {
ProjectName = "Library1",
AndroidResources = {
new AndroidItem.AndroidResource (() => "Resources\\values\\strings2.xml") {
TextContent = () => @"<?xml version=""1.0"" encoding=""utf-8""?>
<resources>
<string name=""hello_me"">Click Me! One</string>
</resources>",
},
},
};
var library2 = new XamarinAndroidLibraryProject () {
ProjectName = "Library2",
AndroidResources = {
new AndroidItem.AndroidResource (() => "Resources\\values\\strings2.xml") {
TextContent = () => @"<?xml version=""1.0"" encoding=""utf-8""?>
<resources>
<string name=""hello_me"">Click Me! Two</string>
</resources>",
},
},
};
var app = new XamarinAndroidApplicationProject () {
PackageName = "Xamarin.ResourceTest",
References = {
new BuildItem.ProjectReference ("..\\Library1\\Library1.csproj"),
new BuildItem.ProjectReference ("..\\Library2\\Library2.csproj"),
},
};
app.LayoutMain = app.LayoutMain.Replace ("@string/hello", "@string/hello_me");
using (var l1 = CreateDllBuilder (Path.Combine ("temp", TestName, library.ProjectName)))
using (var l2 = CreateDllBuilder (Path.Combine ("temp", TestName, library2.ProjectName)))
using (var b = CreateApkBuilder (Path.Combine ("temp", TestName, app.ProjectName))) {
b.ThrowOnBuildFailure = false;
b.LatestTargetFrameworkVersion (out string apiLevel);
app.SupportedOSPlatformVersion = "24";
app.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=""{app.PackageName}"">
<uses-sdk android:targetSdkVersion=""{apiLevel}"" />
<application android:label=""${{PROJECT_NAME}}"">
</application >
</manifest> ";
Assert.IsTrue (l1.Build (library, doNotCleanupOnUpdate: true), $"Build of {library.ProjectName} should have suceeded.");
Assert.IsTrue (l2.Build (library2, doNotCleanupOnUpdate: true), $"Build of {library2.ProjectName} should have suceeded.");
b.BuildLogFile = "build1.log";
Assert.IsTrue (b.Build (app, doNotCleanupOnUpdate: true), $"Build of {app.ProjectName} should have suceeded.");
b.BuildLogFile = "install1.log";
Assert.IsTrue (b.Install (app, doNotCleanupOnUpdate: true), "Install should have suceeded.");
AdbStartActivity ($"{app.PackageName}/{app.JavaPackageName}.MainActivity");
WaitForPermissionActivity (Path.Combine (Root, b.ProjectDirectory, "permission-logcat.log"));
WaitForActivityToStart (app.PackageName, "MainActivity",
Path.Combine (Root, b.ProjectDirectory, "startup-logcat.log"), 15);
ClearBlockingDialogs ();
XDocument ui = GetUI ();
XElement node = ui.XPathSelectElement ($"//node[contains(@resource-id,'myButton')]");
Assert.IsNotNull (node , "Could not find `my-Button` in the user interface. Check the screenshot of the test failure.");
StringAssert.AreEqualIgnoringCase ("Click Me! One", node.Attribute ("text").Value, "Text of Button myButton should have been \"Click Me! One\"");
b.BuildLogFile = "clean.log";
Assert.IsTrue (b.Clean (app, doNotCleanupOnUpdate: true), "Clean should have suceeded.");
app = new XamarinAndroidApplicationProject () {
PackageName = "Xamarin.ResourceTest",
References = {
new BuildItem.ProjectReference ("..\\Library1\\Library1.csproj"),
new BuildItem.ProjectReference ("..\\Library2\\Library2.csproj"),
},
};
library2.References.Add (new BuildItem.ProjectReference ("..\\Library1\\Library1.csproj"));
app.LayoutMain = app.LayoutMain.Replace ("@string/hello", "@string/hello_me");
b.LatestTargetFrameworkVersion (out apiLevel);
app.SupportedOSPlatformVersion = "24";
app.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=""{app.PackageName}"">
<uses-sdk android:targetSdkVersion=""{apiLevel}"" />
<application android:label=""${{PROJECT_NAME}}"">
</application >
</manifest> ";
b.BuildLogFile = "build.log";
Assert.IsTrue (b.Build (app, doNotCleanupOnUpdate: true), $"Build of {app.ProjectName} should have suceeded.");
b.BuildLogFile = "install.log";
Assert.IsTrue (b.Install (app, doNotCleanupOnUpdate: true), "Install should have suceeded.");
AdbStartActivity ($"{app.PackageName}/{app.JavaPackageName}.MainActivity");
WaitForPermissionActivity (Path.Combine (Root, b.ProjectDirectory, "permission-logcat.log"));
WaitForActivityToStart (app.PackageName, "MainActivity",
Path.Combine (Root, b.ProjectDirectory, "startup-logcat.log"), 15);
ui = GetUI ();
node = ui.XPathSelectElement ($"//node[contains(@resource-id,'myButton')]");
StringAssert.AreEqualIgnoringCase ("Click Me! One", node.Attribute ("text").Value, "Text of Button myButton should have been \"Click Me! One\"");
}
}
[Test]
[Category ("WearOS")]
public void DotNetInstallAndRunPreviousSdk ([Values (false, true)] bool isRelease)
{
var proj = new XamarinFormsAndroidApplicationProject () {
TargetFramework = "net7.0-android",
IsRelease = isRelease,
EnableDefaultItems = true,
};
var builder = CreateApkBuilder ();
Assert.IsTrue (builder.Build (proj), "`dotnet build` should succeed");
RunProjectAndAssert (proj, builder);
WaitForPermissionActivity (Path.Combine (Root, builder.ProjectDirectory, "permission-logcat.log"));
bool didLaunch = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "logcat.log"), 30);
Assert.IsTrue(didLaunch, "Activity should have started.");
}
[Test]
public void TypeAndMemberRemapping ([Values (false, true)] bool isRelease)
{
var proj = new XamarinAndroidApplicationProject () {
IsRelease = isRelease,
EnableDefaultItems = true,
OtherBuildItems = {
new AndroidItem._AndroidRemapMembers ("RemapActivity.xml") {
Encoding = Encoding.UTF8,
TextContent = () => ResourceData.RemapActivityXml,
},
new AndroidItem.AndroidJavaSource ("RemapActivity.java") {
Encoding = new UTF8Encoding (encoderShouldEmitUTF8Identifier: false),
TextContent = () => ResourceData.RemapActivityJava,
Metadata = {
{ "Bind", "True" },
},
},
},
};
proj.MainActivity = proj.DefaultMainActivity.Replace (": Activity", ": global::Example.RemapActivity");
var builder = CreateApkBuilder ();
Assert.IsTrue (builder.Build (proj), "`dotnet build` should succeed");
RunProjectAndAssert (proj, builder);
var appStartupLogcatFile = Path.Combine (Root, builder.ProjectDirectory, "logcat.log");
bool didLaunch = WaitForActivityToStart (proj.PackageName, "MainActivity", appStartupLogcatFile);
Assert.IsTrue (didLaunch, "MainActivity should have launched!");
var logcatOutput = File.ReadAllText (appStartupLogcatFile);
StringAssert.Contains (
"RemapActivity.onMyCreate() invoked!",
logcatOutput,
"Activity.onCreate() wasn't remapped to RemapActivity.onMyCreate()!"
);
StringAssert.Contains (
"ViewHelper.mySetOnClickListener() invoked!",
logcatOutput,
"View.setOnClickListener() wasn't remapped to ViewHelper.mySetOnClickListener()!"
);
}
[Test]
public void SupportDesugaringStaticInterfaceMethods ()
{
var proj = new XamarinAndroidApplicationProject () {
IsRelease = true,
EnableDefaultItems = true,
OtherBuildItems = {
new AndroidItem.AndroidJavaSource ("StaticMethodsInterface.java") {
Encoding = new UTF8Encoding (encoderShouldEmitUTF8Identifier: false),
TextContent = () => ResourceData.IdmStaticMethodsInterface,
Metadata = {
{ "Bind", "True" },
},
},
},
};
// Note: To properly test, Desugaring must be *enabled*, which requires that
// `$(SupportedOSPlatformVersion)` be *less than* 23. 21 is currently the default,
// but set this explicitly anyway just so that this implicit requirement is explicit.
proj.SupportedOSPlatformVersion = "21";
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}", @"