示例#1
0
 public static void AttatchLogToTest()
 {
     if (File.Exists(Logpath))
     {
         TestContext.AddTestAttachment(Logpath);
     }
 }
        private void TakeScreenshot(string fileName)
        {
            var chromeDriver = ((ChromeDriver)_driver);

            chromeDriver.GetScreenshot().SaveAsFile($"{fileName}.png");
            TestContext.AddTestAttachment($"{fileName}.png");
        }
示例#3
0
        public void Close()
        {
            var filepath = $"{ TestContext.CurrentContext.TestDirectory}\\{TestContext.CurrentContext.Test.MethodName}.jpg";

            ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(filepath);
            TestContext.AddTestAttachment(filepath, "Test Screenshots");
        }
        public static MediaEntityModelProvider GetScreenShotMedia()
        {
            string screenshotPath = GeneralHelpers.GetScreenshot(reportPath);

            TestContext.AddTestAttachment(screenshotPath);
            return(MediaEntityBuilder.CreateScreenCaptureFromPath(screenshotPath.Replace(reportPath, ".")).Build());
        }
示例#5
0
        protected async Task EasyTest <TAppAdapter>(Func <TAppAdapter> appAdapter,
                                                    Func <TAppAdapter, string, TestApplication> applicationFactory, Func <ICommandAdapter, Task> executeCommands,
                                                    string connectionString = null) where TAppAdapter : IApplicationAdapter
        {
            connectionString ??= InMemoryDataStoreProvider.ConnectionString;
            using TAppAdapter winAdapter = appAdapter();
            var testApplication = applicationFactory(winAdapter, connectionString);

            try{
                var commandAdapter = winAdapter.CreateCommandAdapter();
                commandAdapter.Execute(new LoginCommand());
                await executeCommands(commandAdapter);
            }
            finally{
                var easyTestSettingsFile = testApplication.EasyTestSettingsFile();
                if (File.Exists(easyTestSettingsFile))
                {
                    File.Delete(easyTestSettingsFile);
                }
                WriteLine($"Finally EasyTest {GetType().Assembly.GetName().Name} {TestContext.CurrentContext.Result.Outcome.Status}");
                winAdapter.KillApplication(testApplication, KillApplicationContext.TestNormalEnded);
                if (TestContext.CurrentContext.Result.Outcome.Status != TestStatus.Passed)
                {
                    var path = Path.GetDirectoryName(easyTestSettingsFile);
                    WriteLine(path !);
                    foreach (var file in Directory.GetFiles(path !, "*.log"))
                    {
                        var zipPPath = $"{Path.GetDirectoryName(file)}\\{Path.GetFileNameWithoutExtension(file)}.gz";
                        File.WriteAllBytes(zipPPath, File.ReadAllText(file).GZip());
                        WriteLine($"Attaching {zipPPath}");
                        TestContext.AddTestAttachment(zipPPath);
                    }
                }
            }
        }
 public void SuccessfulWithAttachedFiles()
 {
     TestContext.AddTestAttachment(@"data\MyImage.jpg", "My Image");
     TestContext.AddTestAttachment(@"data\MyImage2.gif");
     TestContext.AddTestAttachment(@"data\Class.cs", "source");
     TestContext.AddTestAttachment(@"data\report.txt");
 }
