示例#1
0
        public void IncrementalCleanDuringClean()
        {
            var path = Path.Combine("temp", TestName);
            var proj = new XamarinAndroidApplicationProject()
            {
                ProjectName = "App1",
                IsRelease   = true,
            };

            proj.SetProperty("AndroidUseManagedDesignTimeResourceGenerator", "True");
            proj.SetProperty("BuildingInsideVisualStudio", "True");
            using (var b = CreateApkBuilder(path)) {
                b.Target = "Compile";
                Assert.IsTrue(b.Build(proj), "DesignTime Build should have succeeded");
                var designTimeDesigner = Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath, "designtime", "Resource.designer.cs");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should have been created.");
                b.Target = "Build";
                Assert.IsTrue(b.Build(proj), "Build should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after Build.");
                b.Target = "Clean";
                Assert.IsTrue(b.Build(proj), "Clean should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after Clean.");
                b.Target = "Compile";
                Assert.IsTrue(b.Build(proj), "Build should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after Compile.");
                b.Target = "Build";
                Assert.IsTrue(b.Build(proj), "Build should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after second Build.");
                Assert.IsTrue(b.Build(proj), "Build should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after third Build.");
                b.Target = "Compile";
                Assert.IsTrue(b.Build(proj), "Build should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after second Compile.");
                b.Target = "Clean";
                Assert.IsTrue(b.Build(proj), "Clean should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after second Clean.");
                b.Target = "ReBuild";
                Assert.IsTrue(b.Build(proj), "ReBuild should have succeeded");
                FileAssert.Exists(designTimeDesigner, $"{designTimeDesigner} should still exist after ReBuild.");
            }
        }
示例#2
0
        public async Task TestNopCommerce()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "nopCommerce.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    DeclarationNodes      = true,
                    LocationData          = false,
                    ReferenceData         = true,
                    EnumDeclarations      = true,
                    StructDeclarations    = true,
                    InterfaceDeclarations = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            var          results  = (await analyzer.AnalyzeSolution(solutionPath)).ToList();

            var enumDeclarations      = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllEnumDeclarations().Count > 0).Sum(s => s.AllEnumDeclarations().Count));
            var structDeclarations    = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllStructDeclarations().Count > 0).Sum(s => s.AllStructDeclarations().Count));
            var arrowClauseStatements = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllArrowExpressionClauses().Count > 0).Sum(s => s.AllArrowExpressionClauses().Count));

            Assert.AreEqual(80, enumDeclarations);
            Assert.AreEqual(1, structDeclarations);
            Assert.AreEqual(2, arrowClauseStatements);

            results.ForEach(r => r.Dispose());
        }
示例#3
0
        public void TestExcelFunctionality_OnSimpleXlsx()
        {
            var LoadDirectory = CreateLoadDirectoryForTest("TestExcelFunctionality_OnSimpleXlsx");

            //clean SetUp anything in the test project folders forloading directory
            foreach (FileInfo fileInfo in LoadDirectory.ForLoading.GetFiles())
            {
                fileInfo.Delete();
            }

            string targetFile = Path.Combine(LoadDirectory.ForLoading.FullName, "Test.xlsx");

            FileInfo fi = new FileInfo(Path.Combine(TestContext.CurrentContext.TestDirectory, "DataLoad", "Engine",
                                                    "Resources", "Test.xlsx"));

            FileAssert.Exists(fi);

            fi.CopyTo(targetFile, true);

            TestConversionFor(targetFile, "*.xlsx", 5, LoadDirectory);
        }
示例#4
0
        public void GenerateBitmap(string toEncode, string testFile)
        {
            // Arrange
            const double scale    = 1D;
            var          settings = GetPdf417Settings(50, 6, 2, 1);

            // Act
            using (IBarcode barcode = new BC.Pdf417())
            {
                using var bmp  = barcode.Encode(toEncode, settings);
                using var bmp2 = new Bitmap((int)(bmp.Width * scale), (int)(bmp.Height * scale));
                using (var gfx = Graphics.FromImage(bmp2))
                {
                    gfx.DrawImage(bmp, new Rectangle(0, 0, bmp2.Width, bmp2.Height));
                }
                bmp2.Save(testFile, ImageFormat.Png);
            }

            //Assert
            FileAssert.Exists(testFile);
        }
        public void LinkTargetCsprojProject()
        {
            // Arrange
            var targetDirectory = Path.Combine(Constants.TestSoltuionSrc, "Console.PackageConfig");
            var dllPath         = Path.Combine(targetDirectory, @"bin\Debug\Package.Csproj.dll");

            var console  = new NuGet.CommandLine.Console();
            var linkArgs = new LinkArgs
            {
                PackageId        = "Package.Csproj",
                CurrentDirectory = targetDirectory,
                Console          = console,
            };
            var runner = new LinkCommandRunner(linkArgs);

            // Act
            runner.Link();

            // Assert
            FileAssert.Exists(dllPath);
        }
        public void AddANoteAndCheckThatTheExportMethodHasExportedAJSONFile()
        {
            using (PlannerContext pc = new PlannerContext())
            {
                Note _testNote = new Note()
                {
                    Title = "TestNote",
                    Body  = "A test note",
                };

                pc.Notes.Add(_testNote);

                pc.SaveChanges();

                _jsonExporter.InitSerialisation();

                _jsonExporter.SerialiseNotes();

                FileAssert.Exists(@"C:\Users\Alex\Documents\Engineering 73\Entity Framework Project\Entity-Framework-Project-Planner\ProjectPlanner\ProjectPlannerTESTS\bin\Debug\netcoreapp3.1\JSON Export\Notes.json");
            }
        }
