@Override public void open() { String paramUrl = paramTranslate(getUrl()); engine.openUrl(paramUrl); try { engine.computeToolbarHeight(); } catch(UnhandledAlertException e) { Alert alert = engine.getDriver().switchTo().alert(); if(alert != null) { alert.dismiss(); engine.computeToolbarHeight(); } } }
/** * 切换到alter,并点击确认框 */ public void clickAlert(String msg) { WebDriverWait webDriverWait = new WebDriverWait(driver, 10); Alert alert; baseOpt.wait(20); // Alert alert = driver.switchTo().alert(); try { // 不稳定,原因待查。还是用上面的吧 // wait and switchTo, Otherwise, throws a TimeoutException alert = webDriverWait.until(ExpectedConditions.alertIsPresent()); } catch (Exception e) { this.screenShot(); LogUtil.info(driver.manage().logs() + "==>alert等待超时!"); alert = driver.switchTo().alert(); // 与waituntil功能重复,但until经常失败,为了增强健壮性才如此写 } if (msg != null) { AssertUtil.assertEquals(alert.getText(), msg, "提示语错误"); } alert.accept(); baseOpt.wait(30); }
@PublicAtsApi public boolean isElementPresent() { // with the current Selenium implementation we do not know whether the opened modal dialog // is alert, prompt or confirmation if (element instanceof UiAlert) { return getAlert() != null; } else if (element instanceof UiPrompt) { Alert prompt = getAlert(); return prompt != null && prompt.getText() != null; } else if (element instanceof UiConfirm) { Alert confirm = getAlert(); return confirm != null && confirm.getText() != null; } HtmlNavigator.getInstance().navigateToFrame(webDriver, element); return RealHtmlElementLocator.findElements(element).size() > 0; }
/** * 验证alert对话框提示信息是否与预期值一致 * @param expectAlertText alert 提示框预期信息 * @author Administrator 郑树恒 */ public static void VerityAlertText(String expectAlertText) { Alert alert=driver.switchTo().alert(); String alertText=alert.getText(); String verityStr="【Assert验证】:弹出的对话框的文本内容是否一致{"+alertText+","+expectAlertText+"}"; log.info("【Assert验证】:弹出的对话框的文本内容是否一致{"+"实际值:"+alertText+","+"预期值"+expectAlertText+"}"); try { Assert.assertEquals(alertText, expectAlertText); AssertPassLog(); assertInfolList.add(verityStr+":pass"); } catch (Error e) { // TODO: handle exception AssertFailedLog(); errors.add(e); errorIndex++; assertInfolList.add(verityStr+":failed"); Assertion.snapshotInfo(); //throw e; } }
/** * 验证alert对话框提示信息是否与预期值一致 * @param expectAlertText alert 提示框预期信息 * @param Message 验证中文描述 * @author Administrator 郑树恒 */ public static void VerityAlertText(String expectAlertText,String Message) { Alert alert=driver.switchTo().alert(); String alertText=alert.getText(); String verityStr="【Assert验证】:弹出的对话框的文本内容是否一致{"+"实际值:"+alertText+","+"预期值:"+expectAlertText+"}"; log.info(Message+":"+verityStr); try { Assert.assertEquals(alertText, expectAlertText); AssertPassLog(); assertInfolList.add(Message+verityStr+":pass"); messageList.add(Message+":pass"); } catch (Error e) { // TODO: handle exception AssertFailedLog(); errors.add(e); errorIndex++; assertInfolList.add(Message+verityStr+":failed"); messageList.add(Message+":failed"); Assertion.snapshotInfo(); //throw e; } }
/** * 获取对话框文本 * @return 返回String */ public String getAlertText() { Alert alert=driver.switchTo().alert(); try { String text=alert.getText().toString(); log.info("获取对话框文本:"+text); return text; } catch (NoAlertPresentException notFindAlert) { // TODO: handle exception log.error("找不到对话框"); //return "找不到对话框"; throw notFindAlert; } }
/** * {@inheritDoc} */ @Override protected Object onCommand(Context context) { Alert alert = getSession().switchTo().alert(); String text = alert.getText(); Object value = getValue(); if (value != null) { alert.sendKeys(value.toString()); } if ("ok".equalsIgnoreCase(click)) { alert.accept(); } else if ("close".equalsIgnoreCase(click)) { alert.dismiss(); } return text; }
@Override protected ExecuteResult execute(final WebSiteConnector connector) { try { final Alert alert = connector.getDriver().switchTo().alert(); if (this.action == Action.ACCEPT) { alert.accept(); LOGGER.info(LEARNER_MARKER, "Accept alert window (ignoreFailure: {}, negated: {}).", ignoreFailure, negated); } else { alert.dismiss(); LOGGER.info(LEARNER_MARKER, "Dismiss alert window (ignoreFailure: {}, negated: {}).", ignoreFailure, negated); } return getSuccessOutput(); } catch (NoAlertPresentException e) { LOGGER.info(LEARNER_MARKER, "Failed accept or dismiss alert window (ignoreFailure: {}, negated: {}).", ignoreFailure, negated); return getFailedOutput(); } }
@Override public ExecuteResult execute(final ConnectorManager connector) { final VariableStoreConnector variableStore = connector.getConnector(VariableStoreConnector.class); final WebSiteConnector webSiteConnector = connector.getConnector(WebSiteConnector.class); try { final Alert alert = webSiteConnector.getDriver().switchTo().alert(); final String text = alert.getText(); variableStore.set(variableName, text); LOGGER.info(LEARNER_MARKER, "Save text '{}' from alert to variable '{}' (ignoreFailure: {}, negated: {}).", text, variableName, ignoreFailure, negated); return getSuccessOutput(); } catch (NoAlertPresentException e) { LOGGER.info(LEARNER_MARKER, "Failed to get text from alert (ignoreFailure: {}, negated: {}).", ignoreFailure, negated); return getFailedOutput(); } }
@Override protected ExecuteResult execute(final WebSiteConnector connector) { try { final Alert alert = connector.getDriver().switchTo().alert(); alert.sendKeys(insertVariableValues(text)); LOGGER.info(LEARNER_MARKER, "Send text '{}' to prompt window (ignoreFailure: {}, negated: {}).", text, ignoreFailure, negated); return getSuccessOutput(); } catch (NoAlertPresentException | ElementNotSelectableException e) { LOGGER.info(LEARNER_MARKER, "Failed to send text '{}' to prompt window (ignoreFailure: {}, negated: {}).", text, ignoreFailure, negated); return getFailedOutput(); } }
@Test(description = "Test to validate the duplication of model name is not allowed on model config page.") public void testAlertOnDuplicationOfModelName() { modelPage.get(); String familyName = Family.NEW_TEST_FAMILY2.name(); String capabilityName = Capability.NEW_TEST_CAP2.name(); // Trying to add a duplicate model. modelPage.addModel(existingModelName, familyName, capabilityName); // Fail the test if no alert message displayed on attempt of duplication of model name. Assert.assertTrue(isAlertPresent(), "No alert message displayed on attempting to duplicate the model name : " + existingModelName); Alert alert = driver.switchTo().alert(); // Validates the alert message. Assert.assertEquals(alert.getText(), existingModelName + TestConstants.MODEL_EXIST_ALERT_MSG_SUFFIX, "The alert message on attempting duplication of model is different from what expected."); }
/** Checks if an Alert is Present returns Boolean Value **/ public static Boolean isAlertPresent(String controlType) { try { if (!controlType.equalsIgnoreCase("Alert")) { Alert alert = Automation.driver.switchTo().alert(); if(alert != null) { TransactionMapping.report.strMessage=alert.getText(); alert.accept(); TransactionMapping.report.strStatus = "FAIL"; TransactionMapping.pauseFun(TransactionMapping.report.strMessage); return true; } } } catch (Exception e) { return false; } return false; }
@Test public void handlingSimpleAlertTest() { final String expected_alert_text = "A Short Title Is Best A message should be a short, complete sentence."; driver.findElement(MobileBy.AccessibilityId("alert_views_button")) .click(); //wait for alert view to load by waiting for "simple" alert button wait.until(ExpectedConditions.visibilityOf(driver.findElement(MobileBy.AccessibilityId("simple_alert_button")))) //and click on it .click(); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); String titleAndMessage = alert.getText(); assertThat(titleAndMessage, is(expected_alert_text)); alert.accept(); }
@Test public void textInputAlertTest() { driver.findElement(MobileBy.AccessibilityId("alert_views_button")) .click(); driver.findElement(MobileBy.AccessibilityId("text_entry_alert_button")) .click(); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); String titleAndMessage = alert.getText(); assertThat(titleAndMessage, is("A Short Title Is Best A message should be a short, complete sentence.")); //input text String text_alert_message = "testing alert text input field"; alert.sendKeys(text_alert_message); String alertTextInputField_value = driver.findElement(MobileBy.xpath("//UIAAlert//UIATextField")).getText(); assertThat(alertTextInputField_value, is(text_alert_message)); }
@Override public WebDriverBrowser acceptAlertIfVisible() { executeAction(new BrowserCallback() { @Override public void execute(Browser browser) { if (isAlertVisible()) { Alert alert = getWebDriver().switchTo().alert(); String text = alert.getText(); alert.accept(); fireEvent(new AcceptedAlertEvent(browser, text)); } } }); return this; }
@Override public WebDriverBrowser declineAlertIfVisible() { executeAction(new BrowserCallback() { @Override public void execute(Browser browser) { if (isAlertVisible()) { Alert alert = getWebDriver().switchTo().alert(); String text = alert.getText(); alert.dismiss(); fireEvent(new DeclinedAlertEvent(browser, text)); } } }); return this; }
private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } }
private void checkCloseWindowAlert(String winh) throws NoAlertPresentException { try { Alert alt = getDriver().switchTo().alert(); if (alt == null) throw GlobalUtils.createInternalError("web driver"); PopupPromptDialog aDialog = new PopupPromptDialog(getDriver(), alt, alerts.size()); aDialog.setClosingWindowHandle(winh); alerts.add(aDialog); } catch (UnreachableBrowserException error) { if (getNumberOfOpenWindows() > 0) throw GlobalUtils .createInternalError("ATE multi windows handler", error); } catch (UnsupportedOperationException e) { throw GlobalUtils .createInternalError("Driver doesn't support alert handling yet", e); } catch (NoSuchWindowException windClosedAlready) { //do nothing if window closed without alert dialog intervention. for example in Chrome. throw new NoAlertPresentException(windClosedAlready); } }
@Test public void shouldSwitchDriverToAlertIfCurrentTargetIsNoLongerAlertAndIsSameAsOriginalTarget() { WebDriver mockDriver = mock(WebDriver.class); TargetLocator mockLocator = mock(TargetLocator.class); when(mockDriver.switchTo()).thenReturn(mockLocator); when(mockLocator.alert()).thenReturn(mock(Alert.class)); CachingTargetLocator targetLocator = new CachingTargetLocator( WebDriverTargets.window("test"), mockDriver); targetLocator.alert(); targetLocator.window("test"); targetLocator.alert(); verify(mockLocator, times(2)).alert(); }
@Test public void shouldSwitchDriverToAlertIfCurrentTargetIsNoLongerAlertAndIsDifferentThanOriginalTarget() { WebDriver mockDriver = mock(WebDriver.class); TargetLocator mockLocator = mock(TargetLocator.class); when(mockDriver.switchTo()).thenReturn(mockLocator); when(mockLocator.alert()).thenReturn(mock(Alert.class)); CachingTargetLocator targetLocator = new CachingTargetLocator( WebDriverTargets.window("test"), mockDriver); targetLocator.alert(); targetLocator.window("different"); targetLocator.alert(); verify(mockLocator, times(2)).alert(); }
@Test public void shouldKeepTrackOfPreviousWebDriverTargetIfAlertIsCurrentTarget() { WebDriver mockDriver = mock(WebDriver.class); TargetLocator mockLocator = mock(TargetLocator.class); when(mockDriver.switchTo()).thenReturn(mockLocator); when(mockLocator.alert()).thenReturn(mock(Alert.class)); CachingTargetLocator targetLocator = new CachingTargetLocator( WebDriverTargets.window("test"), mockDriver); targetLocator.alert(); targetLocator.frame("frame"); assertEquals(WebDriverTargets.frame(WebDriverTargets.window("test"), "frame"), targetLocator.getCurrentTarget()); }
@RobotKeyword("Dismisses currently shown confirmation dialog and returns its message.\r\n" + "\r\n" + "By default, this keyword chooses 'OK' option from the dialog. If 'Cancel' needs to be chosen, keyword `Choose Cancel On Next Confirmation` must be called before the action that causes the confirmation dialog to be shown.\r\n" + "\r\n" + "Example:\r\n" + " | Click Button | Send | | # Shows a confirmation dialog | \r\n" + " | ${message}= | Confirm Action | | # Chooses Ok | \r\n" + " | Should Be Equal | ${message} | Are your sure? | # Check dialog message | \r\n" + " | Choose Cancel On Next Confirmation | | | # Choose cancel on next Confirm Action | \r\n" + " | Click Button | Send | | # Shows a confirmation dialog | \r\n" + " | Confirm Action | | | # Chooses Cancel |") public String confirmAction() { try { Alert alert = browserManagement.getCurrentWebDriver().switchTo().alert(); String text = alert.getText().replace("\n", ""); if (acceptOnNextConfirmation) { alert.accept(); } else { alert.dismiss(); } acceptOnNextConfirmation = acceptOnNextConfirmationDefault; return text; } catch (WebDriverException wde) { throw new SeleniumLibraryNonFatalException("There were no alerts"); } }
private void enterTeamScore(final int teamNumber) throws IOException, InterruptedException { IntegrationTestUtils.loadPage(selenium, TestUtils.URL_ROOT + "scoreEntry/select_team.jsp"); final Select teamSelect = new Select(selenium.findElement(By.id("select-teamnumber"))); teamSelect.selectByValue(String.valueOf(teamNumber)); selenium.findElement(By.id("enter_submit")).click(); selenium.findElement(By.name("g1")).sendKeys(String.valueOf(teamNumber)); selenium.findElement(By.id("Verified_yes")).click(); selenium.findElement(By.id("submit")).click(); final Alert confirmScoreChange = selenium.switchTo().alert(); LOGGER.info("Confirmation text: " + confirmScoreChange.getText()); confirmScoreChange.accept(); }
protected void clickOkButtonInConfirm(int timeoutForConfirm) { try { Alert alert = waitForAlertPresence(timeoutForConfirm); alert.accept(); } catch (Exception ignored) { } }
public synchronized void takeScreenshot(final String errorMessage, final String testName) { try { //This probably could be used someday (do not delete) // int jsErrorNumber = JavaScriptError.readErrors(getWebDriver()).size(); // printStrings(image, removeNL(testName, errorMessage, "The following number of JS errors appeared during the test: " + jsErrorNumber)); BufferedImage image = new OurScreenshot().fullPage().getImage(); printStrings(image, removeNL(testName, errorMessage)); final String pathName = getFilenameFor(testName); final File screenShotWithProjectPath = new File(pathName); ImageIO.write(image, "png", screenShotWithProjectPath); addScreenShotPathForTest(getOriginalTestName(testName), screenShotWithProjectPath.getPath(), errorMessage); attachScreenShotToAllure(errorMessage, testName, screenShotWithProjectPath); //VE path below works for TestNG (do not delete) // String pathToImage = "../../ws/test-reports/test-classes/" + screenShotWithProjectPath.getName(); //VE path below works for ReportNG String pathToImage = "../../test-reports/test-classes/" + screenShotWithProjectPath.getName(); Reporter.log("<br/><a href='" + pathToImage + "' target='_blank'> <img src='" + pathToImage + "' height='100' width='100'/> </a><br/>"); } catch (IOException e) { LOGGER.error("IOException occurs", e); } catch (UnhandledAlertException alertException) { Alert alert = getWebDriver().switchTo().alert(); String alertText = alert.getText(); LOGGER.error("*****ERROR***** Unexpected Alert appeared. Alert text " + alertText); alert.dismiss(); takeScreenshot(errorMessage, testName); } }
@Override public String confirmation() { Alert alert = this.switchTo().alert(); String alertText = alert.getText(); alert.accept(); return alertText; }
/** * * @return {@link Alert} object representing HTML alert, prompt or confirmation modal dialog */ private Alert getAlert() { try { return this.webDriver.switchTo().alert(); } catch (NoAlertPresentException e) { throw new ElementNotFoundException(e); } }
@Override public boolean isElementPresent() { try { if ( (element.getUiDriver() instanceof HiddenBrowserDriver) && (element instanceof UiAlert || element instanceof UiPrompt || element instanceof UiConfirm)) { return false; } if (element instanceof UiAlert || element instanceof UiConfirm) { Alert dialog = webDriver.switchTo().alert(); return dialog != null; } else if (element instanceof UiPrompt) { Alert prompt = webDriver.switchTo().alert(); return prompt.getText() != null && !prompt.getText().equals("false"); // return seleniumBrowser.isPromptPresent(); // Not implemented yet } HiddenHtmlElementLocator.findElement(this.element, null, false); return true; } catch (NotFoundException nfe) { return false; } catch (ElementNotFoundException enfe) { return false; } }
/** * * @return {@link Alert} object representing HTML alert, prompt or confirmation modal dialog */ private Alert getAlert() { try { return this.webDriver.switchTo().alert(); } catch (NoAlertPresentException e) { return null; } }
String closeAlertAndGetItsText() { try { Alert alert = getDriver().switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } }
/** * Get the current javascript alert popup dialog box. * @return The alert */ private Alert getAlert() { logger.debug("Waiting for alert to popup..."); (new WebDriverWait(webDriver, pageWaitSeconds)).pollingEvery(pollFrequencyMilliseconds, TimeUnit.MILLISECONDS) .until(ExpectedConditions.alertIsPresent()); logger.debug("Alert has popped up..."); return webDriver.switchTo().alert(); }
public static final void dismissAlert(){ SeleniumWaitUtils.waitForAlert(); Alert alert = Config.driver().switchTo().alert(); log.info("Alert: " + alert.getText()); alert.dismiss(); log.info("Dismiss Alter"); }
public static final void acceptAlert(WebDriver driver){ SeleniumWaitUtils.waitForAlert(); Alert alert = driver.switchTo().alert(); log.info("Alert: " + alert.getText()); alert.accept(); log.info("Accept Alter"); }
@Override protected void onError(Description description, Throwable testFailure) throws Throwable { super.onError(description, testFailure); WebDriver webDriver = seleniumProvider.getWebDriver(); try { Alert alert = webDriver.switchTo().alert(); testFailure.addSuppressed(new RuntimeException("Unexpected alert with text: '" + alert.getText() + "'!")); } catch (NoAlertPresentException ignored) { } finally { webDriver.switchTo().defaultContent(); } }
/** * This method handles alert windows **/ public static void handleAlert(String status, WebDriver driver) { Alert alert = driver.switchTo().alert(); if (status.equalsIgnoreCase("Y")) { alert.accept(); } else if (status.equalsIgnoreCase("N")) { alert.dismiss(); } }
@Before(EXECUTION_ALERT_ACCEPT) public void beforeAlertAccept(JoinPoint joinPoint) throws Throwable { try { listener.beforeAlertAccept(driver, (Alert) castTarget(joinPoint)); } catch (Throwable t) { throw getRootCause(t); } }
@After(EXECUTION_ALERT_ACCEPT) public void afterAlertAccept(JoinPoint joinPoint) throws Throwable { try { listener.afterAlertAccept(driver, (Alert) castTarget(joinPoint)); } catch (Throwable t) { throw getRootCause(t); } }
@Before(EXECUTION_ALERT_DISMISS) public void beforeAlertDismiss(JoinPoint joinPoint) throws Throwable { try { listener.beforeAlertDismiss(driver, (Alert) castTarget(joinPoint)); } catch (Throwable t) { throw getRootCause(t); } }