Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/java/test/org/openqa/selenium/AlertsTest.java
3991 views
1
// Licensed to the Software Freedom Conservancy (SFC) under one
2
// or more contributor license agreements. See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership. The SFC licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License. You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied. See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
package org.openqa.selenium;
19
20
import static org.assertj.core.api.Assertions.assertThat;
21
import static org.assertj.core.api.Assertions.assertThatCode;
22
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
23
import static org.openqa.selenium.WaitingConditions.newWindowIsOpened;
24
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
25
import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
26
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
27
import static org.openqa.selenium.testing.drivers.Browser.CHROME;
28
import static org.openqa.selenium.testing.drivers.Browser.EDGE;
29
import static org.openqa.selenium.testing.drivers.Browser.FIREFOX;
30
import static org.openqa.selenium.testing.drivers.Browser.SAFARI;
31
32
import java.util.Set;
33
import org.junit.jupiter.api.AfterEach;
34
import org.junit.jupiter.api.Test;
35
import org.openqa.selenium.environment.webserver.Page;
36
import org.openqa.selenium.support.ui.ExpectedCondition;
37
import org.openqa.selenium.testing.Ignore;
38
import org.openqa.selenium.testing.JupiterTestBase;
39
import org.openqa.selenium.testing.NoDriverAfterTest;
40
import org.openqa.selenium.testing.SwitchToTopAfterTest;
41
42
class AlertsTest extends JupiterTestBase {
43
44
private static ExpectedCondition<Boolean> textInElementLocated(
45
final By locator, final String text) {
46
return driver -> text.equals(driver.findElement(locator).getText());
47
}
48
49
private static ExpectedCondition<WebDriver> ableToSwitchToWindow(final String name) {
50
return driver -> driver.switchTo().window(name);
51
}
52
53
@AfterEach
54
public void closeAlertIfPresent() {
55
try {
56
driver.switchTo().alert().dismiss();
57
} catch (WebDriverException ignore) {
58
}
59
}
60
61
private String alertPage(String alertText) {
62
return appServer.create(
63
new Page()
64
.withTitle("Testing Alerts")
65
.withBody(
66
"<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));
67
}
68
69
private String promptPage(String defaultText) {
70
return appServer.create(
71
new Page()
72
.withTitle("Testing Prompt")
73
.withScripts(
74
"function setInnerText(id, value) {",
75
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
76
"}",
77
defaultText == null
78
? "function displayPrompt() { setInnerText('text', prompt('Enter something'));"
79
+ " }"
80
: "function displayPrompt() { setInnerText('text', prompt('Enter something', '"
81
+ defaultText
82
+ "')); }")
83
.withBody(
84
"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",
85
"<div id='text'>acceptor</div>"));
86
}
87
88
@Test
89
void testShouldBeAbleToOverrideTheWindowAlertMethod() {
90
driver.get(alertPage("cheese"));
91
92
((JavascriptExecutor) driver)
93
.executeScript(
94
"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");
95
driver.findElement(By.id("alert")).click();
96
97
// If we can perform any action, we're good to go
98
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
99
}
100
101
@Test
102
void testShouldAllowUsersToAcceptAnAlertManually() {
103
driver.get(alertPage("cheese"));
104
105
driver.findElement(By.id("alert")).click();
106
Alert alert = wait.until(alertIsPresent());
107
alert.accept();
108
109
// If we can perform any action, we're good to go
110
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
111
}
112
113
@Test
114
void testShouldThrowIllegalArgumentExceptionWhenKeysNull() {
115
driver.get(alertPage("cheese"));
116
117
driver.findElement(By.id("alert")).click();
118
Alert alert = wait.until(alertIsPresent());
119
120
assertThatExceptionOfType(IllegalArgumentException.class)
121
.isThrownBy(() -> alert.sendKeys(null));
122
}
123
124
@Test
125
void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() {
126
driver.get(alertPage(""));
127
128
driver.findElement(By.id("alert")).click();
129
Alert alert = wait.until(alertIsPresent());
130
alert.accept();
131
132
// If we can perform any action, we're good to go
133
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
134
}
135
136
@Test
137
void testShouldAllowUsersToDismissAnAlertManually() {
138
driver.get(alertPage("cheese"));
139
140
driver.findElement(By.id("alert")).click();
141
Alert alert = wait.until(alertIsPresent());
142
alert.dismiss();
143
144
// If we can perform any action, we're good to go
145
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
146
}
147
148
@Test
149
void testShouldAllowAUserToAcceptAPrompt() {
150
driver.get(promptPage(null));
151
152
driver.findElement(By.id("prompt")).click();
153
Alert alert = wait.until(alertIsPresent());
154
alert.accept();
155
156
// If we can perform any action, we're good to go
157
assertThat(driver.getTitle()).isEqualTo("Testing Prompt");
158
}
159
160
@Test
161
void testShouldAllowAUserToDismissAPrompt() {
162
driver.get(promptPage(null));
163
164
driver.findElement(By.id("prompt")).click();
165
Alert alert = wait.until(alertIsPresent());
166
alert.dismiss();
167
168
// If we can perform any action, we're good to go
169
assertThat(driver.getTitle()).isEqualTo("Testing Prompt");
170
}
171
172
@Test
173
void testShouldAllowAUserToSetTheValueOfAPrompt() {
174
driver.get(promptPage(null));
175
176
driver.findElement(By.id("prompt")).click();
177
Alert alert = wait.until(alertIsPresent());
178
alert.sendKeys("cheese");
179
alert.accept();
180
181
wait.until(textInElementLocated(By.id("text"), "cheese"));
182
}
183
184
@Test
185
void testSettingTheValueOfAnAlertThrows() {
186
driver.get(alertPage("cheese"));
187
188
driver.findElement(By.id("alert")).click();
189
190
Alert alert = wait.until(alertIsPresent());
191
assertThatExceptionOfType(ElementNotInteractableException.class)
192
.isThrownBy(() -> alert.sendKeys("cheese"));
193
}
194
195
@Test
196
void testShouldAllowTheUserToGetTheTextOfAnAlert() {
197
driver.get(alertPage("cheese"));
198
199
driver.findElement(By.id("alert")).click();
200
Alert alert = wait.until(alertIsPresent());
201
String value = alert.getText();
202
alert.accept();
203
204
assertThat(value).isEqualTo("cheese");
205
}
206
207
@Test
208
void testShouldAllowTheUserToGetTheTextOfAPrompt() {
209
driver.get(promptPage(null));
210
211
driver.findElement(By.id("prompt")).click();
212
Alert alert = wait.until(alertIsPresent());
213
String value = alert.getText();
214
alert.accept();
215
216
assertThat(value).isEqualTo("Enter something");
217
}
218
219
@Test
220
void testAlertShouldNotAllowAdditionalCommandsIfDismissed() {
221
driver.get(alertPage("cheese"));
222
223
driver.findElement(By.id("alert")).click();
224
Alert alert = wait.until(alertIsPresent());
225
alert.accept();
226
227
assertThatExceptionOfType(NoAlertPresentException.class).isThrownBy(alert::getText);
228
}
229
230
@SwitchToTopAfterTest
231
@Test
232
void testShouldAllowUsersToAcceptAnAlertInAFrame() {
233
String iframe =
234
appServer.create(
235
new Page()
236
.withBody(
237
"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"
238
+ " me</a>"));
239
driver.get(
240
appServer.create(
241
new Page()
242
.withTitle("Testing Alerts")
243
.withBody(
244
String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe))));
245
246
driver.switchTo().frame("iframeWithAlert");
247
driver.findElement(By.id("alertInFrame")).click();
248
Alert alert = wait.until(alertIsPresent());
249
alert.accept();
250
251
// If we can perform any action, we're good to go
252
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
253
}
254
255
@SwitchToTopAfterTest
256
@Test
257
void testShouldAllowUsersToAcceptAnAlertInANestedFrame() {
258
String iframe =
259
appServer.create(
260
new Page()
261
.withBody(
262
"<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click"
263
+ " me</a>"));
264
String iframe2 =
265
appServer.create(
266
new Page()
267
.withBody(
268
String.format("<iframe src='%s' name='iframeWithAlert'></iframe>", iframe)));
269
driver.get(
270
appServer.create(
271
new Page()
272
.withTitle("Testing Alerts")
273
.withBody(
274
String.format("<iframe src='%s' name='iframeWithIframe'></iframe>", iframe2))));
275
276
driver.switchTo().frame("iframeWithIframe").switchTo().frame("iframeWithAlert");
277
278
driver.findElement(By.id("alertInFrame")).click();
279
Alert alert = wait.until(alertIsPresent());
280
alert.accept();
281
282
// If we can perform any action, we're good to go
283
assertThat(driver.getTitle()).isEqualTo("Testing Alerts");
284
}
285
286
@Test
287
void testSwitchingToMissingAlertThrows() {
288
driver.get(alertPage("cheese"));
289
290
assertThatExceptionOfType(NoAlertPresentException.class)
291
.isThrownBy(() -> driver.switchTo().alert());
292
}
293
294
@Test
295
void testSwitchingToMissingAlertInAClosedWindowThrows() {
296
String blank = appServer.create(new Page());
297
driver.get(
298
appServer.create(
299
new Page()
300
.withBody(
301
String.format(
302
"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",
303
blank))));
304
305
String mainWindow = driver.getWindowHandle();
306
try {
307
driver.findElement(By.id("open-new-window")).click();
308
wait.until(ableToSwitchToWindow("newwindow"));
309
driver.close();
310
311
assertThatExceptionOfType(NoSuchWindowException.class)
312
.isThrownBy(() -> driver.switchTo().alert());
313
314
} finally {
315
driver.switchTo().window(mainWindow);
316
}
317
}
318
319
@Test
320
void testPromptShouldUseDefaultValueIfNoKeysSent() {
321
driver.get(promptPage("This is a default value"));
322
323
wait.until(presenceOfElementLocated(By.id("prompt"))).click();
324
Alert alert = wait.until(alertIsPresent());
325
alert.accept();
326
327
wait.until(textInElementLocated(By.id("text"), "This is a default value"));
328
}
329
330
@Test
331
void testPromptShouldHaveNullValueIfDismissed() {
332
driver.get(promptPage("This is a default value"));
333
334
driver.findElement(By.id("prompt")).click();
335
Alert alert = wait.until(alertIsPresent());
336
alert.dismiss();
337
338
wait.until(textInElementLocated(By.id("text"), "null"));
339
}
340
341
@Test
342
void testHandlesTwoAlertsFromOneInteraction() {
343
driver.get(
344
appServer.create(
345
new Page()
346
.withScripts(
347
"function setInnerText(id, value) {",
348
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
349
"}",
350
"function displayTwoPrompts() {",
351
" setInnerText('text1', prompt('First'));",
352
" setInnerText('text2', prompt('Second'));",
353
"}")
354
.withBody(
355
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
356
"<div id='text1'></div>",
357
"<div id='text2'></div>")));
358
359
wait.until(presenceOfElementLocated(By.id("double-prompt"))).click();
360
Alert alert1 = wait.until(alertIsPresent());
361
alert1.sendKeys("brie");
362
alert1.accept();
363
364
Alert alert2 = wait.until(alertIsPresent());
365
alert2.sendKeys("cheddar");
366
alert2.accept();
367
368
wait.until(textInElementLocated(By.id("text1"), "brie"));
369
wait.until(textInElementLocated(By.id("text2"), "cheddar"));
370
}
371
372
@Test
373
void testShouldHandleAlertOnPageLoad() {
374
String pageWithOnLoad =
375
appServer.create(
376
new Page()
377
.withOnLoad("javascript:alert(\"onload\")")
378
.withBody("<p>Page with onload event handler</p>"));
379
driver.get(
380
appServer.create(
381
new Page()
382
.withBody(
383
String.format("<a id='link' href='%s'>open new page</a>", pageWithOnLoad))));
384
385
driver.findElement(By.id("link")).click();
386
Alert alert = wait.until(alertIsPresent());
387
String value = alert.getText();
388
alert.accept();
389
390
assertThat(value).isEqualTo("onload");
391
wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));
392
}
393
394
@Test
395
void testShouldHandleAlertOnPageLoadUsingGet() {
396
driver.get(
397
appServer.create(
398
new Page()
399
.withOnLoad("javascript:alert(\"onload\")")
400
.withBody("<p>Page with onload event handler</p>")));
401
402
Alert alert = wait.until(alertIsPresent());
403
String value = alert.getText();
404
alert.accept();
405
406
assertThat(value).isEqualTo("onload");
407
wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler"));
408
}
409
410
@Test
411
@Ignore(value = CHROME, reason = "Hangs")
412
@Ignore(value = EDGE, reason = "Hangs")
413
@Ignore(SAFARI)
414
@NoDriverAfterTest
415
public void testShouldNotHandleAlertInAnotherWindow() {
416
String pageWithOnLoad =
417
appServer.create(
418
new Page()
419
.withOnLoad("javascript:alert(\"onload\")")
420
.withBody("<p>Page with onload event handler</p>"));
421
driver.get(
422
appServer.create(
423
new Page()
424
.withBody(
425
String.format(
426
"<a id='open-new-window' href='%s' target='newwindow'>open new window</a>",
427
pageWithOnLoad))));
428
429
Set<String> currentWindowHandles = driver.getWindowHandles();
430
driver.findElement(By.id("open-new-window")).click();
431
wait.until(newWindowIsOpened(currentWindowHandles));
432
433
assertThatExceptionOfType(TimeoutException.class)
434
.isThrownBy(() -> wait.until(alertIsPresent()));
435
}
436
437
@Test
438
@Ignore(
439
value = FIREFOX,
440
reason = "Per spec, an error data dictionary with text value is optional")
441
public void testIncludesAlertTextInUnhandledAlertException() {
442
driver.get(alertPage("cheese"));
443
444
driver.findElement(By.id("alert")).click();
445
wait.until(alertIsPresent());
446
447
assertThatExceptionOfType(UnhandledAlertException.class)
448
.isThrownBy(driver::getTitle)
449
.withMessageContaining("cheese")
450
.satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese"));
451
}
452
453
@NoDriverAfterTest
454
@Test
455
void testCanQuitWhenAnAlertIsPresent() {
456
driver.get(alertPage("cheese"));
457
458
driver.findElement(By.id("alert")).click();
459
wait.until(alertIsPresent());
460
461
assertThatCode(() -> driver.quit()).doesNotThrowAnyException();
462
}
463
464
@Test
465
void shouldHandleAlertOnFormSubmit() {
466
driver.get(
467
appServer.create(
468
new Page()
469
.withTitle("Testing Alerts")
470
.withBody(
471
"<form id='theForm'"
472
+ " action='/click_tests/submitted_page.html' "
473
+ " onsubmit='return alert(\"Tasty cheese\");'>",
474
"<input id='unused' type='submit' value='Submit'>",
475
"</form>")));
476
477
driver.findElement(By.id("theForm")).submit();
478
Alert alert = wait.until(alertIsPresent());
479
String value = alert.getText();
480
alert.accept();
481
482
assertThat(value).isEqualTo("Tasty cheese");
483
484
wait.until(titleIs("Submitted Successfully!"));
485
assertThat(driver.getCurrentUrl()).contains("submitted_page.html");
486
}
487
}
488
489