示例#7
0
            public void NewObject_GeneratesExpectedFile()
            {
                AnacrosticParameterSet set = new AnacrosticParameterSet {
                    TweetId = 0
                };

                set.Serialize();

                string expectedFilePath = ConfigurationManager.AppSettings["BaseDirectory"] + @"anacrostics\parameter_set_0.xml";

                FileAssert.Exists(expectedFilePath);
                var readAllText = File.ReadAllText(expectedFilePath);

                Console.WriteLine(readAllText);
                Assert.AreEqual(@"<?xml version=""1.0""?>
<AnacrosticParameterSet xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <WordsToUse />
  <WordsToIgnore />
  <TweetId>0</TweetId>
</AnacrosticParameterSet>", readAllText);
            }
        public void BuildAarBindingLibraryStandalone(string classParser)
        {
            var proj = new XamarinAndroidBindingProject()
            {
                UseLatestPlatformSdk = true,
                IsRelease            = true,
            };

            proj.Jars.Add(new AndroidItem.AndroidLibrary("Jars\\material-menu-1.1.0.aar")
            {
                WebContent = "https://repo.jfrog.org/artifactory/libs-release-bintray/com/balysv/material-menu/1.1.0/material-menu-1.1.0.aar"
            });
            proj.AndroidClassParser = classParser;
            using (var b = CreateDllBuilder()) {
                Assert.IsTrue(b.Build(proj), "Build should have succeeded.");
                if (Builder.UseDotNet)
                {
                    FileAssert.Exists(Path.Combine(Root, b.ProjectDirectory, proj.OutputPath, "material-menu-1.1.0.aar"));
                }
            }
        }
示例#9
0
        public void CompressAndDecompressCanHandleSubdirectories()
        {
            var targetDirectory = k_SourceDirectory + "2";
            var success         = FileCompressor.Compress(k_SourceDirectory, "artifacts.sbpGz");

            Assert.IsTrue(success);

            success = FileCompressor.Decompress("artifacts.sbpGz", targetDirectory);
            Assert.IsTrue(success);

            for (int i = 0; i < k_SourceFiles.Length; i++)
            {
                var sourcePath = NormalizePath(k_SourceDirectory + k_SourceFiles[i]);
                var targetPath = NormalizePath(targetDirectory + k_SourceFiles[i]);
                FileAssert.Exists(targetPath);
                FileAssert.AreEqual(sourcePath, targetPath);
            }

            File.Delete("artifacts.sbpGz");
            Directory.Delete(targetDirectory, true);
        }
示例#10
0
        public void TestCookbookCodeIsInSync()
        {
            Regex links = new Regex(@"<sup>(.*)</sup>");

            Regex codeStrings = new Regex("@\"([^\"]*)\"", RegexOptions.Singleline);

            string cookbookDir = Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../../");
            var    cookbook    = Path.Combine(cookbookDir, "Cookbook.md");

            FileAssert.Exists(cookbook);

            string content = File.ReadAllText(cookbook);

            foreach (Match match in links.Matches(content))
            {
                var linkIdx = match.Groups[1].Value.IndexOf("./Tests/Cookbook/");

                if (linkIdx == -1)
                {
                    continue;
                }

                var link = match.Groups[1].Value.Substring(linkIdx).TrimEnd(')');

                TestContext.Out.WriteLine("Looking for " + link);

                var codeFile = Path.Combine(cookbookDir, link);
                FileAssert.Exists(codeFile);

                string codeContent = File.ReadAllText(codeFile);

                foreach (Match codeMatch in codeStrings.Matches(codeContent))
                {
                    if (!content.Contains(codeMatch.Groups[1].Value.Trim()))
                    {
                        Assert.Fail($"Cookbook recipe in file '{codeFile}' had code block not in Cookbook.md.  Code block was:{codeMatch.Groups[1].Value}");
                    }
                }
            }
        }
示例#11
0
        public void ExportSingleTimelineClipFromExportDataTest()
        {
            string cubeSpecialPath = FindPathInUnitTests("Scene/CubeSpecial.prefab");

            GameObject myCube     = AddAssetToScene(cubeSpecialPath);
            string     folderPath = GetRandomFileNamePath(extName: "");
            string     filePath   = null;
            var        exportData = new Dictionary <GameObject, IExportData>();

            PlayableDirector pd = myCube.GetComponent <PlayableDirector>();

            if (pd != null)
            {
                foreach (PlayableBinding output in pd.playableAsset.outputs)
                {
                    AnimationTrack at = output.sourceObject as AnimationTrack;

                    var atComponent = pd.GetGenericBinding(at) as Component;
                    Assert.That(atComponent, Is.Not.Null);

                    var atObject = atComponent.gameObject;

                    // One file by animation clip
                    foreach (TimelineClip timeLineClip in at.GetClips())
                    {
                        Assert.That(timeLineClip.animationClip, Is.Not.Null);

                        filePath             = $"{folderPath}/{atObject.name}@Recorded.fbx";
                        exportData[atObject] = ModelExporter.GetExportData(atObject, timeLineClip.animationClip);
                        break;
                    }
                }
            }
            Assert.That(filePath, Is.Not.Null);
            Assert.That(exportData, Is.Not.Null);
            ModelExporter.ExportObjects(filePath, new UnityEngine.Object[1] {
                myCube
            }, null, exportData);
            FileAssert.Exists(filePath);
        }
示例#12
0
        public void DotNetBuild(string runtimeIdentifier, bool isRelease)
        {
            var abi  = MonoAndroidHelper.RuntimeIdentifierToAbi(runtimeIdentifier);
            var proj = new XASdkProject {
                IsRelease = isRelease
            };

            proj.OtherBuildItems.Add(new AndroidItem.InputJar("javaclasses.jar")
            {
                BinaryContent = () => Convert.FromBase64String(InlineData.JavaClassesJarBase64)
            });
            // TODO: bring back when Xamarin.Android.Bindings.Documentation.targets is working
            //proj.OtherBuildItems.Add (new BuildItem ("JavaSourceJar", "javasources.jar") {
            //	BinaryContent = () => Convert.FromBase64String (InlineData.JavaSourcesJarBase64)
            //});
            proj.SetProperty(KnownProperties.RuntimeIdentifier, runtimeIdentifier);

            var dotnet = CreateDotNetBuilder(proj);

            Assert.IsTrue(dotnet.Build(), "`dotnet build` should succeed");
            Assert.IsTrue(StringAssertEx.ContainsText(dotnet.LastBuildOutput, " 0 Warning(s)"), "Should have no MSBuild warnings.");

            var outputPath   = Path.Combine(Root, dotnet.ProjectDirectory, proj.OutputPath, runtimeIdentifier);
            var assemblyPath = Path.Combine(outputPath, "UnnamedProject.dll");

            FileAssert.Exists(assemblyPath);
            using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) {
                var typeName = "Com.Xamarin.Android.Test.Msbuildtest.JavaSourceJarTest";
                var type     = assembly.MainModule.GetType(typeName);
                Assert.IsNotNull(type, $"{assemblyPath} should contain {typeName}");
            }

            var apk = Path.Combine(outputPath, "UnnamedProject.UnnamedProject.apk");

            FileAssert.Exists(apk);
            using (var zip = ZipHelper.OpenZip(apk)) {
                Assert.IsTrue(zip.ContainsEntry($"lib/{abi}/libmonodroid.so"), "libmonodroid.so should exist.");
                Assert.IsTrue(zip.ContainsEntry($"lib/{abi}/libmonosgen-2.0.so"), "libmonosgen-2.0.so should exist.");
            }
        }