示例#7
0
        /// <summary>
        /// Main “driver” method of all the tests. Contains common housekeeping code. All tests must call it.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     The <paramref name="runner"/> parameter is an action which is passed the following arguments, in
        ///     the order of declaration:
        ///   </para>
        ///   <para>
        ///     <list type="bullet">
        ///        <item>
        ///          <term>TestProjectInfo testInfo</term>
        ///          <description>Information about the location of all the project files and directories</description>
        ///        </item>
        ///
        ///        <item>
        ///          <term>bool many</term>
        ///          <description>whether the test is building more than 20 layouts to test parallel builds</description>
        ///        </item>
        ///
        ///        <item>
        ///          <term>bool dtb</term>
        ///          <description>whether the test is running a design time build (DTB)</description>
        ///        </item>
        ///
        ///        <item>
        ///          <term>LocalBuilder builder</term>
        ///          <description>the object that runs the actual build session</description>
        ///        </item>
        ///     </list>
        ///   </para>
        /// </remarks>
        /// <param name="testName">Name of the test being run. Must be unique</param>
        /// <param name="many">Generate code in parallel if <c>true</c>, serially otherwise</param>
        /// <param name="dtb">Test design-time build if <c>true</c>, regular build otherwise</param>
        /// <param name="runner">Action consituting the main body of the test. Passed parameters are described above in the remarks section.</param>
        void RunTest(string testName, bool many, bool dtb, Action <TestProjectInfo, bool, bool, LocalBuilder> runner)
        {
            string       temporaryProjectDir = PrepareProject(testName);
            LocalBuilder builder             = GetBuilder($"{ProjectName}.{testName}");

            builder.BuildingInsideVisualStudio = dtb;
            var testInfo = new TestProjectInfo(ProjectName, testName, temporaryProjectDir, TestOutputDir);

            try {
                runner(testInfo, many, dtb, builder);

                if (many)
                {
                    Assert.That(WasParsedInParallel(testInfo), Is.True, "Should have been parsed in parallel");
                    Assert.That(WasGeneratedInParallel(testInfo), Is.True, "Should have been generated in parallel");
                }
                else
                {
                    Assert.That(WasParsedInParallel(testInfo), Is.False, "Should have been parsed in serial manner");
                    Assert.That(WasGeneratedInParallel(testInfo), Is.False, "Should have been generated in serial manner");
                }
            } catch {
                CopyLogs(testInfo, false);
                foreach (var file in Directory.GetFiles(testInfo.OutputDirectory, "*.log", SearchOption.AllDirectories))
                {
                    TestContext.AddTestAttachment(file);
                }
                throw;
            }

            // Clean up successful tests
            FileSystemUtils.SetDirectoryWriteable(testInfo.OutputDirectory);
            Directory.Delete(testInfo.OutputDirectory, recursive: true);
        }
示例#8
0
        public void DriverClose()
        {
            if (Page == null)
            {
                return;
            }
            try
            {
                if (TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Failure) || TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Error))
                {
                    var msg      = TestContext.CurrentContext.Result.Message + Environment.NewLine + TestContext.CurrentContext.Result.StackTrace;
                    var fileName = $"{GetSafeFilename(TestContext.CurrentContext.Test.FullName)}.{DateTime.Now:yyyyMMddHHmmss}.png";

                    var fullPath = Path.GetFullPath(fileName);
                    Page.SaveScreenshot(fullPath);
                    if (File.Exists(fullPath))
                    {
                        TestContext.AddTestAttachment(fullPath, msg);
                        Console.WriteLine("Screenshot saved with name:" + fileName);
                    }
                }
            }
            catch { }
            try
            {
                Page.Quit();
            }
            catch { }
            Page = null;
        }
