How to use Interface Decorated class of org.openqa.selenium.support.decorators package

Best Selenium code snippet using org.openqa.selenium.support.decorators.Interface Decorated

Source:AugmenterTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote;18import com.google.common.collect.ImmutableMap;19import org.junit.Test;20import org.junit.experimental.categories.Category;21import org.openqa.selenium.By;22import org.openqa.selenium.Capabilities;23import org.openqa.selenium.HasCapabilities;24import org.openqa.selenium.ImmutableCapabilities;25import org.openqa.selenium.NoSuchElementException;26import org.openqa.selenium.Rotatable;27import org.openqa.selenium.ScreenOrientation;28import org.openqa.selenium.SearchContext;29import org.openqa.selenium.WebDriver;30import org.openqa.selenium.WebElement;31import org.openqa.selenium.firefox.FirefoxOptions;32import org.openqa.selenium.html5.LocationContext;33import org.openqa.selenium.html5.WebStorage;34import org.openqa.selenium.internal.Require;35import org.openqa.selenium.support.decorators.Decorated;36import org.openqa.selenium.support.decorators.WebDriverDecorator;37import org.openqa.selenium.testing.UnitTests;38import java.lang.reflect.Method;39import java.util.ArrayList;40import java.util.Collections;41import java.util.HashMap;42import java.util.List;43import java.util.Map;44import static org.assertj.core.api.Assertions.assertThat;45import static org.assertj.core.api.Assertions.assertThatExceptionOfType;46import static org.mockito.Mockito.mock;47import static org.openqa.selenium.remote.DriverCommand.FIND_ELEMENT;48@Category(UnitTests.class)49public class AugmenterTest {50 private Augmenter getAugmenter() {51 return new Augmenter();52 }53 @Test54 public void shouldAugmentRotatable() {55 final Capabilities caps = new ImmutableCapabilities(CapabilityType.ROTATABLE, true);56 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);57 WebDriver returned = getAugmenter().augment(driver);58 assertThat(returned).isNotSameAs(driver);59 assertThat(returned).isInstanceOf(Rotatable.class);60 }61 @Test62 public void shouldAugmentLocationContext() {63 final Capabilities caps = new ImmutableCapabilities(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);64 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);65 WebDriver returned = getAugmenter().augment(driver);66 assertThat(returned).isNotSameAs(driver);67 assertThat(returned).isInstanceOf(LocationContext.class);68 }69 @Test70 public void shouldAddInterfaceFromCapabilityIfNecessary() {71 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);72 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);73 WebDriver returned = getAugmenter()74 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)75 .augment(driver);76 assertThat(returned).isNotSameAs(driver);77 assertThat(returned).isInstanceOf(HasMagicNumbers.class);78 }79 @Test80 public void shouldNotAddInterfaceWhenBooleanValueForItIsFalse() {81 Capabilities caps = new ImmutableCapabilities("magic.numbers", false);82 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);83 WebDriver returned = getAugmenter()84 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)85 .augment(driver);86 assertThat(returned).isSameAs(driver);87 assertThat(returned).isNotInstanceOf(HasMagicNumbers.class);88 }89 @Test90 public void shouldNotUseNonMatchingInterfaces() {91 Capabilities caps = new ImmutableCapabilities("magic.numbers", true);92 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);93 WebDriver returned = getAugmenter()94 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)95 .augment(driver);96 assertThat(returned).isNotInstanceOf(WebStorage.class);97 }98 @Test99 public void shouldDelegateToHandlerIfAdded() {100 Capabilities caps = new ImmutableCapabilities("foo", true);101 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);102 WebDriver returned = getAugmenter()103 .addDriverAugmentation(104 "foo",105 MyInterface.class,106 (c, exe) -> () -> "Hello World")107 .augment(driver);108 String text = ((MyInterface) returned).getHelloWorld();109 assertThat(text).isEqualTo("Hello World");110 }111 @Test112 public void shouldDelegateUnmatchedMethodCallsToDriverImplementation() {113 Capabilities caps = new ImmutableCapabilities("magic.numbers", true);114 StubExecutor stubExecutor = new StubExecutor(caps);115 stubExecutor.expect(DriverCommand.GET_TITLE, new HashMap<>(), "Title");116 WebDriver driver = new RemoteWebDriver(stubExecutor, caps);117 WebDriver returned = getAugmenter()118 .addDriverAugmentation(119 "magic.numbers",120 HasMagicNumbers.class,121 (c, exe) -> () -> 42)122 .augment(driver);123 assertThat(returned.getTitle()).isEqualTo("Title");124 }125 @Test126 public void proxyShouldNotAppearInStackTraces() {127 // This will force the class to be enhanced128 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);129 DetonatingDriver driver = new DetonatingDriver();130 driver.setCapabilities(caps);131 WebDriver returned = getAugmenter()132 .addDriverAugmentation(133 "magic.numbers",134 HasMagicNumbers.class,135 (c, exe) -> () -> 42)136 .augment(driver);137 assertThatExceptionOfType(NoSuchElementException.class)138 .isThrownBy(() -> returned.findElement(By.id("ignored")));139 }140 @Test141 public void shouldCopyFieldsFromTemplateInstanceIntoChildInstance() {142 ChildRemoteDriver driver = new ChildRemoteDriver();143 HasMagicNumbers holder = (HasMagicNumbers) getAugmenter().augment(driver);144 assertThat(holder.getMagicNumber()).isEqualTo(3);145 }146 @Test147 public void shouldNotChokeOnFinalFields() {148 WithFinals withFinals = new WithFinals();149 getAugmenter().augment(withFinals);150 }151 @Test152 public void shouldAllowReflexiveCalls() {153 Capabilities caps = new ImmutableCapabilities("find by magic", true);154 StubExecutor executor = new StubExecutor(caps);155 final WebElement element = mock(WebElement.class);156 executor.expect(157 FIND_ELEMENT,158 ImmutableMap.of("using", "magic", "value", "cheese"),159 element);160 WebDriver driver = new RemoteWebDriver(executor, caps);161 WebDriver returned = getAugmenter()162 .addDriverAugmentation(163 "find by magic",164 FindByMagic.class,165 (c, exe) -> magicWord -> element)166 .augment(driver);167 // No exception is a Good Thing168 WebElement seen = returned.findElement(new ByMagic("cheese"));169 assertThat(seen).isSameAs(element);170 }171 @Test172 public void shouldAugmentMultipleInterfaces() {173 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true,174 "numbers", true);175 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);176 WebDriver returned = getAugmenter()177 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)178 .addDriverAugmentation("numbers", HasNumbers.class, (c, exe) -> webDriver -> {179 Require.precondition(webDriver instanceof HasMagicNumbers, "Driver must implement HasMagicNumbers");180 return ((HasMagicNumbers)webDriver).getMagicNumber();181 })182 .augment(driver);183 assertThat(returned).isNotSameAs(driver);184 assertThat(returned).isInstanceOf(HasMagicNumbers.class);185 assertThat(returned).isInstanceOf(HasNumbers.class);186 int number = ((HasNumbers)returned).getNumbers(returned);187 assertThat(number).isEqualTo(42);188 }189 @Test190 public void shouldAugmentWebDriverDecorator() {191 final Capabilities caps = new ImmutableCapabilities(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);192 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);193 WebDriver decorated = new ModifyTitleWebDriverDecorator().decorate(driver);194 assertThat(decorated).isNotSameAs(driver);195 WebDriver returned = getAugmenter().augment(decorated);196 assertThat(returned).isNotSameAs(driver);197 assertThat(returned).isNotSameAs(decorated);198 assertThat(returned).isInstanceOf(LocationContext.class);199 String title = returned.getTitle();200 assertThat(title).isEqualTo("title");201 }202 @Test203 public void shouldDecorateAugmentedWebDriver() {204 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true,205 "numbers", true);206 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);207 WebDriver augmented = getAugmenter()208 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)209 .addDriverAugmentation("numbers", HasNumbers.class, (c, exe) -> webDriver -> {210 Require.precondition(webDriver instanceof HasMagicNumbers, "Driver must implement HasMagicNumbers");211 return ((HasMagicNumbers)webDriver).getMagicNumber();212 })213 .augment(driver);214 WebDriver decorated = new ModifyTitleWebDriverDecorator().decorate(augmented);215 assertThat(decorated).isNotSameAs(driver);216 assertThat(augmented).isNotSameAs(decorated);217 assertThat(decorated).isInstanceOf(HasNumbers.class);218 String title = decorated.getTitle();219 assertThat(title).isEqualTo("title");220 int number = ((HasNumbers)decorated).getNumbers(decorated);221 assertThat(number).isEqualTo(42);222 }223 private static class ByMagic extends By {224 private final String magicWord;225 public ByMagic(String magicWord) {226 this.magicWord = magicWord;227 }228 @Override229 public List<WebElement> findElements(SearchContext context) {230 return Collections.singletonList(((FindByMagic) context).findByMagic(magicWord));231 }232 }233 public interface FindByMagic {234 WebElement findByMagic(String magicWord);235 }236 @Test237 public void shouldBeAbleToAugmentMultipleTimes() {238 Capabilities caps = new ImmutableCapabilities("rotatable", true, "magic.numbers", true);239 StubExecutor stubExecutor = new StubExecutor(caps);240 stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION,241 Collections.emptyMap(),242 ScreenOrientation.PORTRAIT.name());243 RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps);244 WebDriver augmented = getAugmenter().augment(driver);245 assertThat(driver).isNotSameAs(augmented);246 assertThat(augmented).isInstanceOf(Rotatable.class);247 assertThat(augmented).isNotInstanceOf(HasMagicNumbers.class);248 WebDriver augmentedAgain = getAugmenter()249 .addDriverAugmentation(250 "magic.numbers",251 HasMagicNumbers.class,252 (c, exe) -> () -> 42)253 .augment(augmented);254 assertThat(augmented).isNotSameAs(augmentedAgain);255 assertThat(augmentedAgain).isInstanceOf(Rotatable.class);256 assertThat(augmentedAgain).isInstanceOf(HasMagicNumbers.class);257 ((Rotatable) augmentedAgain).getOrientation(); // Should not throw.258 assertThat(((HasCapabilities) augmentedAgain).getCapabilities())259 .isSameAs(driver.getCapabilities());260 }261 protected static class StubExecutor implements CommandExecutor {262 private final Capabilities capabilities;263 private final List<Data> expected = new ArrayList<>();264 protected StubExecutor(Capabilities capabilities) {265 this.capabilities = capabilities;266 }267 @Override268 public Response execute(Command command) {269 if (DriverCommand.NEW_SESSION.equals(command.getName())) {270 Response response = new Response(new SessionId("foo"));271 response.setValue(capabilities.asMap());272 return response;273 }274 for (Data possibleMatch : expected) {275 if (possibleMatch.commandName.equals(command.getName()) &&276 possibleMatch.args.equals(command.getParameters())) {277 Response response = new Response(new SessionId("foo"));278 response.setValue(possibleMatch.returnValue);279 return response;280 }281 }282 throw new AssertionError("Unexpected method invocation: " + command);283 }284 public void expect(String commandName, Map<String, ?> args, Object returnValue) {285 expected.add(new Data(commandName, args, returnValue));286 }287 private static class Data {288 public String commandName;289 public Map<String, ?> args;290 public Object returnValue;291 public Data(String commandName, Map<String, ?> args, Object returnValue) {292 this.commandName = commandName;293 this.args = args;294 this.returnValue = returnValue;295 }296 }297 }298 public interface MyInterface {299 String getHelloWorld();300 }301 public static class DetonatingDriver extends RemoteWebDriver {302 private Capabilities caps;303 public void setCapabilities(Capabilities caps) {304 this.caps = caps;305 }306 @Override307 public Capabilities getCapabilities() {308 return caps;309 }310 @Override311 public WebElement findElement(By locator) {312 if (locator instanceof By.Remotable) {313 if ("id".equals(((By.Remotable) locator).getRemoteParameters().using())) {314 throw new NoSuchElementException("Boom");315 }316 }317 return null;318 }319 }320 public interface HasMagicNumbers {321 int getMagicNumber();322 }323 public interface HasNumbers {324 int getNumbers(WebDriver driver);325 }326 public static class ChildRemoteDriver extends RemoteWebDriver implements HasMagicNumbers {327 private int magicNumber = 3;328 @Override329 public Capabilities getCapabilities() {330 return new FirefoxOptions();331 }332 @Override333 public int getMagicNumber() {334 return magicNumber;335 }336 }337 public static class WithFinals extends RemoteWebDriver {338 public final String finalField = "FINAL";339 @Override340 public Capabilities getCapabilities() {341 return new ImmutableCapabilities();342 }343 }344 private static class ModifyTitleWebDriverDecorator extends WebDriverDecorator {345 @Override346 public Object call(Decorated<?> target, Method method, Object[] args) throws Throwable {347 if (method.getDeclaringClass().equals(HasCapabilities.class)) {348 return new ImmutableCapabilities(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);349 }350 if (method.getName().equals("getTitle")) {351 return "title";352 }353 return super.call(target, method, args);354 }355 }356}...

Full Screen

Full Screen

Source:WebDriverDecorator.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.support.decorators;18import org.openqa.selenium.Alert;19import org.openqa.selenium.Beta;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebElement;22import org.openqa.selenium.internal.Require;23import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;24import java.lang.reflect.InvocationHandler;25import java.lang.reflect.InvocationTargetException;26import java.lang.reflect.Method;27import java.lang.reflect.Proxy;28import java.util.HashSet;29import java.util.List;30import java.util.Set;31import java.util.stream.Collectors;32/**33 * This class helps to create decorators for instances of {@link WebDriver} and34 * derived objects, such as {@link WebElement}s and {@link Alert}, that can35 * extend or modify their "regular" behavior. It provides a flexible36 * alternative to subclassing WebDriver.37 * <p>38 * Here is a general usage pattern:39 * <ol>40 * <li>implement a subclass of WebDriverDecorator that adds something to WebDriver behavior:<br>41 * <code>42 * public class MyWebDriverDecorator extends WebDriverDecorator { ... }43 * </code><br>44 * (see below for details)</li>45 * <li>use a decorator instance to decorate a WebDriver object:<br>46 * <code>47 * WebDriver original = new FirefoxDriver();48 * WebDriver decorated = new MyWebDriverDecorator().decorate(original);49 * </code></li>50 * <li>use the decorated WebDriver instead of the original one:<br>51 * <code>52 * decorated.get("http://example.com/");53 * ...54 * decorated.quit();55 * </code>56 * </li>57 * </ol>58 * By subclassing WebDriverDecorator you can define what code should be executed59 * <ul>60 * <li>before executing a method of the underlying object,</li>61 * <li>after executing a method of the underlying object,</li>62 * <li>instead of executing a method of the underlying object,</li>63 * <li>when an exception is thrown by a method of the underlying object.</li>64 * </ul>65 * The same decorator is used under the hood to decorate all the objects66 * derived from the underlying WebDriver instance. For example,67 * <code>decorated.findElement(someLocator)</code> automatically decorates68 * the returned WebElement.69 * <p>70 * Instances created by the decorator implement all the same interfaces as71 * the original objects.72 * <p>73 * When you implement a decorator there are two main options (that can be used74 * both separately and together):75 * <ul>76 * <li>if you want to apply the same behavior modification to all methods of77 * a WebDriver instance and its derived objects you can subclass78 * WebDriverDecorator and override some of the following methods:79 * {@link #beforeCall(Decorated, Method, Object[])},80 * {@link #afterCall(Decorated, Method, Object[], Object)},81 * {@link #call(Decorated, Method, Object[])} and82 * {@link #onError(Decorated, Method, Object[], InvocationTargetException)}</li>83 * <li>if you want to modify behavior of a specific class instances only84 * (e.g. behaviour of WebElement instances) you can override one of the85 * overloaded <code>createDecorated</code> methods to create a non-trivial86 * decorator for the specific class only.</li>87 * </ul>88 * Let's consider both approaches by examples.89 * <p>90 * One of the most widely used decorator examples is a logging decorator.91 * In this case we want to add the same piece of logging code before and after92 * each invoked method:93 * <code>94 * public class LoggingDecorator extends WebDriverDecorator {95 * final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getName());96 *97 * @Override98 * public void beforeCall(Decorated<?> target, Method method, Object[] args) {99 * logger.debug("before {}.{}({})", target, method, args);100 * }101 * @Override102 * public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {103 * logger.debug("after {}.{}({}) => {}", target, method, args, res);104 * }105 * }106 * </code>107 * For the second example let's implement a decorator that implicitly waits108 * for an element to be visible before any click or sendKeys method call.109 * <code>110 * public class ImplicitlyWaitingDecorator extends WebDriverDecorator {111 * private WebDriverWait wait;112 *113 * @Override114 * public Decorated<WebDriver> createDecorated(WebDriver driver) {115 * wait = new WebDriverWait(driver, Duration.ofSeconds(10));116 * return super.createDecorated(driver);117 * }118 * @Override119 * public Decorated<WebElement> createDecorated(WebElement original) {120 * return new DefaultDecorated<>(original, this) {121 * @Override122 * public void beforeCall(Method method, Object[] args) {123 * String methodName = method.getName();124 * if ("click".equals(methodName) || "sendKeys".equals(methodName)) {125 * wait.until(d -> getOriginal().isDisplayed());126 * }127 * }128 * };129 * }130 * }131 * </code>132 * This class is not a pure decorator, it allows to not only add new behavior133 * but also replace "normal" behavior of a WebDriver or derived objects.134 * <p>135 * Let's suppose you want to use JavaScript-powered clicks instead of normal136 * ones (yes, this allows to interact with invisible elements, it's a bad137 * practice in general but sometimes it's inevitable). This behavior change138 * can be achieved with the following "decorator":139 * <code>140 * public class JavaScriptPoweredDecorator extends WebDriverDecorator {141 * @Override142 * public Decorated<WebElement> createDecorated(WebElement original) {143 * return new DefaultDecorated<>(original, this) {144 * @Override145 * public Object call(Method method, Object[] args) throws Throwable {146 * String methodName = method.getName();147 * if ("click".equals(methodName)) {148 * JavascriptExecutor executor = (JavascriptExecutor) getDecoratedDriver().getOriginal();149 * executor.executeScript("arguments[0].click()", getOriginal());150 * return null;151 * } else {152 * return super.call(method, args);153 * }154 * }155 * };156 * }157 * }158 * </code>159 * It is possible to apply multiple decorators to compose behaviors added160 * by each of them. For example, if you want to log method calls and161 * implicitly wait for elements visibility you can use two decorators:162 * <code>163 * WebDriver original = new FirefoxDriver();164 * WebDriver decorated =165 * new ImplicitlyWaitingDecorator().decorate(166 * new LoggingDecorator().decorate(original));167 * </code>168 */169@Beta170public class WebDriverDecorator {171 private Decorated<WebDriver> decorated;172 public final WebDriver decorate(WebDriver original) {173 Require.nonNull("WebDriver", original);174 decorated = createDecorated(original);175 return createProxy(decorated);176 }177 public Decorated<WebDriver> getDecoratedDriver() {178 return decorated;179 }180 public Decorated<WebDriver> createDecorated(WebDriver driver) {181 return new DefaultDecorated<>(driver, this);182 }183 public Decorated<WebElement> createDecorated(WebElement original) {184 return new DefaultDecorated<>(original, this);185 }186 public Decorated<WebDriver.TargetLocator> createDecorated(WebDriver.TargetLocator original) {187 return new DefaultDecorated<>(original, this);188 }189 public Decorated<WebDriver.Navigation> createDecorated(WebDriver.Navigation original) {190 return new DefaultDecorated<>(original, this);191 }192 public Decorated<WebDriver.Options> createDecorated(WebDriver.Options original) {193 return new DefaultDecorated<>(original, this);194 }195 public Decorated<WebDriver.Timeouts> createDecorated(WebDriver.Timeouts original) {196 return new DefaultDecorated<>(original, this);197 }198 public Decorated<WebDriver.Window> createDecorated(WebDriver.Window original) {199 return new DefaultDecorated<>(original, this);200 }201 public Decorated<Alert> createDecorated(Alert original) {202 return new DefaultDecorated<>(original, this);203 }204 public Decorated<VirtualAuthenticator> createDecorated(VirtualAuthenticator original) {205 return new DefaultDecorated<>(original, this);206 }207 public void beforeCall(Decorated<?> target, Method method, Object[] args) {}208 public Object call(Decorated<?> target, Method method, Object[] args) throws Throwable {209 return decorateResult(method.invoke(target.getOriginal(), args));210 }211 public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {}212 public Object onError(Decorated<?> target, Method method, Object[] args,213 InvocationTargetException e) throws Throwable214 {215 throw e.getTargetException();216 }217 private Object decorateResult(Object toDecorate) {218 if (toDecorate instanceof WebDriver) {219 return createProxy(getDecoratedDriver());220 }221 if (toDecorate instanceof WebElement) {222 return createProxy(createDecorated((WebElement) toDecorate));223 }224 if (toDecorate instanceof Alert) {225 return createProxy(createDecorated((Alert) toDecorate));226 }227 if (toDecorate instanceof VirtualAuthenticator) {228 return createProxy(createDecorated((VirtualAuthenticator) toDecorate));229 }230 if (toDecorate instanceof WebDriver.Navigation) {231 return createProxy(createDecorated((WebDriver.Navigation) toDecorate));232 }233 if (toDecorate instanceof WebDriver.Options) {234 return createProxy(createDecorated((WebDriver.Options) toDecorate));235 }236 if (toDecorate instanceof WebDriver.TargetLocator) {237 return createProxy(createDecorated((WebDriver.TargetLocator) toDecorate));238 }239 if (toDecorate instanceof WebDriver.Timeouts) {240 return createProxy(createDecorated((WebDriver.Timeouts) toDecorate));241 }242 if (toDecorate instanceof WebDriver.Window) {243 return createProxy(createDecorated((WebDriver.Window) toDecorate));244 }245 if (toDecorate instanceof List) {246 return ((List<?>) toDecorate).stream()247 .map(this::decorateResult)248 .collect(Collectors.toList());249 }250 return toDecorate;251 }252 protected final <Z> Z createProxy(final Decorated<Z> decorated) {253 Set<Class<?>> decoratedInterfaces = extractInterfaces(decorated);254 Set<Class<?>> originalInterfaces = extractInterfaces(decorated.getOriginal());255 final InvocationHandler handler = (proxy, method, args) -> {256 try {257 if (method.getDeclaringClass().equals(Object.class)258 || decoratedInterfaces.contains(method.getDeclaringClass())) {259 return method.invoke(decorated, args);260 }261 if (originalInterfaces.contains(method.getDeclaringClass())) {262 decorated.beforeCall(method, args);263 Object result = decorated.call(method, args);264 decorated.afterCall(method, result, args);265 return result;266 }267 return method.invoke(decorated.getOriginal(), args);268 } catch (InvocationTargetException e) {269 return decorated.onError(method, e, args);270 }271 };272 Set<Class<?>> allInterfaces = new HashSet<>();273 allInterfaces.addAll(decoratedInterfaces);274 allInterfaces.addAll(originalInterfaces);275 Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[0]);276 return (Z) Proxy.newProxyInstance(277 this.getClass().getClassLoader(), allInterfacesArray, handler);278 }279 static Set<Class<?>> extractInterfaces(final Object object) {280 return extractInterfaces(object.getClass());281 }282 private static Set<Class<?>> extractInterfaces(final Class<?> clazz) {283 Set<Class<?>> allInterfaces = new HashSet<>();284 extractInterfaces(allInterfaces, clazz);285 return allInterfaces;286 }287 private static void extractInterfaces(final Set<Class<?>> collector, final Class<?> clazz) {288 if (clazz == null || Object.class.equals(clazz)) {289 return;290 }291 final Class<?>[] classes = clazz.getInterfaces();292 for (Class<?> interfaceClass : classes) {293 collector.add(interfaceClass);294 for (Class<?> superInterface : interfaceClass.getInterfaces()) {295 collector.add(superInterface);296 extractInterfaces(collector, superInterface);297 }298 }299 extractInterfaces(collector, clazz.getSuperclass());300 }301}...

