org.openqa.selenium.Alert Java Examples

The following examples show how to use org.openqa.selenium.Alert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Browser.java    From aquality-selenium-java with Apache License 2.0 6 votes vote down vote up
/**
 * Accepts or declines prompt with sending message
 *
 * @param alertAction accept or decline
 * @param text        message to send
 */
public void handlePromptAlert(AlertActions alertAction, String text) {
    try {
        Alert alert = getDriver().switchTo().alert();
        if (text != null && !text.isEmpty()) {
            getDriver().switchTo().alert().sendKeys(text);
        }
        if (alertAction.equals(AlertActions.ACCEPT)) {
            alert.accept();
        } else {
            alert.dismiss();
        }
    } catch (NoAlertPresentException exception) {
        localizedLogger.fatal("loc.browser.alert.fail", exception);
        throw exception;
    }
}
 
Example #2
Source File: WebBaseOpt.java    From WebAndAppUITesting with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 切换到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);
}
 
Example #3
Source File: Screenshoter.java    From teasy with MIT License 6 votes vote down vote up
public String takeScreenshot(final String errorMessage, final String testName) {
    try {
        BufferedImage image;
        if (Configuration.browser.equals("chrome")) {
            image = ImageIO.read(new ChromeScreenshoter().getFullScreenshotAs(OutputType.FILE));
        } else {
            image = ImageIO.read(((TakesScreenshot)DriverHolder.getDriver()).getScreenshotAs(OutputType.FILE));
        }

        printStrings(image, removeNL(testName, errorMessage));

        final String pathName = getFilenameFor(testName);
        final File screenShotWithProjectPath = new File(pathName);
        ImageIO.write(image, "png", screenShotWithProjectPath);
        attachScreenShotToAllure(errorMessage, testName, screenShotWithProjectPath);
        return screenShotWithProjectPath.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    } catch (UnhandledAlertException alertException) {
        Alert alert = DriverHolder.getDriver().switchTo().alert();
        alert.dismiss();
        return takeScreenshot(errorMessage, testName);
    }
}
 
