Skip to content

Commit

Permalink
HtmlUnitDriver: basic Alert implementation
Browse files Browse the repository at this point in the history
This adds basic implementation of Alert,
further steps are needed at HtmlUnit
and HtmlUnitDriver sides to fully implement it.

Signed-off-by: Luke Inman-Semerau <luke.semerau@gmail.com>
  • Loading branch information
asashour authored and lukeis committed Jul 15, 2015
1 parent c3bd000 commit 8977ac6
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 29 deletions.
98 changes: 98 additions & 0 deletions java/client/src/org/openqa/selenium/htmlunit/HtmlUnitAlert.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.htmlunit;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import org.apache.http.auth.Credentials;
import org.openqa.selenium.Alert;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoAlertPresentException;

import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.Page;

class HtmlUnitAlert implements Alert, AlertHandler {

private HtmlUnitDriver driver;
private Map<Page, Queue<String>> queues = new HashMap<>();

HtmlUnitAlert(HtmlUnitDriver driver) {
this.driver = driver;
driver.getWebClient().setAlertHandler(this);
}

@Override
public void dismiss() {
accept();
}

@Override
public void accept() {
Queue<String> queue = getCurrentQueue();
if (queue == null || queue.poll() == null) {
throw new NoAlertPresentException();
}
}

@Override
public String getText() {
Queue<String> queue = getCurrentQueue();
if (queue != null) {
String text = queue.peek();
if (text != null) {
return text;
}
}
throw new NoAlertPresentException();
}

@Override
public void sendKeys(String keysToSend) {
throw new ElementNotVisibleException("alert is not visible");
}

@Override
public void authenticateUsing(Credentials credentials) {
}

@Override
public void handleAlert(Page page, String message) {
Queue<String> queue = queues.get(page);
if (queue == null) {
queue = new LinkedList<String>();
queues.put(page, queue);
}
queue.add(message);
}

Queue<String> getCurrentQueue() {
return queues.get(driver.getCurrentWindow().getEnclosedPage());
}

/**
* Closes the current window.
*/
void close() {
queues.remove(driver.getCurrentWindow());
}

}
34 changes: 23 additions & 11 deletions java/client/src/org/openqa/selenium/htmlunit/HtmlUnitDriver.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,6 @@
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.NativeArray;
import net.sourceforge.htmlunit.corejs.javascript.NativeObject;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import net.sourceforge.htmlunit.corejs.javascript.Undefined;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
Expand All @@ -51,6 +42,7 @@
import org.openqa.selenium.InvalidCookieDomainException;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.NoSuchWindowException;
Expand All @@ -61,6 +53,7 @@
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.UnableToSetCookieException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
Expand Down Expand Up @@ -121,6 +114,15 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.NativeArray;
import net.sourceforge.htmlunit.corejs.javascript.NativeObject;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import net.sourceforge.htmlunit.corejs.javascript.Undefined;

