org.openqa.selenium.NoAlertPresentException Java Examples

The following examples show how to use org.openqa.selenium.NoAlertPresentException. 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: ClosingAwareWebDriverWrapperTest.java    From bobcat with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTryToCloseAlertWhenNotMobileDuringCleanup() {
  //given
  setUp(IS_MAXIMIZED, IS_REUSABLE, NOT_MOBILE);
  when(webDriver.manage()).thenReturn(options);
  when(webDriver.manage().window()).thenReturn(window);
  when(webDriver.switchTo()).thenReturn(bobcatTargetLocator);
  when(webDriver.switchTo().alert()).thenReturn(alert);
  doThrow(new NoAlertPresentException()).when(alert).accept();

  //when
  testedObject.quit();

  //then
  verify(alert).accept();
}
 
Example #2
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 #3
Source File: ESXSSTestCase.java    From product-es with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.es.common", description = "Test XSS in Gadgets Page")
public void testListGadgetsXSSTestCase() throws Exception {

    String alertMessage = "XSS";

    String url = baseUrl + "/store/assets/gadget/list?" +
            "sortBy=overview_name&sort=}</script><script>alert('" + alertMessage + "')</script>";
    driver.get(url);

    boolean scriptInjected = false;

    try {
        String actualAlertMessage = closeAlertAndGetItsText(driver, false);

        if (actualAlertMessage.equals(alertMessage))
            scriptInjected = true;
    } catch (NoAlertPresentException ex) {
    }

    assertFalse(scriptInjected, "Script injected via the query string");
}
 
Example #4
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 #5
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 #6
Source File: SeleniumHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @return current alert, if one is present, null otherwise.
 */
public Alert getAlert() {
    Alert alert = null;
    try {
        alert = getTargetLocator().alert();
    } catch (NoAlertPresentException e) {
        // just leave alert null
    }
    return alert;
}
 
Example #7
Source File: WaitActionsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private void testWaitForPageLoadSleepForTimeout()
{
    Mockito.lenient().when(targetLocator.alert()).thenThrow(new NoAlertPresentException());
    mockDescriptiveWait(ChronoUnit.DAYS);
    when(javascriptActions.executeScript(SCRIPT_READY_STATE)).thenReturn(COMPLETE);
    spy.waitForPageLoad();
    verify(spy).sleepForTimeout(TIMEOUT_MILLIS);
}
 
Example #8
Source File: AlertHandler.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
/**
 * Declines any displayed alert message. If no alert is displayed, an exception will be thrown.
 * <p>
 * Fires {@link DeclinedAlertEvent} in case a alert was successfully accepted.
 *
 * @throws NoAlertPresentException in case no alert is present
 * @see Alert#dismiss()
 * @since 2.0
 */
public void decline() throws NoAlertPresentException {
    StringBuilder builder = new StringBuilder();
    ActionTemplate.browser(browser()).execute(browser -> {
        Alert alert = webDriver().switchTo().alert();
        builder.append(alert.getText());
        alert.dismiss();
    }).fireEvent(browser -> new DeclinedAlertEvent(builder.toString()));
    log.debug("alert was declined");
}
 
Example #9
Source File: ElementAction.java    From PatatiumWebUi with Apache License 2.0 5 votes vote down vote up
/**
 * 点击确认按钮
 */
public void alertConfirm()
{
	Alert alert=driver.switchTo().alert();
	try {
		alert.accept();
		log.info("点击确认按钮");
	} catch (NoAlertPresentException notFindAlert) {
		// TODO: handle exception
		//throw notFindAlert;
		log.error("找不到确认按钮");
		throw notFindAlert;
	}
}
 
Example #10
Source File: ElementAction.java    From PatatiumWebUi with Apache License 2.0 5 votes vote down vote up
/**
 * 点击取消按钮
 */
public  void alertDismiss()
{
	Alert alert= driver.switchTo().alert();
	try {
		alert.dismiss();
		log.info("点击取消按钮");
	} catch (NoAlertPresentException notFindAlert) {
		// TODO: handle exception
		//throw notFindAlert;
		log.error("找不到取消按钮");
		throw notFindAlert;
	}
}
 
Example #11
Source File: AlertHelper.java    From SeleniumCucumber with GNU General Public License v3.0 5 votes vote down vote up
public boolean isAlertPresent() {
	try {
		driver.switchTo().alert();
		oLog.info("true");
		return true;
	} catch (NoAlertPresentException e) {
		// Ignore
		oLog.info("false");
		return false;
	}
}
 
