appium-android-driver 6.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +3 -105
  3. package/build/lib/commands/actions.d.ts +0 -1
  4. package/build/lib/commands/actions.d.ts.map +1 -1
  5. package/build/lib/commands/actions.js +14 -139
  6. package/build/lib/commands/actions.js.map +1 -1
  7. package/build/lib/commands/context.d.ts.map +1 -1
  8. package/build/lib/commands/context.js +0 -1
  9. package/build/lib/commands/context.js.map +1 -1
  10. package/build/lib/commands/element.d.ts +0 -1
  11. package/build/lib/commands/element.d.ts.map +1 -1
  12. package/build/lib/commands/element.js +14 -48
  13. package/build/lib/commands/element.js.map +1 -1
  14. package/build/lib/commands/execute.d.ts.map +1 -1
  15. package/build/lib/commands/execute.js +0 -1
  16. package/build/lib/commands/execute.js.map +1 -1
  17. package/build/lib/commands/find.d.ts.map +1 -1
  18. package/build/lib/commands/find.js +1 -1
  19. package/build/lib/commands/find.js.map +1 -1
  20. package/build/lib/commands/general.d.ts +0 -1
  21. package/build/lib/commands/general.d.ts.map +1 -1
  22. package/build/lib/commands/general.js +6 -11
  23. package/build/lib/commands/general.js.map +1 -1
  24. package/build/lib/commands/index.d.ts +23 -23
  25. package/build/lib/commands/mixins.d.ts +2 -6
  26. package/build/lib/commands/mixins.d.ts.map +1 -1
  27. package/build/lib/commands/mixins.js.map +1 -1
  28. package/build/lib/commands/network.d.ts.map +1 -1
  29. package/build/lib/commands/network.js +27 -55
  30. package/build/lib/commands/network.js.map +1 -1
  31. package/build/lib/commands/performance.d.ts +4 -4
  32. package/build/lib/commands/performance.d.ts.map +1 -1
  33. package/build/lib/commands/performance.js +0 -4
  34. package/build/lib/commands/performance.js.map +1 -1
  35. package/build/lib/commands/touch.d.ts +0 -1
  36. package/build/lib/commands/touch.d.ts.map +1 -1
  37. package/build/lib/commands/touch.js +1 -15
  38. package/build/lib/commands/touch.js.map +1 -1
  39. package/build/lib/constraints.d.ts +0 -9
  40. package/build/lib/constraints.d.ts.map +1 -1
  41. package/build/lib/constraints.js +0 -9
  42. package/build/lib/constraints.js.map +1 -1
  43. package/build/lib/driver.d.ts +2 -50
  44. package/build/lib/driver.d.ts.map +1 -1
  45. package/build/lib/driver.js +1 -476
  46. package/build/lib/driver.js.map +1 -1
  47. package/build/lib/helpers/android.d.ts +0 -2
  48. package/build/lib/helpers/android.d.ts.map +1 -1
  49. package/build/lib/helpers/android.js +0 -2
  50. package/build/lib/helpers/android.js.map +1 -1
  51. package/build/lib/helpers/webview.js.map +1 -1
  52. package/build/lib/stubs.d.ts +0 -1
  53. package/build/lib/stubs.d.ts.map +1 -1
  54. package/build/lib/stubs.js +0 -1
  55. package/build/lib/stubs.js.map +1 -1
  56. package/build/lib/utils.d.ts +3 -4
  57. package/build/lib/utils.d.ts.map +1 -1
  58. package/build/lib/utils.js +3 -4
  59. package/build/lib/utils.js.map +1 -1
  60. package/lib/commands/actions.js +15 -163
  61. package/lib/commands/context.js +0 -1
  62. package/lib/commands/element.js +14 -68
  63. package/lib/commands/execute.js +0 -1
  64. package/lib/commands/find.ts +1 -2
  65. package/lib/commands/general.js +6 -11
  66. package/lib/commands/mixins.ts +0 -6
  67. package/lib/commands/network.js +28 -61
  68. package/lib/commands/performance.js +0 -4
  69. package/lib/commands/touch.js +1 -20
  70. package/lib/constraints.ts +0 -9
  71. package/lib/driver.ts +7 -595
  72. package/lib/helpers/android.ts +0 -4
  73. package/lib/helpers/webview.ts +1 -1
  74. package/lib/stubs.ts +0 -1
  75. package/lib/utils.js +4 -5
  76. package/package.json +2 -5
  77. package/bootstrap/README.md +0 -19
  78. package/bootstrap/bin/AppiumBootstrap.jar +0 -0
  79. package/build/index.d.ts +0 -282
  80. package/build/index.d.ts.map +0 -1
  81. package/build/index.js +0 -51
  82. package/build/index.js.map +0 -1
  83. package/build/lib/android-helpers.d.ts +0 -136
  84. package/build/lib/android-helpers.d.ts.map +0 -1
  85. package/build/lib/android-helpers.js +0 -855
  86. package/build/lib/android-helpers.js.map +0 -1
  87. package/build/lib/bootstrap.d.ts +0 -29
  88. package/build/lib/bootstrap.d.ts.map +0 -1
  89. package/build/lib/bootstrap.js +0 -213
  90. package/build/lib/bootstrap.js.map +0 -1
  91. package/build/lib/commands/coverage.d.ts +0 -5
  92. package/build/lib/commands/coverage.d.ts.map +0 -1
  93. package/build/lib/commands/coverage.js +0 -19
  94. package/build/lib/commands/coverage.js.map +0 -1
  95. package/build/lib/desired-caps.d.ts +0 -353
  96. package/build/lib/desired-caps.d.ts.map +0 -1
  97. package/build/lib/desired-caps.js +0 -299
  98. package/build/lib/desired-caps.js.map +0 -1
  99. package/build/lib/uiautomator.d.ts +0 -24
  100. package/build/lib/uiautomator.d.ts.map +0 -1
  101. package/build/lib/uiautomator.js +0 -102
  102. package/build/lib/uiautomator.js.map +0 -1
  103. package/build/lib/unlock-helpers.d.ts +0 -38
  104. package/build/lib/unlock-helpers.d.ts.map +0 -1
  105. package/build/lib/unlock-helpers.js +0 -266
  106. package/build/lib/unlock-helpers.js.map +0 -1
  107. package/build/lib/webview-helpers.d.ts +0 -224
  108. package/build/lib/webview-helpers.d.ts.map +0 -1
  109. package/build/lib/webview-helpers.js +0 -528
  110. package/build/lib/webview-helpers.js.map +0 -1
  111. package/lib/bootstrap.js +0 -227
  112. package/lib/uiautomator.js +0 -109