Full Screen

Full Screen

Source:DecoratedRemoteWebDriverTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.support.decorators;18import com.google.common.collect.ImmutableMap;19import org.junit.Test;20import org.junit.experimental.categories.Category;21import org.openqa.selenium.By;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.remote.Dialect;25import org.openqa.selenium.remote.IsRemoteWebDriver;26import org.openqa.selenium.remote.IsRemoteWebElement;27import org.openqa.selenium.remote.RemoteWebDriver;28import org.openqa.selenium.remote.RemoteWebElement;29import org.openqa.selenium.remote.SessionId;30import org.openqa.selenium.remote.internal.WebElementToJsonConverter;31import org.openqa.selenium.testing.UnitTests;32import java.util.UUID;33import static org.assertj.core.api.Assertions.assertThat;34import static org.mockito.ArgumentMatchers.any;35import static org.mockito.Mockito.mock;36import static org.mockito.Mockito.verify;37import static org.mockito.Mockito.when;38import static org.openqa.selenium.remote.Dialect.OSS;39@Category(UnitTests.class)40public class DecoratedRemoteWebDriverTest {41 @Test42 public void canConvertDecoratedToRemoteWebDriverInterface() {43 SessionId sessionId = new SessionId(UUID.randomUUID());44 RemoteWebDriver originalDriver = mock(RemoteWebDriver.class);45 when(originalDriver.getSessionId()).thenReturn(sessionId);46 IsRemoteWebDriver decoratedDriver = (IsRemoteWebDriver) new WebDriverDecorator().decorate(originalDriver);47 assertThat(decoratedDriver.getSessionId()).isEqualTo(sessionId);48 }49 @Test(expected = ClassCastException.class)50 public void cannotConvertDecoratedToRemoteWebDriver() {51 SessionId sessionId = new SessionId(UUID.randomUUID());52 RemoteWebDriver originalDriver = mock(RemoteWebDriver.class);53 when(originalDriver.getSessionId()).thenReturn(sessionId);54 RemoteWebDriver decoratedDriver = (RemoteWebDriver) new WebDriverDecorator().decorate(originalDriver);55 }56 @Test57 public void canConvertDecoratedRemoteWebElementToJson() {58 RemoteWebDriver originalDriver = mock(RemoteWebDriver.class);59 RemoteWebElement originalElement = new RemoteWebElement();60 String elementId = UUID.randomUUID().toString();61 originalElement.setParent(originalDriver);62 originalElement.setId(elementId);63 when(originalDriver.findElement(any())).thenReturn(originalElement);64 WebDriver decoratedDriver = new WebDriverDecorator().decorate(originalDriver);65 WebElement element = decoratedDriver.findElement(By.id("test"));66 WebElementToJsonConverter converter = new WebElementToJsonConverter();67 ImmutableMap<String, String> result = (ImmutableMap<String, String>) converter.apply(element);68 assertThat(result.get(Dialect.OSS.getEncodedElementKey())).isEqualTo(elementId);69 }70}...

