Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        public void DoubleCache()
        {
            // Store and flip files in our cache. We should always get
            // the most recent file we store for any given URL.

            Uri url = new Uri("http://Double.Rainbow.What.Does.It.Mean/");

            Assert.IsFalse(cache.IsCached(url));

            string file1 = TestData.DogeCoinFlagZip();
            string file2 = TestData.ModuleManagerZip();

            cache.Store(url, file1);
            FileAssert.AreEqual(file1, cache.GetCachedFilename(url));

            cache.Store(url, file2);
            FileAssert.AreEqual(file2, cache.GetCachedFilename(url));

            cache.Store(url, file1);
            FileAssert.AreEqual(file1, cache.GetCachedFilename(url));
        }
Ejemplo n.º 3
0
        public void EncodeRGBAByScanlines(string file)
        {
            string fullPath     = Path.Combine(TestCase.Folder, file);
            string outputPath   = Path.Combine(OutputFolder, file);
            string expectedPath = Path.Combine(ExpectedFolder, file);

            string suffix           = "_rgba_scanlines.tif";
            string fullOutputPath   = outputPath + suffix;
            string fullExpectedPath = expectedPath + suffix;

            using (Bitmap bmp = new Bitmap(fullPath))
            {
                using (Tiff tif = Tiff.Open(fullOutputPath, "w"))
                {
                    Assert.IsNotNull(tif);
                    convertToTiff(bmp, tif, PixelFormat.Format32bppArgb);
                }
            }

            FileAssert.AreEqual(fullExpectedPath, fullOutputPath);
        }
Ejemplo n.º 4
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}");
                    }
                }
            }
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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);
            }
        }
Ejemplo n.º 7
0
        public void TestCompressorWithContextRows()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                jpeg_compress_struct compressor = new jpeg_compress_struct(new jpeg_error_mgr());
                compressor.Image_height     = 100;
                compressor.Image_width      = 100;
                compressor.In_color_space   = J_COLOR_SPACE.JCS_GRAYSCALE;
                compressor.Input_components = 1;
                compressor.jpeg_set_defaults();

                compressor.Dct_method       = J_DCT_METHOD.JDCT_IFAST;
                compressor.Smoothing_factor = 94;
                compressor.jpeg_set_quality(75, true);
                compressor.jpeg_simple_progression();

                compressor.Density_unit = DensityUnit.Unknown;
                compressor.X_density    = (short)96;
                compressor.Y_density    = (short)96;

                compressor.jpeg_stdio_dest(stream);
                compressor.jpeg_start_compress(true);

                byte[][] rowForDecompressor = new byte[1][];
                int      bytesPerPixel      = 1;
                while (compressor.Next_scanline < compressor.Image_height)
                {
                    byte[] row = new byte[100 * bytesPerPixel]; // wasteful, but gets you 0 bytes every time - content is immaterial.
                    rowForDecompressor[0] = row;
                    compressor.jpeg_write_scanlines(rowForDecompressor, 1);
                }
                compressor.jpeg_finish_compress();

                byte[] bytes = stream.ToArray();

                string filename = "TestCompressorWithContextRows.jpg";
                File.WriteAllBytes(Tester.MapOutputPath(filename), bytes);
                FileAssert.AreEqual(Tester.MapExpectedPath(filename), Tester.MapOutputPath(filename));
            }
        }
Ejemplo n.º 8
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.");
            }
        }
Ejemplo n.º 9
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!");
                                }
                            }
                        }
                    }
                }
        }
Ejemplo n.º 10
0
        public void IncrementalCleanDuringClean()
        {
            var path = Path.Combine("temp", TestName);
            var proj = new XamarinAndroidApplicationProject()
            {
                ProjectName = "App1",
                IsRelease   = true,
            };

            proj.SetProperty("AndroidUseManagedDesignTimeResourceGenerator", "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.");
            }
        }
Ejemplo n.º 11
0
Archivo: OwinTests.cs Proyecto: 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);
        }
Ejemplo n.º 12
0
        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");
        }
Ejemplo n.º 13
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}");
            }
        }
Ejemplo n.º 14
0
        public void ExtractAll_FileDeleted()
        {
            using (var zip = ZipArchive.Create(stream)) {
                zip.AddEntry("a.txt", "a", encoding);
                zip.AddEntry("b/b.txt", "b", encoding);
            }

            bool changes = ExtractAll(stream);

            Assert.IsTrue(changes, "ExtractAll should report changes.");

            stream.SetLength(0);
            using (var zip = ZipArchive.Open(stream)) {
                zip.AddEntry("a.txt", "a", encoding);
            }

            changes = ExtractAll(stream);

            Assert.IsTrue(changes, "ExtractAll should report changes.");
            AssertFile("a.txt", "a");
            FileAssert.DoesNotExist(Path.Combine(tempDir, "b", "b.txt"));
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        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"));
        }