/**
* An implementation of {@link WebDriver} that drives <a href="http://htmlunit.sourceforge.net/">HtmlUnit</a>,
* which is a headless (GUI-less) browser simulator.
Expand All @@ -132,6 +134,7 @@ public class HtmlUnitDriver implements WebDriver, JavascriptExecutor,

private WebClient webClient;
private WebWindow currentWindow;
private HtmlUnitAlert alert;

// Fictive position just to implement the API
private Point windowPosition = new Point(0, 0);
Expand Down Expand Up @@ -185,6 +188,7 @@ public HtmlUnitDriver(BrowserVersion version, boolean enableJavascript) {
*/
public HtmlUnitDriver(BrowserVersion version) {
webClient = createWebClient(version);
alert = new HtmlUnitAlert(this);
currentWindow = webClient.getCurrentWindow();
initialWindowDimension = new Dimension(currentWindow.getOuterWidth(), currentWindow.getOuterHeight());

Expand Down Expand Up @@ -573,6 +577,9 @@ public String getCurrentUrl() {

@Override
public String getTitle() {
if (alert.getCurrentQueue() != null && alert.getCurrentQueue().peek() != null) {
throw new UnhandledAlertException("Alert found", alert.getCurrentQueue().peek());
}
Page page = lastPage();
if (page == null || !(page instanceof HtmlPage)) {
return null; // no page so there is no title
Expand Down Expand Up @@ -618,6 +625,7 @@ public void close() {

} else {
if (thisWindow != null) {
alert.close();
((TopLevelWindow) thisWindow.getTopWindow()).close();
}
if (getWebClient().getWebWindows().size() == 0) {
Expand All @@ -629,6 +637,7 @@ public void close() {
@Override
public void quit() {
if (webClient != null) {
alert.close();
webClient.close();
webClient = null;
}
Expand Down Expand Up @@ -1310,7 +1319,7 @@ public WebDriver defaultContent() {
public WebElement activeElement() {
Page page = lastPage();
if (page instanceof HtmlPage) {
HtmlElement element = ((HtmlPage) page).getFocusedElement();
DomElement element = ((HtmlPage) page).getFocusedElement();
if (element == null || element instanceof HtmlHtml) {
List<? extends HtmlElement> allBodies =
((HtmlPage) page).getDocumentElement().getHtmlElementsByTagName("body");
Expand All @@ -1327,7 +1336,10 @@ public WebElement activeElement() {

@Override
public Alert alert() {
throw new UnsupportedOperationException("alert()");
if (alert.getCurrentQueue() == null) {
throw new NoAlertPresentException();
}
return alert;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.


package org.openqa.selenium.htmlunit;

import java.io.IOException;
Expand Down Expand Up @@ -263,7 +262,7 @@ public void clear() {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
htmlTextArea.setText("");
} else if (element.getAttribute("contenteditable") != HtmlElement.ATTRIBUTE_NOT_DEFINED) {
} else if (element.getAttribute("contenteditable") != DomElement.ATTRIBUTE_NOT_DEFINED) {
element.setTextContent("");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.


package org.openqa.selenium.htmlunit;

import static org.openqa.selenium.Keys.ENTER;
Expand Down
37 changes: 31 additions & 6 deletions java/client/test/org/openqa/selenium/AlertsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,19 @@
import static org.openqa.selenium.testing.TestUtilities.isFirefox;
import static org.openqa.selenium.testing.TestUtilities.isNativeEventsEnabled;

import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.NeedsLocalEnvironment;
import org.openqa.selenium.testing.NotYetImplemented;
import org.junit.Before;
import org.junit.Test;

import java.util.Set;

@Ignore({HTMLUNIT, PHANTOMJS, SAFARI})
@Ignore({PHANTOMJS, SAFARI})
public class AlertsTest extends JUnit4TestBase {

private WebDriverWait wait;
Expand Down Expand Up @@ -98,6 +98,7 @@ public void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() {
@JavascriptEnabled
@NeedsLocalEnvironment(reason = "Carefully timing based")
@Test
@NotYetImplemented(HTMLUNIT)
public void testShouldGetTextOfAlertOpenedInSetTimeout() throws Exception {
driver.findElement(By.id("slow-alert")).click();

Expand Down Expand Up @@ -127,6 +128,8 @@ public void testShouldAllowUsersToDismissAnAlertManually() {

@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testShouldAllowAUserToAcceptAPrompt() {
driver.findElement(By.id("prompt")).click();

Expand All @@ -139,6 +142,8 @@ public void testShouldAllowAUserToAcceptAPrompt() {

@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testShouldAllowAUserToDismissAPrompt() {
driver.findElement(By.id("prompt")).click();

Expand All @@ -152,6 +157,8 @@ public void testShouldAllowAUserToDismissAPrompt() {
@Ignore(MARIONETTE)
@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testShouldAllowAUserToSetTheValueOfAPrompt() {
driver.findElement(By.id("prompt")).click();

Expand Down Expand Up @@ -191,6 +198,8 @@ public void testShouldAllowTheUserToGetTheTextOfAnAlert() {
}

@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testShouldAllowTheUserToGetTheTextOfAPrompt() {
driver.findElement(By.id("prompt")).click();

Expand Down Expand Up @@ -291,6 +300,8 @@ public void testSwitchingToMissingAlertInAClosedWindowThrows() throws Exception

@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread.")
public void testPromptShouldUseDefaultValueIfNoKeysSent() {
driver.findElement(By.id("prompt-with-default")).click();

Expand All @@ -302,6 +313,8 @@ public void testPromptShouldUseDefaultValueIfNoKeysSent() {

@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testPromptShouldHaveNullValueIfDismissed() {
driver.findElement(By.id("prompt-with-default")).click();

Expand All @@ -314,6 +327,8 @@ public void testPromptShouldHaveNullValueIfDismissed() {
@Ignore(MARIONETTE)
@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: click()/prompt need to run in different threads.")
public void testHandlesTwoAlertsFromOneInteraction() {
wait.until(presenceOfElementLocated(By.id("double-prompt"))).click();

Expand Down Expand Up @@ -359,6 +374,8 @@ public void testShouldHandleAlertOnPageLoadUsingGet() {
@JavascriptEnabled
@Ignore(value = {CHROME, FIREFOX, IE, MARIONETTE}, reason = "IE: fails in versions 6 and 7")
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread, and .click() already changs the current window.")
public void testShouldNotHandleAlertInAnotherWindow() {
String mainWindow = driver.getWindowHandle();
Set<String> currentWindowHandles = driver.getWindowHandles();
Expand Down Expand Up @@ -388,6 +405,8 @@ public void testShouldNotHandleAlertInAnotherWindow() {
@JavascriptEnabled
@Ignore(value = {CHROME})
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread, and .back() already changs the current window.")
public void testShouldHandleAlertOnPageUnload() {
assumeFalse("Firefox 27 does not trigger alerts on unload",
isFirefox(driver) && getFirefoxVersion(driver) >= 27);
Expand All @@ -404,6 +423,8 @@ public void testShouldHandleAlertOnPageUnload() {

@JavascriptEnabled
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread, and .click() already changs the current window.")
public void testShouldHandleAlertOnPageBeforeUnload() {
driver.get(appServer.whereIs("pageWithOnBeforeUnloadMessage.html"));

Expand All @@ -422,6 +443,8 @@ public void testShouldHandleAlertOnPageBeforeUnload() {

@NoDriverAfterTest
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread.")
public void testShouldHandleAlertOnPageBeforeUnloadAtQuit() {
driver.get(appServer.whereIs("pageWithOnBeforeUnloadMessage.html"));

Expand All @@ -436,6 +459,8 @@ public void testShouldHandleAlertOnPageBeforeUnloadAtQuit() {
@JavascriptEnabled
@Ignore(value = {CHROME})
@Test
@NotYetImplemented(value = HTMLUNIT,
reason = "HtmlUnit: runs on the same test thread.")
public void testShouldHandleAlertOnWindowClose() {
if (isFirefox(driver) &&
isNativeEventsEnabled(driver) &&
Expand Down Expand Up @@ -466,7 +491,6 @@ public void testShouldHandleAlertOnWindowClose() {

@JavascriptEnabled
@Ignore(value = {CHROME, MARIONETTE})
@NotYetImplemented(HTMLUNIT)
@Test
public void testIncludesAlertTextInUnhandledAlertException() {
driver.findElement(By.id("alert")).click();
Expand All @@ -482,6 +506,7 @@ public void testIncludesAlertTextInUnhandledAlertException() {

@NoDriverAfterTest
@Test
@Ignore(HTMLUNIT)
public void testCanQuitWhenAnAlertIsPresent() {
driver.get(pages.alertsPage);
driver.findElement(By.id("alert")).click();
Expand Down
Loading

0 comments on commit 8977ac6

Please sign in to comment.