Example #12
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 #13
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 - driver field")
public void testXSSVenerabilityDriverField() 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/validateconnection-ajaxprocessor.jsp?";
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("dsName", "John"));
    params.add(new BasicNameValuePair("driver", "<script>alert(1)</script>"));
    params.add(new BasicNameValuePair("url", "http://abc.com"));
    params.add(new BasicNameValuePair("username", "John"));
    params.add(new BasicNameValuePair("dsType", "RDBMS"));
    params.add(new BasicNameValuePair("dsProviderType", "default"));
    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 #14
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 - data source name field")
public void testXSSVenerabilityNameField() 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("dsName", "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 #15
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 #16
Source File: WebDriverAlert.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
private void attempt(Consumer<org.openqa.selenium.Alert> action) {
    try {
        action.accept(alert);
    } catch (NoAlertPresentException e) {
        throw new FindableNotPresentException(this, e);
    }
}
 
Example #17
Source File: WebDriverAlert.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
private <T> T attemptAndGet(Function<org.openqa.selenium.Alert, T> action) {
    try {
        return action.apply(alert);
    } catch (NoAlertPresentException e) {
        throw new FindableNotPresentException(this, e);
    }
}
 
Example #18
Source File: ForwardingTargetedAlert.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isPresent() {
    try {
        alert().getText();
        return true;
    } catch (NoAlertPresentException e) {
        return false;
    }
}
 
Example #19
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetErrorCodeForW3cSpec() {
  Exception e = new NoAlertPresentException("This does not exist");
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) err.get("value");
  assertEquals(value.toString(), "no such alert", value.get("error"));
}
 
Example #20
Source File: WebDriverInterface.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if a modal dialog can be switched to 
 * and switched back from; otherwise, returns false.
 * 
 * @return 	Boolean true only if a modal dialog can 
 * be switched to, then switched back from.
 */
public boolean isDialogVisible() {
	try { 
		this.wd.switchTo().alert(); 
		logger.info("Dialog present?: true.");
		return true;
	} catch(UnhandledAlertException uae) {
		logger.info("(Unhandled alert in FF?) Dialog present?: true.  May have ignored dialog...");
		return true;
	} catch(NoAlertPresentException nape) {
		logger.info("Dialog present?: false.");
		return false;
	}
}
 
Example #21
Source File: DriverHelper.java    From carina with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that alert modal is shown.
 * 
 * @return whether the alert modal present.
 */
public boolean isAlertPresent() {
    try {
        getDriver().switchTo().alert();
        return true;
    } catch (NoAlertPresentException Ex) {
        return false;
    }
}
 
Example #22
Source File: ITCreateDuplicateBucket.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        return false;
    }
}
 
Example #23
Source File: AlertActionsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testIsAlertPresentNoAlertPresentException()
{
    when(webDriver.switchTo()).thenReturn(targetLocator);
    doThrow(NoAlertPresentException.class).when(targetLocator).alert();
    boolean answer = alertActions.isAlertPresent(webDriver);
    assertFalse(answer);
}
 
Example #24
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the alerts collected by the driver.
 * Note: it currently works only if no new page has been loaded in the window
 * @param maxWaitTime the maximum time to wait to get the alerts (in millis)
 * @param driver the driver
 * @param alertsLength the expected length of Alerts
 * @return the collected alerts
 * @throws Exception in case of problem
 */
protected List<String> getCollectedAlerts(final long maxWaitTime, final WebDriver driver, final int alertsLength)
        throws Exception {
    final List<String> collectedAlerts = new ArrayList<>();

    long maxWait = System.currentTimeMillis() + maxWaitTime;

    while (collectedAlerts.size() < alertsLength && System.currentTimeMillis() < maxWait) {
        try {
            final Alert alert = driver.switchTo().alert();
            final String text = alert.getText();

            collectedAlerts.add(text);
            alert.accept();

            // handling of alerts requires some time
            // at least for tests with many alerts we have to take this into account
            maxWait += 100;

            if (useRealBrowser()) {
                if (getBrowserVersion().isIE()) {
                    // alerts for real IE are really slow
                    maxWait += 5000;
                }
            }
        }
        catch (final NoAlertPresentException e) {
            Thread.sleep(10);
        }
    }

    return collectedAlerts;
}
 
Example #25
Source File: AbstractRealBrowserDriver.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
* @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);
    }
}
 
Example #26
Source File: RealHtmlElementState.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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;
    }
}
 
Example #27
Source File: Verifications.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private boolean isAlertPresent(WebDriver Driver) {
    try {
        Driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, e);
        return false;
    }
}
 
Example #28
Source File: CommonMethods.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private boolean isAlertPresent(WebDriver Driver) {
    try {
        Driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.OFF, e.getMessage(), e);
        return false;
    }
}
 
Example #29
Source File: General.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public boolean isAlertPresent() {
    try {
        Driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, e);
        return false;
    }
}
 
Example #30
Source File: ClosingAwareWebDriverWrapper.java    From bobcat with Apache License 2.0 5 votes vote down vote up
private void cleanDriver() {
  manage().deleteAllCookies();
  get(BLANK_PAGE);
  if (!mobile) {
    try {
      switchTo().alert().accept();
    } catch (NoAlertPresentException e) {
      LOG.debug("No alert was present when returnDriver was executed", e);
    }
  }
  if (maximize) {
    manage().window().maximize();
  }
}