Ejemplo n.º 17
0
        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 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);
        }
Ejemplo n.º 19
0
        [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.");
            }
        }
Ejemplo n.º 20
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.");
                    }
                }
        }
Ejemplo n.º 21
0
        public void TestExecute_cleans_unfinished_directories_before_starting_the_build()
        {
            using (var tmpDir = new TmpDir()) {
                var partialTask = MockBuildTasks.NoOp("task1")
                                  .WithExecuteAction((sourceDir, outputDir, deps) => {
                    File.WriteAllText(Path.Combine(outputDir, "foo"), "42");
                    throw new Exception("Test exception");
                });
                try {
                    Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), partialTask.Object);
                } catch (Exception) {
                    // ignored
                }
                var fullTask = MockBuildTasks.NoOp("task1")
                               .WithExecuteAction((sourceDir, outputDir, deps) =>
                                                  File.WriteAllText(Path.Combine(outputDir, "bar"), "9001"));
                Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), fullTask.Object);

                FileAssert.AreEqual(tmpDir.CreateFile("9001"), tmpDir.CreatePath("out", "bar"));
                FileAssert.DoesNotExist(tmpDir.CreatePath("out", "foo"));
            }
        }
Ejemplo n.º 22
0
        public void UnhandleExceptionExceptionShouldBeLoggedToDiagLogFile(RunnerInfo runnerInfo)
        {
            AcceptanceTestBase.SetTestEnvironment(this.testEnvironment, runnerInfo);

            var diagLogFilePath = Path.Combine(Path.GetTempPath(), $"std_error_log_{Guid.NewGuid()}.txt");

            File.Delete(diagLogFilePath);

            var assemblyPaths =
                this.BuildMultipleAssemblyPath("SimpleTestProject3.dll").Trim('\"');
            var arguments = PrepareArguments(assemblyPaths, this.GetTestAdapterPath(), string.Empty, runnerInfo.InIsolationValue);

            arguments = string.Concat(arguments, " /testcasefilter:ExitwithUnhandleException");
            arguments = string.Concat(arguments, $" /diag:{diagLogFilePath}");

            this.InvokeVsTest(arguments);

            var errorFirstLine = "Test host standard error line: Unhandled Exception: System.InvalidOperationException: Operation is not valid due to the current state of the object.";

            FileAssert.Contains(diagLogFilePath, errorFirstLine);
            File.Delete(diagLogFilePath);
        }
Ejemplo n.º 23
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);
                }
        }
Ejemplo n.º 24
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);
                }
            });
        }
Ejemplo n.º 25
0
        public void StoreRetrieve()
        {
            Uri    url  = new Uri("http://example.com/");
            string file = Tests.TestData.DogeCoinFlagZip();

            // Sanity check, our cache dir is there, right?
            Assert.IsTrue(Directory.Exists(cache.GetCachePath()));

            // Our URL shouldn't be cached to begin with.
            Assert.IsFalse(cache.IsCached(url));

            // Store our file.
            cache.Store(url, file);

            // Now it should be cached.
            Assert.IsTrue(cache.IsCached(url));

            // Check contents match.
            string cached_file = cache.GetCachedFilename(url);

            FileAssert.AreEqual(file, cached_file);
        }
Ejemplo n.º 26
0
            public void WithoutKey_CreatedExpectedFile()
            {
                HtmlGenerator generator = new HtmlGenerator();

                WordPuzzles.Puzzle.InnerAnacrosticPuzzle puzzle = new WordPuzzles.Puzzle.InnerAnacrosticPuzzle {
                    PhraseAsString = "max peel"
                };
                puzzle.AddWordToClues("example");
                puzzle.PlaceLetters();
                generator.Puzzle = puzzle;

                // ReSharper disable StringLiteralTypo
                const string TEST_PUZZLE_FILENAME      = "test_puzzle_withoutkey.html";
                const string EXPECTED_RESULTS_FILENAME = @"data\puzzle_withoutkey.html";
                // ReSharper restore StringLiteralTypo

                string actualHtml = generator.GenerateHtmlFile(TEST_PUZZLE_FILENAME, false);


                Assert.AreEqual(File.ReadAllText(EXPECTED_RESULTS_FILENAME), actualHtml);
                FileAssert.AreEqual(EXPECTED_RESULTS_FILENAME, TEST_PUZZLE_FILENAME);
            }
