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