Path: blob/trunk/java/test/org/openqa/selenium/AlertsTest.java
3987 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.assertThatCode;21import static org.assertj.core.api.Assertions.assertThatExceptionOfType;22import static org.openqa.selenium.WaitingConditions.newWindowIsOpened;23import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;24import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;25import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;26import static org.openqa.selenium.testing.drivers.Browser.CHROME;27import static org.openqa.selenium.testing.drivers.Browser.EDGE;28import static org.openqa.selenium.testing.drivers.Browser.FIREFOX;29import static org.openqa.selenium.testing.drivers.Browser.SAFARI;3031import java.util.Set;32import org.junit.jupiter.api.AfterEach;33import org.junit.jupiter.api.Test;34import org.openqa.selenium.environment.webserver.Page;35import org.openqa.selenium.support.ui.ExpectedCondition;36import org.openqa.selenium.testing.Ignore;37import org.openqa.selenium.testing.JupiterTestBase;38import org.openqa.selenium.testing.NoDriverAfterTest;39import org.openqa.selenium.testing.SwitchToTopAfterTest;4041class AlertsTest extends JupiterTestBase {4243private static ExpectedCondition<Boolean> textInElementLocated(44final By locator, final String text) {45return driver -> text.equals(driver.findElement(locator).getText());46}4748private static ExpectedCondition<WebDriver> ableToSwitchToWindow(final String name) {49return driver -> driver.switchTo().window(name);50}5152@AfterEach53public void closeAlertIfPresent() {54try {55driver.switchTo().alert().dismiss();56} catch (WebDriverException ignore) {57}58}5960private String alertPage(String alertText) {61return appServer.create(62new Page()63.withTitle("Testing Alerts")64.withBody(65"<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));66}6768private String promptPage(String defaultText) {69return appServer.create(70new Page()71.withTitle("Testing Prompt")72.withScripts(73"function setInnerText(id, value) {",74" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",75"}",76defaultText == null77? "function displayPrompt() { setInnerText('text', prompt('Enter something'));"78+ " }"79: "function displayPrompt() { setInnerText('text', prompt('Enter something', '"80+ defaultText81+ "')); }")82.withBody(83"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",84"<div id='text'>acceptor</div>"));85}8687@Test88void testShouldBeAbleToOverrideTheWindowAlertMethod() {89driver.get(alertPage("cheese"));9091((JavascriptExecutor) driver)92.executeScript(93"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");94driver.findElement(By.id("alert")).click();9596// If we can perform any action, we're good to go97assertThat(driver.getTitle()).isEqualTo("Testing Alerts");98}99100@Test101void testShouldAllowUsersToAcceptAnAlertManually() {102driver.get(alertPage("cheese"));103104driver.findElement(By.id("alert")).click();105Alert alert = wait.until(alertIsPresent());106alert.accept();107108// If we can perform any action, we're good to go109assertThat(driver.getTitle()).isEqualTo("Testing Alerts");110}111112@Test113void testShouldThrowIllegalArgumentExceptionWhenKeysNull() {114driver.get(alertPage("cheese"));115116driver.findElement(By.id("alert")).click();117Alert alert = wait.until(alertIsPresent());118119assertThatExceptionOfType(IllegalArgumentException.class)120.isThrownBy(() -> alert.sendKeys(null));121}122123@Test124void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() {125driver.get(alertPage(""));126127driver.findElement(By.id("alert")).click();128Alert alert = wait.until(alertIsPresent());129alert.accept();130131// If we can perform any action, we're good to go132assertThat(driver.getTitle()).isEqualTo("Testing Alerts");133}134135@Test136void testShouldAllowUsersToDismissAnAlertManually() {137driver.get(alertPage("cheese"));138139driver.findElement(By.id("alert")).click();140Alert alert = wait.until(alertIsPresent());141alert.dismiss();142143// If we can perform any action, we're good to go144assertThat(driver.getTitle()).isEqualTo("Testing Alerts");145}146147@Test148void testShouldAllowAUserToAcceptAPrompt() {149driver.get(promptPage(null));150151driver.findElement(By.id("prompt")).click();152Alert alert = wait.until(alertIsPresent());153alert.accept();154155// If we can perform any action, we're good to go156assertThat(driver.getTitle()).isEqualTo("Testing Prompt");157}158159@Test160void testShouldAllowAUserToDismissAPrompt() {161driver.get(promptPage(null));162163driver.findElement(By.id("prompt")).click();164Alert alert = wait.until(alertIsPresent());165alert.dismiss();166167// If we can perform any action, we're good to go168assertThat(driver.getTitle()).isEqualTo("Testing Prompt");169}170171@Test172void testShouldAllowAUserToSetTheValueOfAPrompt() {173driver.get(promptPage(null));174175driver.findElement(By.id("prompt")).click();176Alert alert = wait.until(alertIsPresent());177alert.sendKeys("cheese");178alert.accept();179180wait.until(textInElementLocated(By.id("text"), "cheese"));181}182183@Test184void testSettingTheValueOfAnAlertThrows() {185driver.get(alertPage("cheese"));186187driver.findElement(By.id("alert")).click();188189Alert alert = wait.until(alertIsPresent());190assertThatExceptionOfType(ElementNotInteractableException.class)191.isThrownBy(() -> alert.sendKeys("cheese"));192}193194@Test195void testShouldAllowTheUserToGetTheTextOfAnAlert() {196driver.get(alertPage("cheese"));197198driver.findElement(By.id("alert")).click();199Alert alert = wait.until(alertIsPresent());200String value = alert.getText();201alert.accept();202203assertThat(value).isEqualTo("cheese");204}205206@Test207void testShouldAllowTheUserToGetTheTextOfAPrompt() {208driver.get(promptPage(null));209210driver.findElement(By.id("prompt")).click();211Alert alert = wait.until(alertIsPresent());212String value = alert.getText();213alert.accept();214215assertThat(value).isEqualTo("Enter something");216}217218@Test219void testAlertShouldNotAllowAdditionalCommandsIfDismissed() {220driver.get(alertPage("cheese"));221222driver.findElement(By.id("alert")).click();223Alert alert = wait.until(alertIsPresent());224alert.accept();225226assertThatExceptionOfType(NoAlertPresentException.class).isThrownBy(alert::getText);227}228229@SwitchToTopAfterTest230@Test231void testShouldAllowUsersToAcceptAnAlertInAFrame() {232String iframe =233appServer.create(234new Page()235.withBody(236"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"237+ " me</a>"));238driver.get(239appServer.create(240new Page()241.withTitle("Testing Alerts")242.withBody(243String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe))));244245driver.switchTo().frame("iframeWithAlert");246driver.findElement(By.id("alertInFrame")).click();247Alert alert = wait.until(alertIsPresent());248alert.accept();249250// If we can perform any action, we're good to go251assertThat(driver.getTitle()).isEqualTo("Testing Alerts");252}253254@SwitchToTopAfterTest255@Test256void testShouldAllowUsersToAcceptAnAlertInANestedFrame() {257String iframe =258appServer.create(259new Page()260.withBody(261"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"262+ " me</a>"));263String iframe2 =264appServer.create(265new Page()266.withBody(267String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe)));268driver.get(269appServer.create(270new Page()271.withTitle("Testing Alerts")272.withBody(273String.format("<iframe src='%s' name='iframeWithIframe'></iframe>", iframe2))));274275driver.switchTo().frame("iframeWithIframe").switchTo().frame("iframeWithAlert");276277driver.findElement(By.id("alertInFrame")).click();278Alert alert = wait.until(alertIsPresent());279alert.accept();280281// If we can perform any action, we're good to go282assertThat(driver.getTitle()).isEqualTo("Testing Alerts");283}284285@Test286void testSwitchingToMissingAlertThrows() {287driver.get(alertPage("cheese"));288289assertThatExceptionOfType(NoAlertPresentException.class)290.isThrownBy(() -> driver.switchTo().alert());291}292293@Test294void testSwitchingToMissingAlertInAClosedWindowThrows() {295String blank = appServer.create(new Page());296driver.get(297appServer.create(298new Page()299.withBody(300String.format(301"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",302blank))));303304String mainWindow = driver.getWindowHandle();305try {306driver.findElement(By.id("open-new-window")).click();307wait.until(ableToSwitchToWindow("newwindow"));308driver.close();309310assertThatExceptionOfType(NoSuchWindowException.class)311.isThrownBy(() -> driver.switchTo().alert());312313} finally {314driver.switchTo().window(mainWindow);315}316}317318@Test319void testPromptShouldUseDefaultValueIfNoKeysSent() {320driver.get(promptPage("This is a default value"));321322wait.until(presenceOfElementLocated(By.id("prompt"))).click();323Alert alert = wait.until(alertIsPresent());324alert.accept();325326wait.until(textInElementLocated(By.id("text"), "This is a default value"));327}328329@Test330void testPromptShouldHaveNullValueIfDismissed() {331driver.get(promptPage("This is a default value"));332333driver.findElement(By.id("prompt")).click();334Alert alert = wait.until(alertIsPresent());335alert.dismiss();336337wait.until(textInElementLocated(By.id("text"), "null"));338}339340@Test341void testHandlesTwoAlertsFromOneInteraction() {342driver.get(343appServer.create(344new Page()345.withScripts(346"function setInnerText(id, value) {",347" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",348"}",349"function displayTwoPrompts() {",350" setInnerText('text1', prompt('First'));",351" setInnerText('text2', prompt('Second'));",352"}")353.withBody(354"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",355"<div id='text1'></div>",356"<div id='text2'></div>")));357358wait.until(presenceOfElementLocated(By.id("double-prompt"))).click();359Alert alert1 = wait.until(alertIsPresent());360alert1.sendKeys("brie");361alert1.accept();362363Alert alert2 = wait.until(alertIsPresent());364alert2.sendKeys("cheddar");365alert2.accept();366367wait.until(textInElementLocated(By.id("text1"), "brie"));368wait.until(textInElementLocated(By.id("text2"), "cheddar"));369}370371@Test372void testShouldHandleAlertOnPageLoad() {373String pageWithOnLoad =374appServer.create(375new Page()376.withOnLoad("javascript:alert(\"onload\")")377.withBody("<p>Page with onload event handler</p>"));378driver.get(379appServer.create(380new Page()381.withBody(382String.format("<a id='link' href='%s'>open new page</a>", pageWithOnLoad))));383384driver.findElement(By.id("link")).click();385Alert alert = wait.until(alertIsPresent());386String value = alert.getText();387alert.accept();388389assertThat(value).isEqualTo("onload");390wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));391}392393@Test394void testShouldHandleAlertOnPageLoadUsingGet() {395driver.get(396appServer.create(397new Page()398.withOnLoad("javascript:alert(\"onload\")")399.withBody("<p>Page with onload event handler</p>")));400401Alert alert = wait.until(alertIsPresent());402String value = alert.getText();403alert.accept();404405assertThat(value).isEqualTo("onload");406wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));407}408409@Test410@Ignore(value = CHROME, reason = "Hangs")411@Ignore(value = EDGE, reason = "Hangs")412@Ignore(SAFARI)413@NoDriverAfterTest414public void testShouldNotHandleAlertInAnotherWindow() {415String pageWithOnLoad =416appServer.create(417new Page()418.withOnLoad("javascript:alert(\"onload\")")419.withBody("<p>Page with onload event handler</p>"));420driver.get(421appServer.create(422new Page()423.withBody(424String.format(425"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",426pageWithOnLoad))));427428Set<String> currentWindowHandles = driver.getWindowHandles();429driver.findElement(By.id("open-new-window")).click();430wait.until(newWindowIsOpened(currentWindowHandles));431432assertThatExceptionOfType(TimeoutException.class)433.isThrownBy(() -> wait.until(alertIsPresent()));434}435436@Test437@Ignore(438value = FIREFOX,439reason = "Per spec, an error data dictionary with text value is optional")440public void testIncludesAlertTextInUnhandledAlertException() {441driver.get(alertPage("cheese"));442443driver.findElement(By.id("alert")).click();444wait.until(alertIsPresent());445446assertThatExceptionOfType(UnhandledAlertException.class)447.isThrownBy(driver::getTitle)448.withMessageContaining("cheese")449.satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese"));450}451452@NoDriverAfterTest453@Test454void testCanQuitWhenAnAlertIsPresent() {455driver.get(alertPage("cheese"));456457driver.findElement(By.id("alert")).click();458wait.until(alertIsPresent());459460assertThatCode(() -> driver.quit()).doesNotThrowAnyException();461}462463@Test464void shouldHandleAlertOnFormSubmit() {465driver.get(466appServer.create(467new Page()468.withTitle("Testing Alerts")469.withBody(470"<form id='theForm'"471+ " action='/click_tests/submitted_page.html' "472+ " onsubmit='return alert(\"Tasty cheese\");'>",473"<input id='unused' type='submit' value='Submit'>",474"</form>")));475476driver.findElement(By.id("theForm")).submit();477Alert alert = wait.until(alertIsPresent());478String value = alert.getText();479alert.accept();480481assertThat(value).isEqualTo("Tasty cheese");482483wait.until(titleIs("Submitted Successfully!"));484assertThat(driver.getCurrentUrl()).contains("submitted_page.html");485}486}487488489