示例#13
0
文件: OwinTests.cs 项目: aws/cta
        public void TestCustomServer(string version)
        {
            TestSolutionAnalysis results = AnalyzeSolution("CustomServer.sln", tempDir, downloadLocation, version);

            var myApp = results.ProjectResults.Where(p => p.CsProjectPath.EndsWith("MyApp.csproj")).FirstOrDefault();
            FileAssert.Exists(myApp.CsProjectPath);
            var customServer = results.ProjectResults.Where(p => p.CsProjectPath.EndsWith("MyCustomServer.csproj")).FirstOrDefault();
            FileAssert.Exists(customServer.CsProjectPath);

            //MyApp
            var myappProjContent = myApp.CsProjectContent;
            var startupText = File.ReadAllText(Path.Combine(myApp.ProjectDirectory, "Startup.cs"));
            var programText = File.ReadAllText(Path.Combine(myApp.ProjectDirectory, "Program.cs"));

            StringAssert.AreEqualIgnoringCase(ExpectedOutputConstants.CustomServerProgram.NormalizeNewLineChars(), programText.NormalizeNewLineChars());
            StringAssert.AreEqualIgnoringCase(ExpectedOutputConstants.CustomServerStartup.NormalizeNewLineChars(), startupText.NormalizeNewLineChars());

            //Check for comment on how to implement a custom server here in program

            //Check that package has been added:
            StringAssert.Contains(@"Microsoft.AspNetCore.Owin", myappProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.Diagnostics", myappProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.Server.Kestrel", myappProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.Hosting", myappProjContent);

            //Check that correct version is used
            Assert.True(myappProjContent.IndexOf(string.Concat(">", version, "<")) > 0);

            //CustomServer
            var customProjContent = customServer.CsProjectContent;
            var customerServerText = File.ReadAllText(Path.Combine(customServer.ProjectDirectory, "CustomServer.cs"));
            var serverFactoryText = File.ReadAllText(Path.Combine(customServer.ProjectDirectory, "ServerFactory.cs"));

            //MyCustomerServer very difficult
            //Keep their server intact but must implement IServer instead of just IDisposable
            //Change their Start class to implement StartAsync instead and change reference to it to startAsync also

            //Check that correct version is used
            Assert.True(customProjContent.IndexOf(string.Concat(">", version, "<")) > 0);
        }
示例#14
0
        public void DotNetBuildBinding()
        {
            var proj = new XASdkProject(outputType: "Library");

            // Both transform files should be applied
            proj.Sources.Add(new AndroidItem.TransformFile("Transforms.xml")
            {
                TextContent = () =>
                              @"<metadata>
  <attr path=""/api/package[@name='com.xamarin.android.test.msbuildtest']"" name=""managedName"">FooBar</attr>
</metadata>",
            });
            proj.Sources.Add(new AndroidItem.TransformFile("Transforms\\Metadata.xml")
            {
                TextContent = () =>
                              @"<metadata>
  <attr path=""/api/package[@managedName='FooBar']"" name=""managedName"">MSBuildTest</attr>
</metadata>",
            });
            proj.Sources.Add(new AndroidItem.AndroidLibrary("javaclasses.jar")
            {
                BinaryContent = () => ResourceData.JavaSourceJarTestJar,
            });
            proj.OtherBuildItems.Add(new BuildItem("JavaSourceJar", "javaclasses-sources.jar")
            {
                BinaryContent = () => ResourceData.JavaSourceJarTestSourcesJar,
            });
            var dotnet = CreateDotNetBuilder(proj);

            Assert.IsTrue(dotnet.Build(), "`dotnet build` should succeed");

            var assemblyPath = Path.Combine(FullProjectDirectory, proj.OutputPath, "UnnamedProject.dll");

            FileAssert.Exists(assemblyPath);
            using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) {
                var typeName = "MSBuildTest.JavaSourceJarTest";
                var type     = assembly.MainModule.GetType(typeName);
                Assert.IsNotNull(type, $"{assemblyPath} should contain {typeName}");
            }
        }
