Exemplo n.º 1
0
        public void EnvironmentFileContents()
        {
            string javaEnv = Path.Combine(testProjectPath, "obj", XABuildPaths.Configuration, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");

            Assert.That(new FileInfo(javaEnv), Does.Exist, $"File {javaEnv} should exist");

            string[] envLines = File.ReadAllLines(javaEnv);
            Assert.That(envLines.Any(l => !String.IsNullOrEmpty(l)), Is.True, $"Environment file {javaEnv} must contain at least one non-empty line");

            bool found = false;

            foreach (string line in envLines)
            {
                if (String.IsNullOrEmpty(line))
                {
                    continue;
                }

                if (line.IndexOf("\"__XA_DSO_IN_APK\",") >= 0)
                {
                    found = true;
                    break;
                }
            }

            Assert.That(found, Is.True, $"The `__XA_DSO_IN_APK` variable wasn't found in the environment file {javaEnv}");

            string dexFile = Path.Combine(testProjectPath, "obj", XABuildPaths.Configuration, "android", "bin", "classes.dex");

            Assert.That(new FileInfo(dexFile), Does.Exist, $"File {dexFile} should exist");
            Assert.That(DexUtils.ContainsClass("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, androidSdkDir), Is.True, $"Dex file {dexFile} should contain the XamarinAndroidEnvironmentVariables class");
        }
Exemplo n.º 2
0
        public void CheckBuildIdIsUnique()
        {
            Dictionary <string, string> buildIds = new Dictionary <string, string> ();
            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease = true,
            };

            proj.SetProperty(proj.ReleaseProperties, "MonoSymbolArchive", "True");
            proj.SetProperty(proj.ReleaseProperties, "DebugSymbols", "true");
            proj.SetProperty(proj.ReleaseProperties, "DebugType", "PdbOnly");
            proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, "true");
            proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidSupportedAbis, "armeabi-v7a;x86");
            using (var b = CreateApkBuilder(Path.Combine("temp", TestContext.CurrentContext.Test.Name))) {
                b.Verbosity           = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;
                b.ThrowOnBuildFailure = false;
                Assert.IsTrue(b.Build(proj), "first build failed");
                var    outputPath        = Path.Combine(Root, b.ProjectDirectory, proj.OutputPath);
                var    archivePath       = Path.Combine(outputPath, proj.PackageName + ".apk.mSYM");
                var    allFilesInArchive = Directory.GetFiles(archivePath, "*", SearchOption.AllDirectories);
                string extension         = "dll";
                Assert.IsTrue(allFilesInArchive.Any(x => Path.GetFileName(x) == $"{proj.ProjectName}.{extension}"), $"{proj.ProjectName}.{extension} should exist in {archivePath}");
                //NOTE: Windows is still generating mdb files here
                extension = IsWindows ? "dll.mdb" : "pdb";
                Assert.IsTrue(allFilesInArchive.Any(x => Path.GetFileName(x) == $"{proj.ProjectName}.{extension}"), $"{proj.ProjectName}.{extension} should exist in {archivePath}");
                string javaEnv = Path.Combine(Root, b.ProjectDirectory,
                                              proj.IntermediateOutputPath, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");
                Assert.IsTrue(File.Exists(javaEnv), $"Java environment source does not exist at {javaEnv}");

                string[] lines = File.ReadAllLines(javaEnv);

                Assert.IsTrue(lines.Any(x => x.Contains("\"XAMARIN_BUILD_ID\",")),
                              "The environment should contain a XAMARIN_BUILD_ID");

                string buildID = lines.First(x => x.Contains("\"XAMARIN_BUILD_ID\","))
                                 .Trim()
                                 .Replace("\", \"", "=")
                                 .Replace("\",", String.Empty)
                                 .Replace("\"", String.Empty);
                buildIds.Add("all", buildID);

                string dexFile = Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "bin", "classes.dex");
                Assert.IsTrue(File.Exists(dexFile), $"dex file does not exist at {dexFile}");
                Assert.IsTrue(DexUtils.ContainsClass("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, b.AndroidSdkDirectory),
                              $"dex file {dexFile} does not contain the XamarinAndroidEnvironmentVariables class");

                var msymDirectory = Path.Combine(Root, b.ProjectDirectory, proj.OutputPath, proj.PackageName + ".apk.mSYM");
                Assert.IsTrue(File.Exists(Path.Combine(msymDirectory, "manifest.xml")), "manifest.xml should exist in", msymDirectory);
                var doc = XDocument.Load(Path.Combine(msymDirectory, "manifest.xml"));

                Assert.IsTrue(doc.Element("mono-debug")
                              .Elements()
                              .Any(x => x.Name == "app-id" && x.Value == proj.PackageName), "app-id is has an incorrect value.");
                var buildId = buildIds.First().Value;
                Assert.IsTrue(doc.Element("mono-debug")
                              .Elements()
                              .Any(x => x.Name == "build-id" && x.Value == buildId.Replace("XAMARIN_BUILD_ID=", "")), "build-id is has an incorrect value.");
            }
        }
Exemplo n.º 3
0
        public void InstantRunSimpleBuild([Values("dx", "d8")] string dexTool)
        {
            if (!CommercialBuildAvailable)
            {
                Assert.Ignore("Not required on Open Source Builds");
            }

            if (!HasDevices)
            {
                Assert.Ignore("Test needs a device attached.");
                return;
            }

            var proj = new XamarinFormsAndroidApplicationProject {
                AndroidFastDeploymentType = "Assemblies:Dexes",
                UseLatestPlatformSdk      = true,
                DexTool = dexTool,
            };
            var b = CreateApkBuilder(Path.Combine("temp", TestName));

            Assert.IsTrue(b.Clean(proj), "Clean should have succeeded.");
            Assert.IsTrue(b.Build(proj), "Build should have succeeded.");

            var manifest = b.Output.GetIntermediaryAsText(BuildOutputFiles.AndroidManifest);

            Assert.IsTrue(File.Exists(b.Output.GetIntermediaryPath("android/bin/dex/mono.android.dex")), "there should be mono.android.dex in the intermediaries.");

            using (var apk = ((AndroidApplicationBuildOutput)b.Output).OpenApk()) {
                var dexFile = Path.GetTempFileName();
                File.WriteAllBytes(dexFile, apk.GetRaw(ApkContents.ClassesDex));
                try {
                    string className = "Lcom/xamarin/forms/platform/android/FormsViewGroup;";
                    Assert.IsFalse(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should *not* include `{className}`!");
                    className = "Lmono/MonoRuntimeProvider;";
                    Assert.IsFalse(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");
                    className = "Lmono/MonoPackageManager;";
                    Assert.IsTrue(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");
                } finally {
                    File.Delete(dexFile);
                }
            }

            b.Dispose();
        }
        public void ChangePackageNamingPolicy()
        {
            var proj = new XamarinAndroidApplicationProject();

            proj.Sources.Add(new BuildItem.Source("Bar.cs")
            {
                TextContent = () => "namespace Foo { class Bar : Java.Lang.Object { } }"
            });
            proj.SetProperty("AndroidPackageNamingPolicy", "LowercaseMD5");
            using (var b = CreateApkBuilder()) {
                Assert.IsTrue(b.Build(proj), "first build should have succeeded.");
                var dexFile   = b.Output.GetIntermediaryPath(Path.Combine("android", "bin", "classes.dex"));
                var className = "Lmd5aaee5c01293e648941eac447719ef3fb/Bar;";
                Assert.IsTrue(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");

                proj.SetProperty("AndroidPackageNamingPolicy", "LowercaseCrc64");
                Assert.IsTrue(b.Build(proj), "second build should have succeeded.");
                Assert.IsFalse(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should *not* include `{className}`!");
                className = "Lcrc64dca3aed1e0ff8a1a/Bar;";
                Assert.IsTrue(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");
            }
        }
Exemplo n.º 5
0
        public void DotNetBuildLibrary(bool isRelease, bool duplicateAar)
        {
            var path    = Path.Combine("temp", TestName);
            var env_var = "MY_ENVIRONMENT_VAR";
            var env_val = "MY_VALUE";

            // Setup dependencies App A -> Lib B -> Lib C

            var libC = new XASdkProject(outputType: "Library")
            {
                ProjectName = "LibraryC",
                IsRelease   = isRelease,
                Sources     =
                {
                    new BuildItem.Source("Bar.cs")
                    {
                        TextContent = () => "public class Bar { }",
                    }
                }
            };

            libC.OtherBuildItems.Add(new AndroidItem.AndroidAsset("Assets\\bar\\bar.txt")
            {
                BinaryContent = () => Array.Empty <byte> (),
            });
            var activity = libC.Sources.FirstOrDefault(s => s.Include() == "MainActivity.cs");

            if (activity != null)
            {
                libC.Sources.Remove(activity);
            }
            var libCBuilder = CreateDotNetBuilder(libC, Path.Combine(path, libC.ProjectName));

            Assert.IsTrue(libCBuilder.Build(), $"{libC.ProjectName} should succeed");

            var libB = new XASdkProject(outputType: "Library")
            {
                ProjectName = "LibraryB",
                IsRelease   = isRelease,
                Sources     =
                {
                    new BuildItem.Source("Foo.cs")
                    {
                        TextContent = () => "public class Foo : Bar { }",
                    }
                }
            };

            libB.OtherBuildItems.Add(new AndroidItem.AndroidAsset("Assets\\foo\\foo.txt")
            {
                BinaryContent = () => Array.Empty <byte> (),
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidResource("Resources\\layout\\MyLayout.axml")
            {
                TextContent = () => "<?xml version=\"1.0\" encoding=\"utf-8\" ?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" />"
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidResource("Resources\\raw\\bar.txt")
            {
                BinaryContent = () => Array.Empty <byte> (),
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidEnvironment("env.txt")
            {
                TextContent = () => $"{env_var}={env_val}",
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidEnvironment("sub\\directory\\env.txt")
            {
                TextContent = () => $"{env_var}={env_val}",
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidLibrary("sub\\directory\\foo.jar")
            {
                BinaryContent = () => Convert.FromBase64String(InlineData.JavaClassesJarBase64),
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidLibrary("sub\\directory\\arm64-v8a\\libfoo.so")
            {
                BinaryContent = () => Array.Empty <byte> (),
            });
            libB.OtherBuildItems.Add(new AndroidItem.AndroidLibrary("libfoo.so")
            {
                MetadataValues = "Link=x86\\libfoo.so",
                BinaryContent  = () => Array.Empty <byte> (),
            });
            libB.AddReference(libC);

            activity = libB.Sources.FirstOrDefault(s => s.Include() == "MainActivity.cs");
            if (activity != null)
            {
                libB.Sources.Remove(activity);
            }
            var libBBuilder = CreateDotNetBuilder(libB, Path.Combine(path, libB.ProjectName));

            Assert.IsTrue(libBBuilder.Build(), $"{libB.ProjectName} should succeed");

            // Check .aar file for class library
            var aarPath = Path.Combine(FullProjectDirectory, libB.OutputPath, $"{libB.ProjectName}.aar");

            FileAssert.Exists(aarPath);
            using (var aar = ZipHelper.OpenZip(aarPath)) {
                aar.AssertContainsEntry(aarPath, "assets/foo/foo.txt");
                aar.AssertContainsEntry(aarPath, "res/layout/mylayout.xml");
                aar.AssertContainsEntry(aarPath, "res/raw/bar.txt");
                aar.AssertContainsEntry(aarPath, ".net/__res_name_case_map.txt");
                aar.AssertContainsEntry(aarPath, ".net/env/190E30B3D205731E.env");
                aar.AssertContainsEntry(aarPath, ".net/env/2CBDAB7FEEA94B19.env");
                aar.AssertContainsEntry(aarPath, "libs/A1AFA985571E728E.jar");
                aar.AssertContainsEntry(aarPath, "jni/arm64-v8a/libfoo.so");
                aar.AssertContainsEntry(aarPath, "jni/x86/libfoo.so");
            }

            // Check EmbeddedResource files do not exist
            var assemblyPath = Path.Combine(FullProjectDirectory, libB.OutputPath, $"{libB.ProjectName}.dll");

            FileAssert.Exists(assemblyPath);
            using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) {
                Assert.AreEqual(0, assembly.MainModule.Resources.Count);
            }

            var appA = new XASdkProject {
                ProjectName = "AppA",
                IsRelease   = isRelease,
                Sources     =
                {
                    new BuildItem.Source("Bar.cs")
                    {
                        TextContent = () => "public class Bar : Foo { }",
                    }
                }
            };

            appA.AddReference(libB);
            if (duplicateAar)
            {
                // Test a duplicate @(AndroidLibrary) item with the same path of LibraryB.aar
                appA.OtherBuildItems.Add(new AndroidItem.AndroidLibrary(aarPath));
            }
            var appBuilder = CreateDotNetBuilder(appA, Path.Combine(path, appA.ProjectName));

            Assert.IsTrue(appBuilder.Build(), $"{appA.ProjectName} should succeed");

            // Check .apk for assets, res, and native libraries
            var apkPath = Path.Combine(FullProjectDirectory, appA.OutputPath, $"{appA.PackageName}.apk");

            FileAssert.Exists(apkPath);
            using (var apk = ZipHelper.OpenZip(apkPath)) {
                apk.AssertContainsEntry(apkPath, "assets/foo/foo.txt");
                apk.AssertContainsEntry(apkPath, "assets/bar/bar.txt");
                apk.AssertContainsEntry(aarPath, "res/layout/mylayout.xml");
                apk.AssertContainsEntry(apkPath, "res/raw/bar.txt");
                apk.AssertContainsEntry(apkPath, "lib/arm64-v8a/libfoo.so");
                apk.AssertContainsEntry(apkPath, "lib/x86/libfoo.so");
            }

            // Check classes.dex contains foo.jar
            var intermediate = Path.Combine(FullProjectDirectory, appA.IntermediateOutputPath);
            var dexFile      = Path.Combine(intermediate, "android", "bin", "classes.dex");

            FileAssert.Exists(dexFile);
            string className = "Lcom/xamarin/android/test/msbuildtest/JavaSourceJarTest;";

            Assert.IsTrue(DexUtils.ContainsClass(className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");

            // Check environment variable
            var environmentFiles     = EnvironmentHelper.GatherEnvironmentFiles(intermediate, "x86", required: true);
            var environmentVariables = EnvironmentHelper.ReadEnvironmentVariables(environmentFiles);

            Assert.IsTrue(environmentVariables.TryGetValue(env_var, out string actual), $"Environment should contain {env_var}");
            Assert.AreEqual(env_val, actual, $"{env_var} should be {env_val}");

            // Check Resource.designer.cs
            var resource_designer_cs = Path.Combine(intermediate, "Resource.designer.cs");

            FileAssert.Exists(resource_designer_cs);
            var resource_designer_text = File.ReadAllText(resource_designer_cs);

            StringAssert.Contains("public const int MyLayout", resource_designer_text);
        }