public void It_exposes_config_to_inject_custom_stylesheets() { SetUpHandler(c => { var assembly = typeof(SwaggerConfig).Assembly; c.EnableDiscoveryUrlSelector(); c.InjectStylesheet(assembly, "Swagger.Net.Dummy.SwaggerExtensions.testStyles1.css"); c.InjectStylesheet(assembly, "Swagger.Net.Dummy.SwaggerExtensions.testStyles2.css", "print"); }); var content = GetContentAsString(TEMP_URI.INDEX); StringAssert.Contains( "<link href='ext/Swagger-Net-Dummy-SwaggerExtensions-testStyles1-css' media='screen' rel='stylesheet' type='text/css' />\r\n" + "<link href='ext/Swagger-Net-Dummy-SwaggerExtensions-testStyles2-css' media='print' rel='stylesheet' type='text/css' />", content); content = GetContentAsString("http://tempuri.org/swagger/ui/ext/Swagger-Net-Dummy-SwaggerExtensions-testStyles1-css"); StringAssert.StartsWith("h1", content); content = GetContentAsString("http://tempuri.org/swagger/ui/ext/Swagger-Net-Dummy-SwaggerExtensions-testStyles2-css"); StringAssert.StartsWith("h2", content); }
public void TestGoToPageWhenUrlIsNotOnPageAndNavigationFailsThrowsAnException() { UriHelper.BaseUri = new Uri("http://localhost:2222"); var testPage = new Mock <IPage>(); var logger = new Mock <ILogger>(MockBehavior.Strict); logger.Setup(l => l.Debug("Navigating to URL: {0}", "http://localhost:2222/foo")); var browser = new Mock <BrowserBase>(MockBehavior.Strict, logger.Object); browser.Setup(b => b.GoTo(new Uri("http://localhost:2222/foo"))).Throws <InvalidOperationException>(); // ReSharper disable once ImplicitlyCapturedClosure ExceptionHelper.SetupForException <PageNavigationException>( () => browser.Object.GoToPage(typeof(TestPage), new Dictionary <string, string>()), ex => { StringAssert.StartsWith(ex.Message, "Could not navigate to URI: http://localhost:2222/foo."); browser.VerifyAll(); testPage.VerifyAll(); logger.VerifyAll(); }); }
public void MoveOutputFiles_MultipleFiles_AutoSaveWithoutEnsureUniqueFilenames_ThirdFileExists_ThirdOutputfileMustNotHaveAppendix() { var fileStub = MockRepository.GenerateStub <IFile>(); fileStub.Stub(x => x.Copy(Arg <string> .Is.Anything, Arg <string> .Is.Anything, Arg <bool> .Is.Anything)) .Repeat.Once(); fileStub.Stub(x => x.Exists(Arg <string> .Is.Anything)).Return(false).Repeat.Twice(); //Simulate existing file in third request for unique filename fileStub.Stub(x => x.Exists(Arg <string> .Is.Anything)).Return(true).Repeat.Once(); fileStub.Stub(x => x.Exists(Arg <string> .Is.Anything)).Return(false); _th.GenerateGsJob(PSfiles.ThreePDFCreatorTestpages, OutputFormat.Pdf); var outputFileMover = BuildAutosaveOutputFileMover(fileStub); _th.Job.Profile.AutoSave.Enabled = true; _th.Job.Profile.AutoSave.EnsureUniqueFilenames = false; _th.Job.TempOutputFiles = _multipleTempOutputFiles; var filenameTemplate = _th.Job.OutputFilenameTemplate; //Save it, because it can change in MoveOutputFiles outputFileMover.MoveOutputFiles(_th.Job); fileStub.AssertWasCalled(x => x.Copy("ignore", "ignore2", true), options => options.IgnoreArguments().Repeat.Times(3)); //Three times, once for each file fileStub.AssertWasCalled(x => x.Delete("ignore"), options => options.IgnoreArguments().Repeat.Times(3)); //Three times, once for each file var templateWithoutExtension = RemoveExtension(filenameTemplate); StringAssert.StartsWith(templateWithoutExtension, _th.Job.OutputFiles[0], "First outputfile is not based on template from job."); StringAssert.EndsWith("1.png", _th.Job.OutputFiles[0], "Failure in file appendix."); StringAssert.StartsWith(templateWithoutExtension, _th.Job.OutputFiles[1], "Second outputfile is not based on template from job."); StringAssert.EndsWith("2.png", _th.Job.OutputFiles[1], "Failure in file appendix."); StringAssert.StartsWith(templateWithoutExtension, _th.Job.OutputFiles[2], "Third outputfile is not based on template from job."); StringAssert.EndsWith("3.png", _th.Job.OutputFiles[2], "Failure in file appendix."); }
public void ShouldInviteToOpenAccount() { // When I proceed to "Bank Manager Login" ngDriver.FindElement(NgBy.ButtonText("Bank Manager Login")).Click(); // And I proceed to "Add Customer" ngDriver.FindElement(NgBy.PartialButtonText("Add Customer")).Click(); // And I fill new Customer data IWebElement ng_first_name = ngDriver.FindElement(NgBy.Model("fName")); ngDriver.Highlight(ng_first_name, highlight_timeout); StringAssert.IsMatch("First Name", ng_first_name.GetAttribute("placeholder")); ng_first_name.SendKeys("John"); IWebElement ng_last_name = ngDriver.FindElement(NgBy.Model("lName")); ngDriver.Highlight(ng_last_name, highlight_timeout); StringAssert.IsMatch("Last Name", ng_last_name.GetAttribute("placeholder")); ng_last_name.SendKeys("Doe"); IWebElement ng_post_code = ngDriver.FindElement(NgBy.Model("postCd")); ngDriver.Highlight(ng_post_code, highlight_timeout); StringAssert.IsMatch("Post Code", ng_post_code.GetAttribute("placeholder")); ng_post_code.SendKeys("11011"); // NOTE: there are two 'Add Customer' buttons on this form NgWebElement ng_add_customer_button = ngDriver.FindElements(NgBy.PartialButtonText("Add Customer"))[1]; actions.MoveToElement(ng_add_customer_button.WrappedElement).Build().Perform(); ngDriver.Highlight(ng_add_customer_button, highlight_timeout); ng_add_customer_button.Submit(); // confirm string alert_text = null; try { alert = ngDriver.WrappedDriver.SwitchTo().Alert(); alert_text = alert.Text; StringAssert.StartsWith("Customer added successfully with customer id :", alert_text); alert.Accept(); } catch (NoAlertPresentException ex) { // Alert not present verificationErrors.Append(ex.StackTrace); } catch (WebDriverException ex) { // Alert not handled by PhantomJS verificationErrors.Append(ex.StackTrace); } int customer_id = 0; int.TryParse(alert_text.FindMatch(@"(?<customer_id>\d+)$"), out customer_id); Assert.AreNotEqual(0, customer_id); // And I switch to "Home" screen ngDriver.FindElement(NgBy.ButtonText("Home")).Click(); // And I proceed to "Customer Login" ngDriver.FindElement(NgBy.ButtonText("Customer Login")).Click(); // And I login as new customer "John Doe" ReadOnlyCollection <NgWebElement> ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); int customer_count = ng_customers.Count; NgWebElement ng_new_customer = ng_customers.First(cust => Regex.IsMatch(cust.Text, "John Doe")); Assert.IsNotNull(ng_new_customer); actions.MoveToElement(ng_new_customer.WrappedElement).Build().Perform(); ngDriver.Highlight(ng_new_customer, highlight_timeout); ng_new_customer.Click(); NgWebElement ng_login_button = ngDriver.FindElement(NgBy.ButtonText("Login")); Assert.IsTrue(ng_login_button.Displayed && ng_login_button.Enabled); ngDriver.Highlight(ng_login_button, highlight_timeout); ng_login_button.Click(); // Then I am greeted as "John Doe" NgWebElement ng_user = ngDriver.FindElement(NgBy.Binding("user")); StringAssert.Contains("John", ng_user.Text); StringAssert.Contains("Doe", ng_user.Text); // And I am invited to open an account Object noAccount = ng_user.Evaluate("noAccount"); Assert.IsTrue(Boolean.Parse(noAccount.ToString())); Boolean hasAccounts = !(Boolean.Parse(noAccount.ToString())); Console.Error.WriteLine("Has accounts: " + hasAccounts); // IWebElement invitationMessage = driver.FindElement(By.CssSelector("span[ng-show='noAccount']")); IWebElement invitationMessage = ng_user.FindElement(By.XPath("..")).FindElement(By.XPath("..")).FindElement(By.CssSelector("span[ng-show='noAccount']")); Assert.IsTrue(invitationMessage.Displayed); ngDriver.Highlight(invitationMessage); StringAssert.Contains("Please open an account with us", invitationMessage.Text); Console.Error.WriteLine(invitationMessage.Text); // And I have no accounts NgWebElement accountNo = ngDriver.FindElement(NgBy.Binding("accountNo")); Assert.IsFalse(accountNo.Displayed); ReadOnlyCollection <NgWebElement> ng_accounts = ngDriver.FindElements(NgBy.Repeater("account for account in Accounts")); Assert.AreEqual(0, ng_accounts.Count); }
/// <summary> /// Tests using the "Remove Precursor Peaks" button. /// This test removes peaks from the "614" precursor of the "SIV..." peptide. /// It removes peaks from the replicates "S_1" and "S_3". /// </summary> private void TestRemovePrecursorPeaks() { RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("RowActionsTest.sky"))); RunUI(() => SkylineWindow.ShowDocumentGrid(true)); var documentGrid = FindOpenForm <DocumentGridForm>(); RunUI(() => documentGrid.DataboundGridControl.ChooseView(new ViewName(PersistedViews.MainGroup.Id, "TransitionAreas"))); WaitForConditionUI(() => documentGrid.IsComplete); var peptideDocNode = SkylineWindow.Document.Peptides.Skip(1).First(); StringAssert.StartsWith(peptideDocNode.Peptide.Sequence, "SIV"); Assert.AreEqual(2, peptideDocNode.TransitionGroupCount); foreach (var precursor in peptideDocNode.TransitionGroups) { Assert.AreEqual(3, precursor.Results.Count); for (int iReplicate = 0; iReplicate < 3; iReplicate++) { Assert.AreEqual(1, precursor.Results[iReplicate].Count); var precursorChromInfo = precursor.Results[iReplicate].First(); Assert.IsNotNull(precursorChromInfo.Area); } } RunUI(() => { var colPeptide = documentGrid.FindColumn(PropertyPath.Parse("Precursor.Peptide")); Assert.IsNotNull(colPeptide); var colPrecursorMz = documentGrid.FindColumn(PropertyPath.Parse("Precursor.Mz")); Assert.IsNotNull(colPrecursorMz); var colReplicate = documentGrid.FindColumn(PropertyPath.Parse("Results!*.Value.PrecursorResult.PeptideResult.ResultFile.Replicate")); Assert.IsNotNull(colReplicate); for (int iRow = 0; iRow < documentGrid.RowCount; iRow++) { var row = documentGrid.DataGridView.Rows[iRow]; var peptide = (Skyline.Model.Databinding.Entities.Peptide)row.Cells[colPeptide.Index].Value; var precursorMz = (double)row.Cells[colPrecursorMz.Index].Value; var replicate = (Replicate)row.Cells[colReplicate.Index].Value; if (peptide.Sequence.StartsWith("SIV") && Math.Abs(precursorMz - 614) < 1 && (replicate.Name == "S_1" || replicate.Name == "S_3")) { row.Selected = true; } } }); var menuItem = GetDropDownItems(documentGrid.NavBar.ActionsButton) .FirstOrDefault(item => item.Text == RemovePeaksAction.Precursors.GetMenuItemText(SrmDocument.DOCUMENT_TYPE.proteomic)); Assert.IsNotNull(menuItem); var confirmDialog = ShowDialog <AlertDlg>(menuItem.PerformClick); string expectedMessage = string.Format( Resources.RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from_one_precursor_, 2); Assert.AreEqual(expectedMessage, confirmDialog.Message); OkDialog(confirmDialog, confirmDialog.ClickOk); peptideDocNode = SkylineWindow.Document.Peptides.Skip(1).First(); Assert.AreEqual(2, peptideDocNode.TransitionGroupCount); for (int iPrecursor = 0; iPrecursor < 2; iPrecursor++) { var precursor = (TransitionGroupDocNode)peptideDocNode.Children[iPrecursor]; Assert.AreEqual(3, precursor.Results.Count); for (int iReplicate = 0; iReplicate < 3; iReplicate++) { Assert.AreEqual(1, precursor.Results[iReplicate].Count); var precursorChromInfo = precursor.Results[iReplicate].First(); bool shouldHaveValue = iPrecursor == 0 || iReplicate == 1; Assert.AreEqual(shouldHaveValue, precursorChromInfo.Area.HasValue); } } var alertDlg = ShowDialog <AlertDlg>(SkylineWindow.NewDocument); OkDialog(alertDlg, alertDlg.ClickNo); }
public void TzdbVersion() { var source = TzdbDateTimeZoneSource.Default; StringAssert.StartsWith("201", source.TzdbVersion); }
public static void ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); }
public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter) { StringAssert.StartsWith(expectedDelimiter, actual); StringAssert.EndsWith(expectedDelimiter, actual); }
public static void should_start_with(this string actual, string start) { StringAssert.StartsWith(start, actual); }
public void GetRandom_String_with_prefix_should_work() { string randomValue = GetRandom.String("testPrefix"); StringAssert.StartsWith(randomValue, "testPrefix"); }
public void Test_Help() { StringAssert.StartsWith(ExecuteAndReturnOutput(PathToConsoleApplication, "-h").ToLower(), "usage"); StringAssert.StartsWith(ExecuteAndReturnOutput(PathToConsoleApplication, "--help").ToLower(), "usage"); }
public void TestMethod1() { StringAssert.StartsWith("ABC012", Ctrls.Transform("XYZ789", true)); }
void declencherAnalyseProfil(String jobName, String[] erreursAttendues, String[] tagsAttendus, Boolean bWithWarns = false) { StreamWriter streamWriter = null; DataControlConfig control = configLoader(jobName); String traceFile = control.traceFile; String profileFile = control.profileFile; String dataFile = control.dataFile; Action <Exception, String> eh = (ex, str) => { Console.WriteLine(ex.GetType().Name + " while trying to use trace file: " + traceFile + ". Complementary message: " + str); throw ex; }; try { streamWriter = new StreamWriter(traceFile); } catch (IOException e) { eh(e, "Mauvaise syntaxe de nom de fichier"); } catch (UnauthorizedAccessException e) { eh(e, "Droits d'accès à corriger"); } catch (System.Security.SecurityException e) { eh(e, "Droits d'accès à corriger"); } RngProfileController rpc = new RngProfileController(); rpc.setTracesWriter(streamWriter); rpc.controlProfileFile(profileFile); StringCollection erreurs = rpc.getErrorsList(); { streamWriter.WriteLine("-----------------"); streamWriter.WriteLine("Liste des erreurs."); if (erreurs != null && erreurs.Count != 0) { foreach (String str in erreurs) { streamWriter.WriteLine(str); } } streamWriter.WriteLine("-----------------"); } streamWriter.Flush(); if (erreursAttendues != null) { /* * int erreur = 0; * if (erreurs != null && erreurs.Count != 0) { * foreach (String str in erreurs) { * if (erreursAttendues.Length > erreur) * StringAssert.StartsWith(str, erreursAttendues[erreur], "Comparaison des erreurs"); * erreur++; * } * } * * Assert.AreEqual(erreursAttendues.Length, erreurs.Count, "Le nombre d'erreurs attendues et obtenues diffère"); * */ StringCollection errors = rpc.getErrorsList(); int erreur = 0; if (errors != null && errors.Count != 0) { foreach (String str in errors) { if (bWithWarns) { if (erreursAttendues.Length > erreur) { StringAssert.StartsWith(str, erreursAttendues[erreur], "Comparaison des erreurs"); } erreur++; } else { if (str.StartsWith("(--) ") == false) { if (erreursAttendues.Length > erreur) { StringAssert.StartsWith(str, erreursAttendues[erreur], "Comparaison des erreurs"); } erreur++; } } } } Assert.AreEqual(erreursAttendues.Length, erreur, "Le nombre d'erreurs attendues et obtenues diffère"); } StringCollection tags = rpc.getExpectedTagsListList(); { streamWriter.WriteLine("-----------------"); streamWriter.WriteLine("Liste des tags."); if (tags != null && tags.Count != 0) { foreach (String str in tags) { streamWriter.WriteLine(str); } } streamWriter.WriteLine("-----------------"); } streamWriter.Flush(); if (erreursAttendues != null) { int tag = 0; if (tags != null && tags.Count != 0) { foreach (String str in tags) { if (tagsAttendus.Length > tag) { StringAssert.StartsWith(str, tagsAttendus[tag], "Comparaison des tags"); } tag++; } } Assert.AreEqual(tagsAttendus.Length, tags.Count, "Le nombre de tags attendus et obtenus diffère"); } streamWriter.Close(); }
/* * * */ public void H04_TestContenuFichierDonnees() { String[] tagsListeClesAttendus = { "#Comment", "#TransferName", "#CustodialHistory", "#ContentDescription.Description", "#OriginatingAgency.BusinessType", "#OriginatingAgency.Description", "#OriginatingAgency.LegalClassification", "#OriginatingAgency.Name", "#OriginatingAgency.Identification", "#KeywordContent[{KW_COMMUNE}]", "#KeywordContent[{KW_EVT}[#1]]", "#ContainsName[ENRSON[#1]]", "#CustodialHistory[ENRSON[#1]]", "#ContentDescription.Description[ENRSON[#1]]", "#KeywordContent[ENRSON[#1]{KW1}]", "#ContainsName[ENRSON[#1]//SAMPLES[#1]]", "#ContentDescription.Description[ENRSON[#1]//SAMPLES[#1]]", "#KeywordContent[ENRSON[#1]//SAMPLES[#1]{KW2}[#1]]", "#ContainsName[ENRSON[#1]//SAMPLES[#1]//DESCRIPTION]", "#ContentDescription.Description[ENRSON[#1]//SAMPLES[#1]//DESCRIPTION]", "#KeywordContent[ENRSON[#1]//SAMPLES[#1]//DESCRIPTION{KW3}]", "#ContainsName[ENRSON[#1]//SAMPLES[#1]//ANNEXE]", "#ContentDescription.Description[ENRSON[#1]//SAMPLES[#1]//ANNEXE]", "#KeywordContent[ENRSON[#1]//SAMPLES[#1]//ANNEXE{KW4}]", }; String[] tagsListeDocumentsAttendus = { "ENRSON[#1]{PDF}", "ENRSON[#1]{MP3}", "ENRSON[#1]{WAV}", "ENRSON[#1]//SAMPLES[#1]", "ENRSON[#1]//SAMPLES[#1]//DESCRIPTION", "ENRSON[#1]//SAMPLES[#1]//ANNEXE", }; DataControlConfig control = configLoader("tags_profil_complet_donnees"); StreamWriter streamWriter = null; Action <Exception, String> eh = (ex, str) => { Console.WriteLine(ex.GetType().Name + " while trying to use trace file: " + control.traceFile + ". Complementary message: " + str); throw ex; }; try { streamWriter = new StreamWriter(control.traceFile); } catch (IOException e) { eh(e, "Mauvaise syntaxe de nom de fichier"); } catch (UnauthorizedAccessException e) { eh(e, "Droits d'accès à corriger"); } catch (System.Security.SecurityException e) { eh(e, "Droits d'accès à corriger"); } CsvArchiveDocuments ad = new CsvArchiveDocuments(); ad.setTracesWriter(streamWriter); ad.loadFile(control.dataFile); StringCollection adErrors = ad.getErrorsList(); streamWriter.WriteLine("\nErreurs dans la lecture du fichier de données"); foreach (String str in adErrors) { streamWriter.WriteLine(str); } streamWriter.Flush(); Assert.AreEqual(0, adErrors.Count, "Aucune erreur n'était attendue"); StringCollection listForKeys = ad.getTagsListForKeys(); StringCollection listForDocuments = ad.getTagsListForDocuments(); int key = 0; if (listForKeys != null && listForKeys.Count != 0) { streamWriter.WriteLine("\nListe des clés lues"); foreach (String str in listForKeys) { streamWriter.WriteLine(str); } streamWriter.Flush(); foreach (String str in listForKeys) { if (tagsListeClesAttendus.Length > key) { StringAssert.StartsWith(str, tagsListeClesAttendus[key], "Comparaison des tags de clés"); } key++; } } Assert.AreEqual(tagsListeClesAttendus.Length, listForKeys.Count, "Le nombre de clés attendues et obtenues diffère"); key = 0; if (listForDocuments != null && listForDocuments.Count != 0) { streamWriter.WriteLine("\nListe des documents lus"); foreach (String str in listForDocuments) { streamWriter.WriteLine(str); } streamWriter.Flush(); foreach (String str in listForDocuments) { if (tagsListeClesAttendus.Length > key) { StringAssert.StartsWith(str, tagsListeDocumentsAttendus[key], "Comparaison des tags de documents"); } key++; } } Assert.AreEqual(tagsListeDocumentsAttendus.Length, listForDocuments.Count, "Le nombre de documents attendus et obtenus diffère"); streamWriter.Flush(); streamWriter.Close(); }
public void TestFullAgentId_3() { Eyes eyes = new Eyes(new ServerConnectorFactory()); StringAssert.StartsWith("Eyes.Selenium.DotNet/", eyes.FullAgentId); }
public void Test_CSV_Attachment(string separator, bool overrideHeaders) { string filename = Path.Combine(LoadDirectory.ForLoading.FullName, "bob.csv"); var sw = new StreamWriter(filename); sw.WriteLine("name,name2"); sw.WriteLine("Bob,Munchousain"); sw.WriteLine("Franky,Hollyw9ood"); sw.Flush(); sw.Close(); sw.Dispose(); string filename2 = Path.Combine(LoadDirectory.ForLoading.FullName, "bob2.csv"); var sw2 = new StreamWriter(filename2); sw2.WriteLine("name,name2"); sw2.WriteLine("Manny2,Ok"); sw2.Flush(); sw2.Close(); sw2.Dispose(); var attacher = new AnySeparatorFileAttacher(); attacher.Initialize(LoadDirectory, _database); attacher.Separator = separator; attacher.FilePattern = "bob*"; attacher.TableName = "Bob"; if (overrideHeaders) { attacher.ForceHeaders = "name,name2"; attacher.ForceHeadersReplacesFirstLineInFile = true; } //Case when you are using the wrong separator if (separator == "|") { var ex = Assert.Throws <FlatFileLoadException>(() => attacher.Attach(new ThrowImmediatelyDataLoadJob(), new GracefulCancellationToken())); Assert.IsNotNull(ex.InnerException); StringAssert.StartsWith("Your separator does not appear in the headers line of your file (bob.csv) but the separator ',' does", ex.InnerException.Message); return; } //other cases (i.e. correct separator) attacher.Attach(new ThrowImmediatelyDataLoadJob(), new GracefulCancellationToken()); var table = _database.ExpectTable("Bob"); Assert.IsTrue(table.Exists()); table.DiscoverColumn("name"); table.DiscoverColumn("name2"); using (var con = _database.Server.GetConnection()) { con.Open(); var r = _database.Server.GetCommand("Select * from Bob", con).ExecuteReader(); Assert.IsTrue(r.Read()); Assert.AreEqual("Bob", r["name"]); Assert.AreEqual("Munchousain", r["name2"]); Assert.IsTrue(r.Read()); Assert.AreEqual("Franky", r["name"]); Assert.AreEqual("Hollyw9ood", r["name2"]); Assert.IsTrue(r.Read()); Assert.AreEqual("Manny2", r["name"]); Assert.AreEqual("Ok", r["name2"]); } attacher.LoadCompletedSoDispose(ExitCodeType.Success, new ThrowImmediatelyDataLoadEventListener()); File.Delete(filename); }
public void FailoverThenReconnect() { var parallelOptions = new ParallelOptions { TaskScheduler = new ThreadPerTaskScheduler(), MaxDegreeOfParallelism = 100 }; var policy = new ConstantReconnectionPolicy(500); var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false); using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build()) { var session = cluster.Connect(); // Check query to host distribution before killing nodes var queriedHosts = new List <string>(); DateTime futureDateTime = DateTime.Now.AddSeconds(120); while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime) { var rs = session.Execute("SELECT * FROM system.local"); queriedHosts.Add(rs.Info.QueriedHost.ToString()); Thread.Sleep(50); } Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!"); // Create list of actions Action selectAction = () => { var rs = session.Execute("SELECT * FROM system.local"); Assert.Greater(rs.Count(), 0); }; var actions = new List <Action>(); for (var i = 0; i < 100; i++) { actions.Add(selectAction); //Check that the control connection is using first host StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString()); //Kill some nodes //Including the one used by the control connection actions.Insert(20, () => nonShareableTestCluster.Stop(1)); actions.Insert(20, () => nonShareableTestCluster.Stop(2)); actions.Insert(80, () => nonShareableTestCluster.Stop(3)); //Execute in parallel more than 100 actions Parallel.Invoke(parallelOptions, actions.ToArray()); //Wait for the nodes to be killed TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20); actions = new List <Action>(); for (var j = 0; j < 100; j++) { actions.Add(selectAction); } //Check that the control connection is using first host //bring back some nodes actions.Insert(3, () => nonShareableTestCluster.Start(3)); actions.Insert(50, () => nonShareableTestCluster.Start(2)); actions.Insert(50, () => nonShareableTestCluster.Start(1)); //Execute in parallel more than 100 actions Trace.TraceInformation("Start invoking with restart nodes"); Parallel.Invoke(parallelOptions, actions.ToArray()); //Wait for the nodes to be restarted TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30); TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30); TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30); queriedHosts.Clear(); // keep querying hosts until they are all queried, or time runs out futureDateTime = DateTime.Now.AddSeconds(120); while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime) { var rs = session.Execute("SELECT * FROM system.local"); queriedHosts.Add(rs.Info.QueriedHost.ToString()); Thread.Sleep(50); } //Check that one of the restarted nodes were queried Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, queriedHosts); //Check that the control connection is still using last host StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString()); } } }
public void Calculate_ValidPathOneCalculation_LogsMessages() { // Setup var hydraulicBoundaryDatabase = new HydraulicBoundaryDatabase { FilePath = validFilePath, HydraulicLocationConfigurationSettings = { CanUsePreprocessor = true, UsePreprocessor = true, PreprocessorDirectory = validPreprocessorDirectory } }; HydraulicBoundaryDatabaseTestHelper.SetHydraulicBoundaryLocationConfigurationSettings(hydraulicBoundaryDatabase); const string calculationIdentifier = "1/100"; const string duneLocationName = "duneLocationName"; var mocks = new MockRepository(); var calculatorFactory = mocks.StrictMock <IHydraRingCalculatorFactory>(); calculatorFactory.Expect(cf => cf.CreateDunesBoundaryConditionsCalculator(Arg <HydraRingCalculationSettings> .Is.NotNull)) .WhenCalled(invocation => { HydraRingCalculationSettingsTestHelper.AssertHydraRingCalculationSettings( HydraulicBoundaryCalculationSettingsFactory.CreateSettings(hydraulicBoundaryDatabase), (HydraRingCalculationSettings)invocation.Arguments[0]); }) .Return(new TestDunesBoundaryConditionsCalculator()); var assessmentSection = mocks.Stub <IAssessmentSection>(); assessmentSection.Stub(a => a.HydraulicBoundaryDatabase) .Return(hydraulicBoundaryDatabase); mocks.ReplayAll(); using (var viewParent = new TestViewParentForm()) using (new HydraRingCalculatorFactoryConfig(calculatorFactory)) { var guiService = new DuneLocationCalculationGuiService(viewParent); // Call void Call() => guiService.Calculate(new[] { new DuneLocationCalculation(new TestDuneLocation(duneLocationName)) }, assessmentSection, 0.01, calculationIdentifier); // Assert TestHelper.AssertLogMessages(Call, messages => { string[] msgs = messages.ToArray(); Assert.AreEqual(8, msgs.Length); Assert.AreEqual($"Hydraulische belastingen berekenen voor locatie '{duneLocationName}' ({calculationIdentifier}) is gestart.", msgs[0]); CalculationServiceTestHelper.AssertValidationStartMessage(msgs[1]); CalculationServiceTestHelper.AssertValidationEndMessage(msgs[2]); CalculationServiceTestHelper.AssertCalculationStartMessage(msgs[3]); Assert.AreEqual($"Hydraulische belastingenberekening voor locatie '{duneLocationName}' ({calculationIdentifier}) is niet geconvergeerd.", msgs[4]); StringAssert.StartsWith("Hydraulische belastingenberekening is uitgevoerd op de tijdelijke locatie", msgs[5]); CalculationServiceTestHelper.AssertCalculationEndMessage(msgs[6]); Assert.AreEqual($"Hydraulische belastingen berekenen voor locatie '{duneLocationName}' ({calculationIdentifier}) is gelukt.", msgs[7]); }); } mocks.VerifyAll(); }
public void CreateTableOperation() { var operation = new CreateTableOperation { Name = "People", Columns = { new AddColumnOperation { Name = "Id", Table = "People", ClrType = typeof(int), IsNullable = false, [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.None, }, new AddColumnOperation { Name = "Id_Identity", Table = "People", ClrType = typeof(int), IsNullable = false, [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.IdentityColumn, }, new AddColumnOperation { Name = "Id_Sequence", Table = "People", ClrType = typeof(int), IsNullable = false, [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.SequenceTrigger, }, new AddColumnOperation { Name = "EmployerId", Table = "People", ClrType = typeof(int), IsNullable = true }, new AddColumnOperation { Name = "SSN", Table = "People", ClrType = typeof(string), ColumnType = "char(11)", IsNullable = true } }, PrimaryKey = new AddPrimaryKeyOperation { Columns = new[] { "Id" } }, UniqueConstraints = { new AddUniqueConstraintOperation { Columns = new[]{ "SSN" } } }, ForeignKeys = { new AddForeignKeyOperation { Columns = new[] { "EmployerId" }, PrincipalTable = "Companies", PrincipalColumns = new[]{ "Id" } } } }; var expectedCreateTable = @"CREATE TABLE ""People"" ( ""Id"" INTEGER NOT NULL, ""Id_Identity"" INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, ""Id_Sequence"" INTEGER NOT NULL, ""EmployerId"" INTEGER, ""SSN"" char(11), PRIMARY KEY (""Id""), UNIQUE (""SSN""), FOREIGN KEY (""EmployerId"") REFERENCES ""Companies"" (""Id"") )"; var batch = Generate(new[] { operation }); Assert.AreEqual(3, batch.Count()); StringAssert.StartsWith(expectedCreateTable, batch[0].CommandText); StringAssert.Contains("rdb$generator_name = ", batch[1].CommandText); StringAssert.StartsWith("CREATE TRIGGER ", batch[2].CommandText); }
public void StartsWith() { StringAssert.StartsWith("Hello world!", "Hello"); }
public void HaveFullNameStartingWithFirstName() { StringAssert.StartsWith(sut.FullName, "Sarah"); }
public async Task TestComputeRunAsyncContinuation() { await Ignite.GetCompute().RunAsync(new ComputeAction()); StringAssert.StartsWith("Thread-", TestUtilsJni.GetJavaThreadName()); }
public void StartsWith() { StringAssert.StartsWith("abc", "abcdef"); StringAssert.StartsWith("abc", "abc"); }
public async Task TestComputeExecuteAsyncContinuation() { await Ignite.GetCompute().ExecuteAsync(new StringLengthEmptyTask(), "abc"); StringAssert.StartsWith("Thread-", TestUtilsJni.GetJavaThreadName()); }
public void VersionId() { var source = TzdbDateTimeZoneSource.Default; StringAssert.StartsWith("TZDB: " + source.TzdbVersion, source.VersionId); }
public void ShouldDisplayErrorMessageForFailingStep() { Assert.That(_results.NumberOfFailingScenarios, Is.EqualTo(1)); StringAssert.StartsWith("Should.Core.Exceptions.EqualException", _results[0].ScenarioResults[0].Message); }
public void ShouldAddCustomer() { // When I proceed to "Bank Manager Login" ngDriver.FindElement(NgBy.ButtonText("Bank Manager Login")).Click(); // And I proceed to "Add Customer" ngDriver.FindElement(NgBy.PartialButtonText("Add Customer")).Click(); // And I fill new Customer data IWebElement ng_first_name = ngDriver.FindElement(NgBy.Model("fName")); ngDriver.Highlight(ng_first_name, highlight_timeout); StringAssert.IsMatch("First Name", ng_first_name.GetAttribute("placeholder")); ng_first_name.SendKeys("John"); IWebElement ng_last_name = ngDriver.FindElement(NgBy.Model("lName")); ngDriver.Highlight(ng_last_name, highlight_timeout); StringAssert.IsMatch("Last Name", ng_last_name.GetAttribute("placeholder")); ng_last_name.SendKeys("Doe"); IWebElement ng_post_code = ngDriver.FindElement(NgBy.Model("postCd")); ngDriver.Highlight(ng_post_code, highlight_timeout); StringAssert.IsMatch("Post Code", ng_post_code.GetAttribute("placeholder")); ng_post_code.SendKeys("11011"); // NOTE: there are two 'Add Customer' buttons on this form NgWebElement ng_add_customer_button = ngDriver.FindElements(NgBy.PartialButtonText("Add Customer"))[1]; actions.MoveToElement(ng_add_customer_button.WrappedElement).Build().Perform(); ngDriver.Highlight(ng_add_customer_button, highlight_timeout); ng_add_customer_button.Submit(); // confirm string alert_text = null; try { alert = ngDriver.WrappedDriver.SwitchTo().Alert(); alert_text = alert.Text; StringAssert.StartsWith("Customer added successfully with customer id :", alert_text); alert.Accept(); } catch (NoAlertPresentException ex) { // Alert not present verificationErrors.Append(ex.StackTrace); } catch (WebDriverException ex) { // Alert not handled by PhantomJS verificationErrors.Append(ex.StackTrace); } int customer_id = 0; int.TryParse(alert_text.FindMatch(@"(?<customer_id>\d+)$"), out customer_id); Assert.AreNotEqual(0, customer_id); // And I switch to "Customers" screen ngDriver.FindElement(NgBy.PartialButtonText("Customers")).Click(); // discover newly added customer ReadOnlyCollection <NgWebElement> ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); int customer_count = ng_customers.Count; NgWebElement ng_new_customer = ng_customers.First(cust => Regex.IsMatch(cust.Text, "John Doe")); Assert.IsNotNull(ng_new_customer); actions.MoveToElement(ng_new_customer.WrappedElement).Build().Perform(); ngDriver.Highlight(ng_new_customer, highlight_timeout); // confirm searching for the customer name ngDriver.FindElement(NgBy.Model("searchCustomer")).SendKeys("John"); ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); Assert.AreEqual(1, ng_customers.Count); // show all customers again ngDriver.FindElement(NgBy.Model("searchCustomer")).Clear(); Thread.Sleep(500); wait.Until(ExpectedConditions.ElementIsVisible(NgBy.Repeater("cust in Customers"))); // discover newly added customer again ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); ng_new_customer = ng_customers.First(cust => Regex.IsMatch(cust.Text, "John Doe")); // delete new customer NgWebElement ng_delete_button = ng_new_customer.FindElement(NgBy.ButtonText("Delete")); Assert.IsNotNull(ng_delete_button); actions.MoveToElement(ng_delete_button.WrappedElement).Build().Perform(); ngDriver.Highlight(ng_delete_button, highlight_timeout); // in slow motion actions.MoveToElement(ng_delete_button.WrappedElement).ClickAndHold().Build().Perform(); Thread.Sleep(1000); actions.Release(); // sometimes actions do not work - for example in this test ng_delete_button.Click(); // wait for customer list to reload Thread.Sleep(1000); wait.Until(ExpectedConditions.ElementIsVisible(NgBy.Repeater("cust in Customers"))); // count the remaining customers ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); int new_customer_count = ng_customers.Count; // conrirm the customer count changed Assert.IsTrue(customer_count - 1 == new_customer_count); }
public void ParseThrowsFormatExceptionForInvalidInput(string range) { var ex = Assert.Throws <FormatException>(() => DateTimeRange.Parse(range)); StringAssert.StartsWith("Unable to parse the DateTimeRange value.", ex.Message); }
public void ShouldOpenAccount() { // switch to "Add Customer" screen ngDriver.FindElement(NgBy.ButtonText("Bank Manager Login")).Click(); ngDriver.FindElement(NgBy.PartialButtonText("Open Account")).Click(); // fill new Account data NgWebElement ng_customer_select = ngDriver.FindElement(NgBy.Model("custId")); StringAssert.IsMatch("userSelect", ng_customer_select.GetAttribute("id")); ReadOnlyCollection <NgWebElement> ng_customers = ng_customer_select.FindElements(NgBy.Repeater("cust in Customers")); // select customer to log in NgWebElement account_customer = ng_customers.First(cust => Regex.IsMatch(cust.Text, "Harry Potter*")); Assert.IsNotNull(account_customer); account_customer.Click(); NgWebElement ng_currencies_select = ngDriver.FindElement(NgBy.Model("currency")); // use core Selenium SelectElement currencies_select = new SelectElement(ng_currencies_select.WrappedElement); IList <IWebElement> account_currencies = currencies_select.Options; IWebElement account_currency = account_currencies.First(cust => Regex.IsMatch(cust.Text, "Dollar")); Assert.IsNotNull(account_currency); currencies_select.SelectByText("Dollar"); // add the account var submit_button = ngDriver.FindElement(By.XPath("/html/body//form/button[@type='submit']")); StringAssert.IsMatch("Process", submit_button.Text); submit_button.Click(); try { alert = driver.SwitchTo().Alert(); alert_text = alert.Text; StringAssert.StartsWith("Account created successfully with account Number", alert_text); alert.Accept(); } catch (NoAlertPresentException ex) { // Alert not present verificationErrors.Append(ex.StackTrace); } catch (WebDriverException ex) { // Alert not handled by PhantomJS verificationErrors.Append(ex.StackTrace); } // Confirm account added for customer Assert.IsEmpty(verificationErrors.ToString()); // switch to "Customers" screen ngDriver.FindElement(NgBy.PartialButtonText("Customers")).Click(); // get customers ng_customers = ngDriver.FindElements(NgBy.Repeater("cust in Customers")); // discover customer NgWebElement ng_customer = ng_customers.First(cust => Regex.IsMatch(cust.Text, "Harry Potter")); Assert.IsNotNull(ng_customer); // extract the account id from the alert message string account_id = alert_text.FindMatch(@"(?<account_id>\d+)$"); Assert.IsNotNullOrEmpty(account_id); // search accounts of specific customer ReadOnlyCollection <NgWebElement> ng_customer_accounts = ng_customer.FindElements(NgBy.Repeater("account in cust.accountNo")); NgWebElement account_matching = ng_customer_accounts.First(acc => String.Equals(acc.Text, account_id)); Assert.IsNotNull(account_matching); ngDriver.Highlight(account_matching, highlight_timeout); }
public void CheckWelcomeStringStartsWith() { string welcomeText = "Welcome to your account."; StringAssert.StartsWith(welcomeText, "Test", "First comes Welcome"); }