示例#15
0
        public void AndroidManifestProperties()
        {
            var packageName      = "com.xamarin.singleproject";
            var applicationLabel = "My Sweet App";
            var versionName      = "2.1";
            var versionCode      = "42";
            var proj             = new XamarinAndroidApplicationProject();

            proj.AndroidManifest = proj.AndroidManifest
                                   .Replace("package=\"${PACKAGENAME}\"", "")
                                   .Replace("android:label=\"${PROJECT_NAME}\"", "")
                                   .Replace("android:versionName=\"1.0\"", "")
                                   .Replace("android:versionCode=\"1\"", "");
            if (!Builder.UseDotNet)
            {
                proj.SetProperty("GenerateApplicationManifest", "true");
            }
            proj.SetProperty("ApplicationId", packageName);
            proj.SetProperty("ApplicationTitle", applicationLabel);
            proj.SetProperty("ApplicationVersion", versionName);
            proj.SetProperty("AndroidVersionCode", versionCode);

            using (var b = CreateApkBuilder()) {
                Assert.IsTrue(b.Build(proj), "Build should have succeeded.");

                var manifest = b.Output.GetIntermediaryPath("android/AndroidManifest.xml");
                FileAssert.Exists(manifest);

                using (var stream = File.OpenRead(manifest)) {
                    var doc = XDocument.Load(stream);
                    Assert.AreEqual(packageName, doc.Root.Attribute("package")?.Value);
                    Assert.AreEqual(versionName, doc.Root.Attribute(AndroidAppManifest.AndroidXNamespace + "versionName")?.Value);
                    Assert.AreEqual(versionCode, doc.Root.Attribute(AndroidAppManifest.AndroidXNamespace + "versionCode")?.Value);
                    Assert.AreEqual(applicationLabel, doc.Root.Element("application").Attribute(AndroidAppManifest.AndroidXNamespace + "label")?.Value);
                }

                var apk = b.Output.GetIntermediaryPath($"android/bin/{packageName}.apk");
                FileAssert.Exists(apk);
            }
        }