示例#9
0
        public static void TakeScreenShotWhenTestFails()
        {
            var scenarioName   = ScenarioContext.Current.ScenarioInfo.Title;
            var todayDate      = DateTime.Now.ToString("dd-MM-yyyy HH.mm.ss tt");
            var screenShotName = $"{scenarioName}-{todayDate}";

            var scenarioPassed = ScenarioContext.Current.TestError == null;

            try
            {
                if (!scenarioPassed)
                {
                    Console.WriteLine(
                        $"\r\nTest scenario: {scenarioName} [Failed] \r\nSee screen shot with following name: {scenarioName}-{todayDate}");
                    CreateFolderInPathIfOneDoesNotExistAlready(ScreenShotSavePath);
                    var screenShot = ((ITakesScreenshot)Driver).GetScreenshot();
                    screenShot.SaveAsFile(ScreenShotSavePath + screenShotName + ".png", ScreenshotImageFormat.Png);
                    TestContext.AddTestAttachment(ScreenShotSavePath);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
示例#10
0
        public static void AfterScenario(IWebDriver driver, TestContext testContext, ScenarioContext scenarioContext)
        {
            if (scenarioContext?.TestError == null)
            {
                return;
            }

            if (TryCleanupAlert(driver))
            {
                return;
            }

            if (!(driver is ITakesScreenshot takesScreenShot))
            {
                return;
            }

            var screenShot = takesScreenShot.GetScreenshot();

            var screenShotFile = GetScreenShotFileName(testContext);

            screenShot.SaveAsFile(screenShotFile, ScreenshotImageFormat.Png);

            TestContext.AddTestAttachment(screenShotFile, "My Screenshot");

            _screenShotCount++;
        }
示例#11
0
        public static void AreEqual(string fileName, UIElement tickBar)
        {
            var assembly = typeof(ImageAssert).Assembly;
            var name     = assembly.GetManifestResourceNames()
                           .SingleOrDefault(x => x.EndsWith(fileName, ignoreCase: true, culture: CultureInfo.InvariantCulture));

            Assert.NotNull(name, $"Did not find a resource named {fileName}");
            using var stream = assembly.GetManifestResourceStream(name);
            Assert.NotNull(stream);
            using var expected = (Bitmap)Image.FromStream(stream);
            using var actual   = tickBar.ToBitmap(expected.Size(), expected.PixelFormat());
            try
            {
                Gu.Wpf.UiAutomation.ImageAssert.AreEqual(expected, actual);
            }
            catch
            {
                var fullFileName = Path.Combine(Path.GetTempPath(), fileName);
                //// ReSharper disable once AssignNullToNotNullAttribute
                _ = Directory.CreateDirectory(Path.GetDirectoryName(fullFileName));
                if (File.Exists(fullFileName))
                {
                    File.Delete(fullFileName);
                }

                actual.Save(fullFileName);
                TestContext.AddTestAttachment(fullFileName);
                throw;
            }
        }
示例#12
0
        /// <summary>
        /// TAKES SCREEN SHOT ONLY ON FAILED TESTCASES
        /// </summary>
        public void TakesScreenshotOnFailedTest()
        {
            if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
            {
                var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                var filename   = TestContext.CurrentContext.Test.MethodName + "_screenshot_" + DateTime.Now.Ticks + ".jpg";

                //need to add relative path from the solution
                try
                {
                    var RootPath = System.IO.Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory,
                        "..\\..\\SeleniumSS\\");
                    if (!Directory.Exists(RootPath))
                    {
                        Directory.CreateDirectory(RootPath);
                    }
                    var path = RootPath + filename;
                    screenshot.SaveAsFile(path, ScreenshotImageFormat.Jpeg);
                    TestContext.AddTestAttachment(path);
                }
                catch (DirectoryNotFoundException dirEx)
                {
                    // Let the user know that the directory did not exist.
                    Console.WriteLine("Directory not found: " + dirEx.Message);
                }
            }
        }
        public static void LogTestCaseEnd()
        {
            string entryText = string.Concat("TEST CASE ENDED: ", TestContext.CurrentContext.Test.Name);

            AppendTextToLog(entryText);
            TestContext.AddTestAttachment(fileName);
        }
示例#14
0
        public static void AddBinaryAttachment(byte[] bytes, string name)
        {
            var filePath = GetFilePath(name);

            File.WriteAllBytes(filePath, bytes);
            TestContext.AddTestAttachment(filePath);
        }
示例#15
0
        public void teardown()
        {
            var testName = TestContext.CurrentContext.Test.Name;
            var fullName = string.Concat(browserName, "_", testName);
            var _status  = TestContext.CurrentContext.Result.Outcome.Status;

            switch (_status)
            {
            case TestStatus.Passed:
                Support.Logger.Info($"--->TEST PASSED - TestCase:{testName}<---");
                break;

            case TestStatus.Failed:
                var path           = ConfigurationManager.AppSettings["ScreenShotPath"];
                var screenshotPath = Support.TakeScreenShoot(Driver, fullName, path);
                TestContext.AddTestAttachment(screenshotPath);
                var msg = $"Output: {TestContext.CurrentContext.Result.Message} {Environment.NewLine} { TestContext.CurrentContext.Result.StackTrace}";
                Support.Logger.Error($"--->TEST FAILED - TestCase:{testName}<---{Environment.NewLine}{msg}");

                Driver.Navigate().GoToUrl(_baseUrl);     //For the next Test Case to have a good & clean starting point. Useful after any fatal failure.
                break;

            case TestStatus.Skipped:
                Support.Logger.Info($"--->TEST SKIPPED - TestCase:{testName}<---");
                break;

            default:
                Support.Logger.InfoFormat("--->Test Finished - Browser:{0}, TestCase:{1}, Reason:{2}<---",
                                          browserName, testName, Enum.GetName(typeof(TestStatus), _status));
                break;
            }
        }
示例#16
0
        public void TestCaptureAndReadBufferedFrames()
        {
            StartVimbaAndShutDown(() =>
            {
                _client.RequestCameraConnection(new CameraConnectionRequest()
                {
                    Command  = ConnectionCommands.Connect,
                    CameraID = CameraId
                });
                var response = _client.RequestCameraAcquisition(new CameraAcquisitionRequest());
                Assert.IsNull(response.Error);

                Task.Delay(1000).Wait();

                // read frame
                var frameResponse = _client.RequestBufferedFrames(new BufferedFramesRequest());
                Assert.IsNull(frameResponse.Error);
                TestContext.WriteLine($"There are {frameResponse.Images.Count} images.");
                foreach (var images in frameResponse.Images)
                {
                    string tempImageFile = Path.GetTempFileName();
                    using (var f = File.Open(tempImageFile, FileMode.OpenOrCreate))
                    {
                        images.WriteTo(f);
                    }

                    TestContext.AddTestAttachment(tempImageFile);
                    TestContext.WriteLine($"Image written to: {tempImageFile}");
                }
            });
        }
示例#17
0
        public static ComparisonResult Differences(string imageName, IWebDriver driver,
                                                   ComparisonOptions options = null)
        {
            var            baseImageFile = $"{BaseDirectory}{imageName}.png";
            Image <Rgba32> baseImage;

            if (File.Exists(baseImageFile))
            {
                baseImage = Image.Load(baseImageFile);
            }
            else
            {
                baseImage     = Screenshotter.GetFullPageScreenshot(driver);
                baseImageFile = baseImage.SaveAs(ImageType.Base, imageName);
            }

            TestContext.AddTestAttachment(baseImageFile, "base image");

            var actualImage     = Screenshotter.GetFullPageScreenshot(driver);
            var actualImageFile = actualImage.SaveAs(ImageType.Actual, imageName);

            TestContext.AddTestAttachment(actualImageFile);

            return(Differences(imageName, baseImage, actualImage, options));
        }
示例#18
0
        public void TakeScreenShoot()
        {
            var screenImage = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, Guid.NewGuid().ToString() + ".png");

            ((ITakesScreenshot)_driver).GetScreenshot().SaveAsFile(screenImage, ScreenshotImageFormat.Png);
            TestContext.AddTestAttachment(screenImage);
        }
        public async Task SaveLoadSave()
        {
            await using var pairTracker = await PoolManager.GetServerClient(new (){ Fresh = true, Disconnected = true });

            var server     = pairTracker.Pair.Server;
            var mapLoader  = server.ResolveDependency <IMapLoader>();
            var mapManager = server.ResolveDependency <IMapManager>();
            await server.WaitPost(() =>
            {
                // TODO: Properly find the "main" station grid.
                var grid0 = mapManager.GetAllGrids().First();
                mapLoader.SaveBlueprint(grid0.Index, "save load save 1.yml");
                var mapId = mapManager.CreateMap();
                var grid  = mapLoader.LoadBlueprint(mapId, "save load save 1.yml").gridId;
                mapLoader.SaveBlueprint(grid !.Value, "save load save 2.yml");
            });

            await server.WaitIdleAsync();

            var userData = server.ResolveDependency <IResourceManager>().UserData;

            string one;
            string two;

            var rp1 = new ResourcePath("/save load save 1.yml");

            using (var stream = userData.Open(rp1, FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    one = reader.ReadToEnd();
                }

            var rp2 = new ResourcePath("/save load save 2.yml");

            using (var stream = userData.Open(rp2, FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    two = reader.ReadToEnd();
                }

            Assert.Multiple(() => {
                Assert.That(two, Is.EqualTo(one));
                var failed = TestContext.CurrentContext.Result.Assertions.FirstOrDefault();
                if (failed != null)
                {
                    var oneTmp = Path.GetTempFileName();
                    var twoTmp = Path.GetTempFileName();

                    File.WriteAllText(oneTmp, one);
                    File.WriteAllText(twoTmp, two);

                    TestContext.AddTestAttachment(oneTmp, "First save file");
                    TestContext.AddTestAttachment(twoTmp, "Second save file");
                    TestContext.Error.WriteLine("Complete output:");
                    TestContext.Error.WriteLine(oneTmp);
                    TestContext.Error.WriteLine(twoTmp);
                }
            });
            await pairTracker.CleanReturnAsync();
        }
示例#20
0
        public void PrintLogs(string LogType, IWebDriver driver)
        {
            var _logs = driver.Manage().Logs;

            try
            {
                var browserLogs = _logs.GetLog(LogType);
                if (browserLogs.Count > 0)
                {
                    var filePath = $"{Path.GetTempPath()}ConsoleLogs-{Guid.NewGuid()}.txt";
                    File.WriteAllText(filePath, "Begin Log: ");

                    foreach (var log in browserLogs)
                    {
                        //log message in a file
                        StreamWriter sw = File.AppendText(filePath);
                        sw.WriteLine(log.ToString());
                        sw.Close();
                    }
                    TestContext.AddTestAttachment(filePath, "Browser Console Logs");
                }
            }
            catch
            {
                Console.WriteLine("No Logs Present");
            }
        }
示例#21
0
		protected override void CleanupTest ()
		{
			if (HasDevices && TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed &&
					TestOutputDirectories.TryGetValue (TestContext.CurrentContext.Test.ID, out string outputDir)) {
				string local = Path.Combine (outputDir, "screenshot.png");
				string deviceLog = Path.Combine (outputDir, "logcat-failed.log");
				string remote = "/data/local/tmp/screenshot.png";
				RunAdbCommand ($"shell screencap {remote}");
				RunAdbCommand ($"pull {remote} \"{local}\"");
				RunAdbCommand ($"shell rm {remote}");
				RunAdbCommand ($"logcat -d > {deviceLog}");
				if (File.Exists (local)) {
					TestContext.AddTestAttachment (local);
				} else {
					TestContext.WriteLine ($"{local} did not exist!");
				}
				if (File.Exists (deviceLog)) {
					TestContext.AddTestAttachment (deviceLog);
				} else {
					TestContext.WriteLine ($"{deviceLog} did not exist!");
				}
			}

			base.CleanupTest ();
		}
示例#22
0
        public void Hover_And_Screenshot()
        {
            By HyperLink_btn     = By.LinkText("HyperLink");
            By GoToHomePage_link = By.XPath("(//a[contains(text(),'Page')])[1]");

            //var actions = new Actions(driver);
            driver.Navigate().GoToUrl("http://www.leafground.com/home.html");

            //Open link in new tab and switch
            new Actions(driver).KeyDown(Keys.Control).Click(driver.FindElement(HyperLink_btn)).Perform();
            driver.SwitchTo().Window(driver.WindowHandles[1]);

            //Hover
            new Actions(driver).MoveToElement(driver.FindElement(GoToHomePage_link)).Perform();

            //Take and save screenshot
            Screenshot myScreenshot   = ((ITakesScreenshot)driver).GetScreenshot();
            var        screenshotPath = Path.Combine(SaveFolder, $"hover_screenshot_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png");

            myScreenshot.SaveAsFile(screenshotPath);
            TestContext.AddTestAttachment(screenshotPath);

            //Close the tab
            //Switch to first tab
            driver.Close();
            driver.SwitchTo().Window(driver.WindowHandles[0]);
        }
示例#23
0
        public FileInfo TakeScreenshot(string stepName)
        {
            var title = $"{TestContext.CurrentContext.Test.Name}_{stepName}"
                        .Replace(" ", "_")
                        .Replace(".", "_");

            var fileInfo = _app.Screenshot(title);

            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileInfo.Name);

            if (fileNameWithoutExt != title)
            {
                var destFileName = Path.Combine(Path.GetDirectoryName(fileInfo.FullName), title + Path.GetExtension(fileInfo.Name));

                if (File.Exists(destFileName))
                {
                    File.Delete(destFileName);
                }

                File.Move(fileInfo.FullName, destFileName);

                TestContext.AddTestAttachment(destFileName, stepName);

                return(new FileInfo(destFileName));
            }
            else
            {
                TestContext.AddTestAttachment(fileInfo.FullName, stepName);

                return(fileInfo);
            }
        }
        public static void TakeScreenShot(IWebDriver webDriver, string screenshotsDirectory, string scenarioTitle, bool testFailed = false)
        {
            try
            {
                DateTime dateTime = DateTime.Now;

                String failureImageName = dateTime.ToString("HH-mm-ss")
                                          + "_"
                                          + scenarioTitle
                                          + ".png";

                ITakesScreenshot screenshotHandler = webDriver as ITakesScreenshot;
                Screenshot       screenshot        = screenshotHandler.GetScreenshot();
                String           screenshotPath    = Path.Combine(screenshotsDirectory, failureImageName);
                screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
                TestContext.AddTestAttachment(screenshotPath, failureImageName);
                if (testFailed)
                {
                    TestContext.Progress.WriteLine($"{scenarioTitle} -- Scenario under feature failed and the screenshot is available at -- {screenshotPath}");
                }
            }
            catch (Exception exception)
            {
                TestContext.Progress.WriteLine("Exception occurred while taking screenshot - " + exception);
            }
        }
        public void TakeScreenShotOnLeafground()
        {
            driver.Navigate().GoToUrl($"http://www.leafground.com/home.html");
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);

            //Open “HyperLink” page in new tab
            new Actions(driver).KeyDown(Keys.Control).Click(driver.FindElement(By.LinkText("HyperLink"))).Perform();
            driver.SwitchTo().Window(driver.WindowHandles.Last());
            Assert.That(driver.Title, Is.EqualTo("TestLeaf - Interact with HyperLinks"));

            //Hover on “Go to Home Page” link
            new Actions(driver).MoveToElement(driver.FindElement(By.XPath("//*[@id='contentblock']/section/div[1]/div/div/a")))
            .Perform();

            //Take a screenshot and save it somewhere
            var    screenshot      = ((ITakesScreenshot)driver).GetScreenshot();
            var    destinationPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\HWTarasMaksymiv";
            string curentDateTime  = string.Format("{0:yyyy-MM-dd_hh-mm-ss}", DateTime.Now);

            System.IO.Directory.CreateDirectory(destinationPath);
            var screenshotPath = Path.Combine(destinationPath, curentDateTime + ".png");

            screenshot.SaveAsFile(screenshotPath);
            TestContext.AddTestAttachment(screenshotPath);

            //Close the tab
            driver.Close();

            //Switch to first tab
            driver.SwitchTo().Window(driver.WindowHandles[0]);
        }
示例#26
0
        public void AttachScreenshotToTestContext(string title = null)
        {
            if (!TestContext.Parameters.Exists("IncludeScreenShots") ||
                !Convert.ToBoolean(TestContext.Parameters["IncludeScreenShots"]))
            {
                return;
            }

            title = title ?? TestContext.CurrentContext.Test.FullName
                    .Replace(".", "_")
                    .Replace(" ", "_");

            FileInfo file = _app.Screenshot(title);

            if (file != null)
            {
                try
                {
                    TestContext.AddTestAttachment(file.FullName, TestContext.CurrentContext.Test.FullName);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine($"Failed to write {file?.FullName} {exc}");
                }
            }
        }
示例#27
0
        public async Task SaveLoadSave()
        {
            var server = StartServer();
            await server.WaitIdleAsync();

            var mapLoader  = server.ResolveDependency <IMapLoader>();
            var mapManager = server.ResolveDependency <IMapManager>();

            server.Post(() =>
            {
                // TODO: Un-hardcode the grid Id for this test.
                mapLoader.SaveBlueprint(new GridId(1), "save load save 1.yml");
                var mapId = mapManager.CreateMap();
                var grid  = mapLoader.LoadBlueprint(mapId, "save load save 1.yml");
                mapLoader.SaveBlueprint(grid !.Index, "save load save 2.yml");
            });

            await server.WaitIdleAsync();

            var userData = server.ResolveDependency <IResourceManager>().UserData;

            string one;
            string two;

            var rp1 = new ResourcePath("/save load save 1.yml");

            using (var stream = userData.Open(rp1, FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    one = reader.ReadToEnd();
                }

            var rp2 = new ResourcePath("/save load save 2.yml");

            using (var stream = userData.Open(rp2, FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    two = reader.ReadToEnd();
                }

            Assert.Multiple(() => {
                Assert.That(two, Is.EqualTo(one));
                var failed = TestContext.CurrentContext.Result.Assertions.FirstOrDefault();
                if (failed != null)
                {
                    var oneTmp = Path.GetTempFileName();
                    var twoTmp = Path.GetTempFileName();

                    File.WriteAllText(oneTmp, one);
                    File.WriteAllText(twoTmp, two);

                    TestContext.AddTestAttachment(oneTmp, "First save file");
                    TestContext.AddTestAttachment(twoTmp, "Second save file");
                    TestContext.Error.WriteLine("Complete output:");
                    TestContext.Error.WriteLine(oneTmp);
                    TestContext.Error.WriteLine(twoTmp);
                }
            });
        }
示例#28
0
文件: Utils.cs 项目: bertt/SharpGLTF
        public static void AttachLink(this TestContext context, string linkPath, string targetPath)
        {
            linkPath = context.GetAttachmentPath(linkPath);

            linkPath = ShortcutUtils.CreateLink(linkPath, targetPath);

            TestContext.AddTestAttachment(linkPath);
        }
示例#29
0
文件: Utils.cs 项目: bertt/SharpGLTF
        public static void AttachText(this TestContext context, string fileName, string[] lines)
        {
            fileName = context.GetAttachmentPath(fileName, true);

            System.IO.File.WriteAllLines(fileName, lines.ToArray());

            TestContext.AddTestAttachment(fileName);
        }
        public void AttachmentsAreOptional()
        {
            var tempFile = Path.GetTempFileName();

            TestContext.AddTestAttachment(tempFile);

            File.Delete(tempFile);
        }