-
-
Notifications
You must be signed in to change notification settings - Fork 8k
/
WebDriverDecorator.java
415 lines (371 loc) · 15.6 KB
/
WebDriverDecorator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// 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.decorators;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.matcher.ElementMatchers;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Beta;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.WrapsElement;
import org.openqa.selenium.internal.Require;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* This class helps to create decorators for instances of {@link WebDriver} and
* derived objects, such as {@link WebElement}s and {@link Alert}, that can
* extend or modify their "regular" behavior. It provides a flexible
* alternative to subclassing WebDriver.
* <p>
* Here is a general usage pattern:
* <ol>
* <li>implement a subclass of WebDriverDecorator that adds something to WebDriver behavior:<br>
* <pre><code>
* public class MyWebDriverDecorator extends WebDriverDecorator { ... }
* </code></pre>
* (see below for details)</li>
* <li>use a decorator instance to decorate a WebDriver object:<br>
* <pre><code>
* WebDriver original = new FirefoxDriver();
* WebDriver decorated = new MyWebDriverDecorator().decorate(original);
* </code></pre></li>
* <li>use the decorated WebDriver instead of the original one:<br>
* <pre><code>
* decorated.get("http://example.com/");
* ...
* decorated.quit();
* </code></pre>
* </li>
* </ol>
* By subclassing WebDriverDecorator you can define what code should be executed
* <ul>
* <li>before executing a method of the underlying object,</li>
* <li>after executing a method of the underlying object,</li>
* <li>instead of executing a method of the underlying object,</li>
* <li>when an exception is thrown by a method of the underlying object.</li>
* </ul>
* The same decorator is used under the hood to decorate all the objects
* derived from the underlying WebDriver instance. For example,
* <code>decorated.findElement(someLocator)</code> automatically decorates
* the returned WebElement.
* <p>
* Instances created by the decorator implement all the same interfaces as
* the original objects.
* <p>
* When you implement a decorator there are two main options (that can be used
* both separately and together):
* <ul>
* <li>if you want to apply the same behavior modification to all methods of
* a WebDriver instance and its derived objects you can subclass
* WebDriverDecorator and override some of the following methods:
* {@link #beforeCall(Decorated, Method, Object[])},
* {@link #afterCall(Decorated, Method, Object[], Object)},
* {@link #call(Decorated, Method, Object[])} and
* {@link #onError(Decorated, Method, Object[], InvocationTargetException)}</li>
* <li>if you want to modify behavior of a specific class instances only
* (e.g. behaviour of WebElement instances) you can override one of the
* overloaded <code>createDecorated</code> methods to create a non-trivial
* decorator for the specific class only.</li>
* </ul>
* Let's consider both approaches by examples.
* <p>
* One of the most widely used decorator examples is a logging decorator.
* In this case we want to add the same piece of logging code before and after
* each invoked method:
* <pre><code>
* public class LoggingDecorator extends WebDriverDecorator {
* final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getName());
*
* @Override
* public void beforeCall(Decorated<?> target, Method method, Object[] args) {
* logger.debug("before {}.{}({})", target, method, args);
* }
* @Override
* public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {
* logger.debug("after {}.{}({}) => {}", target, method, args, res);
* }
* }
* </code></pre>
* For the second example let's implement a decorator that implicitly waits
* for an element to be visible before any click or sendKeys method call.
* <pre><code>
* public class ImplicitlyWaitingDecorator extends WebDriverDecorator {
* private WebDriverWait wait;
*
* @Override
* public Decorated<WebDriver> createDecorated(WebDriver driver) {
* wait = new WebDriverWait(driver, Duration.ofSeconds(10));
* return super.createDecorated(driver);
* }
* @Override
* public Decorated<WebElement> createDecorated(WebElement original) {
* return new DefaultDecorated<>(original, this) {
* @Override
* public void beforeCall(Method method, Object[] args) {
* String methodName = method.getName();
* if ("click".equals(methodName) || "sendKeys".equals(methodName)) {
* wait.until(d -> getOriginal().isDisplayed());
* }
* }
* };
* }
* }
* </code></pre>
* This class is not a pure decorator, it allows to not only add new behavior
* but also replace "normal" behavior of a WebDriver or derived objects.
* <p>
* Let's suppose you want to use JavaScript-powered clicks instead of normal
* ones (yes, this allows to interact with invisible elements, it's a bad
* practice in general but sometimes it's inevitable). This behavior change
* can be achieved with the following "decorator":
* <pre><code>
* public class JavaScriptPoweredDecorator extends WebDriverDecorator {
* @Override
* public Decorated<WebElement> createDecorated(WebElement original) {
* return new DefaultDecorated<>(original, this) {
* @Override
* public Object call(Method method, Object[] args) throws Throwable {
* String methodName = method.getName();
* if ("click".equals(methodName)) {
* JavascriptExecutor executor = (JavascriptExecutor) getDecoratedDriver().getOriginal();
* executor.executeScript("arguments[0].click()", getOriginal());
* return null;
* } else {
* return super.call(method, args);
* }
* }
* };
* }
* }
* </code></pre>
* It is possible to apply multiple decorators to compose behaviors added
* by each of them. For example, if you want to log method calls and
* implicitly wait for elements visibility you can use two decorators:
* <pre><code>
* WebDriver original = new FirefoxDriver();
* WebDriver decorated =
* new ImplicitlyWaitingDecorator().decorate(
* new LoggingDecorator().decorate(original));
* </code></pre>
*/
@Beta
public class WebDriverDecorator<T extends WebDriver> {
private final Class<T> targetWebDriverClass;
private Decorated<T> decorated;
@SuppressWarnings("unchecked")
public WebDriverDecorator() {
this((Class<T>) WebDriver.class);
}
public WebDriverDecorator(Class<T> targetClass) {
this.targetWebDriverClass = targetClass;
}
public final T decorate(T original) {
Require.nonNull("WebDriver", original);
decorated = createDecorated(original);
return createProxy(decorated, targetWebDriverClass);
}
public Decorated<T> getDecoratedDriver() {
return decorated;
}
public Decorated<T> createDecorated(T driver) {
return new DefaultDecorated<>(driver, this);
}
public Decorated<WebElement> createDecorated(WebElement original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<WebDriver.TargetLocator> createDecorated(WebDriver.TargetLocator original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<WebDriver.Navigation> createDecorated(WebDriver.Navigation original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<WebDriver.Options> createDecorated(WebDriver.Options original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<WebDriver.Timeouts> createDecorated(WebDriver.Timeouts original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<WebDriver.Window> createDecorated(WebDriver.Window original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<Alert> createDecorated(Alert original) {
return new DefaultDecorated<>(original, this);
}
public Decorated<VirtualAuthenticator> createDecorated(VirtualAuthenticator original) {
return new DefaultDecorated<>(original, this);
}
public void beforeCall(Decorated<?> target, Method method, Object[] args) {}
public Object call(Decorated<?> target, Method method, Object[] args) throws Throwable {
return decorateResult(method.invoke(target.getOriginal(), args));
}
public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {}
public Object onError(
Decorated<?> target,
Method method,
Object[] args,
InvocationTargetException e) throws Throwable {
throw e.getTargetException();
}
private Object decorateResult(Object toDecorate) {
if (toDecorate instanceof WebDriver) {
return createProxy(getDecoratedDriver(), targetWebDriverClass);
}
if (toDecorate instanceof WebElement) {
return createProxy(createDecorated((WebElement) toDecorate), WebElement.class);
}
if (toDecorate instanceof Alert) {
return createProxy(createDecorated((Alert) toDecorate), Alert.class);
}
if (toDecorate instanceof VirtualAuthenticator) {
return createProxy(createDecorated((VirtualAuthenticator) toDecorate), VirtualAuthenticator.class);
}
if (toDecorate instanceof WebDriver.Navigation) {
return createProxy(createDecorated((WebDriver.Navigation) toDecorate), WebDriver.Navigation.class);
}
if (toDecorate instanceof WebDriver.Options) {
return createProxy(createDecorated((WebDriver.Options) toDecorate), WebDriver.Options.class);
}
if (toDecorate instanceof WebDriver.TargetLocator) {
return createProxy(createDecorated((WebDriver.TargetLocator) toDecorate), WebDriver.TargetLocator.class);
}
if (toDecorate instanceof WebDriver.Timeouts) {
return createProxy(createDecorated((WebDriver.Timeouts) toDecorate), WebDriver.Timeouts.class);
}
if (toDecorate instanceof WebDriver.Window) {
return createProxy(createDecorated((WebDriver.Window) toDecorate), WebDriver.Window.class);
}
if (toDecorate instanceof List) {
return ((List<?>) toDecorate).stream()
.map(this::decorateResult)
.collect(Collectors.toList());
}
return toDecorate;
}
protected final <Z> Z createProxy(final Decorated<Z> decorated, Class<Z> clazz) {
Set<Class<?>> decoratedInterfaces = extractInterfaces(decorated);
Set<Class<?>> originalInterfaces = extractInterfaces(decorated.getOriginal());
Map<Class<?>, InvocationHandler> derivedInterfaces = deriveAdditionalInterfaces(decorated.getOriginal());
final InvocationHandler handler = (proxy, method, args) -> {
try {
if (method.getDeclaringClass().equals(Object.class)
|| decoratedInterfaces.contains(method.getDeclaringClass())) {
return method.invoke(decorated, args);
}
if (originalInterfaces.contains(method.getDeclaringClass())) {
decorated.beforeCall(method, args);
Object result = decorated.call(method, args);
decorated.afterCall(method, result, args);
return result;
}
if (derivedInterfaces.containsKey(method.getDeclaringClass())) {
return derivedInterfaces.get(method.getDeclaringClass()).invoke(proxy, method, args);
}
return method.invoke(decorated.getOriginal(), args);
} catch (InvocationTargetException e) {
return decorated.onError(method, e, args);
}
};
Set<Class<?>> allInterfaces = new HashSet<>();
allInterfaces.addAll(decoratedInterfaces);
allInterfaces.addAll(originalInterfaces);
allInterfaces.addAll(derivedInterfaces.keySet());
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[0]);
Class<? extends Z> proxy = new ByteBuddy()
.subclass(clazz.isInterface() ? Object.class : clazz)
.implement(allInterfacesArray)
.method(ElementMatchers.any())
.intercept(InvocationHandlerAdapter.of(handler))
.make()
.load(clazz.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.asSubclass(clazz);
try {
return proxy.newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Unable to create new proxy", e);
}
}
static Set<Class<?>> extractInterfaces(final Object object) {
return extractInterfaces(object.getClass());
}
private static Set<Class<?>> extractInterfaces(final Class<?> clazz) {
Set<Class<?>> allInterfaces = new HashSet<>();
extractInterfaces(allInterfaces, clazz);
return allInterfaces;
}
private static void extractInterfaces(final Set<Class<?>> collector, final Class<?> clazz) {
if (clazz == null || Object.class.equals(clazz)) {
return;
}
final Class<?>[] classes = clazz.getInterfaces();
for (Class<?> interfaceClass : classes) {
collector.add(interfaceClass);
for (Class<?> superInterface : interfaceClass.getInterfaces()) {
collector.add(superInterface);
extractInterfaces(collector, superInterface);
}
}
extractInterfaces(collector, clazz.getSuperclass());
}
private Map<Class<?>, InvocationHandler> deriveAdditionalInterfaces(Object object) {
Map<Class<?>, InvocationHandler> handlers = new HashMap<>();
if (object instanceof WebDriver && !(object instanceof WrapsDriver)) {
handlers.put(WrapsDriver.class, (proxy, method, args) -> {
if ("getWrappedDriver".equals(method.getName())) {
return object;
}
throw new UnsupportedOperationException(method.getName());
});
}
if (object instanceof WebElement && !(object instanceof WrapsElement)) {
handlers.put(WrapsElement.class, (proxy, method, args) -> {
if ("getWrappedElement".equals(method.getName())) {
return object;
}
throw new UnsupportedOperationException(method.getName());
});
}
try {
Method toJson = object.getClass().getDeclaredMethod("toJson");
toJson.setAccessible(true);
handlers.put(JsonSerializer.class, ((proxy, method, args) -> {
if ("toJson".equals(method.getName())) {
return toJson.invoke(object);
}
throw new UnsupportedOperationException(method.getName());
}));
} catch (NoSuchMethodException e) {
// Fine. Just fall through
}
return handlers;
}
@FunctionalInterface
protected interface JsonSerializer {
Object toJson();
}
}