示例#16
0
        public void ApkSet()
        {
            if (!HasDevices)
            {
                Assert.Ignore("Skipping Installation. No devices available.");
            }

            Assert.IsTrue(appBuilder.RunTarget(app, "Install"), "App should have installed.");

            var aab = Path.Combine(intermediate, "android", "bin", "UnnamedProject.UnnamedProject.apks");

            FileAssert.Exists(aab);
            // Expecting: splits/base-arm64_v8a.apk, splits/base-en.apk, splits/base-master.apk, splits/base-xxxhdpi.apk
            // This are split up based on: abi, language, base, and dpi
            var contents = ListArchiveContents(aab).Where(a => a.EndsWith(".apk", StringComparison.OrdinalIgnoreCase)).ToArray();

            Assert.AreEqual(4, contents.Length, "Expecting four APKs!");

            using (var stream = new MemoryStream())
                using (var apkSet = ZipArchive.Open(aab, FileMode.Open)) {
                    // We have a zip inside a zip
                    var baseMaster = apkSet.ReadEntry("splits/base-master.apk");
                    baseMaster.Extract(stream);

                    stream.Position = 0;
                    var uncompressed = new [] { ".dll", ".bar", ".wav" };
                    using (var baseApk = ZipArchive.Open(stream)) {
                        foreach (var file in baseApk)
                        {
                            foreach (var ext in uncompressed)
                            {
                                if (file.FullName.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
                                {
                                    Assert.AreEqual(CompressionMethod.Store, file.CompressionMethod, $"{file.FullName} should be uncompressed!");
                                }
                            }
                        }
                    }
                }
        }
        public void SignAndroidPackage_UpdateProperties()
        {
            string versionCode = "1234",
                   versionName = "1.2.3.4",
                   packageName = "com.mycompany.myapp";

            var versionCodeElement = MSBuild.NewElement("AndroidVersionCode").WithValue(versionCode);
            var versionNameElement = MSBuild.NewElement("AndroidVersionName").WithValue(versionName);
            var packageNameElement = MSBuild.NewElement("AndroidPackageName").WithValue(packageName);

            var project       = MSBuild.NewProject(testDirectory);
            var propertyGroup = MSBuild.NewElement("PropertyGroup");

            propertyGroup.Add(versionCodeElement);
            propertyGroup.Add(versionNameElement);
            propertyGroup.Add(packageNameElement);
            project.AddFirst(propertyGroup);

            var projectFile = Path.Combine(tempDirectory, "test.csproj");

            project.Save(projectFile);
            MSBuild.Restore(projectFile);
            MSBuild.Build(projectFile, "SignAndroidPackage");

            versionCodeElement.Value = versionCode = "99";
            versionNameElement.Value = versionName = "2.0";
            packageNameElement.Value = packageName = "com.mycompany.myapp2";
            project.Save(projectFile);
            MSBuild.Build(projectFile, "SignAndroidPackage");

            var manifestPath = Path.Combine(objDirectory, "AndroidManifest.xml");

            FileAssert.Exists(manifestPath);
            var ns       = AndroidManifest.AndroidNamespace.Namespace;
            var manifest = AndroidManifest.Read(manifestPath);

            Assert.AreEqual(versionCode, manifest.Document.Attribute(ns + "versionCode")?.Value, "versionCode should match");
            Assert.AreEqual(versionName, manifest.Document.Attribute(ns + "versionName")?.Value, "versionName should match");
            Assert.AreEqual(packageName, manifest.Document.Attribute("package")?.Value, "package should match");
        }
        public void Should_Delete_Existing_File()
        {
            var existingFile = m_TestDirectory + "/Parent/Existing.txt";
            var newFile      = m_TestDirectory + "/Parent/File.txt";

            Directory.CreateDirectory(m_TestDirectory + "/Parent");
            File.Create(existingFile).Dispose();

            FileAssert.Exists(existingFile);

            using (var tracker = new TemporaryFileTracker())
            {
                tracker.TrackFile(existingFile, ensureDoesntExist: false);
                File.Create(tracker.TrackFile(newFile)).Dispose();

                FileAssert.Exists(existingFile);
                FileAssert.Exists(newFile);
            }

            FileAssert.DoesNotExist(existingFile);
            FileAssert.DoesNotExist(newFile);
        }
示例#19
0
        public void TestExcelFunctionality_DodgyFileExtension()
        {
            var LoadDirectory = CreateLoadDirectoryForTest("TestExcelFunctionality_DodgyFileExtension");

            //clean SetUp anything in the test project folders forloading directory
            foreach (FileInfo fileInfo in LoadDirectory.ForLoading.GetFiles())
            {
                fileInfo.Delete();
            }

            string   targetFile = Path.Combine(LoadDirectory.ForLoading.FullName, "Test.xml");
            FileInfo fi         = new FileInfo(Path.Combine(TestContext.CurrentContext.TestDirectory, "DataLoad", "Engine",
                                                            "Resources", "XmlTestForExcel.xml"));

            FileAssert.Exists(fi);

            fi.CopyTo(targetFile, true);

            var ex = Assert.Throws <Exception>(() => TestConversionFor(targetFile, "*.fish", 1, LoadDirectory));

            Assert.IsTrue(ex.Message.StartsWith("Did not find any files matching Pattern '*.fish' in directory"));
        }
示例#20
0
        private void TestWebSocketSample(string version)
        {
            TestSolutionAnalysis results = AnalyzeSolution("WebSocketSample.sln", tempDir, downloadLocation, version);

            var sampleClient = results.ProjectResults.Where(p => p.CsProjectPath.EndsWith("SampleClient.csproj")).FirstOrDefault();

            FileAssert.Exists(sampleClient.CsProjectPath);
            var webSocketServer = results.ProjectResults.Where(p => p.CsProjectPath.EndsWith("WebSocketServer.csproj")).FirstOrDefault();

            FileAssert.Exists(webSocketServer.CsProjectPath);

            var clientProgramText = File.ReadAllText(Path.Combine(sampleClient.ProjectDirectory, "Program.cs"));

            var serverStartupText = File.ReadAllText(Path.Combine(webSocketServer.ProjectDirectory, "Startup.cs"));
            var serverProgramText = File.ReadAllText(Path.Combine(webSocketServer.ProjectDirectory, "Program.cs"));

            StringAssert.Contains(@"Microsoft.AspNetCore.Builder", serverStartupText);
            StringAssert.Contains(@"IApplicationBuilder", serverStartupText);
            StringAssert.Contains(@"UseOwin", serverStartupText);

            StringAssert.Contains("WebHostBuilder", serverProgramText);
        }
        public void FileScreenshotConsumer_FileName()
        {
            consumerBuilder.
            WithFileName(@"{screenshot-number:d3} {screenshot-title:* - }{screenshot-pageobjectname}").
            Build();

            Go.To <BasicControlsPage>();

            AtataContext.Current.Log.Screenshot();
            AtataContext.Current.Log.Screenshot("Some title");

            string folderPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "Logs",
                AtataContext.BuildStart.Value.ToString(FileScreenshotConsumer.DefaultDateTimeFormat),
                nameof(FileScreenshotConsumer_FileName));

            foldersToDelete.Add(folderPath);

            FileAssert.Exists(Path.Combine(folderPath, "001 Basic Controls.png"));
            FileAssert.Exists(Path.Combine(folderPath, "002 Some title - Basic Controls.png"));
        }
        public void FileScreenshotConsumer_FilePath()
        {
            consumerBuilder.
            WithFilePath(@"TestLogs\{build-start}\Test {test-name}\{screenshot-number:d2}{screenshot-title: - *}").
            Build();

            Go.To <BasicControlsPage>();

            AtataContext.Current.Log.Screenshot();
            AtataContext.Current.Log.Screenshot("Some title");

            string folderPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "TestLogs",
                AtataContext.BuildStart.Value.ToString(FileScreenshotConsumer.DefaultDateTimeFormat),
                $"Test {nameof(FileScreenshotConsumer_FilePath)}");

            foldersToDelete.Add(folderPath);

            FileAssert.Exists(Path.Combine(folderPath, "01.png"));
            FileAssert.Exists(Path.Combine(folderPath, "02 - Some title.png"));
        }
    public void SingleFileBasicOperationTest()
    {
        var inFile = CreateInputFile(TestData.IMG_013, nameof(TestData.IMG_013) + ".dcm");

        var outDir = AssertRunsSuccesfully(1, 0, null,

                                           //Treat Csv column "ID" as a replacement for PatientID
                                           CreateExtraMappingsFile("ID:PatientID"), inFile.Directory,

                                           //Give it BasicTest.csv
                                           o => o.InputCsv = Path.Combine(TestContext.CurrentContext.TestDirectory, "BasicTest.csv"));

        //Anonymous dicom image should exist
        var expectedFile = new FileInfo(Path.Combine(outDir.FullName, nameof(TestData.IMG_013) + ".dcm"));

        FileAssert.Exists(expectedFile);

        //it should have the patient ID from the csv
        DicomFile file = DicomFile.Open(expectedFile.FullName);

        Assert.AreEqual("NewPatientID1", file.Dataset.GetValue <string>(DicomTag.PatientID, 0));
    }
        public void FileScreenshotConsumer_FileName_Sanitizing()
        {
            consumerBuilder.
            UseTestName("FileScreenshotConsumer_File\"Name\\_/Sanitizing").
            Build();

            Go.To <BasicControlsPage>();

            AtataContext.Current.Log.Screenshot();
            AtataContext.Current.Log.Screenshot("Some\\ /:title");

            string folderPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "Logs",
                AtataContext.BuildStart.Value.ToString(FileScreenshotConsumer.DefaultDateTimeFormat),
                nameof(FileScreenshotConsumer_FileName_Sanitizing));

            foldersToDelete.Add(folderPath);

            FileAssert.Exists(Path.Combine(folderPath, "01 - Basic Controls page.png"));
            FileAssert.Exists(Path.Combine(folderPath, "02 - Basic Controls page - Some title.png"));
        }