Full Screen

Full Screen

Source:InterfacesTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.support.decorators;18import static org.assertj.core.api.Assertions.assertThat;19import static org.mockito.Mockito.mock;20import org.junit.Test;21import org.junit.experimental.categories.Category;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.testing.UnitTests;24@Category(UnitTests.class)25public class InterfacesTest {26 private interface SomeOtherInterface {}27 private interface ExtendedDriver extends WebDriver, SomeOtherInterface {}28 @Test29 public void shouldNotAddInterfacesNotAvailableInTheOriginalDriver() {30 WebDriver driver = mock(WebDriver.class);31 assertThat(driver).isNotInstanceOf(SomeOtherInterface.class);32 WebDriver decorated = new WebDriverDecorator().decorate(driver);33 assertThat(decorated).isNotInstanceOf(SomeOtherInterface.class);34 }35 @Test36 public void shouldRespectInterfacesAvailableInTheOriginalDriver() {37 WebDriver driver = mock(ExtendedDriver.class);38 assertThat(driver).isInstanceOf(SomeOtherInterface.class);39 WebDriver decorated = new WebDriverDecorator().decorate(driver);40 assertThat(decorated).isInstanceOf(SomeOtherInterface.class);41 }42}...

Full Screen

Full Screen

Source:Decorated.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.support.decorators;18import java.lang.reflect.InvocationTargetException;19import java.lang.reflect.Method;20public interface Decorated<T> {21 T getOriginal();22 WebDriverDecorator getDecorator();23 void beforeCall(Method method, Object[] args);24 Object call(Method method, Object[] args) throws Throwable;25 void afterCall(Method method, Object result, Object[] args);26 Object onError(Method method, InvocationTargetException e, Object[] args) throws Throwable;27}...