Ejemplo n.º 27
0
        public void AreEqualFailsWithStreams()
        {
            string expectedFile = "Test1.jpg";
            string actualFile   = "Test2.jpg";

            using (TestFile tf1 = new TestFile(expectedFile, "TestImage1.jpg"))
            {
                using (TestFile tf2 = new TestFile(actualFile, "TestImage2.jpg"))
                {
                    using (FileStream expected = File.OpenRead(expectedFile))
                    {
                        using (FileStream actual = File.OpenRead(actualFile))
                        {
                            expectedMessage =
                                string.Format("  Expected Stream length {0} but was {1}." + Environment.NewLine,
                                              new FileInfo(expectedFile).Length, new FileInfo(actualFile).Length);
                            FileAssert.AreEqual(expected, actual);
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
        private async Task AssertSinglePageTiffResultsAsync(IEnumerable <ConversionResult> results, Action <string> customAssertions = null)
        {
            for (int i = 0; i < results.Count(); i++)
            {
                ConversionResult result = results.ElementAt(i);

                Assert.IsTrue(result.IsSuccess);
                Assert.AreEqual(1, result.PageCount, "Wrong page count for result");

                ConversionSourceDocument resultSourceDocument = result.Sources.ToList()[0];
                Assert.IsNotNull(resultSourceDocument.RemoteWorkFile);
                Assert.IsNull(resultSourceDocument.Password);
                Assert.AreEqual((i + 1).ToString(), resultSourceDocument.Pages, "Wrong source page range for result");

                string filename = $"page-{i}.tiff";
                await result.RemoteWorkFile.SaveAsync(filename);

                FileAssert.IsTiff(filename);

                customAssertions?.Invoke(filename);
            }
        }
Ejemplo n.º 29
0
        public void CanExtractZipFile()
        {
            var root = Path.Combine(Path.GetDirectoryName(typeof(ZipTests).Assembly.Location), "Exracted");

            if (Directory.Exists(root))
            {
                Directory.Delete(root, recursive: true);
            }
            File.WriteAllText("foo.txt", "Hello World", encoding: Encoding.ASCII);
            File.WriteAllText("foo1.txt", TEXT, encoding: Encoding.ASCII);
            using (var zip = ZipArchive.Open("test-archive-write.zip", FileMode.Open)) {
                zip.ExtractAll(root);
                FileAssert.AreEqual(Path.Combine(root, "file1.txt"), "file1.txt", "file1.txt should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "path", "ZipTestCopy.exe"), "file1.txt", "ZipTestCopy.exe should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "path", "ZipTestCopy2.exe"), "file1.txt", "ZipTestCopy2.exe should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "path", "ZipTestCopy3.exe"), "file1.txt", "ZipTestCopy3.exe should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "invalid", "archive", "path", "ZipTestCopy4.exe"), "file1.txt", "ZipTestCopy4.exe should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "data", "foo.txt"), "foo.txt", "foo.txt should have been 'Hello World'");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "foo", "foo.exe"), "file1.txt", "foo.exe should have been 1111");
                FileAssert.AreEqual(Path.Combine(root, "in", "archive", "foo", "foo1.txt"), "foo1.txt", $"foo1.txt should have been {TEXT}");
            }
        }
Ejemplo n.º 30
0
        public static void Test(String tempFolderName, String sourceSubfolderPath)
        {
            String subfolderName = Path.GetFileName(sourceSubfolderPath);

            String tempFolder     = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.WorkDirectory, @"Temp\XlsxConverterTesting"));
            String tempFolderPath = Path.Combine(tempFolder, subfolderName);

            String xlsxFilePath     = GetFilePath(Path.Combine(sourceSubfolderPath, "source.xlsx"));
            String templateFilePath = GetFilePath(Path.Combine(sourceSubfolderPath, "template.csv"));
            String csvFilePath      = PrepareCsvFile(Path.Combine(tempFolder, tempFolderName, subfolderName, "result.csv"));

            using (StreamWriter streamWriter = new StreamWriter(csvFilePath))
            {
                CsvWriter csvWriter = new CsvWriter(streamWriter);
                MoqDelimitedTextWriter delimitedTextWriter = new MoqDelimitedTextWriter(csvWriter);
                XlsxConverter.Convert(xlsxFilePath, delimitedTextWriter);
                delimitedTextWriter.Flush();
                streamWriter.Flush();
            }

            FileAssert.AreEqual(csvFilePath, templateFilePath);
        }