Example #4
Source File: Assertion.java    From PatatiumWebUi with Apache License 2.0 6 votes vote down vote up
/**
 * 验证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;
	}

}
 
Example #5
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
public static ExpectedCondition<Alert> alertIsPresent() {
  return new ExpectedCondition<Alert>() {
    @Override
    public Alert apply(WebDriver driver) {
      try {
        return driver.switchTo().alert();
      } catch (NoAlertPresentException e) {
        return null;
      }
    }

    @Override
    public String toString() {
      return "alert to be present";
    }
  };
}
 
Example #6
Source File: Assertion.java    From PatatiumWebUi with Apache License 2.0 6 votes vote down vote up
/**
 * 验证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;
	}

}
 
Example #7
Source File: IosEncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String alertOperation(IOSDriver<IOSElement> appium, String operation) {
	String result = "";
	Alert alert = appium.switchTo().alert();
	switch (operation) {
	case "alertaccept":
		alert.accept();
		LogUtil.APP.info("�����������ͬ��...");
		break;
	case "alertdismiss":
		alert.dismiss();
		LogUtil.APP.info("�����������ȡ��...");
		break;
	case "alertgettext":
		result = "��ȡ����ֵ�ǡ�" + alert.getText() + "��";
		LogUtil.APP.info("���������ͨ��getText��ȡ����text����...��Text����ֵ:{}��",alert.getText());
		break;
	default:
		break;
	}
	return result;
}
 
Example #8
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String alertOperation(WebDriver wd, String operation) {
    String result = "";
    Alert alert = wd.switchTo().alert();
    switch (operation) {
        case "alertaccept":
            alert.accept();
            result = "�����������ͬ��...";
            LogUtil.APP.info(result);
            break;
        case "alertdismiss":
            alert.dismiss();
            result = "�����������ȡ��...";
            LogUtil.APP.info(result);
            break;
        case "alertgettext":
            result = "��ȡ����ֵ�ǡ�" + alert.getText() + "��";
            LogUtil.APP.info("���������ͨ��getText��ȡ����text����...��Text����ֵ:{}��",alert.getText());
            break;
        default:
            break;
    }
    return result;
}
 
Example #9
Source File: ListenableObjectTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Test public void listenableObjectSample() {
    try {
        ContextAware listenableContextAware =
                getEventFiringObject(contextAware, emptyWebDriver, contextListener, alertListener);
        WebDriver webDriver = listenableContextAware.context("NATIVE_APP");
        assertTrue(contextAwarePredicate.test(listenableContextAware));

        Alert alert = webDriver.switchTo().alert();
        assertTrue(alertPredicate.test(alert));

        assertTrue(webDriverPredicate.test(getEventFiringWebDriver(webDriver, searchingListener)));
    } finally {
        listeners.get(ContextListener.class).messages.clear();
        listeners.get(AlertListener.class).messages.clear();
        listeners.get(SearchingListener.class).messages.clear();
    }
}
 
Example #10
Source File: RealHtmlElementState.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
Source File: CachingTargetLocatorTest.java    From darcy-webdriver with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #12
Source File: WebDriverEventListenerCompatibilityTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void alertEventTest() {
    try {
        Alert alert = driver.switchTo().alert();
        alert.accept();
        alert.dismiss();
        alert.sendKeys("Keys");

        assertThat(listener.messages,
                hasItems(WEBDRIVER_EVENT_LISTENER + "Attempt to accept alert",
                        WEBDRIVER_EVENT_LISTENER + "The alert was accepted",
                        WEBDRIVER_EVENT_LISTENER + "Attempt to dismiss alert",
                        WEBDRIVER_EVENT_LISTENER + "The alert was dismissed"));
    } finally {
        listener.messages.clear();
    }
}
 
Example #13
Source File: ElementAction.java    From PatatiumWebUi with Apache License 2.0 6 votes vote down vote up
/**
 * 获取对话框文本
 * @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;

	}
}
 
Example #14
Source File: CachingTargetLocator.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Alert alert() {
    if (alert == null) {
        // Cache the alert to avoid repeat switches.
        // If alert is switched _from_, it must be nulled out.
        alert = driver.switchTo().alert();
    }

    return alert;
}
 
Example #15
Source File: WebDriverITBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Accept the javascript alert (clicking OK)
 *
*/
protected void acceptAlert()
{
    Alert alert = driver.switchTo().alert();
    //update is executed
    alert.accept();
}
 
Example #16
Source File: WebDriverWebController.java    From stevia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void promptInputPressOK(String inputMessage) {
	Alert alert = waitForAlert();
	alert.sendKeys(inputMessage);
	alert.accept();

}
 
Example #17
Source File: AlertHelper.java    From SeleniumCucumber with GNU General Public License v3.0 5 votes vote down vote up
public void AcceptPrompt(String text) {
	
	if (!isAlertPresent())
		return;
	
	Alert alert = getAlert();
	alert.sendKeys(text);
	alert.accept();
	oLog.info(text);
}
 
Example #18
Source File: WebDriverITBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Dismiss the javascript alert (clicking Cancel)
 *
*/
protected void dismissAlert()
{
    Alert alert = driver.switchTo().alert();
    //update is executed
    alert.dismiss();
}
 
Example #19
Source File: DataSourcesTestCase.java    From product-cep with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.cep", description = "Verifying XSS Vulnerability in event data sources - description field")
public void testXSSVenerabilityDescriptionField() throws Exception {
    boolean isVulnerable = false;

    // Login
    driver.get(getLoginURL());
    driver.findElement(By.id("txtUserName")).clear();
    driver.findElement(By.id("txtUserName")).sendKeys(cepServer.getContextTenant().getContextUser().getUserName());
    driver.findElement(By.id("txtPassword")).clear();
    driver.findElement(By.id("txtPassword")).sendKeys(cepServer.getContextTenant().getContextUser().getPassword());
    driver.findElement(By.cssSelector("input.button")).click();

    // Sending request to even-tracer admin service
    String url = backendURL.substring(0, 22) + "/carbon/ndatasource/newdatasource.jsp?";
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("description", "RiskScoringDB\"><script>alert(1)</script><example attr=\""));
    params.add(new BasicNameValuePair("edit", "true"));
    url += URLEncodedUtils.format(params, "UTF-8");

    driver.get(url);
    try {
        // Alert appears if vulnerable to XSS attack.
        Alert alert = driver.switchTo().alert();
        alert.accept();
        isVulnerable = true;
    } catch (NoAlertPresentException e) {
        // XSS vulnerability is not there
    }
    Assert.assertFalse(isVulnerable);
    driver.close();
}
 