@@ -1,855 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ensureNetworkSpeed = exports.prepareAvdArgs = exports.APP_STATE = exports.SETTINGS_HELPER_PKG_ID = exports.helpers = void 0;
7
- const lodash_1 = __importDefault(require("lodash"));
8
- const path_1 = __importDefault(require("path"));
9
- const asyncbox_1 = require("asyncbox");
10
- const logger_1 = __importDefault(require("./logger"));
11
- const support_1 = require("@appium/support");
12
- const io_appium_settings_1 = require("io.appium.settings");
13
- const bootstrap_1 = __importDefault(require("./bootstrap"));
14
- const bluebird_1 = __importDefault(require("bluebird"));
15
- const appium_adb_1 = __importDefault(require("appium-adb"));
16
- const unlock_helpers_1 = require("./unlock-helpers");
17
- const os_1 = require("os");
18
- const semver_1 = __importDefault(require("semver"));
19
- const MOCK_APP_IDS_STORE = '/data/local/tmp/mock_apps.json';
20
- const PACKAGE_INSTALL_TIMEOUT_MS = 90000;
21
- const HELPER_APP_INSTALL_RETRIES = 3;
22
- const HELPER_APP_INSTALL_RETRY_DELAY_MS = 5000;
23
- // https://cs.chromium.org/chromium/src/chrome/browser/devtools/device/android_device_info_query.cc
24
- const CHROME_BROWSER_PACKAGE_ACTIVITY = {
25
- chrome: {
26
- pkg: 'com.android.chrome',
27
- activity: 'com.google.android.apps.chrome.Main',
28
- },
29
- chromium: {
30
- pkg: 'org.chromium.chrome.shell',
31
- activity: '.ChromeShellActivity',
32
- },
33
- chromebeta: {
34
- pkg: 'com.chrome.beta',
35
- activity: 'com.google.android.apps.chrome.Main',
36
- },
37
- browser: {
38
- pkg: 'com.android.browser',
39
- activity: 'com.android.browser.BrowserActivity',
40
- },
41
- 'chromium-browser': {
42
- pkg: 'org.chromium.chrome',
43
- activity: 'com.google.android.apps.chrome.Main',
44
- },
45
- 'chromium-webview': {
46
- pkg: 'org.chromium.webview_shell',
47
- activity: 'org.chromium.webview_shell.WebViewBrowserActivity',
48
- },
49
- default: {
50
- pkg: 'com.android.chrome',
51
- activity: 'com.google.android.apps.chrome.Main',
52
- },
53
- };
54
- const SETTINGS_HELPER_PKG_ID = 'io.appium.settings';
55
- exports.SETTINGS_HELPER_PKG_ID = SETTINGS_HELPER_PKG_ID;
56
- const SETTING_NOTIFICATIONS_LISTENER_SERVICE = `${SETTINGS_HELPER_PKG_ID}/.NLService`;
57
- const EMULATOR_PATTERN = /\bemulator\b/i;
58
- // These constants are in sync with
59
- // https://developer.apple.com/documentation/xctest/xcuiapplicationstate/xcuiapplicationstaterunningbackground?language=objc
60
- const APP_STATE = Object.freeze({
61
- NOT_INSTALLED: 0,
62
- NOT_RUNNING: 1,
63
- RUNNING_IN_BACKGROUND: 3,
64
- RUNNING_IN_FOREGROUND: 4
65
- });
66
- exports.APP_STATE = APP_STATE;
67
- function ensureNetworkSpeed(adb, networkSpeed) {
68
- if (lodash_1.default.values(adb.NETWORK_SPEED).includes(networkSpeed)) {
69
- return networkSpeed;
70
- }
71
- logger_1.default.warn(`Wrong network speed param '${networkSpeed}', using default: ${adb.NETWORK_SPEED.FULL}. ` +
72
- `Supported values: ${lodash_1.default.values(adb.NETWORK_SPEED)}`);
73
- return adb.NETWORK_SPEED.FULL;
74
- }
75
- exports.ensureNetworkSpeed = ensureNetworkSpeed;
76
- function prepareAvdArgs(adb, opts) {
77
- const { networkSpeed, isHeadless, avdArgs, } = opts;
78
- const result = [];
79
- if (avdArgs) {
80
- if (lodash_1.default.isArray(avdArgs)) {
81
- result.push(...avdArgs);
82
- }
83
- else {
84
- result.push(...(support_1.util.shellParse(`${avdArgs}`)));
85
- }
86
- }
87
- if (networkSpeed) {
88
- result.push('-netspeed', ensureNetworkSpeed(adb, networkSpeed));
89
- }
90
- if (isHeadless) {
91
- result.push('-no-window');
92
- }
93
- return result;
94
- }
95
- exports.prepareAvdArgs = prepareAvdArgs;
96
- function toCredentialType(unlockType) {
97
- const result = {
98
- [unlock_helpers_1.PIN_UNLOCK]: 'pin',
99
- [unlock_helpers_1.PIN_UNLOCK_KEY_EVENT]: 'pin',
100
- [unlock_helpers_1.PASSWORD_UNLOCK]: 'password',
101
- [unlock_helpers_1.PATTERN_UNLOCK]: 'pattern',
102
- }[unlockType];
103
- if (result) {
104
- return result;
105
- }
106
- throw new Error(`Unlock type '${unlockType}' is not known`);
107
- }
108
- const helpers = {};
109
- exports.helpers = helpers;
110
- helpers.createBaseADB = async function createBaseADB(opts = {}) {
111
- // filter out any unwanted options sent in
112
- // this list should be updated as ADB takes more arguments
113
- const { adbPort, suppressKillServer, remoteAdbHost, clearDeviceLogsOnStart, adbExecTimeout, useKeystore, keystorePath, keystorePassword, keyAlias, keyPassword, remoteAppsCacheLimit, buildToolsVersion, allowOfflineDevices, allowDelayAdb, } = opts;
114
- return await appium_adb_1.default.createADB({
115
- adbPort,
116
- suppressKillServer,
117
- remoteAdbHost,
118
- clearDeviceLogsOnStart,
119
- adbExecTimeout,
120
- useKeystore,
121
- keystorePath,
122
- keystorePassword,
123
- keyAlias,
124
- keyPassword,
125
- remoteAppsCacheLimit,
126
- buildToolsVersion,
127
- allowOfflineDevices,
128
- allowDelayAdb,
129
- });
130
- };
131
- helpers.prepareEmulator = async function prepareEmulator(adb, opts) {
132
- const { avd, avdEnv: env, language, locale: country, avdLaunchTimeout: launchTimeout, avdReadyTimeout: readyTimeout, } = opts;
133
- if (!avd) {
134
- throw new Error('Cannot launch AVD without AVD name');
135
- }
136
- const avdName = avd.replace('@', '');
137
- let isEmulatorRunning = true;
138
- try {
139
- await adb.getRunningAVDWithRetry(avdName, 5000);
140
- }
141
- catch (e) {
142
- logger_1.default.debug(`Emulator '${avdName}' is not running: ${e.message}`);
143
- isEmulatorRunning = false;
144
- }
145
- const args = prepareAvdArgs(adb, opts);
146
- if (isEmulatorRunning) {
147
- if (args.includes('-wipe-data')) {
148
- logger_1.default.debug(`Killing '${avdName}' because it needs to be wiped at start.`);
149
- await adb.killEmulator(avdName);
150
- }
151
- else {
152
- logger_1.default.debug('Not launching AVD because it is already running.');
153
- return;
154
- }
155
- }
156
- await adb.launchAVD(avd, {
157
- args,
158
- env,
159
- language,
160
- country,
161
- launchTimeout,
162
- readyTimeout,
163
- });
164
- };
165
- /**
166
- * Set and ensure the locale name of the device under test.
167
- *
168
- * @param {Object} adb - The adb module instance.
169
- * @param {string} language - Language. The language field is case insensitive, but Locale always canonicalizes to lower case.
170
- * format: [a-zA-Z]{2,8}. e.g. en, ja : https://developer.android.com/reference/java/util/Locale.html
171
- * @param {string} country - Country. The country (region) field is case insensitive, but Locale always canonicalizes to upper case.
172
- * format: [a-zA-Z]{2} | [0-9]{3}. e.g. US, JP : https://developer.android.com/reference/java/util/Locale.html
173
- * @param {?string} script - Script. The script field is case insensitive but Locale always canonicalizes to title case.
174
- * format: [a-zA-Z]{4}. e.g. Hans in zh-Hans-CN : https://developer.android.com/reference/java/util/Locale.html
175
- * @throws {Error} If it failed to set locale properly
176
- */
177
- helpers.ensureDeviceLocale = async function ensureDeviceLocale(adb, language, country, script = null) {
178
- if (!lodash_1.default.isString(language) && !lodash_1.default.isString(country)) {
179
- logger_1.default.warn(`setDeviceLanguageCountry requires language or country.`);
180
- logger_1.default.warn(`Got language: '${language}' and country: '${country}'`);
181
- return;
182
- }
183
- await adb.setDeviceLanguageCountry(language, country, script);
184
- if (!await adb.ensureCurrentLocale(language, country, script)) {
185
- const message = script ? `language: ${language}, country: ${country} and script: ${script}` : `language: ${language} and country: ${country}`;
186
- throw new Error(`Failed to set ${message}`);
187
- }
188
- };
189
- helpers.getDeviceInfoFromCaps = async function getDeviceInfoFromCaps(opts = {}) {
190
- // we can create a throwaway ADB instance here, so there is no dependency
191
- // on instantiating on earlier (at this point, we have no udid)
192
- // we can only use this ADB object for commands that would not be confused
193
- // if multiple devices are connected
194
- const adb = await helpers.createBaseADB(opts);
195
- let udid = opts.udid;
196
- let emPort = null;
197
- // a specific avd name was given. try to initialize with that
198
- if (opts.avd) {
199
- await helpers.prepareEmulator(adb, opts);
200
- udid = adb.curDeviceId;
201
- emPort = adb.emulatorPort;
202
- }
203
- else {
204
- // no avd given. lets try whatever's plugged in devices/emulators
205
- logger_1.default.info('Retrieving device list');
206
- let devices = await adb.getDevicesWithRetry();
207
- // udid was given, lets try to init with that device
208
- if (udid) {
209
- if (!lodash_1.default.includes(lodash_1.default.map(devices, 'udid'), udid)) {
210
- logger_1.default.errorAndThrow(`Device ${udid} was not in the list of connected devices`);
211
- }
212
- emPort = adb.getPortFromEmulatorString(udid);
213
- }
214
- else if (opts.platformVersion) {
215
- opts.platformVersion = `${opts.platformVersion}`.trim();
216
- // a platform version was given. lets try to find a device with the same os
217
- const platformVersion = semver_1.default.coerce(opts.platformVersion) || opts.platformVersion;
218
- logger_1.default.info(`Looking for a device with Android '${platformVersion}'`);
219
- // in case we fail to find something, give the user a useful log that has
220
- // the device udids and os versions so they know what's available
221
- const availDevices = [];
222
- let partialMatchCandidate = null;
223
- // first try started devices/emulators
224
- for (const device of devices) {
225
- // direct adb calls to the specific device
226
- await adb.setDeviceId(device.udid);
227
- const rawDeviceOS = await adb.getPlatformVersion();
228
- // The device OS could either be a number, like `6.0`
229
- // or an abbreviation, like `R`
230
- availDevices.push(`${device.udid} (${rawDeviceOS})`);
231
- const deviceOS = semver_1.default.coerce(rawDeviceOS) || rawDeviceOS;
232
- if (!deviceOS) {
233
- continue;
234
- }
235
- const bothVersionsCanBeCoerced = semver_1.default.valid(deviceOS) && semver_1.default.valid(platformVersion);
236
- const bothVersionsAreStrings = lodash_1.default.isString(deviceOS) && lodash_1.default.isString(platformVersion);
237
- if (bothVersionsCanBeCoerced && deviceOS.version === platformVersion.version
238
- || bothVersionsAreStrings && lodash_1.default.toLower(deviceOS) === lodash_1.default.toLower(platformVersion)) {
239
- // Got an exact match - proceed immediately
240
- udid = device.udid;
241
- break;
242
- }
243
- else if (!bothVersionsCanBeCoerced) {
244
- // There is no point to check for partial match if either of version numbers is not coercible
245
- continue;
246
- }
247
- if ((!lodash_1.default.includes(opts.platformVersion, '.') && platformVersion.major === deviceOS.major
248
- || platformVersion.major === deviceOS.major && platformVersion.minor === deviceOS.minor)
249
- // Got a partial match - make sure we consider the most recent
250
- // device version available on the host system
251
- && (partialMatchCandidate && semver_1.default.gt(deviceOS, lodash_1.default.values(partialMatchCandidate)[0])
252
- || !partialMatchCandidate)) {
253
- partialMatchCandidate = { [device.udid]: deviceOS };
254
- }
255
- }
256
- if (!udid && partialMatchCandidate) {
257
- udid = lodash_1.default.keys(partialMatchCandidate)[0];
258
- await adb.setDeviceId(udid);
259
- }
260
- if (!udid) {
261
- // we couldn't find anything! quit
262
- logger_1.default.errorAndThrow(`Unable to find an active device or emulator ` +
263
- `with OS ${opts.platformVersion}. The following are available: ` +
264
- availDevices.join(', '));
265
- }
266
- emPort = adb.getPortFromEmulatorString(udid);
267
- }
268
- else {
269
- // a udid was not given, grab the first device we see
270
- udid = devices[0].udid;
271
- emPort = adb.getPortFromEmulatorString(udid);
272
- }
273
- }
274
- logger_1.default.info(`Using device: ${udid}`);
275
- return { udid, emPort };
276
- };
277
- // returns a new adb instance with deviceId set
278
- helpers.createADB = async function createADB(opts = {}) {
279
- const { udid, emPort } = opts;
280
- const adb = await helpers.createBaseADB(opts);
281
- adb.setDeviceId(udid);
282
- if (emPort) {
283
- adb.setEmulatorPort(emPort);
284
- }
285
- return adb;
286
- };
287
- helpers.validatePackageActivityNames = function validatePackageActivityNames(opts) {
288
- for (const key of ['appPackage', 'appActivity', 'appWaitPackage', 'appWaitActivity']) {
289
- const name = opts[key];
290
- if (!name) {
291
- continue;
292
- }
293
- const match = /([^\w.*,])+/.exec(name);
294
- if (!match) {
295
- continue;
296
- }
297
- logger_1.default.warn(`Capability '${key}' is expected to only include latin letters, digits, underscore, dot, comma and asterisk characters.`);
298
- logger_1.default.warn(`Current value '${name}' has non-matching character at index ${match.index}: '${name.substring(0, match.index + 1)}'`);
299
- }
300
- };
301
- helpers.getLaunchInfo = async function getLaunchInfo(adb, opts) {
302
- let { app, appPackage, appActivity, appWaitPackage, appWaitActivity } = opts;
303
- if (!app) {
304
- logger_1.default.warn('No app sent in, not parsing package/activity');
305
- return;
306
- }
307
- this.validatePackageActivityNames(opts);
308
- if (appPackage && appActivity) {
309
- return;
310
- }
311
- logger_1.default.debug('Parsing package and activity from app manifest');
312
- let { apkPackage, apkActivity } = await adb.packageAndLaunchActivityFromManifest(app);
313
- if (apkPackage && !appPackage) {
314
- appPackage = apkPackage;
315
- }
316
- if (!appWaitPackage) {
317
- appWaitPackage = appPackage;
318
- }
319
- if (apkActivity && !appActivity) {
320
- appActivity = apkActivity;
321
- }
322
- if (!appWaitActivity) {
323
- appWaitActivity = appActivity;
324
- }
325
- logger_1.default.debug(`Parsed package and activity are: ${apkPackage}/${apkActivity}`);
326
- return { appPackage, appWaitPackage, appActivity, appWaitActivity };
327
- };
328
- helpers.resetApp = async function resetApp(adb, opts = {}) {
329
- const { app, appPackage, fastReset, fullReset, androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS, autoGrantPermissions, allowTestPackages } = opts;
330
- if (!appPackage) {
331
- throw new Error("'appPackage' option is required");
332
- }
333
- const isInstalled = await adb.isAppInstalled(appPackage);
334
- if (isInstalled) {
335
- try {
336
- await adb.forceStop(appPackage);
337
- }
338
- catch (ign) { }
339
- // fullReset has priority over fastReset
340
- if (!fullReset && fastReset) {
341
- const output = await adb.clear(appPackage);
342
- if (lodash_1.default.isString(output) && output.toLowerCase().includes('failed')) {
343
- throw new Error(`Cannot clear the application data of '${appPackage}'. Original error: ${output}`);
344
- }
345
- // executing `shell pm clear` resets previously assigned application permissions as well
346
- if (autoGrantPermissions) {
347
- try {
348
- await adb.grantAllPermissions(appPackage);
349
- }
350
- catch (error) {
351
- logger_1.default.error(`Unable to grant permissions requested. Original error: ${error.message}`);
352
- }
353
- }
354
- logger_1.default.debug(`Performed fast reset on the installed '${appPackage}' application (stop and clear)`);
355
- return;
356
- }
357
- }
358
- if (!app) {
359
- throw new Error(`Either provide 'app' option to install '${appPackage}' or ` +
360
- `consider setting 'noReset' to 'true' if '${appPackage}' is supposed to be preinstalled.`);
361
- }
362
- logger_1.default.debug(`Running full reset on '${appPackage}' (reinstall)`);
363
- if (isInstalled) {
364
- await adb.uninstallApk(appPackage);
365
- }
366
- await adb.install(app, {
367
- grantPermissions: autoGrantPermissions,
368
- timeout: androidInstallTimeout,
369
- allowTestPackages,
370
- });
371
- };
372
- helpers.installApk = async function installApk(adb, opts = {}) {
373
- const { app, appPackage, fastReset, fullReset, androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS, autoGrantPermissions, allowTestPackages, enforceAppInstall, } = opts;
374
- if (!app || !appPackage) {
375
- throw new Error("'app' and 'appPackage' options are required");
376
- }
377
- if (fullReset) {
378
- await this.resetApp(adb, opts);
379
- return;
380
- }
381
- const { appState, wasUninstalled } = await adb.installOrUpgrade(app, appPackage, {
382
- grantPermissions: autoGrantPermissions,
383
- timeout: androidInstallTimeout,
384
- allowTestPackages,
385
- enforceCurrentBuild: enforceAppInstall,
386
- });
387
- // There is no need to reset the newly installed app
388
- const isInstalledOverExistingApp = !wasUninstalled
389
- && appState !== adb.APP_INSTALL_STATE.NOT_INSTALLED;
390
- if (fastReset && isInstalledOverExistingApp) {
391
- logger_1.default.info(`Performing fast reset on '${appPackage}'`);
392
- await this.resetApp(adb, opts);
393
- }
394
- };
395
- /**
396
- * Installs an array of apks
397
- * @param {ADB} adb Instance of Appium ADB object
398
- * @param {Object} opts Opts defined in driver.js
399
- */
400
- helpers.installOtherApks = async function installOtherApks(otherApps, adb, opts) {
401
- let { androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS, autoGrantPermissions, allowTestPackages } = opts;
402
- // Install all of the APK's asynchronously
403
- await bluebird_1.default.all(otherApps.map((otherApp) => {
404
- logger_1.default.debug(`Installing app: ${otherApp}`);
405
- return adb.installOrUpgrade(otherApp, null, {
406
- grantPermissions: autoGrantPermissions,
407
- timeout: androidInstallTimeout,
408
- allowTestPackages,
409
- });
410
- }));
411
- };
412
- /**
413
- * Uninstall an array of packages
414
- * @param {ADB} adb Instance of Appium ADB object
415
- * @param {Array<string>} appPackages An array of package names to uninstall. If this includes `'*'`, uninstall all of 3rd party apps
416
- * @param {Array<string>} filterPackages An array of packages does not uninstall when `*` is provided as `appPackages`
417
- */
418
- helpers.uninstallOtherPackages = async function uninstallOtherPackages(adb, appPackages, filterPackages = []) {
419
- if (appPackages.includes('*')) {
420
- logger_1.default.debug('Uninstall third party packages');
421
- appPackages = await this.getThirdPartyPackages(adb, filterPackages);
422
- }
423
- logger_1.default.debug(`Uninstalling packages: ${appPackages}`);
424
- await bluebird_1.default.all(appPackages.map((appPackage) => adb.uninstallApk(appPackage)));
425
- };
426
- /**
427
- * Get third party packages filtered with `filterPackages`
428
- * @param {ADB} adb Instance of Appium ADB object
429
- * @param {Array<string>} filterPackages An array of packages does not uninstall when `*` is provided as `appPackages`
430
- * @returns {Array<string>} An array of installed third pary packages
431
- */
432
- helpers.getThirdPartyPackages = async function getThirdPartyPackages(adb, filterPackages = []) {
433
- try {
434
- const packagesString = await adb.shell(['pm', 'list', 'packages', '-3']);
435
- const appPackagesArray = packagesString.trim().replace(/package:/g, '').split(os_1.EOL);
436
- logger_1.default.debug(`'${appPackagesArray}' filtered with '${filterPackages}'`);
437
- return lodash_1.default.difference(appPackagesArray, filterPackages);
438
- }
439
- catch (err) {
440
- logger_1.default.warn(`Unable to get packages with 'adb shell pm list packages -3': ${err.message}`);
441
- return [];
442
- }
443
- };
444
- helpers.initUnicodeKeyboard = async function initUnicodeKeyboard(adb) {
445
- logger_1.default.debug('Enabling Unicode keyboard support');
446
- // get the default IME so we can return back to it later if we want
447
- let defaultIME = await adb.defaultIME();
448
- logger_1.default.debug(`Unsetting previous IME ${defaultIME}`);
449
- const appiumIME = `${SETTINGS_HELPER_PKG_ID}/.UnicodeIME`;
450
- logger_1.default.debug(`Setting IME to '${appiumIME}'`);
451
- await adb.enableIME(appiumIME);
452
- await adb.setIME(appiumIME);
453
- return defaultIME;
454
- };
455
- helpers.setMockLocationApp = async function setMockLocationApp(adb, app) {
456
- try {
457
- if (await adb.getApiLevel() < 23) {
458
- await adb.shell(['settings', 'put', 'secure', 'mock_location', '1']);
459
- }
460
- else {
461
- await adb.shell(['appops', 'set', app, 'android:mock_location', 'allow']);
462
- }
463
- }
464
- catch (err) {
465
- logger_1.default.warn(`Unable to set mock location for app '${app}': ${err.message}`);
466
- return;
467
- }
468
- try {
469
- let pkgIds = [];
470
- if (await adb.fileExists(MOCK_APP_IDS_STORE)) {
471
- try {
472
- pkgIds = JSON.parse(await adb.shell(['cat', MOCK_APP_IDS_STORE]));
473
- }
474
- catch (ign) { }
475
- }
476
- if (pkgIds.includes(app)) {
477
- return;
478
- }
479
- pkgIds.push(app);
480
- const tmpRoot = await support_1.tempDir.openDir();
481
- const srcPath = path_1.default.posix.join(tmpRoot, path_1.default.posix.basename(MOCK_APP_IDS_STORE));
482
- try {
483
- await support_1.fs.writeFile(srcPath, JSON.stringify(pkgIds), 'utf8');
484
- await adb.push(srcPath, MOCK_APP_IDS_STORE);
485
- }
486
- finally {
487
- await support_1.fs.rimraf(tmpRoot);
488
- }
489
- }
490
- catch (e) {
491
- logger_1.default.warn(`Unable to persist mock location app id '${app}': ${e.message}`);
492
- }
493
- };
494
- helpers.resetMockLocation = async function resetMockLocation(adb) {
495
- try {
496
- if (await adb.getApiLevel() < 23) {
497
- await adb.shell(['settings', 'put', 'secure', 'mock_location', '0']);
498
- return;
499
- }
500
- const thirdPartyPkgIdsPromise = helpers.getThirdPartyPackages(adb);
501
- let pkgIds = [];
502
- if (await adb.fileExists(MOCK_APP_IDS_STORE)) {
503
- try {
504
- pkgIds = JSON.parse(await adb.shell(['cat', MOCK_APP_IDS_STORE]));
505
- }
506
- catch (ign) { }
507
- }
508
- const thirdPartyPkgIds = await thirdPartyPkgIdsPromise;
509
- // Only include currently installed packages
510
- const resultPkgs = lodash_1.default.intersection(pkgIds, thirdPartyPkgIds);
511
- if (lodash_1.default.size(resultPkgs) <= 1) {
512
- await adb.shell(['appops', 'set', resultPkgs[0] ?? SETTINGS_HELPER_PKG_ID, 'android:mock_location', 'deny']);
513
- return;
514
- }
515
- logger_1.default.debug(`Resetting mock_location permission for the following apps: ${resultPkgs}`);
516
- await bluebird_1.default.all(resultPkgs.map((pkgId) => (async () => {
517
- try {
518
- await adb.shell(['appops', 'set', pkgId, 'android:mock_location', 'deny']);
519
- }
520
- catch (ign) { }
521
- })()));
522
- }
523
- catch (err) {
524
- logger_1.default.warn(`Unable to reset mock location: ${err.message}`);
525
- }
526
- };
527
- helpers.installHelperApp = async function installHelperApp(adb, apkPath, packageId) {
528
- // Sometimes adb push or adb instal take more time than expected to install an app
529
- // e.g. https://github.com/appium/io.appium.settings/issues/40#issuecomment-476593174
530
- await (0, asyncbox_1.retryInterval)(HELPER_APP_INSTALL_RETRIES, HELPER_APP_INSTALL_RETRY_DELAY_MS, async function retryInstallHelperApp() {
531
- await adb.installOrUpgrade(apkPath, packageId, { grantPermissions: true });
532
- });
533
- };
534
- /**
535
- * Pushes and installs io.appium.settings app.
536
- * Throws an error if the setting app is required
537
- *
538
- * @param {Adb} adb - The adb module instance.
539
- * @param {Object} opts - Driver options dictionary.
540
- * @param {boolean} throwError [false] - Whether throw an error if Settings app fails to start
541
- * @throws {Error} If throwError is true and something happens in installation step
542
- */
543
- helpers.pushSettingsApp = async function pushSettingsApp(adb, throwError = false, opts = {}) {
544
- logger_1.default.debug('Pushing settings apk to device...');
545
- try {
546
- await helpers.installHelperApp(adb, io_appium_settings_1.path, SETTINGS_HELPER_PKG_ID, throwError);
547
- }
548
- catch (err) {
549
- if (throwError) {
550
- throw err;
551
- }
552
- logger_1.default.warn(`Ignored error while installing '${io_appium_settings_1.path}': ` +
553
- `'${err.message}'. Features that rely on this helper ` +
554
- 'require the apk such as toggle WiFi and getting location ' +
555
- 'will raise an error if you try to use them.');
556
- }
557
- // Reinstall would stop the settings helper process anyway, so
558
- // there is no need to continue if the application is still running
559
- if (await adb.processExists(SETTINGS_HELPER_PKG_ID)) {
560
- logger_1.default.debug(`${SETTINGS_HELPER_PKG_ID} is already running. ` +
561
- `There is no need to reset its permissions.`);
562
- return;
563
- }
564
- const apiLevel = await adb.getApiLevel();
565
- if (apiLevel >= 29) {
566
- // https://github.com/appium/io.appium.settings#internal-audio--video-recording
567
- try {
568
- await adb.shell(['appops', 'set', SETTINGS_HELPER_PKG_ID, 'PROJECT_MEDIA', 'allow']);
569
- }
570
- catch (err) {
571
- logger_1.default.debug(err.message);
572
- }
573
- try {
574
- await adb.shell(['cmd', 'notification', 'allow_listener', SETTING_NOTIFICATIONS_LISTENER_SERVICE]);
575
- }
576
- catch (err) {
577
- logger_1.default.debug(err.message);
578
- }
579
- }
580
- if (apiLevel <= 23) { // Android 6- devices should have granted permissions
581
- // https://github.com/appium/appium/pull/11640#issuecomment-438260477
582
- const perms = ['SET_ANIMATION_SCALE', 'CHANGE_CONFIGURATION', 'ACCESS_FINE_LOCATION'];
583
- logger_1.default.info(`Granting permissions ${perms} to '${SETTINGS_HELPER_PKG_ID}'`);
584
- await adb.grantPermissions(SETTINGS_HELPER_PKG_ID, perms.map((x) => `android.permission.${x}`));
585
- }
586
- // launch io.appium.settings app due to settings failing to be set
587
- // if the app is not launched prior to start the session on android 7+
588
- // see https://github.com/appium/appium/issues/8957
589
- try {
590
- await adb.requireRunningSettingsApp({
591
- timeout: helpers.isEmulator(adb, opts) ? 30000 : 5000
592
- });
593
- }
594
- catch (err) {
595
- logger_1.default.debug(err);
596
- if (throwError) {
597
- throw err;
598
- }
599
- }
600
- };
601
- /**
602
- * Extracts string.xml and converts it to string.json and pushes
603
- * it to /data/local/tmp/string.json on for use of bootstrap
604
- * If app is not present to extract string.xml it deletes remote strings.json
605
- * If app does not have strings.xml we push an empty json object to remote
606
- *
607
- * @param {?string} language - Language abbreviation, for example 'fr'. The default language
608
- * is used if this argument is not defined.
609
- * @param {Object} adb - The adb module instance.
610
- * @param {Object} opts - Driver options dictionary.
611
- * @returns {Object} The dictionary, where string resource identifiers are keys
612
- * along with their corresponding values for the given language or an empty object
613
- * if no matching resources were extracted.
614
- */
615
- helpers.pushStrings = async function pushStrings(language, adb, opts) {
616
- const remoteDir = '/data/local/tmp';
617
- const stringsJson = 'strings.json';
618
- const remoteFile = path_1.default.posix.resolve(remoteDir, stringsJson);
619
- // clean up remote string.json if present
620
- await adb.rimraf(remoteFile);
621
- let app;
622
- try {
623
- app = opts.app || await adb.pullApk(opts.appPackage, opts.tmpDir);
624
- }
625
- catch (err) {
626
- logger_1.default.info(`Failed to pull an apk from '${opts.appPackage}' to '${opts.tmpDir}'. Original error: ${err.message}`);
627
- }
628
- if (lodash_1.default.isEmpty(opts.appPackage) || !(await support_1.fs.exists(app))) {
629
- logger_1.default.debug(`No app or package specified. Returning empty strings`);
630
- return {};
631
- }
632
- const stringsTmpDir = path_1.default.resolve(opts.tmpDir, opts.appPackage);
633
- try {
634
- logger_1.default.debug('Extracting strings from apk', app, language, stringsTmpDir);
635
- const { apkStrings, localPath } = await adb.extractStringsFromApk(app, language, stringsTmpDir);
636
- await adb.push(localPath, remoteDir);
637
- return apkStrings;
638
- }
639
- catch (err) {
640
- logger_1.default.warn(`Could not get strings, continuing anyway. Original error: ${err.message}`);
641
- await adb.shell('echo', [`'{}' > ${remoteFile}`]);
642
- }
643
- finally {
644
- await support_1.fs.rimraf(stringsTmpDir);
645
- }
646
- return {};
647
- };
648
- helpers.unlock = async function unlock(driver, adb, capabilities) {
649
- if (!(await adb.isScreenLocked())) {
650
- logger_1.default.info('Screen already unlocked, doing nothing');
651
- return;
652
- }
653
- logger_1.default.debug('Screen is locked, trying to unlock');
654
- if (!capabilities.unlockType && !capabilities.unlockKey) {
655
- logger_1.default.info(`Neither 'unlockType' nor 'unlockKey' capability is provided. ` +
656
- `Assuming the device is locked with a simple lock screen.`);
657
- await adb.dismissKeyguard();
658
- return;
659
- }
660
- const { unlockType, unlockKey, unlockStrategy, unlockSuccessTimeout, } = unlock_helpers_1.helpers.validateUnlockCapabilities(capabilities);
661
- if (unlockKey && unlockType !== unlock_helpers_1.FINGERPRINT_UNLOCK
662
- && (lodash_1.default.isNil(unlockStrategy) || lodash_1.default.toLower(unlockStrategy) === 'locksettings')
663
- && await adb.isLockManagementSupported()) {
664
- await unlock_helpers_1.helpers.fastUnlock(adb, {
665
- credential: unlockKey,
666
- credentialType: toCredentialType(unlockType),
667
- });
668
- }
669
- else {
670
- const unlockMethod = {
671
- [unlock_helpers_1.PIN_UNLOCK]: unlock_helpers_1.helpers.pinUnlock,
672
- [unlock_helpers_1.PIN_UNLOCK_KEY_EVENT]: unlock_helpers_1.helpers.pinUnlockWithKeyEvent,
673
- [unlock_helpers_1.PASSWORD_UNLOCK]: unlock_helpers_1.helpers.passwordUnlock,
674
- [unlock_helpers_1.PATTERN_UNLOCK]: unlock_helpers_1.helpers.patternUnlock,
675
- [unlock_helpers_1.FINGERPRINT_UNLOCK]: unlock_helpers_1.helpers.fingerprintUnlock,
676
- }[unlockType];
677
- await unlockMethod(adb, driver, capabilities);
678
- }
679
- await helpers.verifyUnlock(adb, unlockSuccessTimeout);
680
- };
681
- helpers.verifyUnlock = async function verifyUnlock(adb, timeoutMs = null) {
682
- try {
683
- await (0, asyncbox_1.waitForCondition)(async () => !(await adb.isScreenLocked()), {
684
- waitMs: timeoutMs ?? 2000,
685
- intervalMs: 500,
686
- });
687
- }
688
- catch (ign) {
689
- throw new Error('The device has failed to be unlocked');
690
- }
691
- logger_1.default.info('The device has been successfully unlocked');
692
- };
693
- helpers.initDevice = async function initDevice(adb, opts) {
694
- const { skipDeviceInitialization, locale, language, localeScript, unicodeKeyboard, disableWindowAnimation, skipUnlock, mockLocationApp, skipLogcatCapture, logcatFormat, logcatFilterSpecs, } = opts;
695
- if (skipDeviceInitialization) {
696
- logger_1.default.info(`'skipDeviceInitialization' is set. Skipping device initialization.`);
697
- }
698
- else {
699
- if (helpers.isEmulator(adb, opts)) {
700
- // Check if the device wake up only for an emulator.
701
- // It takes 1 second or so even when the device is already awake in a real device.
702
- await adb.waitForDevice();
703
- }
704
- // pushSettingsApp required before calling ensureDeviceLocale for API Level 24+
705
- // Some feature such as location/wifi are not necessary for all users,
706
- // but they require the settings app. So, try to configure it while Appium
707
- // does not throw error even if they fail.
708
- const shouldThrowError = language
709
- || locale
710
- || localeScript
711
- || unicodeKeyboard
712
- || disableWindowAnimation
713
- || !skipUnlock;
714
- await helpers.pushSettingsApp(adb, shouldThrowError, opts);
715
- }
716
- if (!helpers.isEmulator(adb, opts)) {
717
- if (mockLocationApp || lodash_1.default.isUndefined(mockLocationApp)) {
718
- await helpers.setMockLocationApp(adb, mockLocationApp || SETTINGS_HELPER_PKG_ID);
719
- }
720
- else {
721
- await helpers.resetMockLocation(adb);
722
- }
723
- }
724
- if (language || locale) {
725
- await helpers.ensureDeviceLocale(adb, language, locale, localeScript);
726
- }
727
- if (skipLogcatCapture) {
728
- logger_1.default.info(`'skipLogcatCapture' is set. Skipping starting logcat capture.`);
729
- }
730
- else {
731
- await adb.startLogcat({
732
- format: logcatFormat,
733
- filterSpecs: logcatFilterSpecs,
734
- });
735
- }
736
- if (unicodeKeyboard) {
737
- return await helpers.initUnicodeKeyboard(adb);
738
- }
739
- };
740
- helpers.removeNullProperties = function removeNullProperties(obj) {
741
- for (let key of lodash_1.default.keys(obj)) {
742
- if (lodash_1.default.isNull(obj[key]) || lodash_1.default.isUndefined(obj[key])) {
743
- delete obj[key];
744
- }
745
- }
746
- };
747
- helpers.truncateDecimals = function truncateDecimals(number, digits) {
748
- let multiplier = Math.pow(10, digits), adjustedNum = number * multiplier, truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);
749
- return truncatedNum / multiplier;
750
- };
751
- helpers.isChromeBrowser = function isChromeBrowser(browser) {
752
- return lodash_1.default.includes(Object.keys(CHROME_BROWSER_PACKAGE_ACTIVITY), (browser || '').toLowerCase());
753
- };
754
- helpers.getChromePkg = function getChromePkg(browser) {
755
- return CHROME_BROWSER_PACKAGE_ACTIVITY[browser.toLowerCase()] || CHROME_BROWSER_PACKAGE_ACTIVITY.default;
756
- };
757
- helpers.removeAllSessionWebSocketHandlers = async function removeAllSessionWebSocketHandlers(server, sessionId) {
758
- if (!server || !lodash_1.default.isFunction(server.getWebSocketHandlers)) {
759
- return;
760
- }
761
- const activeHandlers = await server.getWebSocketHandlers(sessionId);
762
- for (const pathname of lodash_1.default.keys(activeHandlers)) {
763
- await server.removeWebSocketHandler(pathname);
764
- }
765
- };
766
- /**
767
- * Takes a desired capability and tries to JSON.parse it as an array,
768
- * and either returns the parsed array or a singleton array.
769
- *
770
- * @param {any} cap A desired capability
771
- */
772
- helpers.parseArray = function parseArray(cap) {
773
- let parsedCaps;
774
- try {
775
- parsedCaps = JSON.parse(cap);
776
- }
777
- catch (ign) { }
778
- if (lodash_1.default.isArray(parsedCaps)) {
779
- return parsedCaps;
780
- }
781
- else if (lodash_1.default.isString(cap)) {
782
- return [cap];
783
- }
784
- throw new Error(`must provide a string or JSON Array; received ${cap}`);
785
- };
786
- /**
787
- * Validate desired capabilities. Returns true if capability is valid
788
- *
789
- * @param {*} cap A desired capability
790
- * @return {boolean} Returns true if the capability is valid
791
- * @throws {Error} If the caps has invalid capability
792
- */
793
- helpers.validateDesiredCaps = function validateDesiredCaps(caps) {
794
- if (caps.browserName) {
795
- if (caps.app) {
796
- // warn if the capabilities have both `app` and `browser, although this is common with selenium grid
797
- logger_1.default.warn(`The desired capabilities should generally not include both an 'app' and a 'browserName'`);
798
- }
799
- if (caps.appPackage) {
800
- logger_1.default.errorAndThrow(`The desired should not include both of an 'appPackage' and a 'browserName'`);
801
- }
802
- }
803
- if (caps.uninstallOtherPackages) {
804
- try {
805
- this.parseArray(caps.uninstallOtherPackages);
806
- }
807
- catch (e) {
808
- logger_1.default.errorAndThrow(`Could not parse "uninstallOtherPackages" capability: ${e.message}`);
809
- }
810
- }
811
- return true;
812
- };
813
- /**
814
- * Adjust the capabilities for a browser session
815
- *
816
- * @param {Object} caps - Current capabilities object
817
- * !!! The object is mutated by this method call !!!
818
- * @returns {Object} The same possibly mutated `opts` instance.
819
- * No mutation is happening is the current session if
820
- * appPackage/appActivity caps have already been provided.
821
- */
822
- helpers.adjustBrowserSessionCaps = function adjustBrowserSessionCaps(caps = {}) {
823
- const { browserName } = caps;
824
- logger_1.default.info(`The current session is considered browser-based`);
825
- logger_1.default.info(`Supported browser names: ${JSON.stringify(lodash_1.default.keys(CHROME_BROWSER_PACKAGE_ACTIVITY))}`);
826
- if (caps.appPackage || caps.appActivity) {
827
- logger_1.default.info(`Not overriding appPackage/appActivity capability values for '${browserName}' ` +
828
- 'because some of them have been already provided');
829
- return caps;
830
- }
831
- const { pkg, activity } = this.getChromePkg(browserName);
832
- caps.appPackage = pkg;
833
- caps.appActivity = activity;
834
- logger_1.default.info(`appPackage/appActivity capabilities have been automatically set to ${pkg}/${activity} ` +
835
- `for '${browserName}'`);
836
- logger_1.default.info(`Consider changing the browserName to the one from the list of supported browser names ` +
837
- `or provide custom appPackage/appActivity capability values if the automatically assigned ones do ` +
838
- `not make sense`);
839
- return caps;
840
- };
841
- /**
842
- * Checks whether the current device under test is an emulator
843
- *
844
- * @param {ADB} adb - appium-adb instance
845
- * @param {Object} opts - driver options mapping
846
- * @returns {boolean} `true` if the device is an Android emulator
847
- */
848
- helpers.isEmulator = function isEmulator(adb, opts) {
849
- const possibleNames = [opts.udid, adb?.curDeviceId];
850
- return !!opts.avd || possibleNames.some((x) => EMULATOR_PATTERN.test(x));
851
- };
852
- helpers.bootstrap = bootstrap_1.default;
853
- helpers.unlocker = unlock_helpers_1.helpers;
854
- exports.default = helpers;
855
- //# sourceMappingURL=android-helpers.js.map