示例#25
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new IronPythonRuntime())
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"f = open('workDirTest.txt', 'w')
f.write('test')
f.close()");
                    FileAssert.Exists(outPath);

                    outPath = Path.Combine(tempDir.TempPath, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"f = open('workDirTest.txt', 'w')
f.write('test')
f.close()", tempDir.TempPath);
                    FileAssert.Exists(outPath);
                }
        }
示例#26
0
        private void AssertDocFiles(List <string> expectedDocFilesNames, string generatedFilesFolderName)
        {
            Assert.Multiple(() =>
            {
                var docFilesPath             = OutPutFilePath + "docs\\" + generatedFilesFolderName + "\\";
                var generatedDocFileNameList = GetFileNamesList(docFilesPath);
                foreach (var expectedFileName in expectedDocFilesNames)
                {
                    Assert.Contains(expectedFileName, generatedDocFileNameList);
                    var expected = docFilesPath + expectedFileName;
                    var actual   = ActualFilesPath + "docs\\" + generatedFilesFolderName + "\\" + expectedFileName;

                    FileAssert.Exists(expected, $"{expected} does not exist");
                    FileAssert.Exists(actual, $"{actual} does not exist");
                    TestContext.WriteLine(expected + " ---vs--- " + actual);


                    FileAssert.AreEqual(expected, actual,
                                        "Test failure for " + expectedFileName);
                }
            });
        }
        [NonParallelizable]         // Commonly fails NuGet restore
        public void CheckAapt2WarningsDoNotGenerateErrors()
        {
            //https://github.com/xamarin/xamarin-android/issues/3083
            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease = true,
                TargetFrameworkVersion = Versions.Oreo_27,
                UseLatestPlatformSdk   = false,
            };

            proj.PackageReferences.Add(KnownPackages.XamarinForms_2_3_4_231);
            proj.PackageReferences.Add(KnownPackages.AndroidSupportV4_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportCompat_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportCoreUI_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportCoreUtils_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportDesign_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportFragment_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportMediaCompat_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportV7AppCompat_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportV7CardView_27_0_2_1);
            proj.PackageReferences.Add(KnownPackages.SupportV7MediaRouter_27_0_2_1);
            proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, true);
            proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidSupportedAbis, "armeabi-v7a;x86");
            using (var b = CreateApkBuilder(Path.Combine("temp", TestName))) {
                if (!b.TargetFrameworkExists(proj.TargetFrameworkVersion))
                {
                    Assert.Ignore($"Skipped as {proj.TargetFrameworkVersion} not available.");
                }
                Assert.IsTrue(b.Build(proj), "first build should have succeeded.");
                string intermediateDir = TestEnvironment.IsWindows
                                        ? Path.Combine(proj.IntermediateOutputPath, proj.TargetFrameworkAbbreviated) : proj.IntermediateOutputPath;
                var packagedResource = Path.Combine(b.Root, b.ProjectDirectory, intermediateDir, "android", "bin", "packaged_resources");
                FileAssert.Exists(packagedResource, $"{packagedResource} should have been created.");
                var packagedResourcearm = packagedResource + "-armeabi-v7a";
                FileAssert.Exists(packagedResourcearm, $"{packagedResourcearm} should have been created.");
                var packagedResourcex86 = packagedResource + "-x86";
                FileAssert.Exists(packagedResourcex86, $"{packagedResourcex86} should have been created.");
            }
        }
