/// <summary> /// Records any exception which is thrown by the given code that has /// a return value. Generally used for testing property accessors. /// </summary> /// <param name="code">The code which may thrown an exception.</param> /// <returns>Returns the exception that was thrown by the code; null, otherwise.</returns> public static Exception Exception(Assert.ThrowsDelegateWithReturn code) { try { code(); return null; } catch (Exception ex) { return ex; } }
public void Region() { var area = new AreaOfRegion(); Assert.AreEqual(area.Area(), "North"); }
public void ShadowScopeComplete() { var loggerFactory = NullLoggerFactory.Instance; var path = HostingEnvironment.MapPathContentRoot("FileSysTests"); var shadowfs = HostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); Directory.CreateDirectory(path); Directory.CreateDirectory(shadowfs); var scopedFileSystems = false; var phy = new PhysicalFileSystem(IOHelper, HostingEnvironment, Logger, path, "ignore"); var globalSettings = Options.Create(new GlobalSettings()); var fileSystems = new FileSystems(loggerFactory, IOHelper, globalSettings, HostingEnvironment) { IsScoped = () => scopedFileSystems }; var shadowPath = $"x/{Guid.NewGuid().ToString("N").Substring(0, 6)}"; var sw = (ShadowWrapper)fileSystems.CreateShadowWrapper(phy, shadowPath); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f1.txt", ms); } Assert.IsTrue(phy.FileExists("sub/f1.txt")); string id; // explicit shadow without scope does not work sw.Shadow(id = ShadowWrapper.CreateShadowId(HostingEnvironment)); Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f2.txt", ms); } Assert.IsTrue(phy.FileExists("sub/f2.txt")); sw.UnShadow(true); Assert.IsTrue(phy.FileExists("sub/f2.txt")); Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)); // shadow with scope but no complete does not complete scopedFileSystems = true; // pretend we have a scope var scope = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId(HostingEnvironment)); Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f3.txt", ms); } Assert.IsFalse(phy.FileExists("sub/f3.txt")); var dirs = Directory.GetDirectories(shadowfs); Assert.AreEqual(1, dirs.Length); Assert.AreEqual((shadowfs + "/" + id).Replace('\\', '/'), dirs[0].Replace('\\', '/')); dirs = Directory.GetDirectories(dirs[0]); var typedDir = dirs.FirstOrDefault(x => x.Replace('\\', '/').EndsWith("/x")); Assert.IsNotNull(typedDir); dirs = Directory.GetDirectories(typedDir); var scopedDir = dirs.FirstOrDefault(x => x.Replace('\\', '/').EndsWith("/" + shadowPath)); // this is where files go Assert.IsNotNull(scopedDir); scope.Dispose(); scopedFileSystems = false; Assert.IsFalse(phy.FileExists("sub/f3.txt")); TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id))); // shadow with scope and complete does complete scopedFileSystems = true; // pretend we have a scope scope = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId(HostingEnvironment)); Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f4.txt", ms); } Assert.IsFalse(phy.FileExists("sub/f4.txt")); Assert.AreEqual(1, Directory.GetDirectories(shadowfs).Length); scope.Complete(); scope.Dispose(); scopedFileSystems = false; TestHelper.TryAssert(() => Assert.AreEqual(0, Directory.GetDirectories(shadowfs).Length)); Assert.IsTrue(phy.FileExists("sub/f4.txt")); Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)); // test scope for "another thread" scopedFileSystems = true; // pretend we have a scope scope = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId(HostingEnvironment)); Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f5.txt", ms); } Assert.IsFalse(phy.FileExists("sub/f5.txt")); // pretend we're another thread w/out scope scopedFileSystems = false; using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { sw.AddFile("sub/f6.txt", ms); } scopedFileSystems = true; // pretend we have a scope Assert.IsTrue(phy.FileExists("sub/f6.txt")); // other thread has written out to fs scope.Complete(); scope.Dispose(); scopedFileSystems = false; Assert.IsTrue(phy.FileExists("sub/f5.txt")); TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id))); }
public async Task TaskCancelationPropagation() { IExceptionGrain grain = GrainFactory.GetGrain <IExceptionGrain>(GetRandomGrainId()); await Assert.ThrowsAsync <TaskCanceledException>( () => grain.Canceled()); }
public void DeleteUpdateAssociationTest() { foreach (IDataService dataService in DataServices) { // Arrange. SQLDataService ds = dataService as SQLDataService; //TODO: Fix OracleDataService error. if (dataService is OracleDataService) { continue; } var masterBreedType = new ТипПороды { Название = "тип породы1", ДатаРегистрации = DateTime.Now }; var innerMasterBreed = new Порода { Название = "порода1", ТипПороды = masterBreedType }; var innerMasterCat = new Кошка { Кличка = "кошка", ДатаРождения = (NullableDateTime)DateTime.Now, Тип = ТипКошки.Дикая, Порода = innerMasterBreed }; var innerKitten = new Котенок { КличкаКотенка = "котеночек", Кошка = innerMasterCat }; // Act ds.UpdateObject(innerKitten); LoadingCustomizationStruct lcsKitten = LoadingCustomizationStruct.GetSimpleStruct(typeof(Котенок), Котенок.Views.КотенокE); LoadingCustomizationStruct lcsCat = LoadingCustomizationStruct.GetSimpleStruct(typeof(Кошка), Кошка.Views.КошкаE); LoadingCustomizationStruct lcsBreed = LoadingCustomizationStruct.GetSimpleStruct(typeof(Порода), Порода.Views.ПородаE); LoadingCustomizationStruct lcsBreedType = LoadingCustomizationStruct.GetSimpleStruct(typeof(ТипПороды), ТипПороды.Views.ТипПородыE); DataObject[] dataObjectsKitten = ds.LoadObjects(lcsKitten); DataObject[] dataObjectsCats = ds.LoadObjects(lcsCat); DataObject[] dataObjectsBreed = ds.LoadObjects(lcsBreed); DataObject[] dataObjectsBreedTypes = ds.LoadObjects(lcsBreedType); int countKittenBefore = ds.GetObjectsCount(lcsKitten); int countCatBefore = ds.GetObjectsCount(lcsCat); int countBreedBefore = ds.GetObjectsCount(lcsBreed); int countBreedTypeBefore = ds.GetObjectsCount(lcsBreed); List <DataObject> objectsForUpdateList = new List <DataObject>(); foreach (Котенок котенок in dataObjectsKitten) { котенок.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(котенок); } foreach (Кошка кошка in dataObjectsCats) { кошка.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(кошка); } foreach (Порода порода in dataObjectsBreed) { порода.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(порода); } foreach (ТипПороды типПороды in dataObjectsBreedTypes) { типПороды.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(типПороды); } DataObject[] objectsForUpdate = objectsForUpdateList.ToArray(); ds.UpdateObjects(ref objectsForUpdate); int countKittenAfter = ds.GetObjectsCount(lcsKitten); int countCatAfter = ds.GetObjectsCount(lcsCat); int countBreedAfter = ds.GetObjectsCount(lcsBreed); int countBreedTypeAfter = ds.GetObjectsCount(lcsBreedType); // Assert Assert.Equal(1, countKittenBefore); Assert.Equal(1, countCatBefore); Assert.Equal(1, countBreedBefore); Assert.Equal(1, countBreedTypeBefore); Assert.Equal(0, countKittenAfter); Assert.Equal(0, countCatAfter); Assert.Equal(0, countBreedAfter); Assert.Equal(0, countBreedTypeAfter); } }
public void DetailsDeleteTest() { foreach (IDataService dataService in DataServices) { // Arrange SQLDataService ds = (SQLDataService)dataService; const string First = "Первый"; const string Second = "Второй"; const string Third = "Третий"; const string Fourth = "Четвертый"; ТипЛапы передняяЛапа = new ТипЛапы { Актуально = true, Название = "Передняя" }; ТипЛапы задняяЛапа = new ТипЛапы { Актуально = true, Название = "Задняя" }; Кошка aggregator = new Кошка { ДатаРождения = (NullableDateTime)DateTime.Now, Тип = ТипКошки.Дикая, Порода = new Порода { Название = "Чеширская" }, Кличка = "Мурка" }; aggregator.Лапа.AddRange( new Лапа { Цвет = First, ТипЛапы = передняяЛапа }, new Лапа { Цвет = Second, ТипЛапы = передняяЛапа }, new Лапа { Цвет = Third, ТипЛапы = задняяЛапа }, new Лапа { Цвет = Fourth, ТипЛапы = задняяЛапа }); ds.UpdateObject(aggregator); LoadingCustomizationStruct lcsCat = LoadingCustomizationStruct.GetSimpleStruct(typeof(Кошка), Кошка.Views.КошкаE); LoadingCustomizationStruct lcsPaws = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лапа), Лапа.Views.ЛапаFull); LoadingCustomizationStruct lcsPawsType = LoadingCustomizationStruct.GetSimpleStruct(typeof(ТипЛапы), ТипЛапы.Views.ТипЛапыE); DataObject[] dataObjectsCats = ds.LoadObjects(lcsCat); DataObject[] dataObjectsPawsTypes = ds.LoadObjects(lcsPawsType); // Act int countCatBefore = ds.GetObjectsCount(lcsCat); int countPawsBefore = ds.GetObjectsCount(lcsPaws); int countPawsTypeBefore = ds.GetObjectsCount(lcsPawsType); List <DataObject> objectsForUpdateList = new List <DataObject>(); foreach (Кошка кошка in dataObjectsCats) { кошка.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(кошка); } foreach (ТипЛапы типЛапы in dataObjectsPawsTypes) { типЛапы.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(типЛапы); } DataObject[] objectsForUpdate = objectsForUpdateList.ToArray(); ds.UpdateObjects(ref objectsForUpdate); int countCatAfter = ds.GetObjectsCount(lcsCat); int countPawsAfter = ds.GetObjectsCount(lcsPaws); int countPawsTypeAfter = ds.GetObjectsCount(lcsPawsType); // Assert Assert.Equal(1, countCatBefore); Assert.Equal(4, countPawsBefore); Assert.Equal(2, countPawsTypeBefore); Assert.Equal(0, countCatAfter); Assert.Equal(0, countPawsAfter); Assert.Equal(0, countPawsTypeAfter); } }
private TestResult VerifyActivateDataset(Application application, Log log) { const string prefix = "Dataset activation"; var result = new TestResult(); var assert = new Assert(result, log); try { // Start new project via File menu var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - The project page was not opened."); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); // Wait for datasets to be created ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 3); var datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); var ids = new List<int>(datasetIds); ids.Sort(); ProjectPageControlProxies.ActivateDataset(application, log, ids[1]); var isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsTrue(isDataset1Activated, prefix + " - Failed to activate the first dataset."); var isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsFalse(isDataset2Activated, prefix + " - Activated the second dataset while it should not have been."); ProjectPageControlProxies.ActivateDataset(application, log, ids[2]); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsTrue(isDataset1Activated, prefix + " - Deactivated the first dataset when it should not have been."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsTrue(isDataset2Activated, prefix + " - Failed to activate the second dataset."); /* // Undo MenuProxies.UndoViaEditMenu(application, log); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsTrue(isDataset1Activated, prefix + " - Deactivated the first dataset when it should not have been."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsFalse(isDataset2Activated, prefix + " - Did not undo the activation state of the second dataset."); // Undo MenuProxies.UndoViaEditMenu(application, log); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsFalse(isDataset1Activated, prefix + " - Did not undo the activation state of the first dataset."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsFalse(isDataset2Activated, prefix + " - Still did not undo the activation state of the second dataset."); // Redo MenuProxies.RedoViaEditMenu(application, log); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsTrue(isDataset1Activated, prefix + " - Did not redo the undone activation state of the first dataset."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsFalse(isDataset2Activated, prefix + " - Redid the activation state of the second dataset when it should not have been."); // Redo MenuProxies.RedoViaEditMenu(application, log); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsTrue(isDataset1Activated, prefix + " - Changed the activation state of the first dataset when it should not have been."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsTrue(isDataset2Activated, prefix + " - Did not redo the undone activation state of the second dataset."); * */ ProjectPageControlProxies.DeactivateDataset(application, log, ids[1]); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsFalse(isDataset1Activated, prefix + " - Failed to deactivate the first dataset."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsTrue(isDataset2Activated, prefix + " - Deactivated the second dataset when it should not have been."); ProjectPageControlProxies.DeactivateDataset(application, log, ids[2]); isDataset1Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[1]); assert.IsFalse(isDataset1Activated, prefix + " - Failed to deactivate the first dataset."); isDataset2Activated = ProjectPageControlProxies.IsDatasetActivated(application, log, ids[2]); assert.IsFalse(isDataset2Activated, prefix + " - Failed to deactivate the second dataset."); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
private TestResult VerifyTabBehaviour(Application application, Log log) { const string prefix = "Tabs"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { log.Info(prefix, "Opening start page."); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); } // Make sure we don't close the welcome tab upon opening the project page WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { log.Info(prefix, "Opening project page."); WelcomePageControlProxies.OpenProjectPageViaWelcomePageButton(application, log); } startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { var message = "Failed to open the start page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { var message = "Failed to open the project page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } try { if (!startPage.IsSelected) { log.Info(prefix, "Setting focus to start page."); startPage.Select(); } } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to select the start page tab. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } assert.IsTrue(startPage.IsSelected, prefix + " - Start is selected"); assert.IsFalse(projectPage.IsSelected, prefix + " - Project is not selected"); MenuProxies.SwitchToProjectPageViaViewStartPageMenuItem(application, log); assert.IsFalse(startPage.IsSelected, prefix + " - Start is not selected"); assert.IsTrue(projectPage.IsSelected, prefix + " - Project is selected"); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); assert.IsTrue(startPage.IsSelected, prefix + " - Start is selected"); assert.IsFalse(projectPage.IsSelected, prefix + " - Project is not selected"); TabProxies.CloseProjectPageTab(application, log); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public async Task ItReturnsTheResponseFromTheInnerHandler() { var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com"); var response = await HttpClient.SendAsync(request); Assert.That(InnerHandler.NextResponse, Is.SameAs(response)); }
public void FormsAdminTest() { // GOOD TEST //Login Page + User Management Page appURL = "Your Website"; driver.Navigate().GoToUrl(appURL + "/"); driver.FindElement(By.Id("HTML Id Assigned to Username Textbox")).SendKeys("username"); driver.FindElement(By.Id("HTML Id Assigned to Password Textbox")).SendKeys("password"); driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Login1_LoginButton")).Click(); driver.FindElement(By.Id("search")).SendKeys("Nisha Verma" + Keys.Enter); WebDriverWait impersonateWait = new WebDriverWait(driver, TimeSpan.FromSeconds(40)); impersonateWait.Until(ExpectedConditions.ElementIsVisible(By.Id("impersonateButton"))); driver.FindElement(By.Id("impersonateButton")).Click(); Assert.IsTrue(driver.Title.Contains("User Management"), "Verified title of the page"); //Admin Page //appURL = "Your Website"; //driver.Navigate().GoToUrl(appURL + "/"); ////Search Textbox //driver.FindElement(By.Id("searchBar")).SendKeys("Admin Page"); ////System Filter //driver.FindElement(By.XPath("//div[@id='sectionSystemFilter']/input")).Click(); //driver.FindElement(By.XPath("//div[@id='sectionSystemFilter']/input")).SendKeys("Change Control"); //driver.FindElement(By.XPath("//div[@id='sectionSystemFilter']/input")).SendKeys(Keys.ArrowDown); //driver.FindElement(By.XPath("//div[@id='sectionSystemFilter']/input")).SendKeys(Keys.Enter); ////Record Type Filter //driver.FindElement(By.XPath("//div[@id='sectionRecordTypeFilter']/input")).SendKeys("None"); ////Save Button //driver.FindElement(By.Id("theSaveButton")).Click(); ////Results //Assert.IsTrue(driver.Title.Contains("Forms System Admin"), "Verified title of the page"); //Forms Record Page appURL = "Your Website"; driver.Navigate().GoToUrl(appURL + "/"); //System Filter driver.FindElement(By.XPath("//div[@id='systemFilter']/input")).Click(); driver.FindElement(By.XPath("//div[@id='systemFilter']/input")).SendKeys("Maintenance Management"); driver.FindElement(By.XPath("//div[@id='systemFilter']/input")).SendKeys(Keys.ArrowDown); driver.FindElement(By.XPath("//div[@id='systemFilter']/input")).SendKeys(Keys.Enter); //Type Filter var education = driver.FindElement(By.Id("recordType")); var selectElement = new OpenQA.Selenium.Support.UI.SelectElement(education); selectElement.SelectByText("Maintenance Work Request"); //Search Textbox driver.FindElement(By.Id("searchBar")).SendKeys("Records Page"); //Location Filter WebDriverWait locationWait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); locationWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@class='datum col-sm-1'][1]/div/div/div/div/div/div/div/div/div/div/div/div/input"))); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][1]/div/div/div/div/div/div/div/div/div/div/div/div/input")).SendKeys("Die Design" + Keys.Tab); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][1]/div/div/div/div/div/div/div/div/div/div/div/div/input")).Click(); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][1]/div/div/div/div/div/div/div/div/div/div/div/div/input")).SendKeys(Keys.Enter); //Priority Filter WebDriverWait priorityWait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); priorityWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@class='datum col-sm-1'][2]/div/div/div/input"))); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][2]/div/div/div/input")).SendKeys("3 - Improvement" + Keys.Tab); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][2]/div/div/div/input")).Click(); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][2]/div/div/div/input")).SendKeys(Keys.Enter); //Status Filter WebDriverWait statusWait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); statusWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@class='datum col-sm-1'][3]/div/div/div/input"))); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][3]/div/div/div/input")).SendKeys("Safety issue" + Keys.Tab); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][3]/div/div/div/input")).Click(); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][3]/div/div/div/input")).SendKeys(Keys.Enter); //Problem & Comments Textbox driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][4]/div/textarea")).SendKeys("Problems"); driver.FindElement(By.XPath("//div[@class='datum col-sm-1'][5]/div/textarea")).SendKeys("Comments"); //Create Button driver.FindElement(By.Id("theSaveButton")).Click(); Assert.IsTrue(driver.Title.Contains("New Record"), "Verified title of the page"); }
public void CastStreamingExecution() { IEnumerable <string> enumerable = LateThrowingData().Cast <string>(); Assert.DoesNotThrow(() => enumerable.MoveNext()); // # LateThrownException was not thrown since sequence was not fully enumerated }
public void CastInvalidCast() { Assert.Throws <InvalidCastException>(() => Data('c').Cast <DateTime>().Iterate()); }
public void CastSourceArgumentNull() { Assert.Throws <ArgumentNullException>(() => NullData.Cast <string>()).WithParameter("source"); }
public void GetNumberOfPositiveIntegersWhoseSquareIsLessThanANegativeTests(int a) { Assert.Throws<ArgumentException>(() => Cycles.GetNumberOfPositiveIntegersWhoseSquareIsLessThanA(a)); }
public void GetNumberOfPositiveIntegersWhoseSquareIsLessThanATests(int a, int expected) { int actual = Cycles.GetNumberOfPositiveIntegersWhoseSquareIsLessThanA(a); Assert.AreEqual(expected, actual); }
public TestResult VerifyShowWelcomePageCheckbox(Application application, Log log) { const string prefix = "Verify show welcome page"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNull(startPage, prefix + " - Start page was open on application start."); WelcomePageControlProxies.CheckShowWelcomePageOnApplicationStart(application, log); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public TestResult VerifyWelcomeTab(Application application, Log log) { const string prefix = "Welcome tab"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { log.Info(prefix, "Opening start page."); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); } startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { var message = "Failed to get the start page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } try { if (!startPage.IsSelected) { log.Info(prefix, "Setting focus to start page."); startPage.Select(); } } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to select the start page tab. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } var applicationNameSearchCiteria = SearchCriteria .ByAutomationId(WelcomeViewAutomationIds.ApplicationName); var nameLabel = Retry.Times( () => { log.Debug(prefix, "Trying to get the application name label."); var label = (Label)startPage.Get(applicationNameSearchCiteria); if (label == null) { log.Error(prefix, "Failed to find the application name label."); } return label; }); if (nameLabel == null) { var message = "Failed to get the application name label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } var nameText = nameLabel.Text; assert.AreEqual(ProductInformation.ProductName, nameText, prefix + " - Product Name"); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public async Task ItPassesTheRequestToTheInnerHandler() { var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com"); await HttpClient.SendAsync(request); Assert.That(InnerHandler.LastRequest, Is.SameAs(request)); }
private TestResult VerifyDatasetCreation(Application application, Log log) { const string prefix = "Dataset information"; var result = new TestResult(); var assert = new Assert(result, log); try { var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - The project page was not opened."); var datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); var datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs before creating sub-datasets."); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after creating 1 sub-dataset."); ProjectPageControlProxies.CreateChildDatasetForRoot(application, log); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after creating 2 sub-datasets."); // Undo MenuProxies.UndoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after undoing the creation of the second dataset."); // Undo MenuProxies.UndoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 1); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after undoing the creation of the first dataset."); // Redo MenuProxies.RedoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after redoing the creation of the first dataset."); // Redo MenuProxies.RedoViaEditMenu(application, log); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 3); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after redoing the creation of the second dataset."); // Delete first child var ids = new List<int>(datasetIds); ids.Sort(); ProjectPageControlProxies.DeleteDataset(application, log, ids[1]); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 2); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after the deletion of the first dataset."); assert.IsTrue(datasetIds.Contains(ids[2]), prefix + " - The second dataset was deleted but should not have been."); // Delete second child ProjectPageControlProxies.DeleteDataset(application, log, ids[2]); ProjectPageControlProxies.WaitForDatasetCreationOrDeletion(application, log, 1); datasetCount = ProjectPageControlProxies.GetNumberOfDatasetsViaProjectControl(application, log); datasetIds = ProjectPageControlProxies.GetDatasetIds(application, log); assert.AreEqual( datasetIds.Count(), datasetCount, prefix + " - The number of datasets does not match the number of dataset IDs after the deletion of the second dataset."); } catch (RegressionTestFailedException e) { var message = string.Format(CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public void TestMethod1() { try { var fabric = new ManualFabricBridge(); var bridgeOut = fabric[FabricMode.Queue]; var bridgein = fabric[FabricMode.Broadcast]; var key = CreateSalt(128); var encOut = new AesEncryptionHandler("rogue1", key, keySize: 128); var encIn = new AesEncryptionHandler("rogue2", key, keySize: 128); PersistenceClient<Guid, SecureMe> init; DebugMemoryDataCollector memp1, memp2; var p1 = new MicroservicePipeline("Sender") .AddEncryptionHandler(encOut) .AdjustPolicyCommunication((p, c) => p.BoundaryLoggingActiveDefault = true) .AddDataCollector((c) => new DebugMemoryDataCollector(), (c) => memp1 = c) .AddChannelIncoming("cresponse") .AttachListener(bridgein.GetListener()) .Revert() .AddChannelOutgoing("crequest") .AttachTransportPayloadEncryption("rogue1") .AttachSender(bridgeOut.GetSender()) .AttachPersistenceClient("cresponse", out init) .Revert() ; var p2 = new MicroservicePipeline("Receiver") .AddEncryptionHandler(encIn) .AdjustPolicyCommunication((p, c) => p.BoundaryLoggingActiveDefault = true) .AddDataCollector((c) => new DebugMemoryDataCollector(), (c) => memp2 = c) .AddChannelIncoming("crequest") .AttachTransportPayloadDecryption("rogue2") .AttachListener(bridgeOut.GetListener()) .AttachCommand(new PersistenceManagerHandlerMemory<Guid, SecureMe>((e) => e.Id, (s) => new Guid(s))) .Revert() .AddChannelOutgoing("cresponse") .AttachSender(bridgein.GetSender()) ; p1.Start(); p2.Start(); int check1 = p1.ToMicroservice().Commands.Count(); int check2 = p2.ToMicroservice().Commands.Count(); var entity = new SecureMe() { Message = "Momma" }; var rs = init.Create(entity, new RepositorySettings() { WaitTime = TimeSpan.FromMinutes(5) }).Result; var rs2 = init.Read(entity.Id).Result; Assert.IsTrue(rs2.IsSuccess); Assert.IsTrue(rs2.Entity.Message == "Momma"); } catch (Exception ex) { throw; } }
public void GetNumbersDivisibleByANegativeTests(int a) { Assert.Throws<ArgumentOutOfRangeException>(() => Cycles.GetNumbersDivisibleByA(a)); }
public void TestConfirmSignUpFail() { Assert.ThrowsAsync <CodeMismatchException>(() => user.ConfirmSignUpAsync("fakeConfirmationCode", false)); }
public void CascadeDeleteTest() { // TODO: "Раскомментируйте этот тест после закрытия ошибки \"Удаление объектов и их мастеров\" (номер 4010)." foreach (IDataService dataService in DataServices) { var master = new SomeMasterClass { FieldA = "someFieldA_value" }; var detail1 = new SomeDetailClass { FieldB = "SomeFieldB1", SomeMasterClass = master }; var detail2 = new SomeDetailClass { FieldB = "SomeFieldB2", SomeMasterClass = master }; var objsToUpdate = new DataObject[] { master, detail1, detail2 }; dataService.UpdateObjects(ref objsToUpdate); // Попробуем удалить мастеровой объект master.SetStatus(ObjectStatus.Deleted); try { dataService.UpdateObject(master); Assert.True(false, "Assert.Fail"); } catch (ExecutingQueryException) { // Если провалился сюда - значит все хорошо } // Теперь попробуем удалить его и утащить за ним все данные в нем. // Примечание: логика написана в бизнес-сервере, который находится в файле SomeMasterClass.cs master.DynamicProperties.Add("DeleteAll", true); master.DynamicProperties.Add("dataService", dataService); try { dataService.UpdateObject(master); } catch (ExecutingQueryException) { // Почистим данные из базы. master.SetStatus(ObjectStatus.Deleted); detail1.SetStatus(ObjectStatus.Deleted); detail2.SetStatus(ObjectStatus.Deleted); var objectsToDelete = new DataObject[] { master, detail1, detail2 }; dataService.UpdateObjects(ref objectsToDelete); Assert.True(false, "Объекты не хотят удаляться при удалении мастера"); } // После корректного срабатывания теста в базе не должно остаться ни одной записи. var detailCount = ((SQLDataService)dataService).Query <SomeDetailClass>(SomeDetailClass.Views.ClassBE).Count(); var masterCount = ((SQLDataService)dataService).Query <SomeMasterClass>(SomeMasterClass.Views.ClassAE).Count(); Assert.True(detailCount == 0); Assert.True(masterCount == 0); } }
public void TestMethod1() { Assert.IsFalse(false); }
public void DeleteAggregatorWithHierarhiAndAssociationTest() { foreach (IDataService dataService in DataServices) { // Arrange. SQLDataService ds = dataService as SQLDataService; //TODO: Fix OracleDataService error. if (dataService is OracleDataService) { continue; } var masterForest = new Лес { Название = "лес1" }; var aggregatorBear = new Медведь { ПорядковыйНомер = 1, ЛесОбитания = masterForest }; ds.UpdateObject(aggregatorBear); var aggregatorBearMother = new Медведь { ПорядковыйНомер = 2 }; var aggregatorBearFather = new Медведь { ПорядковыйНомер = 2 }; aggregatorBear.Мама = aggregatorBearMother; aggregatorBear.Папа = aggregatorBearFather; ds.UpdateObject(aggregatorBear); // Act & Assert. LoadingCustomizationStruct lcsBear = LoadingCustomizationStruct.GetSimpleStruct(typeof(Медведь), Медведь.Views.МедведьE); LoadingCustomizationStruct lcsForest = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лес), Лес.Views.ЛесE); DataObject[] dataObjectsBear = ds.LoadObjects(lcsBear); DataObject[] dataObjectsForest = ds.LoadObjects(lcsForest); // Act int countBearBefore = ds.GetObjectsCount(lcsBear); int countForestBefore = ds.GetObjectsCount(lcsForest); List <DataObject> objectsForUpdateList = new List <DataObject>(); foreach (Медведь медведь in dataObjectsBear) { медведь.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(медведь); } foreach (Лес лес in dataObjectsForest) { лес.SetStatus(ObjectStatus.Deleted); objectsForUpdateList.Add(лес); } DataObject[] objectsForUpdate = objectsForUpdateList.ToArray(); ds.UpdateObjects(ref objectsForUpdate); int countBearAfter = ds.GetObjectsCount(lcsBear); int countForestAfter = ds.GetObjectsCount(lcsForest); // Assert Assert.Equal(3, countBearBefore); Assert.Equal(1, countForestBefore); Assert.Equal(0, countBearAfter); Assert.Equal(0, countForestAfter); } }
public static byte[] ReaderLoop(int inpuDataLength, out int length, ref Utf8JsonReader json) { byte[] outputArray = new byte[inpuDataLength]; Span<byte> destination = outputArray; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.HasValueSequence ? json.ValueSequence.ToArray() : json.ValueSpan; if (json.HasValueSequence) { Assert.True(json.ValueSpan == default); if ((tokenType != JsonTokenType.String && tokenType != JsonTokenType.PropertyName) || json.GetString().Length != 0) { // Empty strings could still make this true, i.e. "" Assert.False(json.ValueSequence.IsEmpty); } } else { Assert.True(json.ValueSequence.IsEmpty); if ((tokenType != JsonTokenType.String && tokenType != JsonTokenType.PropertyName) || json.GetString().Length != 0) { // Empty strings could still make this true, i.e. "" Assert.False(json.ValueSpan == default); } } switch (tokenType) { case JsonTokenType.PropertyName: valueSpan.CopyTo(destination); destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.Number: case JsonTokenType.String: case JsonTokenType.Comment: valueSpan.CopyTo(destination); destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.True: // Special casing True/False so that the casing matches with Json.NET destination[0] = (byte)'T'; destination[1] = (byte)'r'; destination[2] = (byte)'u'; destination[3] = (byte)'e'; destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.False: destination[0] = (byte)'F'; destination[1] = (byte)'a'; destination[2] = (byte)'l'; destination[3] = (byte)'s'; destination[4] = (byte)'e'; destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.Null: // Special casing Null so that it matches what JSON.NET does break; case JsonTokenType.StartObject: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'{' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndObject: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'}' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.StartArray: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'[' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndArray: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)']' })); Assert.True(json.ValueSequence.IsEmpty); break; default: break; } } length = outputArray.Length - destination.Length; return outputArray; }
public async Task HandleRequestAsync_InvokesServer_RemapsEdits() { // Arrange var documentManager = new TestDocumentManager(); documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>(s => s.Uri == Uri && s.Snapshot == Mock.Of <ITextSnapshot>())); var invokedServer = false; var mappedTextEdits = false; var requestInvoker = new Mock <LSPRequestInvoker>(MockBehavior.Strict); requestInvoker .Setup(r => r.ReinvokeRequestOnServerAsync <DocumentOnAutoInsertParams, DocumentOnAutoInsertResponseItem>(MSLSPMethods.OnAutoInsertName, It.IsAny <string>(), It.IsAny <DocumentOnAutoInsertParams>(), It.IsAny <CancellationToken>())) .Callback <string, string, DocumentOnAutoInsertParams, CancellationToken>((method, serverContentType, formattingParams, ct) => { invokedServer = true; }) .Returns(Task.FromResult(new DocumentOnAutoInsertResponseItem() { TextEdit = new TextEdit() { Range = new Range(), NewText = "sometext" } })); var projectionUri = new Uri(Uri.AbsoluteUri + "__virtual.html"); var projectionResult = new ProjectionResult() { Uri = projectionUri, LanguageKind = RazorLanguageKind.Html, }; var projectionProvider = new Mock <LSPProjectionProvider>(); projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult)); var documentMappingProvider = new Mock <LSPDocumentMappingProvider>(MockBehavior.Strict); documentMappingProvider .Setup(d => d.RemapTextEditsAsync(projectionUri, It.IsAny <TextEdit[]>(), It.IsAny <CancellationToken>())) .Callback(() => { mappedTextEdits = true; }) .Returns(Task.FromResult(new[] { new TextEdit() })); var handler = new OnAutoInsertHandler(documentManager, requestInvoker.Object, projectionProvider.Object, documentMappingProvider.Object); var request = new DocumentOnAutoInsertParams() { Character = "=", TextDocument = new TextDocumentIdentifier() { Uri = Uri }, Options = new FormattingOptions() { OtherOptions = new Dictionary <string, object>() }, Position = new Position(1, 4) }; // Act var response = await handler.HandleRequestAsync(request, new ClientCapabilities(), CancellationToken.None).ConfigureAwait(false); // Assert Assert.True(invokedServer); Assert.True(mappedTextEdits); Assert.NotNull(response); }
public static Dictionary<string, object> ReaderDictionaryLoop(ref Utf8JsonReader json) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); string key = ""; object value = null; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.ValueSpan; switch (tokenType) { case JsonTokenType.PropertyName: key = json.GetString(); dictionary.Add(key, null); break; case JsonTokenType.True: case JsonTokenType.False: value = valueSpan[0] == 't'; if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.Number: json.TryGetDouble(out double valueDouble); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = valueDouble; } else { dictionary.Add(key, valueDouble); } break; case JsonTokenType.String: string valueString = json.GetString(); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = valueString; } else { dictionary.Add(key, valueString); } break; case JsonTokenType.Null: value = null; if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.StartObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); value = ReaderDictionaryLoop(ref json); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.StartArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); value = ReaderListLoop(ref json); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.EndObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'}' })); return dictionary; case JsonTokenType.None: case JsonTokenType.Comment: default: break; } } return dictionary; }
public async Task Should_fallback_to_json_even_if_no_accept_header() { var response = await this.httpClient.GetAsync("/negotiate"); Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString()); }
public static void MarshalStringToCS() { TestClass.string_res = null; Runtime.InvokeJS("call_test_method(\"InvokeString\", \"s\", [\"hello\"])"); Assert.AreEqual(TestClass.string_res, "hello"); }
/// <summary> /// Verifies that the 'File' menu works as expected. /// </summary> /// <param name="application">The application.</param> /// <param name="log">The log object.</param> /// <returns>The test result for the current test case.</returns> public TestResult VerifyFileMenu(Application application, Log log) { const string prefix = "File menu"; var result = new TestResult(); var assert = new Assert(result, log); try { var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage != null) { TabProxies.CloseProjectPageTab(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNull(projectPage, prefix + " - The project page was not closed."); MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - A new project was not created."); var fileCloseMenu = MenuProxies.GetFileCloseMenuItem(application, log); assert.IsTrue(fileCloseMenu.Enabled, prefix + " - File - Close menu is not enabled"); MenuProxies.CloseProjectViaFileCloseMenuItem(application, log); projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNull(projectPage, prefix + " - The project page was not closed."); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public static void GuidOfTest() { Assert.That(typeof(IStartMenuPinnedList).GUID, Is.EqualTo(IID_IStartMenuPinnedList)); }
/// <summary> /// Verifies that the 'View' menu works as expected. /// </summary> /// <param name="application">The application.</param> /// <param name="log">The log object.</param> /// <returns>The test result for the current test case.</returns> public TestResult VerifyViewMenu(Application application, Log log) { const string prefix = "View menu"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage != null) { log.Info(prefix, "Closing start page."); TabProxies.CloseStartPageTab(application, log); } // Make sure we don't close the welcome tab upon opening the project page WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage != null) { log.Info(prefix, "Closing project page."); TabProxies.CloseProjectPageTab(application, log); } // Open start page via view menu MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); startPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNotNull(startPage, prefix + " - Check start page exists after clicking start page menu item"); assert.IsTrue(startPage.IsSelected, prefix + " - Check start page is focussed after clicking start page menu item"); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public static void IsBlittableTest() { Assert.That(Marshal.SizeOf <IStartMenuPinnedList>(), Is.EqualTo(sizeof(IStartMenuPinnedList))); }
private static void VerifyAboutDialog(Application application, Log log, TestResult result) { const string prefix = "About dialog"; var assert = new Assert(result, log); log.Info(prefix, "Verifying content ..."); MenuProxies.OpenAboutDialogViaHelpAboutMenuItem(application, log); var dialog = DialogProxies.AboutWindow(application, log); if (dialog == null) { var message = "Failed to get dialog."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } // Check application name var applicationNameSearchCiteria = SearchCriteria .ByAutomationId(AboutAutomationIds.ProductName); var nameLabel = Retry.Times(() => (Label)dialog.Get(applicationNameSearchCiteria)); if (nameLabel == null) { var message = "Failed to get name label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var nameText = nameLabel.Text; assert.AreEqual(ProductInformation.ProductName, nameText, prefix + " - Product name"); // Check application version var applicationVersionSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.ProductVersion); var versionLabel = Retry.Times(() => (Label)dialog.Get(applicationVersionSearchCriteria)); if (versionLabel == null) { var message = "Failed to get version label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var versionText = versionLabel.Text; var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); var version = (versionAttribute[0] as AssemblyInformationalVersionAttribute).InformationalVersion; assert.AreEqual(version, versionText, prefix + " - Product version"); // Check company name var companyNameSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.CompanyName); var companyLabel = Retry.Times(() => (Label)dialog.Get(companyNameSearchCriteria)); if (companyLabel == null) { var message = "Failed to get company label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var companyText = companyLabel.Text; assert.AreEqual(CompanyInformation.CompanyName, companyText, prefix + " - Company name"); // Check copyright var copyrightSearchCriteria = SearchCriteria .ByAutomationId(AboutAutomationIds.Copyright); var copyrightLabel = Retry.Times(() => (Label)dialog.Get(copyrightSearchCriteria)); if (copyrightLabel == null) { var message = "Failed to get copyright label."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return; } var copyrightText = copyrightLabel.Text; assert.AreEqual( string.Format( CultureInfo.InvariantCulture, "Copyright {0} 2009 - {1}", CompanyInformation.CompanyName, DateTimeOffset.Now.Year), copyrightText, prefix + " - Copyright"); try { dialog.Close(); } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to close the dialog. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } }
public static void IsLayoutSequentialTest() { Assert.That(typeof(IStartMenuPinnedList).IsLayoutSequential, Is.True); }
public TestResult VerifyCloseOnProjectOpenCheckbox(Application application, Log log) { const string prefix = "Close welcome tab on project open"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { log.Info(prefix, "Opening start page."); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); } startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { var message = "Failed to get the start page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } try { if (!startPage.IsSelected) { log.Info(prefix, "Setting focus to start page."); startPage.Select(); } } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to select the start page tab. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } // Check 'keep open' flag WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); // New button var newProjectSearchCriteria = SearchCriteria .ByAutomationId(WelcomeViewAutomationIds.NewProject); var newProjectButton = (Button)startPage.Get(newProjectSearchCriteria); if (newProjectButton == null) { var message = "Failed to get the 'New Project' button."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } newProjectButton.Click(); // Check that the start page hasn't been closed var currentStartPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNotNull(currentStartPage, prefix + " - Start page does not exist after opening project"); assert.IsFalse(currentStartPage.IsSelected, prefix + " - Start page is selected after opening project"); var currentProjectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(currentProjectPage, prefix + " - Project page does not exist after opening project"); assert.IsTrue(currentProjectPage.IsSelected, prefix + " - Project page is not selected after opening project"); // Check that File - close has been enabled var fileCloseMenu = MenuProxies.GetFileCloseMenuItem(application, log); assert.IsTrue(fileCloseMenu.Enabled, prefix + " - File - Close menu is not enabled"); // HACK: It seems that the File menu stays open when we check the File - close menu item var fileMenu = MenuProxies.GetFileMenuItem(application, log); if (fileMenu == null) { var message = "Failed to get the file menu."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } if (fileMenu.IsFocussed) { fileMenu.Click(); } // Close the project via the close button on the tab page TabProxies.CloseProjectPageTab(application, log); WelcomePageControlProxies.CheckCloseWelcomePageOnProjectOpen(application, log); // New button newProjectButton.Click(); // Check that the start page has been closed currentStartPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNull(currentStartPage, prefix + " - Start page exists after opening project"); // Close the project via the close button on the tab page TabProxies.CloseProjectPageTab(application, log); WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public void EmptyWithIndexedSelector() { Assert.Equal(Enumerable.Empty <int>(), Enumerable.Empty <string>().Select((s, i) => s.Length + i)); }
private TestResult VerifyProjectInformation(Application application, Log log) { const string prefix = "Project information"; var result = new TestResult(); var assert = new Assert(result, log); try { // Start new project via File menu var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage == null) { MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - The project page was not opened."); // Set a name var name = "Project-Test-Name"; ProjectPageControlProxies.ProjectName(application, log, name); var storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The written project name does not match the stored project name."); // Set a summary var summary = "Project-Test-Summary"; ProjectPageControlProxies.ProjectSummary(application, log, summary); var storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.AreEqual(summary, storedSummary, prefix + " - The written project summary does not match the stored project summary."); // Set focus away from the text control so that the changes 'stick' by clicking somewhere, in this case the project tab item. projectPage.Click(); // Undo MenuProxies.UndoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The project name change was undone too early."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was not undone."); // Undo MenuProxies.UndoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.IsTrue(string.IsNullOrEmpty(storedName), prefix + " - The change to the project name was not undone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was not undone."); // Redo MenuProxies.RedoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The change to the project name was not redone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.IsTrue(string.IsNullOrEmpty(storedSummary), prefix + " - The change to the project summary was redone too early."); // Redo MenuProxies.RedoViaEditMenu(application, log); storedName = ProjectPageControlProxies.ProjectName(application, log); assert.AreEqual(name, storedName, prefix + " - The change to the project name was not redone."); storedSummary = ProjectPageControlProxies.ProjectSummary(application, log); assert.AreEqual(summary, storedSummary, prefix + " - The change to the project summary was not redone."); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public void Select_SourceIsArray_Count() { var source = new[] { 1, 2, 3, 4 }; Assert.Equal(source.Length, source.Select(i => i * 2).Count()); }
public LambdaTestCommand(IMethodInfo method, Assert.ThrowsDelegate lambda) : base(method, null, 0) { this.lambda = lambda; }
public void GetObjectIndexesWithPksOrderingTest() { foreach (IDataService dataService in DataServices) { //TODO: Fix OracleDataService error. if (dataService is OracleDataService) { continue; } // Arrange. SQLDataService ds = dataService as SQLDataService; SQLWhereLanguageDef langDef = SQLWhereLanguageDef.LanguageDef; List <DataObject> dataObjects = new List <DataObject>(); bool isMssql = dataService.GetType() == typeof(MSSQLDataService) || dataService.GetType().IsSubclassOf(typeof(MSSQLDataService)); // MSSQL в отличие от других хранилищ имеет свой формат сортировки гуидов. Для его поддержки приходится пользоваться специальным типом SqlGuid. List <SqlGuid> keysMssqlList = new List <SqlGuid>(); List <Guid> keysPostgresList = new List <Guid>(); // Создадим 1000 медведей. int objectsCount = 1000; for (int i = 0; i < objectsCount; i++) { // Для простоты анализа проблем с данными, если они возникнут, выдадим ненастоящие последовательные гуиды. byte[] bytes = new byte[16]; BitConverter.GetBytes(i).CopyTo(bytes, 0); var pk = new Guid(bytes); if (isMssql) { keysMssqlList.Add(pk); } else { keysPostgresList.Add(pk); } var createdBear = new Медведь { __PrimaryKey = pk, ЦветГлаз = "Косолапый Мишка " + i, Вес = i }; dataObjects.Add(createdBear); } DataObject[] dataObjectsForUpdate = dataObjects.ToArray(); ds.UpdateObjects(ref dataObjectsForUpdate); LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Медведь), Медведь.Views.МедведьL); Function findFunction = langDef.GetFunction(langDef.funcL, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <Медведь>(m => m.Вес)), objectsCount); if (isMssql) { keysMssqlList.Sort(); } else { keysPostgresList.Sort(); } // Act. IDictionary <int, string> result = ds.GetObjectIndexesWithPks(lcs, findFunction, null); // Assert. var values = result.Values.GetEnumerator(); var keys = result.Keys.GetEnumerator(); for (int i = 0; i < objectsCount; i++) { Assert.Equal(objectsCount, result.Count); values.MoveNext(); keys.MoveNext(); string key = isMssql ? ((Guid)keysMssqlList[i]).ToString("B") : keysPostgresList[i].ToString("B"); Assert.Equal(key, values.Current); Assert.Equal(i + 1, keys.Current); } } }