Example #20
Source File: PopupDialogsBrowser.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * check state pop up browser window
 *
 * @return
 */
public boolean isAlertPresent() {
  try {
    Alert alert = seleniumWebDriver.switchTo().alert();
    return !alert.getText().isEmpty();
  } catch (Exception e) {
    return false;
  }
}
 
Example #21
Source File: AlertActions.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public void processAlert(Action action)
{
    Alert alert = switchToAlert(webDriverProvider.get());
    if (alert != null)
    {
        action.process(alert, webDriverManager);
    }
}
 
Example #22
Source File: ESPublisherNewGlobalPageTestCase.java    From product-es with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #23
Source File: CachingTargetLocatorTest.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldNotSwitchDriverToAlertIfCurrentTargetIsAlert() {
    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.alert();

    verify(mockLocator, times(1)).alert();
}
 
Example #24
Source File: BrowserTest.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
@WaitUntil
public boolean dismissAlert() {
    Alert alert = getAlert();
    boolean result = false;
    if (alert != null) {
        alert.dismiss();
        onAlertHandled(false);
        result = true;
    }
    return result;
}
 
Example #25
Source File: EventFiringWebDriverTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void alertEvents() {
  final WebDriver mockedDriver = mock(WebDriver.class);
  final Alert mockedAlert = mock(Alert.class);
  final WebDriver.TargetLocator mockedTargetLocator = mock(WebDriver.TargetLocator.class);

  when(mockedDriver.switchTo()).thenReturn(mockedTargetLocator);
  when(mockedTargetLocator.alert()).thenReturn(mockedAlert);

  WebDriverEventListener listener = mock(WebDriverEventListener.class);

  EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener);

  testedDriver.switchTo().alert().accept();
  testedDriver.switchTo().alert().dismiss();

  InOrder order = Mockito.inOrder(mockedDriver, mockedAlert, listener);
  order.verify(mockedDriver).switchTo();
  order.verify(listener).beforeAlertAccept(any(WebDriver.class));
  order.verify(mockedAlert).accept();
  order.verify(listener).afterAlertAccept(any(WebDriver.class));
  order.verify(mockedDriver).switchTo();
  order.verify(listener).beforeAlertDismiss(any(WebDriver.class));
  order.verify(mockedAlert).dismiss();
  order.verify(listener).afterAlertDismiss(any(WebDriver.class));
  verifyNoMoreInteractions(mockedDriver, mockedAlert, listener);
}
 
Example #26
Source File: ESStoreAddedAssetTestCase.java    From product-es with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #27
Source File: AlertHandler.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
/**
 * Accept any displayed alert message. If no alert is displayed, an exception will be thrown.
 * <p>
 * Fires {@link AcceptedAlertEvent} in case a alert was successfully accepted.
 *
 * @throws NoAlertPresentException in case no alert is present
 * @see Alert#accept()
 * @since 2.0
 */
public void accept() throws NoAlertPresentException {
    StringBuilder builder = new StringBuilder();
    ActionTemplate.browser(browser()).execute(browser -> {
        Alert alert = webDriver().switchTo().alert();
        builder.append(alert.getText());
        alert.accept();
    }).fireEvent(browser -> new AcceptedAlertEvent(builder.toString()));
    log.debug("alert was accepted");
}
 
Example #28
Source File: WebDriverWebController.java    From stevia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void promptInputPressCancel(String inputMessage) {
	Alert alert = waitForAlert();
	alert.sendKeys(inputMessage);
	alert.dismiss();

}
 
Example #29
Source File: ITDeleteSingleBucketCancel.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #30
Source File: ESStoreNewGlobalPageTestCase.java    From product-es with Apache License 2.0 5 votes vote down vote up
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;
    }
}