Full Screen

Full Screen

Interface Decorated

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.support.decorators.Decorated;2import org.openqa.selenium.support.decorators.Decorator;3import java.lang.reflect.Field;4import java.lang.reflect.Method;5import java.lang.reflect.Proxy;6import java.util.Arrays;7import java.util.List;8import java.util.stream.Collectors;9import static java.util.Arrays.stream;10import static java.util.stream.Collectors.toList;11public class DecoratorFactory {12 public static <T> T decorate(Class<T> interfaceClass, Object instance) {13 ClassLoader classLoader = instance.getClass().getClassLoader();14 Class<?>[] interfaces = new Class<?>[] { interfaceClass, Decorated.class };15 return interfaceClass.cast(Proxy.newProxyInstance(classLoader, interfaces, new Decorator(instance)));16 }17 public static <T> T decorateAll(Class<T> interfaceClass, Object instance) {18 List<Field> fields = stream(instance.getClass().getDeclaredFields())19 .filter(field -> field.getType().isInterface())20 .collect(toList());21 fields.forEach(field -> {22 try {23 field.setAccessible(true);24 field.set(instance, decorate(field.getType(), field.get(instance)));25 } catch (IllegalAccessException e) {26 throw new RuntimeException(e);27 }28 });29 return decorate(interfaceClass, instance);30 }31 public static <T> T decorateAll(Class<T> interfaceClass, Object instance, Class<?>... exclude) {32 List<Class<?>> excluded = Arrays.asList(exclude);33 List<Field> fields = stream(instance.getClass().getDeclaredFields())34 .filter(field -> field.getType().isInterface())35 .filter(field -> !excluded.contains(field.getType()))36 .collect(toList());37 fields.forEach(field -> {38 try {39 field.setAccessible(true);40 field.set(instance, decorate(field.getType(), field.get(instance)));41 } catch (IllegalAccessException e) {42 throw new RuntimeException(e);43 }44 });45 return decorate(interfaceClass, instance);46 }47 public static <T> T decorateAll(Object instance) {48 List<Field> fields = stream(instance.getClass().getDeclaredFields())49 .filter(field -> field.getType().isInterface())50 .collect(toList());51 fields.forEach(field -> {52 try {53 field.setAccessible(true);54 field.set(instance, decorate(field.getType(), field.get(instance)));55 } catch (IllegalAccessException e) {56 throw new RuntimeException(e);57 }58 });59 return (T) instance;60 }61 public static <T> T decorateAll(Object instance, Class<?>

Full Screen

Full Screen
copy
1@FixMethodOrder(MethodSorters.NAME_ASCENDING)2
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

...Most popular Stackoverflow questions on Interface-Decorated

Most used methods in Interface-Decorated

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful