forked from appium/java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppiumDriver.java
349 lines (315 loc) · 15 KB
/
AppiumDriver.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
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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 io.appium.java_client;
import com.google.common.collect.ImmutableMap;
import io.appium.java_client.internal.CapabilityHelpers;
import io.appium.java_client.internal.ReflectionHelpers;
import io.appium.java_client.internal.SessionHelpers;
import io.appium.java_client.remote.AppiumCommandExecutor;
import io.appium.java_client.remote.AppiumNewSessionCommandPayload;
import io.appium.java_client.remote.AppiumW3CHttpCommandCodec;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.options.BaseOptions;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.ErrorHandler;
import org.openqa.selenium.remote.ExecuteMethod;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec;
import org.openqa.selenium.remote.html5.RemoteLocationContext;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpMethod;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static io.appium.java_client.internal.CapabilityHelpers.APPIUM_PREFIX;
import static io.appium.java_client.remote.MobileCapabilityType.AUTOMATION_NAME;
import static io.appium.java_client.remote.MobileCapabilityType.PLATFORM_NAME;
import static org.apache.commons.lang3.StringUtils.isBlank;
/**
* Default Appium driver implementation.
*/
public class AppiumDriver extends RemoteWebDriver implements
ExecutesMethod,
ComparesImages,
ExecutesDriverScript,
LogsEvents,
HasBrowserCheck,
CanRememberExtensionPresence,
HasSettings {
private static final ErrorHandler errorHandler = new ErrorHandler(new ErrorCodesMobile(), true);
// frequently used command parameters
private final URL remoteAddress;
protected final RemoteLocationContext locationContext;
private final ExecuteMethod executeMethod;
private final Set<String> absentExtensionNames = new HashSet<>();
/**
* Creates a new instance based on command {@code executor} and {@code capabilities}.
*
* @param executor is an instance of {@link HttpCommandExecutor}
* or class that extends it. Default commands or another vendor-specific
* commands may be specified there.
* @param capabilities take a look at {@link Capabilities}
*/
public AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, capabilities);
this.executeMethod = new AppiumExecutionMethod(this);
locationContext = new RemoteLocationContext(executeMethod);
super.setErrorHandler(errorHandler);
this.remoteAddress = executor.getAddressOfRemoteServer();
}
public AppiumDriver(AppiumClientConfig clientConfig, Capabilities capabilities) {
this(new AppiumCommandExecutor(MobileCommand.commandRepository, clientConfig), capabilities);
}
public AppiumDriver(URL remoteAddress, Capabilities capabilities) {
this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress),
capabilities);
}
public AppiumDriver(URL remoteAddress, HttpClient.Factory httpClientFactory,
Capabilities capabilities) {
this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress,
httpClientFactory), capabilities);
}
public AppiumDriver(AppiumDriverLocalService service, Capabilities capabilities) {
this(new AppiumCommandExecutor(MobileCommand.commandRepository, service),
capabilities);
}
public AppiumDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory,
Capabilities capabilities) {
this(new AppiumCommandExecutor(MobileCommand.commandRepository, service, httpClientFactory),
capabilities);
}
public AppiumDriver(AppiumServiceBuilder builder, Capabilities capabilities) {
this(builder.build(), capabilities);
}
public AppiumDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory,
Capabilities capabilities) {
this(builder.build(), httpClientFactory, capabilities);
}
public AppiumDriver(HttpClient.Factory httpClientFactory, Capabilities capabilities) {
this(AppiumDriverLocalService.buildDefaultService(), httpClientFactory,
capabilities);
}
public AppiumDriver(Capabilities capabilities) {
this(AppiumDriverLocalService.buildDefaultService(), capabilities);
}
/**
* This is a special constructor used to connect to a running driver instance.
* It does not do any necessary verifications, but rather assumes the given
* driver session is already running at `remoteSessionAddress`.
* The maintenance of driver state(s) is the caller's responsibility.
* !!! This API is supposed to be used for **debugging purposes only**.
*
* @param remoteSessionAddress The address of the **running** session including the session identifier.
* @param platformName The name of the target platform.
* @param automationName The name of the target automation.
*/
public AppiumDriver(URL remoteSessionAddress, String platformName, String automationName) {
super();
ReflectionHelpers.setPrivateFieldValue(
RemoteWebDriver.class, this, "capabilities", new ImmutableCapabilities(
ImmutableMap.of(
PLATFORM_NAME, platformName,
APPIUM_PREFIX + AUTOMATION_NAME, automationName
)
)
);
SessionHelpers.SessionAddress sessionAddress = SessionHelpers.parseSessionAddress(remoteSessionAddress);
AppiumCommandExecutor executor = new AppiumCommandExecutor(
MobileCommand.commandRepository, sessionAddress.getServerUrl()
);
executor.setCommandCodec(new AppiumW3CHttpCommandCodec());
executor.setResponseCodec(new W3CHttpResponseCodec());
setCommandExecutor(executor);
this.executeMethod = new AppiumExecutionMethod(this);
locationContext = new RemoteLocationContext(executeMethod);
super.setErrorHandler(errorHandler);
this.remoteAddress = executor.getAddressOfRemoteServer();
setSessionId(sessionAddress.getId());
}
/**
* Changes platform name if it is not set and returns merged capabilities.
*
* @param originalCapabilities the given {@link Capabilities}.
* @param defaultName a {@link MobileCapabilityType#PLATFORM_NAME} value which has
* to be set up
* @return {@link Capabilities} with changed platform name value or the original capabilities
*/
protected static Capabilities ensurePlatformName(
Capabilities originalCapabilities, String defaultName) {
return originalCapabilities.getPlatformName() == null
? originalCapabilities.merge(new ImmutableCapabilities(PLATFORM_NAME, defaultName))
: originalCapabilities;
}
/**
* Changes automation name if it is not set and returns merged capabilities.
*
* @param originalCapabilities the given {@link Capabilities}.
* @param defaultName a {@link MobileCapabilityType#AUTOMATION_NAME} value which has
* to be set up
* @return {@link Capabilities} with changed mobile automation name value or the original capabilities
*/
protected static Capabilities ensureAutomationName(
Capabilities originalCapabilities, String defaultName) {
String currentAutomationName = CapabilityHelpers.getCapability(
originalCapabilities, AUTOMATION_NAME, String.class);
if (isBlank(currentAutomationName)) {
String capabilityName = originalCapabilities.getCapabilityNames()
.contains(AUTOMATION_NAME) ? AUTOMATION_NAME : APPIUM_PREFIX + AUTOMATION_NAME;
return originalCapabilities.merge(new ImmutableCapabilities(capabilityName, defaultName));
}
return originalCapabilities;
}
/**
* Changes platform and automation names if they are not set
* and returns merged capabilities.
*
* @param originalCapabilities the given {@link Capabilities}.
* @param defaultPlatformName a {@link MobileCapabilityType#PLATFORM_NAME} value which has
* to be set up
* @param defaultAutomationName The default automation name to set up for this class
* @return {@link Capabilities} with changed platform/automation name value or the original capabilities
*/
protected static Capabilities ensurePlatformAndAutomationNames(
Capabilities originalCapabilities, String defaultPlatformName, String defaultAutomationName) {
Capabilities capsWithPlatformFixed = ensurePlatformName(originalCapabilities, defaultPlatformName);
return ensureAutomationName(capsWithPlatformFixed, defaultAutomationName);
}
@Override
public ExecuteMethod getExecuteMethod() {
return executeMethod;
}
/**
* This method is used to get build version status of running Appium server.
*
* @return map containing version details
*/
public Map<String, Object> getStatus() {
//noinspection unchecked
return (Map<String, Object>) execute(DriverCommand.STATUS).getValue();
}
/**
* This method is used to add custom appium commands in Appium 2.0.
*
* @param httpMethod the available {@link HttpMethod}.
* @param url The url to URL template as https://www.w3.org/TR/webdriver/#endpoints.
* @param methodName The name of custom appium command.
*/
public void addCommand(HttpMethod httpMethod, String url, String methodName) {
switch (httpMethod) {
case GET:
MobileCommand.commandRepository.put(methodName, MobileCommand.getC(url));
break;
case POST:
MobileCommand.commandRepository.put(methodName, MobileCommand.postC(url));
break;
case DELETE:
MobileCommand.commandRepository.put(methodName, MobileCommand.deleteC(url));
break;
default:
throw new WebDriverException(String.format("Unsupported HTTP Method: %s. Only %s methods are supported",
httpMethod,
Arrays.toString(HttpMethod.values())));
}
((AppiumCommandExecutor) getCommandExecutor()).refreshAdditionalCommands();
}
public URL getRemoteAddress() {
return remoteAddress;
}
@Override
protected void startSession(Capabilities capabilities) {
Response response = execute(new AppiumNewSessionCommandPayload(capabilities));
if (response == null) {
throw new SessionNotCreatedException(
"The underlying command executor returned a null response.");
}
Object responseValue = response.getValue();
if (responseValue == null) {
throw new SessionNotCreatedException(
"The underlying command executor returned a response without payload: "
+ response);
}
if (!(responseValue instanceof Map)) {
throw new SessionNotCreatedException(
"The underlying command executor returned a response with a non well formed payload: "
+ response);
}
@SuppressWarnings("unchecked") Map<String, Object> rawCapabilities = (Map<String, Object>) responseValue;
// TODO: remove this workaround for Selenium API enforcing some legacy capability values in major version
rawCapabilities.remove("platform");
if (rawCapabilities.containsKey(CapabilityType.BROWSER_NAME)
&& isBlank((String) rawCapabilities.get(CapabilityType.BROWSER_NAME))) {
rawCapabilities.remove(CapabilityType.BROWSER_NAME);
}
MutableCapabilities returnedCapabilities = new BaseOptions<>(rawCapabilities);
ReflectionHelpers.setPrivateFieldValue(
RemoteWebDriver.class, this, "capabilities", returnedCapabilities
);
setSessionId(response.getSessionId());
}
@Override
public Response execute(String driverCommand, Map<String, ?> parameters) {
return super.execute(driverCommand, parameters);
}
@Override
public Response execute(String command) {
return super.execute(command, Collections.emptyMap());
}
@Override
public <X> X getScreenshotAs(OutputType<X> outputType) {
// TODO: Eventually we should not override this method.
// TODO: Although, we have a legacy burden,
// TODO: so it's impossible to do it the other way as of Oct 29 2022.
// TODO: See https://github.com/SeleniumHQ/selenium/issues/11168
return super.getScreenshotAs(new OutputType<X>() {
@Override
public X convertFromBase64Png(String base64Png) {
String rfc4648Base64 = base64Png.replaceAll("\\r?\\n", "");
return outputType.convertFromBase64Png(rfc4648Base64);
}
@Override
public X convertFromPngBytes(byte[] png) {
return outputType.convertFromPngBytes(png);
}
});
}
@Override
public AppiumDriver assertExtensionExists(String extName) {
if (absentExtensionNames.contains(extName)) {
throw new UnsupportedCommandException();
}
return this;
}
@Override
public AppiumDriver markExtensionAbsence(String extName) {
absentExtensionNames.add(extName);
return this;
}
}