示例#28
0
        void CompareFilesIgnoreRuntimeInfoString(string file1, string file2)
        {
            FileAssert.Exists(file1);
            FileAssert.Exists(file2);
            var content1 = File.ReadAllText(file1);
            var content2 = File.ReadAllText(file2);
            // This string is only generated when running on mono, replace with a new line that will be stripped when comparing.
            var runtimeVersionRegex = new Regex(@"//\s*Runtime Version:.*");

            content1 = runtimeVersionRegex.Replace(content1, Environment.NewLine);
            content2 = runtimeVersionRegex.Replace(content2, Environment.NewLine);

            using (var s1 = new MemoryStream(Encoding.UTF8.GetBytes(content1)))
                using (var s2 = new MemoryStream(Encoding.UTF8.GetBytes(content2))) {
                    if (!StreamCompare(s1, s2))
                    {
                        TestContext.AddTestAttachment(file1, Path.GetFileName(file1));
                        TestContext.AddTestAttachment(file2, Path.GetFileName(file2));
                        Assert.Fail($"{file1} and {file2} do not match.");
                    }
                }
        }
示例#29
0
        public void AppBundle()
        {
            var aab = Path.Combine(intermediate, "android", "bin", "UnnamedProject.UnnamedProject.aab");

            FileAssert.Exists(aab);
            var contents = ListArchiveContents(aab);

            CollectionAssert.AreEqual(contents, new [] {
                "base/dex/classes.dex",
                "base/lib/arm64-v8a/libmono-btls-shared.so",
                "base/lib/arm64-v8a/libmonodroid.so",
                "base/lib/arm64-v8a/libmono-native.so",
                "base/lib/arm64-v8a/libmonosgen-2.0.so",
                "base/lib/armeabi-v7a/libmono-btls-shared.so",
                "base/lib/armeabi-v7a/libmonodroid.so",
                "base/lib/armeabi-v7a/libmono-native.so",
                "base/lib/armeabi-v7a/libmonosgen-2.0.so",
                "base/manifest/AndroidManifest.xml",
                "base/native.pb",
                "base/res/drawable-hdpi-v4/icon.png",
                "base/res/drawable-mdpi-v4/icon.png",
                "base/res/drawable-xhdpi-v4/icon.png",
                "base/res/drawable-xxhdpi-v4/icon.png",
                "base/res/drawable-xxxhdpi-v4/icon.png",
                "base/res/layout/main.xml",
                "base/resources.pb",
                "base/root/assemblies/Java.Interop.dll",
                "base/root/assemblies/Mono.Android.dll",
                "base/root/assemblies/mscorlib.dll",
                "base/root/assemblies/System.Core.dll",
                "base/root/assemblies/System.dll",
                "base/root/assemblies/System.Runtime.Serialization.dll",
                "base/root/assemblies/UnnamedProject.dll",
                "base/root/NOTICE",
                "base/root/typemap.jm",
                "base/root/typemap.mj",
                "BundleConfig.pb"
            });
        }
        public void DeterministicBuilds([Values(true, false)] bool deterministic)
        {
            var proj = new XamarinAndroidApplicationProject {
                Deterministic = deterministic,
                //NOTE: so _BuildApkEmbed runs in commercial tests
                EmbedAssembliesIntoApk  = true,
                AndroidUseSharedRuntime = false,
            };

            // NOTE: Deterministic is only supported for DebugType=portable
            proj.SetProperty(proj.ActiveConfigurationProperties, "DebugType", "portable");
            using (var b = CreateApkBuilder()) {
                Assert.IsTrue(b.Build(proj), "first build should have succeeded.");
                var output = Path.Combine(Root, b.ProjectDirectory, proj.OutputPath, $"{proj.ProjectName}.dll");
                FileAssert.Exists(output);
                string expectedHash = MonoAndroidHelper.HashFile(output);
                Guid   expectedMvid;
                using (var assembly = AssemblyDefinition.ReadAssembly(output)) {
                    expectedMvid = assembly.MainModule.Mvid;
                }

                proj.Touch("MainActivity.cs");
                Assert.IsTrue(b.Build(proj, doNotCleanupOnUpdate: true), "second build should have succeeded.");
                FileAssert.Exists(output);
                using (var assembly = AssemblyDefinition.ReadAssembly(output)) {
                    if (deterministic)
                    {
                        Assert.AreEqual(expectedMvid, assembly.MainModule.Mvid, "Mvid should match");
                        Assert.AreEqual(expectedHash, MonoAndroidHelper.HashFile(output), "hash should match");
                    }
                    else
                    {
                        Assert.AreNotEqual(expectedMvid, assembly.MainModule.Mvid, "Mvid should *not* match");
                        Assert.AreNotEqual(expectedHash, MonoAndroidHelper.HashFile(output), "hash should *not* match");
                    }
                }
            }
        }