Path: blob/trunk/java/test/org/openqa/selenium/AlertsTest.java
1865 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617package org.openqa.selenium;1819import static org.assertj.core.api.Assertions.assertThat;20import static org.assertj.core.api.Assertions.assertThatExceptionOfType;21import static org.openqa.selenium.WaitingConditions.newWindowIsOpened;22import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;23import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;24import static org.openqa.selenium.testing.drivers.Browser.CHROME;25import static org.openqa.selenium.testing.drivers.Browser.EDGE;26import static org.openqa.selenium.testing.drivers.Browser.FIREFOX;27import static org.openqa.selenium.testing.drivers.Browser.SAFARI;2829import java.util.Set;30import org.junit.jupiter.api.AfterEach;31import org.junit.jupiter.api.Test;32import org.openqa.selenium.environment.webserver.Page;33import org.openqa.selenium.support.ui.ExpectedCondition;34import org.openqa.selenium.testing.Ignore;35import org.openqa.selenium.testing.JupiterTestBase;36import org.openqa.selenium.testing.NoDriverAfterTest;37import org.openqa.selenium.testing.SwitchToTopAfterTest;3839class AlertsTest extends JupiterTestBase {4041private static ExpectedCondition<Boolean> textInElementLocated(42final By locator, final String text) {43return driver -> text.equals(driver.findElement(locator).getText());44}4546private static ExpectedCondition<WebDriver> ableToSwitchToWindow(final String name) {47return driver -> driver.switchTo().window(name);48}4950@AfterEach51public void closeAlertIfPresent() {52try {53driver.switchTo().alert().dismiss();54} catch (WebDriverException ignore) {55}56}5758private String alertPage(String alertText) {59return appServer.create(60new Page()61.withTitle("Testing Alerts")62.withBody(63"<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));64}6566private String promptPage(String defaultText) {67return appServer.create(68new Page()69.withTitle("Testing Prompt")70.withScripts(71"function setInnerText(id, value) {",72" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",73"}",74defaultText == null75? "function displayPrompt() { setInnerText('text', prompt('Enter something'));"76+ " }"77: "function displayPrompt() { setInnerText('text', prompt('Enter something', '"78+ defaultText79+ "')); }")80.withBody(81"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",82"<div id='text'>acceptor</div>"));83}8485@Test86void testShouldBeAbleToOverrideTheWindowAlertMethod() {87driver.get(alertPage("cheese"));8889((JavascriptExecutor) driver)90.executeScript(91"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");92driver.findElement(By.id("alert")).click();9394// If we can perform any action, we're good to go95assertThat(driver.getTitle()).isEqualTo("Testing Alerts");96}9798@Test99void testShouldAllowUsersToAcceptAnAlertManually() {100driver.get(alertPage("cheese"));101102driver.findElement(By.id("alert")).click();103Alert alert = wait.until(alertIsPresent());104alert.accept();105106// If we can perform any action, we're good to go107assertThat(driver.getTitle()).isEqualTo("Testing Alerts");108}109110@Test111void testShouldThrowIllegalArgumentExceptionWhenKeysNull() {112driver.get(alertPage("cheese"));113114driver.findElement(By.id("alert")).click();115Alert alert = wait.until(alertIsPresent());116117assertThatExceptionOfType(IllegalArgumentException.class)118.isThrownBy(() -> alert.sendKeys(null));119}120121@Test122void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() {123driver.get(alertPage(""));124125driver.findElement(By.id("alert")).click();126Alert alert = wait.until(alertIsPresent());127alert.accept();128129// If we can perform any action, we're good to go130assertThat(driver.getTitle()).isEqualTo("Testing Alerts");131}132133@Test134void testShouldAllowUsersToDismissAnAlertManually() {135driver.get(alertPage("cheese"));136137driver.findElement(By.id("alert")).click();138Alert alert = wait.until(alertIsPresent());139alert.dismiss();140141// If we can perform any action, we're good to go142assertThat(driver.getTitle()).isEqualTo("Testing Alerts");143}144145@Test146void testShouldAllowAUserToAcceptAPrompt() {147driver.get(promptPage(null));148149driver.findElement(By.id("prompt")).click();150Alert alert = wait.until(alertIsPresent());151alert.accept();152153// If we can perform any action, we're good to go154assertThat(driver.getTitle()).isEqualTo("Testing Prompt");155}156157@Test158void testShouldAllowAUserToDismissAPrompt() {159driver.get(promptPage(null));160161driver.findElement(By.id("prompt")).click();162Alert alert = wait.until(alertIsPresent());163alert.dismiss();164165// If we can perform any action, we're good to go166assertThat(driver.getTitle()).isEqualTo("Testing Prompt");167}168169@Test170void testShouldAllowAUserToSetTheValueOfAPrompt() {171driver.get(promptPage(null));172173driver.findElement(By.id("prompt")).click();174Alert alert = wait.until(alertIsPresent());175alert.sendKeys("cheese");176alert.accept();177178wait.until(textInElementLocated(By.id("text"), "cheese"));179}180181@Test182void testSettingTheValueOfAnAlertThrows() {183driver.get(alertPage("cheese"));184185driver.findElement(By.id("alert")).click();186187Alert alert = wait.until(alertIsPresent());188assertThatExceptionOfType(ElementNotInteractableException.class)189.isThrownBy(() -> alert.sendKeys("cheese"));190}191192@Test193void testShouldAllowTheUserToGetTheTextOfAnAlert() {194driver.get(alertPage("cheese"));195196driver.findElement(By.id("alert")).click();197Alert alert = wait.until(alertIsPresent());198String value = alert.getText();199alert.accept();200201assertThat(value).isEqualTo("cheese");202}203204@Test205void testShouldAllowTheUserToGetTheTextOfAPrompt() {206driver.get(promptPage(null));207208driver.findElement(By.id("prompt")).click();209Alert alert = wait.until(alertIsPresent());210String value = alert.getText();211alert.accept();212213assertThat(value).isEqualTo("Enter something");214}215216@Test217void testAlertShouldNotAllowAdditionalCommandsIfDismissed() {218driver.get(alertPage("cheese"));219220driver.findElement(By.id("alert")).click();221Alert alert = wait.until(alertIsPresent());222alert.accept();223224assertThatExceptionOfType(NoAlertPresentException.class).isThrownBy(alert::getText);225}226227@SwitchToTopAfterTest228@Test229void testShouldAllowUsersToAcceptAnAlertInAFrame() {230String iframe =231appServer.create(232new Page()233.withBody(234"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"235+ " me</a>"));236driver.get(237appServer.create(238new Page()239.withTitle("Testing Alerts")240.withBody(241String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe))));242243driver.switchTo().frame("iframeWithAlert");244driver.findElement(By.id("alertInFrame")).click();245Alert alert = wait.until(alertIsPresent());246alert.accept();247248// If we can perform any action, we're good to go249assertThat(driver.getTitle()).isEqualTo("Testing Alerts");250}251252@SwitchToTopAfterTest253@Test254void testShouldAllowUsersToAcceptAnAlertInANestedFrame() {255String iframe =256appServer.create(257new Page()258.withBody(259"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"260+ " me</a>"));261String iframe2 =262appServer.create(263new Page()264.withBody(265String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe)));266driver.get(267appServer.create(268new Page()269.withTitle("Testing Alerts")270.withBody(271String.format("<iframe src='%s' name='iframeWithIframe'></iframe>", iframe2))));272273driver.switchTo().frame("iframeWithIframe").switchTo().frame("iframeWithAlert");274275driver.findElement(By.id("alertInFrame")).click();276Alert alert = wait.until(alertIsPresent());277alert.accept();278279// If we can perform any action, we're good to go280assertThat(driver.getTitle()).isEqualTo("Testing Alerts");281}282283@Test284void testSwitchingToMissingAlertThrows() {285driver.get(alertPage("cheese"));286287assertThatExceptionOfType(NoAlertPresentException.class)288.isThrownBy(() -> driver.switchTo().alert());289}290291@Test292void testSwitchingToMissingAlertInAClosedWindowThrows() {293String blank = appServer.create(new Page());294driver.get(295appServer.create(296new Page()297.withBody(298String.format(299"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",300blank))));301302String mainWindow = driver.getWindowHandle();303try {304driver.findElement(By.id("open-new-window")).click();305wait.until(ableToSwitchToWindow("newwindow"));306driver.close();307308assertThatExceptionOfType(NoSuchWindowException.class)309.isThrownBy(() -> driver.switchTo().alert());310311} finally {312driver.switchTo().window(mainWindow);313}314}315316@Test317void testPromptShouldUseDefaultValueIfNoKeysSent() {318driver.get(promptPage("This is a default value"));319320wait.until(presenceOfElementLocated(By.id("prompt"))).click();321Alert alert = wait.until(alertIsPresent());322alert.accept();323324wait.until(textInElementLocated(By.id("text"), "This is a default value"));325}326327@Test328void testPromptShouldHaveNullValueIfDismissed() {329driver.get(promptPage("This is a default value"));330331driver.findElement(By.id("prompt")).click();332Alert alert = wait.until(alertIsPresent());333alert.dismiss();334335wait.until(textInElementLocated(By.id("text"), "null"));336}337338@Test339void testHandlesTwoAlertsFromOneInteraction() {340driver.get(341appServer.create(342new Page()343.withScripts(344"function setInnerText(id, value) {",345" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",346"}",347"function displayTwoPrompts() {",348" setInnerText('text1', prompt('First'));",349" setInnerText('text2', prompt('Second'));",350"}")351.withBody(352"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",353"<div id='text1'></div>",354"<div id='text2'></div>")));355356wait.until(presenceOfElementLocated(By.id("double-prompt"))).click();357Alert alert1 = wait.until(alertIsPresent());358alert1.sendKeys("brie");359alert1.accept();360361Alert alert2 = wait.until(alertIsPresent());362alert2.sendKeys("cheddar");363alert2.accept();364365wait.until(textInElementLocated(By.id("text1"), "brie"));366wait.until(textInElementLocated(By.id("text2"), "cheddar"));367}368369@Test370void testShouldHandleAlertOnPageLoad() {371String pageWithOnLoad =372appServer.create(373new Page()374.withOnLoad("javascript:alert(\"onload\")")375.withBody("<p>Page with onload event handler</p>"));376driver.get(377appServer.create(378new Page()379.withBody(380String.format("<a id='link' href='%s'>open new page</a>", pageWithOnLoad))));381382driver.findElement(By.id("link")).click();383Alert alert = wait.until(alertIsPresent());384String value = alert.getText();385alert.accept();386387assertThat(value).isEqualTo("onload");388wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));389}390391@Test392void testShouldHandleAlertOnPageLoadUsingGet() {393driver.get(394appServer.create(395new Page()396.withOnLoad("javascript:alert(\"onload\")")397.withBody("<p>Page with onload event handler</p>")));398399Alert alert = wait.until(alertIsPresent());400String value = alert.getText();401alert.accept();402403assertThat(value).isEqualTo("onload");404wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));405}406407@Test408@Ignore(value = CHROME, reason = "Hangs")409@Ignore(value = EDGE, reason = "Hangs")410@Ignore(SAFARI)411@NoDriverAfterTest412public void testShouldNotHandleAlertInAnotherWindow() {413String pageWithOnLoad =414appServer.create(415new Page()416.withOnLoad("javascript:alert(\"onload\")")417.withBody("<p>Page with onload event handler</p>"));418driver.get(419appServer.create(420new Page()421.withBody(422String.format(423"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",424pageWithOnLoad))));425426Set<String> currentWindowHandles = driver.getWindowHandles();427driver.findElement(By.id("open-new-window")).click();428wait.until(newWindowIsOpened(currentWindowHandles));429430assertThatExceptionOfType(TimeoutException.class)431.isThrownBy(() -> wait.until(alertIsPresent()));432}433434@Test435@Ignore(436value = FIREFOX,437reason = "Per spec, an error data dictionary with text value is optional")438public void testIncludesAlertTextInUnhandledAlertException() {439driver.get(alertPage("cheese"));440441driver.findElement(By.id("alert")).click();442wait.until(alertIsPresent());443444assertThatExceptionOfType(UnhandledAlertException.class)445.isThrownBy(driver::getTitle)446.withMessageContaining("cheese")447.satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese"));448}449450@NoDriverAfterTest451@Test452void testCanQuitWhenAnAlertIsPresent() {453driver.get(alertPage("cheese"));454455driver.findElement(By.id("alert")).click();456wait.until(alertIsPresent());457458driver.quit();459}460461@Test462void shouldHandleAlertOnFormSubmit() {463driver.get(464appServer.create(465new Page()466.withTitle("Testing Alerts")467.withBody(468"<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>",469"<input id='unused' type='submit' value='Submit'>",470"</form>")));471472driver.findElement(By.id("theForm")).submit();473Alert alert = wait.until(alertIsPresent());474String value = alert.getText();475alert.accept();476477assertThat(value).isEqualTo("Tasty cheese");478assertThat(driver.getTitle()).isEqualTo("Testing Alerts");479}480}481482483