diff --git a/java/src/org/openqa/selenium/support/events/AbstractWebDriverEventListener.java b/java/src/org/openqa/selenium/support/events/AbstractWebDriverEventListener.java deleted file mode 100644 index 64c73ced8fee2..0000000000000 --- a/java/src/org/openqa/selenium/support/events/AbstractWebDriverEventListener.java +++ /dev/null @@ -1,166 +0,0 @@ -// 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.support.events; - -import org.openqa.selenium.By; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; - -/** - * Use this class as base class, if you want to implement a {@link WebDriverEventListener} and are - * only interested in some events. All methods provided by this class have an empty method body. - */ -@Deprecated -public abstract class AbstractWebDriverEventListener implements WebDriverEventListener { - - @Override - public void beforeAlertAccept(WebDriver driver) { - // Do nothing. - } - - @Override - public void afterAlertAccept(WebDriver driver) { - // Do nothing. - } - - @Override - public void afterAlertDismiss(WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeAlertDismiss(WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeNavigateTo(String url, WebDriver driver) { - // Do nothing. - } - - @Override - public void afterNavigateTo(String url, WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeNavigateBack(WebDriver driver) { - // Do nothing. - } - - @Override - public void afterNavigateBack(WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeNavigateForward(WebDriver driver) { - // Do nothing. - } - - @Override - public void afterNavigateForward(WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeNavigateRefresh(WebDriver driver) { - // Do nothing. - } - - @Override - public void afterNavigateRefresh(WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeFindBy(By by, WebElement element, WebDriver driver) { - // Do nothing. - } - - @Override - public void afterFindBy(By by, WebElement element, WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeClickOn(WebElement element, WebDriver driver) { - // Do nothing. - } - - @Override - public void afterClickOn(WebElement element, WebDriver driver) { - // Do nothing. - } - - @Override - public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) { - // Do nothing. - } - - @Override - public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) { - // Do nothing. - } - - @Override - public void beforeScript(String script, WebDriver driver) { - // Do nothing - } - - @Override - public void afterScript(String script, WebDriver driver) { - // Do nothing - } - - @Override - public void afterSwitchToWindow(String windowName, WebDriver driver) { - // Do nothing - } - - @Override - public void beforeSwitchToWindow(String windowName, WebDriver driver) { - // Do nothing - } - - @Override - public void onException(Throwable throwable, WebDriver driver) { - // Do nothing - } - - @Override - public void beforeGetScreenshotAs(OutputType target) { - // Do nothing - } - - @Override - public void afterGetScreenshotAs(OutputType target, X screenshot) { - // Do nothing - } - - @Override - public void beforeGetText(WebElement element, WebDriver driver) { - // Do nothing - } - - @Override - public void afterGetText(WebElement element, WebDriver driver, String text) { - // Do nothing - } -} diff --git a/java/src/org/openqa/selenium/support/events/EventFiringWebDriver.java b/java/src/org/openqa/selenium/support/events/EventFiringWebDriver.java deleted file mode 100644 index adc3477506f51..0000000000000 --- a/java/src/org/openqa/selenium/support/events/EventFiringWebDriver.java +++ /dev/null @@ -1,846 +0,0 @@ -// 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.support.events; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Proxy; -import java.net.URL; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import org.openqa.selenium.Alert; -import org.openqa.selenium.Beta; -import org.openqa.selenium.By; -import org.openqa.selenium.Capabilities; -import org.openqa.selenium.Cookie; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.HasCapabilities; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.Point; -import org.openqa.selenium.Rectangle; -import org.openqa.selenium.SearchContext; -import org.openqa.selenium.TakesScreenshot; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.WindowType; -import org.openqa.selenium.WrapsDriver; -import org.openqa.selenium.WrapsElement; -import org.openqa.selenium.interactions.Coordinates; -import org.openqa.selenium.interactions.Interactive; -import org.openqa.selenium.interactions.Locatable; -import org.openqa.selenium.interactions.Sequence; -import org.openqa.selenium.logging.Logs; - -/** - * A wrapper around an arbitrary {@link WebDriver} instance which supports registering of a {@link - * WebDriverEventListener}, e.g. for logging purposes. - * - * @deprecated Use {@link EventFiringDecorator} and {@link WebDriverListener} instead - */ -@Deprecated -public class EventFiringWebDriver - implements WebDriver, - JavascriptExecutor, - TakesScreenshot, - WrapsDriver, - Interactive, - HasCapabilities { - - private final WebDriver driver; - - private final List eventListeners = new ArrayList<>(); - private final WebDriverEventListener dispatcher = - (WebDriverEventListener) - Proxy.newProxyInstance( - WebDriverEventListener.class.getClassLoader(), - new Class[] {WebDriverEventListener.class}, - (proxy, method, args) -> { - try { - for (WebDriverEventListener eventListener : eventListeners) { - method.invoke(eventListener, args); - } - return null; - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } - }); - - public EventFiringWebDriver(final WebDriver driver) { - Class[] allInterfaces = extractInterfaces(driver); - - this.driver = - (WebDriver) - Proxy.newProxyInstance( - WebDriverEventListener.class.getClassLoader(), - allInterfaces, - (proxy, method, args) -> { - if ("getWrappedDriver".equals(method.getName())) { - return driver; - } - - try { - return method.invoke(driver, args); - } catch (InvocationTargetException e) { - dispatcher.onException(e.getTargetException(), driver); - throw e.getTargetException(); - } - }); - } - - private Class[] extractInterfaces(Object object) { - Set> allInterfaces = new HashSet<>(); - allInterfaces.add(WrapsDriver.class); - if (object instanceof WebElement) { - allInterfaces.add(WrapsElement.class); - } - extractInterfaces(allInterfaces, object.getClass()); - - return allInterfaces.toArray(new Class[0]); - } - - private void extractInterfaces(Set> addTo, Class clazz) { - if (Object.class.equals(clazz)) { - return; // Done - } - - Class[] classes = clazz.getInterfaces(); - addTo.addAll(Arrays.asList(classes)); - extractInterfaces(addTo, clazz.getSuperclass()); - } - - /** - * @param eventListener the event listener to register - * @return this for method chaining. - */ - public EventFiringWebDriver register(WebDriverEventListener eventListener) { - eventListeners.add(eventListener); - return this; - } - - /** - * @param eventListener the event listener to unregister - * @return this for method chaining. - */ - public EventFiringWebDriver unregister(WebDriverEventListener eventListener) { - eventListeners.remove(eventListener); - return this; - } - - @Override - public WebDriver getWrappedDriver() { - if (driver instanceof WrapsDriver) { - return ((WrapsDriver) driver).getWrappedDriver(); - } - return driver; - } - - @Override - public void get(String url) { - dispatcher.beforeNavigateTo(url, driver); - driver.get(url); - dispatcher.afterNavigateTo(url, driver); - } - - @Override - public String getCurrentUrl() { - return driver.getCurrentUrl(); - } - - @Override - public String getTitle() { - return driver.getTitle(); - } - - @Override - public List findElements(By by) { - dispatcher.beforeFindBy(by, null, driver); - List temp = driver.findElements(by); - dispatcher.afterFindBy(by, null, driver); - List result = new ArrayList<>(temp.size()); - for (WebElement element : temp) { - result.add(createWebElement(element)); - } - return result; - } - - @Override - public WebElement findElement(By by) { - dispatcher.beforeFindBy(by, null, driver); - WebElement temp = driver.findElement(by); - dispatcher.afterFindBy(by, temp, driver); - return createWebElement(temp); - } - - @Override - public String getPageSource() { - return driver.getPageSource(); - } - - @Override - public void close() { - driver.close(); - } - - @Override - public void quit() { - driver.quit(); - } - - @Override - public Set getWindowHandles() { - return driver.getWindowHandles(); - } - - @Override - public String getWindowHandle() { - return driver.getWindowHandle(); - } - - @Override - public Object executeScript(String script, Object... args) { - if (driver instanceof JavascriptExecutor) { - dispatcher.beforeScript(script, driver); - Object[] usedArgs = unpackWrappedArgs(args); - Object result = ((JavascriptExecutor) driver).executeScript(script, usedArgs); - dispatcher.afterScript(script, driver); - return wrapResult(result); - } - throw new UnsupportedOperationException( - "Underlying driver instance does not support executing javascript"); - } - - @Override - public Object executeAsyncScript(String script, Object... args) { - if (driver instanceof JavascriptExecutor) { - dispatcher.beforeScript(script, driver); - Object[] usedArgs = unpackWrappedArgs(args); - Object result = ((JavascriptExecutor) driver).executeAsyncScript(script, usedArgs); - dispatcher.afterScript(script, driver); - return result; - } - throw new UnsupportedOperationException( - "Underlying driver instance does not support executing javascript"); - } - - private Object[] unpackWrappedArgs(Object... args) { - // Walk the args: the various drivers expect unpacked versions of the elements - Object[] usedArgs = new Object[args.length]; - for (int i = 0; i < args.length; i++) { - usedArgs[i] = unpackWrappedElement(args[i]); - } - return usedArgs; - } - - private Object unpackWrappedElement(Object arg) { - if (arg instanceof List) { - List aList = (List) arg; - List toReturn = new ArrayList<>(); - for (Object anAList : aList) { - toReturn.add(unpackWrappedElement(anAList)); - } - return toReturn; - } else if (arg instanceof Map) { - Map aMap = (Map) arg; - Map toReturn = new HashMap<>(); - for (Map.Entry entry : aMap.entrySet()) { - toReturn.put(entry.getKey(), unpackWrappedElement(entry.getValue())); - } - return toReturn; - } else if (arg instanceof EventFiringWebElement) { - return ((EventFiringWebElement) arg).getWrappedElement(); - } else { - return arg; - } - } - - private Object wrapResult(Object result) { - if (result instanceof WebElement) { - return new EventFiringWebElement((WebElement) result); - } - if (result instanceof List) { - return ((List) result).stream().map(this::wrapResult).collect(Collectors.toList()); - } - if (result instanceof Map) { - return ((Map) result) - .entrySet().stream() - .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll); - } - - return result; - } - - @Override - public X getScreenshotAs(OutputType target) throws WebDriverException { - if (driver instanceof TakesScreenshot) { - dispatcher.beforeGetScreenshotAs(target); - X screenshot = ((TakesScreenshot) driver).getScreenshotAs(target); - dispatcher.afterGetScreenshotAs(target, screenshot); - return screenshot; - } - - throw new UnsupportedOperationException( - "Underlying driver instance does not support taking screenshots"); - } - - @Override - public TargetLocator switchTo() { - return new EventFiringTargetLocator(driver.switchTo()); - } - - @Override - public Navigation navigate() { - return new EventFiringNavigation(driver.navigate()); - } - - @Override - public Options manage() { - return new EventFiringOptions(driver.manage()); - } - - private WebElement createWebElement(WebElement from) { - return new EventFiringWebElement(from); - } - - @Override - public void perform(Collection actions) { - if (driver instanceof Interactive) { - ((Interactive) driver).perform(actions); - return; - } - throw new UnsupportedOperationException( - "Underlying driver does not implement advanced" + " user interactions yet."); - } - - @Override - public void resetInputState() { - if (driver instanceof Interactive) { - ((Interactive) driver).resetInputState(); - return; - } - throw new UnsupportedOperationException( - "Underlying driver does not implement advanced" + " user interactions yet."); - } - - @Override - public Capabilities getCapabilities() { - if (driver instanceof HasCapabilities) { - return ((HasCapabilities) driver).getCapabilities(); - } - throw new UnsupportedOperationException( - "Underlying driver does not implement getting capabilities yet."); - } - - private class EventFiringWebElement - implements WebElement, WrapsElement, WrapsDriver, org.openqa.selenium.interactions.Locatable { - - private final WebElement element; - private final WebElement underlyingElement; - - private EventFiringWebElement(final WebElement element) { - this.element = - (WebElement) - Proxy.newProxyInstance( - WebDriverEventListener.class.getClassLoader(), - extractInterfaces(element), - (proxy, method, args) -> { - if (method.getName().equals("getWrappedElement")) { - return element; - } - try { - return method.invoke(element, args); - } catch (InvocationTargetException e) { - dispatcher.onException(e.getTargetException(), driver); - throw e.getTargetException(); - } - }); - this.underlyingElement = element; - } - - @Override - public void click() { - dispatcher.beforeClickOn(element, driver); - element.click(); - dispatcher.afterClickOn(element, driver); - } - - @Override - public void submit() { - element.submit(); - } - - @Override - public void sendKeys(CharSequence... keysToSend) { - dispatcher.beforeChangeValueOf(element, driver, keysToSend); - element.sendKeys(keysToSend); - dispatcher.afterChangeValueOf(element, driver, keysToSend); - } - - @Override - public void clear() { - dispatcher.beforeChangeValueOf(element, driver, null); - element.clear(); - dispatcher.afterChangeValueOf(element, driver, null); - } - - @Override - public String getTagName() { - return element.getTagName(); - } - - @Override - public String getDomProperty(String name) { - return element.getDomProperty(name); - } - - @Override - public String getAttribute(String name) { - return element.getAttribute(name); - } - - @Override - public String getAriaRole() { - return element.getAriaRole(); - } - - @Override - public String getAccessibleName() { - return element.getAccessibleName(); - } - - @Override - public String getDomAttribute(String name) { - return element.getDomAttribute(name); - } - - @Override - public boolean isSelected() { - return element.isSelected(); - } - - @Override - public boolean isEnabled() { - return element.isEnabled(); - } - - @Override - public String getText() { - dispatcher.beforeGetText(element, driver); - String text = element.getText(); - dispatcher.afterGetText(element, driver, text); - return text; - } - - @Override - public SearchContext getShadowRoot() { - return element.getShadowRoot(); - } - - @Override - public boolean isDisplayed() { - return element.isDisplayed(); - } - - @Override - public Point getLocation() { - return element.getLocation(); - } - - @Override - public Dimension getSize() { - return element.getSize(); - } - - @Override - public Rectangle getRect() { - return element.getRect(); - } - - @Override - public String getCssValue(String propertyName) { - return element.getCssValue(propertyName); - } - - @Override - public WebElement findElement(By by) { - dispatcher.beforeFindBy(by, element, driver); - WebElement temp = element.findElement(by); - dispatcher.afterFindBy(by, element, driver); - return createWebElement(temp); - } - - @Override - public List findElements(By by) { - dispatcher.beforeFindBy(by, element, driver); - List temp = element.findElements(by); - dispatcher.afterFindBy(by, element, driver); - List result = new ArrayList<>(temp.size()); - for (WebElement element : temp) { - result.add(createWebElement(element)); - } - return result; - } - - @Override - public WebElement getWrappedElement() { - return underlyingElement; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof WebElement)) { - return false; - } - - WebElement other = (WebElement) obj; - if (other instanceof WrapsElement) { - other = ((WrapsElement) other).getWrappedElement(); - } - - return underlyingElement.equals(other); - } - - @Override - public int hashCode() { - return underlyingElement.hashCode(); - } - - @Override - public String toString() { - return underlyingElement.toString(); - } - - @Override - public WebDriver getWrappedDriver() { - return driver; - } - - @Override - public Coordinates getCoordinates() { - return ((Locatable) underlyingElement).getCoordinates(); - } - - @Override - public X getScreenshotAs(OutputType outputType) throws WebDriverException { - return element.getScreenshotAs(outputType); - } - } - - private class EventFiringNavigation implements Navigation { - - private final WebDriver.Navigation navigation; - - EventFiringNavigation(Navigation navigation) { - this.navigation = navigation; - } - - @Override - public void to(String url) { - dispatcher.beforeNavigateTo(url, driver); - navigation.to(url); - dispatcher.afterNavigateTo(url, driver); - } - - @Override - public void to(URL url) { - to(String.valueOf(url)); - } - - @Override - public void back() { - dispatcher.beforeNavigateBack(driver); - navigation.back(); - dispatcher.afterNavigateBack(driver); - } - - @Override - public void forward() { - dispatcher.beforeNavigateForward(driver); - navigation.forward(); - dispatcher.afterNavigateForward(driver); - } - - @Override - public void refresh() { - dispatcher.beforeNavigateRefresh(driver); - navigation.refresh(); - dispatcher.afterNavigateRefresh(driver); - } - } - - private class EventFiringOptions implements Options { - - private Options options; - - private EventFiringOptions(Options options) { - this.options = options; - } - - @Override - public Logs logs() { - return options.logs(); - } - - @Override - public void addCookie(Cookie cookie) { - options.addCookie(cookie); - } - - @Override - public void deleteCookieNamed(String name) { - options.deleteCookieNamed(name); - } - - @Override - public void deleteCookie(Cookie cookie) { - options.deleteCookie(cookie); - } - - @Override - public void deleteAllCookies() { - options.deleteAllCookies(); - } - - @Override - public Set getCookies() { - return options.getCookies(); - } - - @Override - public Cookie getCookieNamed(String name) { - return options.getCookieNamed(name); - } - - @Override - public Timeouts timeouts() { - return new EventFiringTimeouts(options.timeouts()); - } - - @Override - @Beta - public Window window() { - return new EventFiringWindow(options.window()); - } - } - - private class EventFiringTimeouts implements Timeouts { - - private final Timeouts timeouts; - - EventFiringTimeouts(Timeouts timeouts) { - this.timeouts = timeouts; - } - - @Deprecated - @Override - public Timeouts implicitlyWait(long time, TimeUnit unit) { - return implicitlyWait(Duration.ofMillis(unit.toMillis(time))); - } - - @Override - public Timeouts implicitlyWait(Duration duration) { - timeouts.implicitlyWait(duration); - return this; - } - - @Override - public Duration getImplicitWaitTimeout() { - return timeouts.getImplicitWaitTimeout(); - } - - @Deprecated - @Override - public Timeouts setScriptTimeout(long time, TimeUnit unit) { - return setScriptTimeout(Duration.ofMillis(unit.toMillis(time))); - } - - @Deprecated - @Override - public Timeouts setScriptTimeout(Duration duration) { - timeouts.setScriptTimeout(duration); - return this; - } - - @Override - public Duration getScriptTimeout() { - return timeouts.getScriptTimeout(); - } - - @Deprecated - @Override - public Timeouts pageLoadTimeout(long time, TimeUnit unit) { - return pageLoadTimeout(Duration.ofMillis(unit.toMillis(time))); - } - - @Override - public Timeouts pageLoadTimeout(Duration duration) { - timeouts.pageLoadTimeout(duration); - return this; - } - - @Override - public Duration getPageLoadTimeout() { - return timeouts.getPageLoadTimeout(); - } - } - - private class EventFiringTargetLocator implements TargetLocator { - - private TargetLocator targetLocator; - - private EventFiringTargetLocator(TargetLocator targetLocator) { - this.targetLocator = targetLocator; - } - - @Override - public WebDriver frame(int frameIndex) { - return targetLocator.frame(frameIndex); - } - - @Override - public WebDriver frame(String frameName) { - return targetLocator.frame(frameName); - } - - @Override - public WebDriver frame(WebElement frameElement) { - return targetLocator.frame(frameElement); - } - - @Override - public WebDriver parentFrame() { - return targetLocator.parentFrame(); - } - - @Override - public WebDriver window(String windowName) { - dispatcher.beforeSwitchToWindow(windowName, driver); - WebDriver driverToReturn = targetLocator.window(windowName); - dispatcher.afterSwitchToWindow(windowName, driver); - return driverToReturn; - } - - @Override - public WebDriver newWindow(WindowType typeHint) { - dispatcher.beforeSwitchToWindow(null, driver); - WebDriver driverToReturn = targetLocator.newWindow(typeHint); - dispatcher.afterSwitchToWindow(null, driver); - return driverToReturn; - } - - @Override - public WebDriver defaultContent() { - return targetLocator.defaultContent(); - } - - @Override - public WebElement activeElement() { - return targetLocator.activeElement(); - } - - @Override - public Alert alert() { - return new EventFiringAlert(this.targetLocator.alert()); - } - } - - @Beta - private class EventFiringWindow implements Window { - private final Window window; - - EventFiringWindow(Window window) { - this.window = window; - } - - @Override - public void setSize(Dimension targetSize) { - window.setSize(targetSize); - } - - @Override - public void setPosition(Point targetLocation) { - window.setPosition(targetLocation); - } - - @Override - public Dimension getSize() { - return window.getSize(); - } - - @Override - public Point getPosition() { - return window.getPosition(); - } - - @Override - public void maximize() { - window.maximize(); - } - - @Override - public void minimize() { - window.minimize(); - } - - @Override - public void fullscreen() { - window.fullscreen(); - } - } - - private class EventFiringAlert implements Alert { - private final Alert alert; - - private EventFiringAlert(Alert alert) { - this.alert = alert; - } - - @Override - public void dismiss() { - dispatcher.beforeAlertDismiss(driver); - alert.dismiss(); - dispatcher.afterAlertDismiss(driver); - } - - @Override - public void accept() { - dispatcher.beforeAlertAccept(driver); - alert.accept(); - dispatcher.afterAlertAccept(driver); - } - - @Override - public String getText() { - return alert.getText(); - } - - @Override - public void sendKeys(String keysToSend) { - alert.sendKeys(keysToSend); - } - } -} diff --git a/java/src/org/openqa/selenium/support/events/WebDriverEventListener.java b/java/src/org/openqa/selenium/support/events/WebDriverEventListener.java deleted file mode 100644 index 3280d20b557a4..0000000000000 --- a/java/src/org/openqa/selenium/support/events/WebDriverEventListener.java +++ /dev/null @@ -1,271 +0,0 @@ -// 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.support.events; - -import org.openqa.selenium.Alert; -import org.openqa.selenium.By; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.WindowType; - -/** - * @deprecated Use {@link EventFiringDecorator} and {@link WebDriverListener} instead - */ -@Deprecated -public interface WebDriverEventListener { - - /** - * This action will be performed each time before {@link Alert#accept()} - * - * @param driver WebDriver - */ - void beforeAlertAccept(WebDriver driver); - - /** - * This action will be performed each time after {@link Alert#accept()} - * - * @param driver WebDriver - */ - void afterAlertAccept(WebDriver driver); - - /** - * This action will be performed each time before {@link Alert#dismiss()} - * - * @param driver WebDriver - */ - void afterAlertDismiss(WebDriver driver); - - /** - * This action will be performed each time after {@link Alert#dismiss()} - * - * @param driver WebDriver - */ - void beforeAlertDismiss(WebDriver driver); - - /** - * Called before {@link org.openqa.selenium.WebDriver#get get(String url)} respectively {@link - * org.openqa.selenium.WebDriver.Navigation#to navigate().to(String url)}. - * - * @param url URL - * @param driver WebDriver - */ - void beforeNavigateTo(String url, WebDriver driver); - - /** - * Called after {@link org.openqa.selenium.WebDriver#get get(String url)} respectively {@link - * org.openqa.selenium.WebDriver.Navigation#to navigate().to(String url)}. Not called, if an - * exception is thrown. - * - * @param url URL - * @param driver WebDriver - */ - void afterNavigateTo(String url, WebDriver driver); - - /** - * Called before {@link org.openqa.selenium.WebDriver.Navigation#back navigate().back()}. - * - * @param driver WebDriver - */ - void beforeNavigateBack(WebDriver driver); - - /** - * Called after {@link org.openqa.selenium.WebDriver.Navigation navigate().back()}. Not called, if - * an exception is thrown. - * - * @param driver WebDriver - */ - void afterNavigateBack(WebDriver driver); - - /** - * Called before {@link org.openqa.selenium.WebDriver.Navigation#forward navigate().forward()}. - * - * @param driver WebDriver - */ - void beforeNavigateForward(WebDriver driver); - - /** - * Called after {@link org.openqa.selenium.WebDriver.Navigation#forward navigate().forward()}. Not - * called, if an exception is thrown. - * - * @param driver WebDriver - */ - void afterNavigateForward(WebDriver driver); - - /** - * Called before {@link org.openqa.selenium.WebDriver.Navigation#refresh navigate().refresh()}. - * - * @param driver WebDriver - */ - void beforeNavigateRefresh(WebDriver driver); - - /** - * Called after {@link org.openqa.selenium.WebDriver.Navigation#refresh navigate().refresh()}. Not - * called, if an exception is thrown. - * - * @param driver WebDriver - */ - void afterNavigateRefresh(WebDriver driver); - - /** - * Called before {@link WebDriver#findElement WebDriver.findElement(...)}, or {@link - * WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement - * WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}. - * - * @param element will be null, if a find method of WebDriver is called. - * @param by locator being used - * @param driver WebDriver - */ - void beforeFindBy(By by, WebElement element, WebDriver driver); - - /** - * Called after {@link WebDriver#findElement WebDriver.findElement(...)}, or {@link - * WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement - * WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}. - * - * @param element will be null, if a find method of WebDriver is called. - * @param by locator being used - * @param driver WebDriver - */ - void afterFindBy(By by, WebElement element, WebDriver driver); - - /** - * Called before {@link WebElement#click WebElement.click()}. - * - * @param driver WebDriver - * @param element the WebElement being used for the action - */ - void beforeClickOn(WebElement element, WebDriver driver); - - /** - * Called after {@link WebElement#click WebElement.click()}. Not called, if an exception is - * thrown. - * - * @param driver WebDriver - * @param element the WebElement being used for the action - */ - void afterClickOn(WebElement element, WebDriver driver); - - /** - * Called before {@link WebElement#clear WebElement.clear()}, {@link WebElement#sendKeys - * WebElement.sendKeys(...)}. - * - * @param driver WebDriver - * @param element the WebElement being used for the action - */ - void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend); - - /** - * Called after {@link WebElement#clear WebElement.clear()}, {@link WebElement#sendKeys - * WebElement.sendKeys(...)}}. Not called, if an exception is thrown. - * - * @param driver WebDriver - * @param element the WebElement being used for the action - */ - void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend); - - /** - * Called before {@link org.openqa.selenium.remote.RemoteWebDriver#executeScript(String, - * Object...)} - * - * @param driver WebDriver - * @param script the script to be executed - */ - // Previously: Called before {@link WebDriver#executeScript(String)} - // See the same issue below. - void beforeScript(String script, WebDriver driver); - - /** - * Called after {@link org.openqa.selenium.remote.RemoteWebDriver#executeScript(String, - * Object...)}. Not called if an exception is thrown - * - * @param driver WebDriver - * @param script the script that was executed - */ - // Previously: Called after {@link WebDriver#executeScript(String)}. Not called if an exception is - // thrown - // So someone should check if this is right. There is no executeScript method - // in WebDriver, but there is in several other places, like this one - void afterScript(String script, WebDriver driver); - - /** - * This action will be performed each time before {@link - * org.openqa.selenium.WebDriver.TargetLocator#window(String)} - * - * @param windowName The name of the window or the handle as returned by {@link - * org.openqa.selenium.WebDriver#getWindowHandle()} or null if switching to a new - * window created by {@link org.openqa.selenium.WebDriver.TargetLocator#newWindow(WindowType)} - * @param driver WebDriver - */ - void beforeSwitchToWindow(String windowName, WebDriver driver); - - /** - * This action will be performed each time after {@link - * org.openqa.selenium.WebDriver.TargetLocator#window(String)} - * - * @param windowName The name of the window or the handle as returned by {@link - * org.openqa.selenium.WebDriver#getWindowHandle()} or null if switching to a new - * window created by {@link org.openqa.selenium.WebDriver.TargetLocator#newWindow(WindowType)} - * @param driver WebDriver - */ - void afterSwitchToWindow(String windowName, WebDriver driver); - - /** - * Called whenever an exception would be thrown. - * - * @param driver WebDriver - * @param throwable the exception that will be thrown - */ - void onException(Throwable throwable, WebDriver driver); - - /** - * Called before {@link org.openqa.selenium.TakesScreenshot#getScreenshotAs(OutputType)} allows - * the implementation to determine which type of output will be generated - * - * @param Return type for getScreenshotAs. - * @param target target type, @see OutputType - */ - void beforeGetScreenshotAs(OutputType target); - - /** - * Called after {@link org.openqa.selenium.TakesScreenshot#getScreenshotAs(OutputType)} allows the - * implementation to determine which type of output was generated and to access the output itself - * - * @param Return type for getScreenshotAs. - * @param target target type, @see OutputType - * @param screenshot screenshot output of the specified type - */ - void afterGetScreenshotAs(OutputType target, X screenshot); - - /** - * Called before {@link WebElement#getText()} method is being called - * - * @param element - {@link WebElement} against which call is being made - * @param driver - instance of {@link WebDriver} - */ - void beforeGetText(WebElement element, WebDriver driver); - - /** - * Called right after {@link WebElement#getText()} method is being called - * - * @param element - {@link WebElement} against which call is being made - * @param driver - instance of {@link WebDriver} - * @param text - {@link String} object extracted from respective {@link WebElement} - */ - void afterGetText(WebElement element, WebDriver driver, String text); -} diff --git a/java/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java b/java/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java deleted file mode 100644 index f3906497e0079..0000000000000 --- a/java/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java +++ /dev/null @@ -1,524 +0,0 @@ -// 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.support.events; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; - -import com.google.common.collect.ImmutableMap; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; -import org.openqa.selenium.Alert; -import org.openqa.selenium.By; -import org.openqa.selenium.Capabilities; -import org.openqa.selenium.HasCapabilities; -import org.openqa.selenium.ImmutableCapabilities; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.NoSuchElementException; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.StubDriver; -import org.openqa.selenium.TakesScreenshot; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriver.Navigation; -import org.openqa.selenium.WebDriver.TargetLocator; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.WrapsDriver; -import org.openqa.selenium.WrapsElement; - -@Tag("UnitTests") -class EventFiringWebDriverTest { - - @Test - void alertEvents() { - final WebDriver mockedDriver = mock(WebDriver.class); - final Alert mockedAlert = mock(Alert.class); - final WebDriver.TargetLocator mockedTargetLocator = mock(WebDriver.TargetLocator.class); - - when(mockedDriver.switchTo()).thenReturn(mockedTargetLocator); - when(mockedTargetLocator.alert()).thenReturn(mockedAlert); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - testedDriver.switchTo().alert().accept(); - testedDriver.switchTo().alert().dismiss(); - - InOrder order = Mockito.inOrder(mockedDriver, mockedAlert, listener); - order.verify(mockedDriver).switchTo(); - order.verify(listener).beforeAlertAccept(any(WebDriver.class)); - order.verify(mockedAlert).accept(); - order.verify(listener).afterAlertAccept(any(WebDriver.class)); - order.verify(mockedDriver).switchTo(); - order.verify(listener).beforeAlertDismiss(any(WebDriver.class)); - order.verify(mockedAlert).dismiss(); - order.verify(listener).afterAlertDismiss(any(WebDriver.class)); - verifyNoMoreInteractions(mockedDriver, mockedAlert, listener); - } - - @Test - void navigationEvents() { - final WebDriver mockedDriver = mock(WebDriver.class); - final Navigation mockedNavigation = mock(Navigation.class); - - when(mockedDriver.navigate()).thenReturn(mockedNavigation); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - testedDriver.get("http://www.get.com"); - testedDriver.navigate().to("http://www.navigate-to.com"); - testedDriver.navigate().back(); - testedDriver.navigate().forward(); - testedDriver.navigate().refresh(); - - InOrder order = Mockito.inOrder(mockedDriver, mockedNavigation, listener); - order.verify(listener).beforeNavigateTo(eq("http://www.get.com"), any(WebDriver.class)); - order.verify(mockedDriver).get("http://www.get.com"); - order.verify(listener).afterNavigateTo(eq("http://www.get.com"), any(WebDriver.class)); - order.verify(mockedDriver).navigate(); - order.verify(listener).beforeNavigateTo(eq("http://www.navigate-to.com"), any(WebDriver.class)); - order.verify(mockedNavigation).to("http://www.navigate-to.com"); - order.verify(listener).afterNavigateTo(eq("http://www.navigate-to.com"), any(WebDriver.class)); - order.verify(mockedDriver).navigate(); - order.verify(listener).beforeNavigateBack(any(WebDriver.class)); - order.verify(mockedNavigation).back(); - order.verify(listener).afterNavigateBack(any(WebDriver.class)); - order.verify(mockedDriver).navigate(); - order.verify(listener).beforeNavigateForward(any(WebDriver.class)); - order.verify(mockedNavigation).forward(); - order.verify(listener).afterNavigateForward(any(WebDriver.class)); - order.verify(mockedDriver).navigate(); - order.verify(listener).beforeNavigateRefresh(any(WebDriver.class)); - order.verify(mockedNavigation).refresh(); - order.verify(listener).afterNavigateRefresh(any(WebDriver.class)); - verifyNoMoreInteractions(mockedDriver, mockedNavigation, listener); - } - - @Test - void clickEvent() { - final WebDriver mockedDriver = mock(WebDriver.class); - final WebElement mockedElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.name("foo"))).thenReturn(mockedElement); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - testedDriver.findElement(By.name("foo")).click(); - - InOrder order = Mockito.inOrder(mockedDriver, mockedElement, listener); - order.verify(listener).beforeFindBy(eq(By.name("foo")), eq(null), any(WebDriver.class)); - order.verify(mockedDriver).findElement(By.name("foo")); - order.verify(listener).afterFindBy(eq(By.name("foo")), eq(mockedElement), any(WebDriver.class)); - order.verify(listener).beforeClickOn(any(WebElement.class), any(WebDriver.class)); - order.verify(mockedElement).click(); - order.verify(listener).afterClickOn(any(WebElement.class), any(WebDriver.class)); - verifyNoMoreInteractions(mockedDriver, mockedElement, listener); - } - - @Test - void windowEvent() { - String windowName = "Window name"; - WebDriver mockedDriver = mock(WebDriver.class); - TargetLocator mockedTargetLocator = mock(TargetLocator.class); - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - when(mockedDriver.switchTo()).thenReturn(mockedTargetLocator); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - testedDriver.switchTo().window(windowName); - - InOrder order = Mockito.inOrder(mockedTargetLocator, listener); - order.verify(listener).beforeSwitchToWindow(eq(windowName), any(WebDriver.class)); - order.verify(mockedTargetLocator).window(windowName); - order.verify(listener).afterSwitchToWindow(eq(windowName), any(WebDriver.class)); - verifyNoMoreInteractions(mockedTargetLocator, listener); - } - - @Test - void changeValueEvent() { - final WebDriver mockedDriver = mock(WebDriver.class); - final WebElement mockedElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.name("foo"))).thenReturn(mockedElement); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - String someText = "some text"; - - testedDriver.findElement(By.name("foo")).clear(); - testedDriver.findElement(By.name("foo")).sendKeys(someText); - - InOrder order = Mockito.inOrder(mockedElement, listener); - order - .verify(listener) - .beforeChangeValueOf(any(WebElement.class), any(WebDriver.class), eq(null)); - order.verify(mockedElement).clear(); - order - .verify(listener) - .afterChangeValueOf(any(WebElement.class), any(WebDriver.class), eq(null)); - order - .verify(listener) - .beforeChangeValueOf( - any(WebElement.class), any(WebDriver.class), eq(new CharSequence[] {someText})); - order.verify(mockedElement).sendKeys(someText); - order - .verify(listener) - .afterChangeValueOf( - any(WebElement.class), any(WebDriver.class), eq(new CharSequence[] {someText})); - - verify(mockedDriver, times(2)).findElement(By.name("foo")); - verify(listener, times(2)).beforeFindBy(eq(By.name("foo")), eq(null), any(WebDriver.class)); - verify(listener, times(2)) - .afterFindBy(eq(By.name("foo")), eq(mockedElement), any(WebDriver.class)); - verifyNoMoreInteractions(mockedDriver, mockedElement, listener); - } - - @Test - void findByEvent() { - final WebDriver mockedDriver = mock(WebDriver.class); - final WebElement mockedElement = mock(WebElement.class); - final WebElement mockedChildElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.id("foo"))).thenReturn(mockedElement); - when(mockedElement.findElement(any())).thenReturn(mockedChildElement); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - WebElement element = testedDriver.findElement(By.id("foo")); - element.findElement(By.linkText("bar")); - element.findElements(By.name("xyz")); - testedDriver.findElements(By.xpath("//link[@type = 'text/css']")); - - InOrder order = Mockito.inOrder(mockedElement, mockedDriver, listener); - verify(listener).beforeFindBy(eq(By.id("foo")), eq(null), any(WebDriver.class)); - order.verify(mockedDriver).findElement(By.id("foo")); - verify(listener).afterFindBy(eq(By.id("foo")), eq(mockedElement), any(WebDriver.class)); - verify(listener) - .beforeFindBy(eq(By.linkText("bar")), any(WebElement.class), any(WebDriver.class)); - order.verify(mockedElement).findElement(By.linkText("bar")); - verify(listener) - .afterFindBy(eq(By.linkText("bar")), any(WebElement.class), any(WebDriver.class)); - verify(listener).beforeFindBy(eq(By.name("xyz")), any(WebElement.class), any(WebDriver.class)); - order.verify(mockedElement).findElements(By.name("xyz")); - verify(listener).afterFindBy(eq(By.name("xyz")), any(WebElement.class), any(WebDriver.class)); - verify(listener) - .beforeFindBy(eq(By.xpath("//link[@type = 'text/css']")), eq(null), any(WebDriver.class)); - order.verify(mockedDriver).findElements(By.xpath("//link[@type = 'text/css']")); - verify(listener) - .afterFindBy(eq(By.xpath("//link[@type = 'text/css']")), eq(null), any(WebDriver.class)); - verifyNoMoreInteractions(mockedElement, mockedDriver, listener); - } - - @Test - void shouldCallListenersWhenAnExceptionIsThrown() { - final WebDriver mockedDriver = mock(WebDriver.class); - - final NoSuchElementException exception = new NoSuchElementException("argh"); - - when(mockedDriver.findElement(By.id("foo"))).thenThrow(exception); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - assertThatExceptionOfType(NoSuchElementException.class) - .isThrownBy(() -> testedDriver.findElement(By.id("foo"))); - - InOrder order = Mockito.inOrder(mockedDriver, listener); - order.verify(listener).beforeFindBy(eq(By.id("foo")), eq(null), any(WebDriver.class)); - order.verify(mockedDriver).findElement(By.id("foo")); - order.verify(listener).onException(any(NoSuchElementException.class), any(WebDriver.class)); - verifyNoMoreInteractions(mockedDriver, listener); - } - - @Test - void shouldUnpackElementArgsWhenCallingScripts() { - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - final WebElement stubbedElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.id("foo"))).thenReturn(stubbedElement); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - testedDriver.register(new AbstractWebDriverEventListener() {}); - - WebElement element = testedDriver.findElement(By.id("foo")); - testedDriver.executeScript("foo", element); - verify((JavascriptExecutor) mockedDriver).executeScript("foo", element); - } - - @Test - void shouldWrapElementFoundWhenCallingScripts() { - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - final WebElement stubbedElement = mock(WebElement.class); - - when(((JavascriptExecutor) mockedDriver).executeScript("foo")).thenReturn(stubbedElement); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - - Object res = testedDriver.executeScript("foo"); - verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res).isInstanceOf(WebElement.class).isInstanceOf(WrapsElement.class); - assertThat(((WrapsElement) res).getWrappedElement()).isSameAs(stubbedElement); - } - - @Test - void testShouldUnpackListOfElementArgsWhenCallingScripts() { - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - final WebElement mockElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.id("foo"))).thenReturn(mockElement); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - testedDriver.register(new AbstractWebDriverEventListener() {}); - - final WebElement foundElement = testedDriver.findElement(By.id("foo")); - assertThat(foundElement).isInstanceOf(WrapsElement.class); - assertThat(((WrapsElement) foundElement).getWrappedElement()).isSameAs(mockElement); - - List args = Arrays.asList("before", foundElement, "after"); - - testedDriver.executeScript("foo", args); - - verify((JavascriptExecutor) mockedDriver).executeScript("foo", args); - } - - @Test - void shouldWrapMultipleElementsFoundWhenCallingScripts() { - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - final WebElement stubbedElement1 = mock(WebElement.class); - final WebElement stubbedElement2 = mock(WebElement.class); - - when(((JavascriptExecutor) mockedDriver).executeScript("foo")) - .thenReturn(Arrays.asList(stubbedElement1, stubbedElement2)); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - - Object res = testedDriver.executeScript("foo"); - verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res).isInstanceOf(List.class); - List resList = (List) res; - resList.forEach(el -> assertThat(el).isInstanceOf(WrapsElement.class)); - assertThat(((WrapsElement) resList.get(0)).getWrappedElement()).isSameAs(stubbedElement1); - assertThat(((WrapsElement) resList.get(1)).getWrappedElement()).isSameAs(stubbedElement2); - } - - @Test - void shouldWrapMapsWithNullValues() { - Map map = new HashMap<>(); - map.put("a", null); - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - when(((JavascriptExecutor) mockedDriver).executeScript("foo")).thenReturn(map); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - - Object res = testedDriver.executeScript("foo"); - verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res).isInstanceOf(Map.class); - assertThat(((Map) res).get("a")).isNull(); - } - - @Test - void testShouldUnpackMapOfElementArgsWhenCallingScripts() { - final WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class)); - final WebElement mockElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.id("foo"))).thenReturn(mockElement); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - testedDriver.register(mock(WebDriverEventListener.class)); - - final WebElement foundElement = testedDriver.findElement(By.id("foo")); - assertThat(foundElement).isInstanceOf(WrapsElement.class); - assertThat(((WrapsElement) foundElement).getWrappedElement()).isSameAs(mockElement); - - ImmutableMap args = - ImmutableMap.of( - "foo", - "bar", - "element", - foundElement, - "nested", - Arrays.asList("before", foundElement, "after")); - - testedDriver.executeScript("foo", args); - - verify((JavascriptExecutor) mockedDriver).executeScript("foo", args); - } - - @Test - void shouldBeAbleToWrapSubclassesOfSomethingImplementingTheWebDriverInterface() { - new EventFiringWebDriver(new ChildDriver()); - // We should get this far - } - - @Test - void shouldBeAbleToAccessWrappedInstanceFromEventCalls() { - final WebDriver stub = mock(WebDriver.class); - EventFiringWebDriver driver = new EventFiringWebDriver(stub); - WebDriver wrapped = driver.getWrappedDriver(); - assertThat(wrapped).isEqualTo(stub); - - class MyListener extends AbstractWebDriverEventListener { - @Override - public void beforeNavigateTo(String url, WebDriver driver) { - WebDriver unwrapped = ((WrapsDriver) driver).getWrappedDriver(); - - assertThat(unwrapped).isEqualTo(stub); - } - } - - driver.register(new MyListener()); - - driver.get("http://example.org"); - } - - @Test - void shouldBeAbleToAccessWrappedElementInstanceFromEventCalls() { - final WebElement stubElement = mock(WebElement.class); - - final WebDriver stubDriver = mock(WebDriver.class); - when(stubDriver.findElement(By.name("stub"))).thenReturn(stubElement); - - EventFiringWebDriver driver = new EventFiringWebDriver(stubDriver); - - class MyListener extends AbstractWebDriverEventListener { - @Override - public void beforeClickOn(WebElement element, WebDriver driver) { - assertThat(((WrapsElement) element).getWrappedElement()).isEqualTo(stubElement); - } - } - - driver.register(new MyListener()); - - driver.findElement(By.name("stub")).click(); - } - - @Test - void shouldReturnLocatorFromToStringMethod() { - final WebElement stubElement = mock(WebElement.class); - when(stubElement.toString()).thenReturn("cheese"); - - final WebDriver driver = mock(WebDriver.class); - when(driver.findElement(By.id("ignored"))).thenReturn(stubElement); - - EventFiringWebDriver firingDriver = new EventFiringWebDriver(driver); - WebElement firingElement = firingDriver.findElement(By.id("ignored")); - - assertThat(firingElement.toString()).isEqualTo(stubElement.toString()); - } - - private static class ChildDriver extends StubDriver {} - - @Test - void getScreenshotAs() { - final String DATA = "data"; - WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(TakesScreenshot.class)); - WebDriverEventListener listener = mock(WebDriverEventListener.class); - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - doReturn(DATA).when((TakesScreenshot) mockedDriver).getScreenshotAs(OutputType.BASE64); - - String screenshot = ((TakesScreenshot) testedDriver).getScreenshotAs(OutputType.BASE64); - assertThat(screenshot).isEqualTo(DATA); - - InOrder order = Mockito.inOrder(mockedDriver, listener); - order.verify(listener).beforeGetScreenshotAs(OutputType.BASE64); - order.verify((TakesScreenshot) mockedDriver).getScreenshotAs(OutputType.BASE64); - order.verify(listener).afterGetScreenshotAs(OutputType.BASE64, screenshot); - verifyNoMoreInteractions(mockedDriver, listener); - } - - @Test - void shouldFireEventsAroundGetText() { - final String SAMPLE = "Sample text"; - final WebDriver mockedDriver = mock(WebDriver.class); - final WebElement mockedElement = mock(WebElement.class); - - when(mockedDriver.findElement(By.name("foo"))).thenReturn(mockedElement); - when(mockedElement.getText()).thenReturn(SAMPLE); - - WebDriverEventListener listener = mock(WebDriverEventListener.class); - - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - - String text = testedDriver.findElement(By.name("foo")).getText(); - assertThat(text).isEqualTo(SAMPLE); - - InOrder order = Mockito.inOrder(mockedDriver, mockedElement, listener); - order.verify(listener).beforeFindBy(eq(By.name("foo")), eq(null), any(WebDriver.class)); - order.verify(mockedDriver).findElement(By.name("foo")); - order.verify(listener).afterFindBy(eq(By.name("foo")), eq(mockedElement), any(WebDriver.class)); - order.verify(listener).beforeGetText(any(WebElement.class), any(WebDriver.class)); - order.verify(mockedElement).getText(); - order.verify(listener).afterGetText(any(WebElement.class), any(WebDriver.class), eq(text)); - verifyNoMoreInteractions(mockedDriver, mockedElement, listener); - } - - @Test - void shouldReturnCapabilitiesWhenUnderlyingDriverImplementsInterface() { - WebDriver mockedDriver = - mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class)); - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - - final Capabilities caps = new ImmutableCapabilities(); - when(((HasCapabilities) mockedDriver).getCapabilities()).thenReturn(caps); - - assertThat(testedDriver.getCapabilities()).isSameAs(caps); - } - - @Test - void shouldThrowExceptionWhenUnderlyingDriverDoesNotImplementInterface() { - WebDriver mockedDriver = mock(WebDriver.class); - EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - - assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(testedDriver::getCapabilities) - .withMessage("Underlying driver does not implement getting capabilities yet."); - } -}