-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathDevToolsHandling.java
275 lines (247 loc) · 10.8 KB
/
DevToolsHandling.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
package aquality.selenium.browser.devtools;
import aquality.selenium.browser.AqualityServices;
import aquality.selenium.core.localization.ILocalizedLogger;
import aquality.selenium.logging.DevToolsCommandLoggingOptions;
import aquality.selenium.logging.LoggingParameters;
import org.openqa.selenium.chromium.ChromiumDriver;
import org.openqa.selenium.devtools.Command;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.Event;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v85.performance.Performance;
import org.openqa.selenium.devtools.v85.performance.model.Metric;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static aquality.selenium.logging.LocalizedLoggerUtility.logByLevel;
/**
* Wrapper for Selenium {@link DevTools} functionality.
*/
public class DevToolsHandling {
private final HasDevTools devToolsProvider;
private final ILocalizedLogger logger;
private DevTools session;
private NetworkHandling network;
private EmulationHandling emulation;
private JavaScriptHandling javaScript;
/**
* Initializes an instance of {@link DevToolsHandling}
* @param devToolsProvider Instance of {@link org.openqa.selenium.WebDriver} which supports CDP protocol.
*/
public DevToolsHandling(HasDevTools devToolsProvider) {
this.devToolsProvider = devToolsProvider;
this.logger = AqualityServices.getLocalizedLogger();
}
HasDevTools getDevToolsProvider() {
return devToolsProvider;
}
private DevTools getDevTools() {
return getDevTools("default");
}
private DevTools getDevTools(String handleToLog) {
if (session == null) {
logger.info("loc.browser.devtools.session.get", handleToLog);
session = devToolsProvider.getDevTools();
}
return session;
}
private void logCommand(String commandName, Map<String, Object> commandParameters,
DevToolsCommandLoggingOptions loggingOptions) {
LoggingParameters logging = (loggingOptions == null ? new DevToolsCommandLoggingOptions() : loggingOptions)
.getCommand();
if (!logging.isEnabled())
{
return;
}
if (!commandParameters.isEmpty()) {
logByLevel(logging.getLogLevel(), "loc.browser.devtools.command.execute.withparams", commandName, commandParameters);
}
else {
logByLevel(logging.getLogLevel(), "loc.browser.devtools.command.execute", commandName);
}
}
private void logCommandResult(Object result, DevToolsCommandLoggingOptions loggingOptions) {
LoggingParameters logging = (loggingOptions == null ? new DevToolsCommandLoggingOptions() : loggingOptions)
.getCommand();
if (result != null && logging.isEnabled()) {
if (result instanceof Map && ((Map<?, ?>) result).isEmpty()) {
return;
}
logByLevel(logging.getLogLevel(), "loc.browser.devtools.command.execute.result", result);
}
}
/**
* Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol, if there is not one.
* If the session already exist, returns existing session.
* Defaults to autodetect the protocol version for Chromium, V85 for Firefox.
* @return The active session to use to communicate with the Chromium Developer Tools debugging protocol.
*/
public DevTools getDevToolsSession() {
getDevTools().createSessionIfThereIsNotOne();
return session;
}
/**
* Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol, if there is not one, on given window/tab (aka target).
* If the session already exist, returns existing session.
* If windowHandle is null, then the first "page" type will be selected.
* Pass the windowHandle if you have multiple windows/tabs opened to connect to the expected window/tab.
* Defaults to autodetect the protocol version for Chromium, V85 for Firefox.
* @param windowHandle result of {@link org.openqa.selenium.WebDriver#getWindowHandle()}, optional. *
* @return The active session to use to communicate with the Chromium Developer Tools debugging protocol.
*/
public DevTools getDevToolsSession(String windowHandle) {
getDevTools(windowHandle).createSessionIfThereIsNotOne(windowHandle);
return session;
}
/**
* Gets a value indicating whether a DevTools session is active.
* @return true if there is an active session, false otherwise.
*/
public boolean hasActiveDevToolsSession() {
logger.info("loc.browser.devtools.session.isactive");
boolean result = devToolsProvider.getDevTools().getCdpSession() != null;
logger.info("loc.browser.devtools.session.isactive.result", result);
return result;
}
/**
* Closes a DevTools session.
*/
public void closeDevToolsSession() {
logger.info("loc.browser.devtools.session.close");
getDevTools().disconnectSession();
}
/**
* Executes a custom Chromium Dev Tools Protocol Command.
* Note: works only if current driver is instance of {@link ChromiumDriver}.
* @param commandName Name of the command to execute.
* @param commandParameters Parameters of the command to execute.
* @return An object representing the result of the command, if applicable.
*/
public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> commandParameters) {
return executeCdpCommand(commandName, commandParameters, null);
}
/**
* Executes a custom Chromium Dev Tools Protocol Command.
* Note: works only if current driver is instance of {@link ChromiumDriver}.
* @param commandName Name of the command to execute.
* @param commandParameters Parameters of the command to execute.
* @param loggingOptions Logging preferences.
* @return An object representing the result of the command, if applicable.
*/
public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> commandParameters,
DevToolsCommandLoggingOptions loggingOptions) {
if (devToolsProvider instanceof ChromiumDriver) {
logCommand(commandName, commandParameters, loggingOptions);
ChromiumDriver driver = (ChromiumDriver) devToolsProvider;
Map<String, Object> result = driver.executeCdpCommand(commandName, commandParameters);
logCommandResult(result, loggingOptions);
return result;
}
else {
throw new UnsupportedOperationException("Execution of CDP command directly is not supported for current browser. Try sendCommand method instead.");
}
}
/**
* Sends the specified command and returns the associated command response.
* @param command An instance of the {@link Command} to send.
* @param <X> The type of the command's result. For most commands it's {@link Void}
* @return the result of the command, if applicable
*/
public <X> X sendCommand(Command<X> command) {
return sendCommand(command, null);
}
/**
* Sends the specified command and returns the associated command response.
* @param command An instance of the {@link Command} to send.
* @param <X> The type of the command's result. For most commands it's {@link Void}
* @param loggingOptions Logging preferences.
* @return the result of the command, if applicable
*/
public <X> X sendCommand(Command<X> command, DevToolsCommandLoggingOptions loggingOptions) {
logCommand(command.getMethod(), command.getParams(), loggingOptions);
X result = getDevToolsSession().send(command);
logCommandResult(result, loggingOptions);
return result;
}
/**
* Adds a listener for a specific event with the handler for it.
* @param event Event to listen for
* @param handler Handler to call
* @param <X> The type of the event's result.
*/
public <X> void addListener(Event<X> event, Consumer<X> handler) {
logger.info("loc.browser.devtools.listener.add", event.getMethod());
getDevToolsSession().addListener(event, handler);
}
/**
* Removes all the listeners, and disables all the domains.
*/
public void clearListeners() {
logger.info("loc.browser.devtools.listener.clear");
getDevToolsSession().clearListeners();
}
/**
* Version-independent emulation DevTools commands.
* @return an instance of {@link EmulationHandling}.
*/
public EmulationHandling emulation() {
if (emulation == null) {
emulation = new EmulationHandling(this);
}
return emulation;
}
/**
* DevTools commands for network requests interception.
* @return an instance of {@link NetworkHandling}.
*/
public NetworkHandling network() {
if (network == null) {
network = new NetworkHandling(this);
}
return network;
}
/**
* Provides JavaScript Monitoring functionality.
* @return an instance of {@link JavaScriptHandling}
*/
public JavaScriptHandling javaScript() {
if (javaScript == null) {
javaScript = new JavaScriptHandling(this);
}
return javaScript;
}
/**
* Disable collecting and reporting metrics.
*/
public void disablePerformanceMonitoring() {
sendCommand(Performance.disable());
}
/**
* Enable collecting and reporting metrics.
* @param timeDomain Time domain to use for collecting and reporting duration metrics.
* Allowed Values: timeTicks, threadTicks.
*/
public void enablePerformanceMonitoring(String timeDomain) {
sendCommand(Performance.enable(Optional.of(Performance.EnableTimeDomain.fromString(timeDomain))));
}
/**
* Enable collecting and reporting metrics.
*/
public void enablePerformanceMonitoring() {
sendCommand(Performance.enable(Optional.empty()));
}
/**
* Retrieve current values of run-time metrics.
* @return Current values for run-time metrics
*/
public Map<String, Number> getPerformanceMetrics() {
Command<List<Metric>> command = Performance.getMetrics();
logCommand(command.getMethod(), command.getParams(), null);
List<Metric> metrics = getDevToolsSession().send(command);
Map<String, Number> result = metrics.stream().collect(Collectors.toMap(Metric::getName, Metric::getValue));
logCommandResult(result.isEmpty() ? "empty" : result, null);
return result;
}
}