protected void HandleError(Exception ex, string screenshotName, List <string> outputs = null, List <string> errors = null) { Log($"Handling error {ex.Message}."); var screenshotPath = this.TakeScreenshot(screenshotName); string errorOutputs = ""; if (errors != null) { errorOutputs = String.Join("\r\n", errors); } string normalOutputs = ""; if (outputs != null) { normalOutputs = String.Join("\r\n", outputs); } Log($"{ex.ToString()}."); IAlert alert = this.Driver.WaitForAlert(500); alert?.Dismiss(); throw new TelimenaTestException($"{ex}\r\n\r\n{this.PresentParams()}\r\n\r\n{errorOutputs}\r\n\r\n{normalOutputs}\r\n\r\nScreenshot Path:\r\n\r\n{screenshotPath}", ex); }
protected void HandleError(Exception ex, List <string> outputs = null, List <string> errors = null, [CallerMemberName] string memberName = "") { Screenshot screen = this.Screenshooter.GetScreenshot(); string path = Common.CreatePngPath(memberName); screen.SaveAsFile(path, ScreenshotImageFormat.Png); string page = this.Driver.PageSource; string errorOutputs = ""; if (errors != null) { errorOutputs = string.Join("\r\n", errors); } string normalOutputs = ""; if (outputs != null) { normalOutputs = string.Join("\r\n", outputs); } IAlert alert = this.Driver.WaitForAlert(500); alert?.Dismiss(); throw new AssertFailedException($"{ex}\r\n\r\n{this.PresentParams()}\r\n\r\n{errorOutputs}\r\n\r\n{normalOutputs}\r\n\r\n{page}", ex); //this.TestContext.AddResultFile(path); }
private string TakeScreenshot(string screenshotName) { int attempt = 0; while (attempt < 5) { attempt++; IntegrationTestBase.Log($"Saving error screenshot: {screenshotName} for test run {TestRunTimestamp}"); string path = CreatePngPath(screenshotName, this.GetType().Name); IntegrationTestBase.Log($"{path}"); try { Screenshot screen = this.Screenshooter.GetScreenshot(); screen.SaveAsFile(path, ScreenshotImageFormat.Png); TestContext.AddTestAttachment(path); return(path); } catch (UnhandledAlertException alertException) { IntegrationTestBase.Log($"Attempt {attempt} - Unexpected alert {screenshotName} for test run {TestRunTimestamp}.\r\n{alertException}"); IAlert unexpectedAlert = this.Driver.SwitchTo().Alert(); IntegrationTestBase.Log($"Attempt {attempt} - Alert text: [{unexpectedAlert?.Text}]"); unexpectedAlert?.Dismiss(); try { Screenshot screen = this.Screenshooter.GetScreenshot(); screen.SaveAsFile(path, ScreenshotImageFormat.Png); } catch (Exception screenshotError) { IntegrationTestBase.Log($"Attempt {attempt} - Error while saving screenshot after dismissing alert: {screenshotError}"); } } catch (Exception screenshotError) { IntegrationTestBase.Log($"Attempt {attempt} - Error while saving screenshot: {screenshotError}"); } } return("Failed to take screenshot"); }
/// <summary> /// Close Alert box /// </summary> /// <returns></returns> public ActionResult CloseAlertBox() { try { IAlert alert = Browser.driver.SwitchTo().Alert(); alert.Dismiss(); return(new ActionResult { IsSuccess = true, ErrorMessage = string.Empty }); } catch (Exception e) { if (Screenshot.BoolScreenShotOnException) { path = Screenshot.CaptureScreenWithCallStack(); } return(new ActionResult { IsSuccess = false, ErrorMessage = e.Message, Screenpath = path }); } }
protected string CloseAlertAndGetItsText(bool acceptNextAlert = true) { try { IAlert alert = manager.Driver.SwitchTo().Alert(); string alertText = alert.Text; if (acceptNextAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { acceptNextAlert = true; } }
public string CloseAlertAndGetItsText(bool acceptAlert) { try { IAlert alert = SwitchTo().Alert(); string alertText = alert.Text; if (acceptAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } catch (NoAlertPresentException) { return(string.Empty); } }
public void TestConfirmDismiss() { //Clicking button will show a Confirmation Alert with OK and Cancel Button IWebElement button = driver.FindElement(By.Id("confirm")); button.Click(); try { //Get the Alert IAlert alert = driver.SwitchTo().Alert(); //Click OK button, by calling accept() method of Alert Class alert.Dismiss(); //Verify Page displays correct message on Accept IWebElement message = driver.FindElement(By.Id("demo")); Assert.AreEqual("You Dismissed Alert!", message.Text); } catch (NoAlertPresentException e) { Assert.Fail("Alert not found!!"); } }
public void AlertOkOrCancelPressCancel() { AlertPage alertdo = new AlertPage(driver); alertdo.AlertWithOkayAndCancelChoose(); alertdo.DisplayConfirmButtonClick(); IAlert alert = driver.SwitchTo().Alert(); alert.Dismiss(); IWebElement AlertResponse = driver.FindElement(By.Id("demo")); try { Assert.IsTrue(AlertResponse.Text.Contains("You Pressed Cancel")); } catch { throw; } }
protected string CloseAlertAndGetItsText() { try { IAlert alert = this.WebDriver.SwitchTo().Alert(); string alertText = alert.Text; if (this.acceptNextAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { this.acceptNextAlert = true; } }
/// <summary> /// Close Alert and Get Its Txt /// Created by Selenium in default /// </summary> /// <returns></returns> internal static string CloseAlertAndGetItsText(this TestBase uiTest) { try { IAlert alert = uiTest.driver.SwitchTo().Alert(); string alertText = alert.Text; if (uiTest.acceptNextAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { uiTest.acceptNextAlert = true; } }
internal void DeleteRecord() { Thread.Sleep(3000); driver.FindElement(By.XPath("//*[@id=\"tmsGrid\"]/div[3]/table/tbody/tr[1]/td[5]/a[2]")).Click(); IAlert text = driver.SwitchTo().Alert(); string alertmessage = text.Text; Console.WriteLine(alertmessage); { if (alertmessage.Equals("Are you sure you want to delete this record?")) { Console.WriteLine("Correct message"); } else { Console.WriteLine("InCorrect message"); } } text.Dismiss(); }
private string CloseAlertAndGetItsText() { try { IAlert alert = driver.SwitchTo().Alert(); string alertText = alert.Text; if (acceptNextAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { acceptNextAlert = true; } }
public void HandlingAlertsTest() { Init(); driver.Navigate().GoToUrl("http://toolsqa.com/handling-alerts-using-selenium-webdriver/"); Thread.Sleep(5000); try { IWebElement SimpleAlertBtn = driver.FindElement(By.XPath("//button[.= 'Simple Alert']")); SimpleAlertBtn.Click(); Thread.Sleep(2000); IAlert SimpleAlert = driver.SwitchTo().Alert(); Console.WriteLine(SimpleAlert.Text); SimpleAlert.Accept(); driver.SwitchTo().DefaultContent(); IWebElement ConfirmAlertBtn = driver.FindElement(By.XPath("//button[.= 'Confirm Pop up']")); ConfirmAlertBtn.Click(); Thread.Sleep(2000); IAlert ConfirmAlert = driver.SwitchTo().Alert(); Console.WriteLine(ConfirmAlert.Text); ConfirmAlert.Dismiss(); driver.SwitchTo().DefaultContent(); IWebElement PromptPopupBtn = driver.FindElement(By.XPath("//button[.= 'Prompt Pop up']")); PromptPopupBtn.Click(); Thread.Sleep(2000); IAlert PromptAlert = driver.SwitchTo().Alert(); Console.WriteLine(PromptAlert.Text); PromptAlert.SendKeys("Yes"); PromptAlert.Accept(); } catch (Exception e) { Console.WriteLine(e.StackTrace); } finally { driver.Quit(); } }
public void alertpop() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://demo.opencart.com/"); driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("alert('This is an information box')"); System.Threading.Thread.Sleep(2000); IAlert alert = driver.SwitchTo().Alert(); string alertmsg = alert.Text; alert.Accept(); if (alertmsg.Equals("This is an information box")) { Console.WriteLine("Alert Message match found"); } else { Console.WriteLine("Alert message match not found"); } //conform alert popup js = (IJavaScriptExecutor)driver; js.ExecuteScript("confirm('Do u want to continue(y/n)?')"); System.Threading.Thread.Sleep(2000); alert = driver.SwitchTo().Alert(); alertmsg = alert.Text; alert.Dismiss(); if (alertmsg.Equals("Do u want to continue(y/n)?")) { Console.WriteLine("Alert Message match found"); } else { Console.WriteLine("Alert Message match not found"); } }
public void Check_Mail_PopUp() { IWebElement FourthLetter = driver.FindElement(By.XPath("//span[text()='Ласкаво просимо на I.UA!']")); Actions actions = new Actions(driver); actions.MoveToElement(FourthLetter).Build().Perform(); IWebElement Popup = driver.FindElement(By.Id("prflpudvmbox_userInfoPopUp")); IWebElement PopupText = Popup.FindElement(By.XPath("//li[2]")); IWebElement MailCheckBox = driver.FindElement(By.XPath("//input[@value='5b026e6ede88']")); MailCheckBox.Click(); Assert.IsTrue(MailCheckBox.Selected); IWebElement DeleteButton = driver.FindElement(By.XPath("//div[@id='fieldset1']/fieldset[3]")); DeleteButton.Click(); IAlert RemoveMailAlert = driver.SwitchTo().Alert(); RemoveMailAlert.Dismiss(); }
public string alertControl(bool acceptAlert) { log("alertControl(" + acceptAlert + ")"); try { IAlert alert = driver.SwitchTo().Alert(); string alertText = alert.Text; if (acceptAlert) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { acceptAlert = true; } }
public void Wrong_User_Credtentials() { driver.Url = "https://localhost:44313/userLogin.aspx"; Assert.AreEqual("User Login", driver.Title); driver.FindElement(By.Id("ContentPlaceHolder1_TextBox1")) .SendKeys("WrongName"); driver.FindElement(By.Id("ContentPlaceHolder1_TextBox2")) .SendKeys("WrongPassword"); driver.FindElement(By.Id("ContentPlaceHolder1_Button1")) .Click(); IAlert alert = driver.SwitchTo().Alert(); string errMsg = alert.Text; if (errMsg.Equals("Invalid credentials")) { alert.Dismiss(); } }
protected void DismissAlert(int maxWaitTime = 0) { IAlert alertHandle = null; maxWaitTime = maxWaitTime > 0 ? maxWaitTime : ElementSyncTimeOut; try { alertHandle = GetAlertHandle(maxWaitTime); if (alertHandle != null) { alertHandle.Dismiss(); } else { throw new Exception("Alert handle not available"); } } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// Clicks all accordion menus lists on a member's page /// </summary> public uint CountClickableAccordions() { uint totalClicked = 0; string[] AccoridionIDs = { "abasicConfig", "ainformationDetails", "aQuesSupp", "testReq", "aPaymentReq", "aSupReq", "aRecReq", "aCutOffConfig", "aSDSConfiguration", "aFinAidConfig", "aDynamicText" }; foreach (string id in AccoridionIDs) { try { _utilsValidation.ExplicitWait(DriverUtilities.ElementAccessorType.ID, id, 60); _utilsValidation.Click(DriverUtilities.ElementAccessorType.ID, id); totalClicked++; //Thread.Sleep(200); // works, but not an optimal solution } catch (UnhandledAlertException ex) { IAlert alert = _driver.SwitchTo().Alert(); alert.Dismiss(); Console.WriteLine(ex.Message); } } return(totalClicked); }
//Obsluga Alert'ow private string handleAlert() { try { IAlert alert = driver.SwitchTo().Alert(); string alertText = alert.Text; if (accAlert = true) { alert.Accept(); } else { alert.Dismiss(); } return(alertText); } finally { accAlert = true; } }
public void MovingbetweenWindowsAndFramesAlerts() { /* * Some web applications have many frames or multiple windows. * WebDriver supports moving between named windows using the SwitchTo() method. * Also propery driver.WindowHandles gets the window handles of Opened Browser Windows. * window got one method. * But for Frame we have 3 overloads * index * frameElement * frameName * */ IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl(@"http://www.google.com"); //Moving Between Windows and Frames & Alert driver.SwitchTo().Window("windowName"); driver.SwitchTo().Frame("frameName"); //Reverting back from Frame to Default driver.SwitchTo().DefaultContent(); //Switching to Alert IAlert alert = driver.SwitchTo().Alert(); alert.Accept(); alert.Dismiss(); string alertText = alert.Text; //Gets the window handles of open browser windows. foreach (string handle in driver.WindowHandles) { driver.SwitchTo().Window(handle); } }
public async Task HandleFormWithJavascriptAction() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("form_handling_js_submit.html"); await driver.GoToUrl(url); IWebElement element = await driver.FindElement(By.Id("theForm")); await element.Submit(); IAlert alert = await WaitFor(async() => { try { return(await driver.SwitchTo().Alert()); } catch (NoAlertPresentException) { return(null); } }, "No alert found before timeout."); string text = await alert.Text(); await alert.Dismiss(); Assert.AreEqual("Tasty cheese", text); }
internal static void TakeScreenshot(out string filePath, IWebElement HightLightElement = null, string captureLocation = "c:\\temp\\testresults\\") { string timeStamp = DateTime.Now.ToString("ddMMyyyyHHmmss"); filePath = captureLocation + "ErrorCapture" + timeStamp + ".png"; if (HightLightElement != null) { ((IJavaScriptExecutor)Browser.Driver).ExecuteScript("arguments[0].style.border='3px solid red'", HightLightElement); } try { //TODO : Add more info to the filename and suitable location to save to Screenshot screenshot = ((ITakesScreenshot)Browser.Driver).GetScreenshot(); screenshot.SaveAsFile(filePath, ScreenshotImageFormat.Png); } catch (UnhandledAlertException) { IAlert alert = WebDriver.SwitchTo().Alert(); alert.Dismiss(); Screenshot screenshot = ((ITakesScreenshot)Browser.Driver).GetScreenshot(); screenshot.SaveAsFile(filePath, ScreenshotImageFormat.Png); } catch (Exception e) { Console.WriteLine("TakeScreenshot encountered an error. " + e.Message); } //Console.WriteLine(callingClassName + "." + callingMethodName + " generated an error. A ScreenShot of the browser has been saved. " + filePath); }
public void Test() { IWebDriver driver = new ChromeDriver(); driver.Url = "http://toolsqa.wpengine.com/handling-alerts-using-selenium-webdriver/"; driver.Manage().Window.Maximize(); //This step produce an alert on screen IWebElement element = driver.FindElement(By.XPath("//*[@id='content']/p[8]/button")); // 'IJavaScriptExecutor' is an interface which is used to run the 'JavaScript code' into the webdriver (Browser) ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element); // Switch the control of 'driver' to the Alert from main window IAlert confirmationAlert = driver.SwitchTo().Alert(); // Get the Text of Alert String alertText = confirmationAlert.Text; Console.WriteLine("Alert text is " + alertText); //'.Dismiss()' is used to cancel the alert '(click on the Cancel button)' confirmationAlert.Dismiss(); }
public void HandleBSTAlert() { try { WebDriverWait _wait1 = new WebDriverWait(webDriver, TimeSpan.FromSeconds(60)); IAlert alertDialog = _wait1.Until <IAlert>(ExpectedConditions.AlertIsPresent()); if (alertDialog != null) { alertDialog.Dismiss(); } webDriver.SwitchTo().DefaultContent(); } catch (UnhandledAlertException) { try { webDriver.SwitchTo().Alert().Dismiss(); } catch (NoAlertPresentException) { } webDriver.SwitchTo().DefaultContent(); } catch { webDriver.SwitchTo().DefaultContent(); } webDriver.SwitchTo().Frame(StandardConfigFrame); }
//Closing an Alert public void AlertClose() { IAlert alert = driver.SwitchTo().Alert(); alert.Dismiss(); }
public virtual TResult Dismiss <TResult>() where TResult : IBlock { Alert.Dismiss(); return(Session.CurrentBlock <TResult>(Parent)); }
/// <summary> /// dismiss /// </summary> public void Dismiss() { IAlert alert = Driver.SwitchTo().Alert(); alert.Dismiss(); }
public void Tooltip_and_Double_Click() { string actualResult; string ExpectedResult = "ToolsQA – Demo Website to Practice Automation – Demo Website to Practice Automation"; _driver.Manage().Window.Maximize(); _driver.Navigate().GoToUrl("https://demoqa.com/"); actualResult = _driver.Title; Assert.AreEqual(actualResult, ExpectedResult); string expectedResult = "Tooltip and Double click"; //Navigate to HTML contact form _driver.FindElement(By.LinkText("Tooltip and Double click")).Click(); //Asser that correct page was selected Assert.AreEqual(expectedResult, _driver.FindElement(By.ClassName("entry-title")).Text); WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)); //Double click button Actions actionsDouble = new Actions(_driver); IWebElement doubleClickButton = _driver.FindElement(By.Id("doubleClickBtn")); actionsDouble.DoubleClick(doubleClickButton).Perform(); wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent()); IAlert doubleClickButtonAlert = _driver.SwitchTo().Alert(); string AlertString = doubleClickButtonAlert.Text; string ext = AlertString.Substring(0, 18); Assert.AreEqual("Double Click Alert", ext); doubleClickButtonAlert.Dismiss(); //Right click button Actions actionsRight = new Actions(_driver); IWebElement rightClickButton = _driver.FindElement(By.Id("rightClickBtn")); actionsRight.ContextClick(rightClickButton).Perform(); _driver.FindElement(By.XPath("//*[@id='rightclickItem']/div[1]")).Click(); wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent()); IAlert rightClickButtonAlert = _driver.SwitchTo().Alert(); Assert.AreEqual("You have selected Edit", rightClickButtonAlert.Text); rightClickButtonAlert.Dismiss(); //Tooltip Actions actionsTool = new Actions(_driver); IWebElement tooltipLink = _driver.FindElement(By.Id("tooltipDemo")); actionsTool.MoveToElement(tooltipLink).Perform(); IWebElement toolTip = _driver.FindElement(By.XPath("//*[@id='tooltipDemo']/span")); Assert.AreEqual("We ask for your age only for statistical purposes.", toolTip.Text); }
public void CreateUserFieldValidation(List <string> userinfo, List <string> usererror, List <string> normaluser) { //try //{ //login using admin_operator Login(userinfo[0], userinfo[1]); //click on User tab ClickOn(Link_UserTab); Wait(7); //click on Add user ClickOn(Button_AddUser); //input all the user info Wait(5); Set_Textbox(Input_Userbox, userinfo[2]); VerifyUserFieldError(P_UserError, usererror[0]); Wait(2); Set_Textbox(Input_Pass, userinfo[3]); if (P_PasswordErrors.Count > 0) { VerifyUserFieldError(P_PasswordErrors[0], usererror[1]); VerifyUserFieldError(P_PasswordErrors[1], usererror[2]); VerifyUserFieldError(P_PasswordErrors[2], usererror[3]); } Wait(2); Set_Textbox(Input_ConfirmPass, userinfo[4]); VerifyUserFieldError(P_ConfirmPasswordError, usererror[4]); Wait(2); Set_Textbox(Input_FirstName, userinfo[5]); VerifyUserFieldError(P_FirstNameError, usererror[5]); Wait(2); Set_Textbox(Input_SurName, userinfo[6]); VerifyUserFieldError(P_SurNameError, usererror[6]); Wait(2); Set_Textbox(Input_Email, userinfo[7]); VerifyUserFieldError(P_EmailError, usererror[7]); Wait(2); ClickOn(Button_Save); Wait(2); ClickOn(Link_Cancel); Wait(5); IAlert alert = driver.SwitchTo().Alert(); alert.Dismiss(); ClickOn(Link_ActivitiesTab); driver.SwitchTo().Alert(); alert.Dismiss(); //click on streamtab ClickOn(VideoStreaming.Link_StreamTab); driver.SwitchTo().Alert(); alert.Dismiss(); ClickOn(Link_Cancel); Wait(5); alert = driver.SwitchTo().Alert(); alert.Accept(); Wait(5); ClickOn(Button_AddUser); Wait(3); Set_Textbox(Input_Userbox, normaluser[0]); Set_Textbox(Input_Pass, normaluser[1]); Set_Textbox(Input_ConfirmPass, normaluser[1]); Set_Textbox(Input_FirstName, normaluser[2]); Set_Textbox(Input_SurName, normaluser[3]); Set_Textbox(Input_Email, normaluser[4]); ClickOn(Input_AdminRole); ClickOn(Div_MediaDownload); ClickOn(Button_Save); Wait(3); VerifyUserFieldError(Span_UserNameExists, usererror[8]); Wait(3); Set_Textbox(Input_Userbox, "±newuserdelimeter"); Wait(3); VerifyUserFieldError(P_UserError, usererror[9]); Wait(3); Set_Textbox(Input_Pass, "±newuserdelimeter"); Wait(2); VerifyUserFieldError(P_PasswordErrors[2], usererror[9]); //} //catch (Exception ex) //{ // ExtentReportUtil.Test.Log(Status.Pass, "Verification Successful:"); //} }
/// <summary> /// Method to dismiss condition specify in alert /// </summary> public void AlertDismiss() { try { //Implicitely wait for an alert to appear. DelAlertLoaded = WaitAndGetAlert; _alert = AlertLoadingWait.Until(DelAlertLoaded); _alert.Dismiss(); } catch (WebDriverException e) { if (e.Message.Contains(Exceptions.ERROR_NORESPONSEURL)) { throw new WebDriverException(Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message); } throw new Exception(Utility.GetCommonMsgVariable("KRYPTONERRCODE0054") + ":" + e.Message); } catch (Exception) { throw new Exception(Utility.GetCommonMsgVariable("KRYPTONERRCODE0011")); } }