-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
adb-commands.js
1917 lines (1795 loc) · 66.5 KB
/
adb-commands.js
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import log from '../logger.js';
import {
getIMEListFromOutput, isShowingLockscreen, isCurrentFocusOnKeyguard,
getSurfaceOrientation, isScreenOnFully, extractMatchingPermissions
} from '../helpers.js';
import path from 'path';
import _ from 'lodash';
import { fs, util } from 'appium-support';
import net from 'net';
import { EOL } from 'os';
import Logcat from '../logcat';
import { sleep, waitForCondition } from 'asyncbox';
import { SubProcess } from 'teen_process';
import B from 'bluebird';
import { quote } from 'shell-quote';
const SETTINGS_HELPER_ID = 'io.appium.settings';
const WIFI_CONNECTION_SETTING_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.WiFiConnectionSettingReceiver`;
const WIFI_CONNECTION_SETTING_ACTION = `${SETTINGS_HELPER_ID}.wifi`;
const DATA_CONNECTION_SETTING_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.DataConnectionSettingReceiver`;
const DATA_CONNECTION_SETTING_ACTION = `${SETTINGS_HELPER_ID}.data_connection`;
const ANIMATION_SETTING_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.AnimationSettingReceiver`;
const ANIMATION_SETTING_ACTION = `${SETTINGS_HELPER_ID}.animation`;
const LOCALE_SETTING_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.LocaleSettingReceiver`;
const LOCALE_SETTING_ACTION = `${SETTINGS_HELPER_ID}.locale`;
const LOCATION_SERVICE = `${SETTINGS_HELPER_ID}/.LocationService`;
const LOCATION_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.LocationInfoReceiver`;
const LOCATION_RETRIEVAL_ACTION = `${SETTINGS_HELPER_ID}.location`;
const CLIPBOARD_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.ClipboardReceiver`;
const CLIPBOARD_RETRIEVAL_ACTION = `${SETTINGS_HELPER_ID}.clipboard.get`;
const NOTIFICATIONS_RECEIVER = `${SETTINGS_HELPER_ID}/.receivers.NotificationsReceiver`;
const NOTIFICATIONS_RETRIEVAL_ACTION = `${SETTINGS_HELPER_ID}.notifications`;
const APPIUM_IME = `${SETTINGS_HELPER_ID}/.AppiumIME`;
const MAX_SHELL_BUFFER_LENGTH = 1000;
const NOT_CHANGEABLE_PERM_ERROR = /not a changeable permission type/i;
const IGNORED_PERM_ERRORS = [
NOT_CHANGEABLE_PERM_ERROR,
/Unknown permission/i,
];
let methods = {};
/**
* Get the path to adb executable amd assign it
* to this.executable.path and this.binaries.adb properties.
*
* @return {string} Full path to adb executable.
*/
methods.getAdbWithCorrectAdbPath = async function getAdbWithCorrectAdbPath () {
this.executable.path = await this.getSdkBinaryPath('adb');
return this.adb;
};
/**
* Get the full path to aapt tool and assign it to
* this.binaries.aapt property
*/
methods.initAapt = async function initAapt () {
await this.getSdkBinaryPath('aapt');
};
/**
* Get the full path to aapt2 tool and assign it to
* this.binaries.aapt2 property
*/
methods.initAapt2 = async function initAapt2 () {
await this.getSdkBinaryPath('aapt2');
};
/**
* Get the full path to zipalign tool and assign it to
* this.binaries.zipalign property
*/
methods.initZipAlign = async function initZipAlign () {
await this.getSdkBinaryPath('zipalign');
};
/**
* Get the full path to bundletool binary and assign it to
* this.binaries.bundletool property
*/
methods.initBundletool = async function initBundletool () {
try {
this.binaries.bundletool = await fs.which('bundletool.jar');
} catch (err) {
throw new Error('bundletool.jar binary is expected to be present in PATH. ' +
'Visit https://github.com/google/bundletool for more details.');
}
};
/**
* Retrieve the API level of the device under test.
*
* @return {number} The API level as integer number, for example 21 for
* Android Lollipop. The result of this method is cached, so all the further
* calls return the same value as the first one.
*/
methods.getApiLevel = async function getApiLevel () {
if (!_.isInteger(this._apiLevel)) {
try {
const strOutput = await this.getDeviceProperty('ro.build.version.sdk');
let apiLevel = parseInt(strOutput.trim(), 10);
// Temp workaround. Android Q beta emulators report SDK 28 when they should be 29
if (apiLevel === 28 && (await this.getDeviceProperty('ro.build.version.release')).toLowerCase() === 'q') {
log.debug('Release version is Q but found API Level 28. Setting API Level to 29');
apiLevel = 29;
}
this._apiLevel = apiLevel;
log.debug(`Device API level: ${this._apiLevel}`);
if (isNaN(this._apiLevel)) {
throw new Error(`The actual output '${strOutput}' cannot be converted to an integer`);
}
} catch (e) {
throw new Error(`Error getting device API level. Original error: ${e.message}`);
}
}
return this._apiLevel;
};
/**
* Retrieve the platform version of the device under test.
*
* @return {string} The platform version as a string, for example '5.0' for
* Android Lollipop.
*/
methods.getPlatformVersion = async function getPlatformVersion () {
log.info('Getting device platform version');
try {
return await this.getDeviceProperty('ro.build.version.release');
} catch (e) {
throw new Error(`Error getting device platform version. Original error: ${e.message}`);
}
};
/**
* Verify whether a device is connected.
*
* @return {boolean} True if at least one device is visible to adb.
*/
methods.isDeviceConnected = async function isDeviceConnected () {
let devices = await this.getConnectedDevices();
return devices.length > 0;
};
/**
* Recursively create a new folder on the device under test.
*
* @param {string} remotePath - The new path to be created.
* @return {string} mkdir command output.
*/
methods.mkdir = async function mkdir (remotePath) {
return await this.shell(['mkdir', '-p', remotePath]);
};
/**
* Verify whether the given argument is a
* valid class name.
*
* @param {string} classString - The actual class name to be verified.
* @return {?Array.<Match>} The result of Regexp.exec operation
* or _null_ if no matches are found.
*/
methods.isValidClass = function isValidClass (classString) {
// some.package/some.package.Activity
return new RegExp(/^[a-zA-Z0-9./_]+$/).exec(classString);
};
/**
* Force application to stop on the device under test.
*
* @param {string} pkg - The package name to be stopped.
* @return {string} The output of the corresponding adb command.
*/
methods.forceStop = async function forceStop (pkg) {
return await this.shell(['am', 'force-stop', pkg]);
};
/*
* Kill application
*
* @param {string} pkg - The package name to be stopped.
* @return {string} The output of the corresponding adb command.
*/
methods.killPackage = async function killPackage (pkg) {
return await this.shell(['am', 'kill', pkg]);
};
/**
* Clear the user data of the particular application on the device
* under test.
*
* @param {string} pkg - The package name to be cleared.
* @return {string} The output of the corresponding adb command.
*/
methods.clear = async function clear (pkg) {
return await this.shell(['pm', 'clear', pkg]);
};
/**
* Grant all permissions requested by the particular package.
* This method is only useful on Android 6.0+ and for applications
* that support components-based permissions setting.
*
* @param {string} pkg - The package name to be processed.
* @param {string} apk - The path to the actual apk file.
* @throws {Error} If there was an error while granting permissions
*/
methods.grantAllPermissions = async function grantAllPermissions (pkg, apk) {
const apiLevel = await this.getApiLevel();
let targetSdk = 0;
let dumpsysOutput = null;
try {
if (!apk) {
/**
* If apk not provided, considering apk already installed on the device
* and fetching targetSdk using package name.
*/
dumpsysOutput = await this.shell(['dumpsys', 'package', pkg]);
targetSdk = await this.targetSdkVersionUsingPKG(pkg, dumpsysOutput);
} else {
targetSdk = await this.targetSdkVersionFromManifest(apk);
}
} catch (e) {
//avoiding logging error stack, as calling library function would have logged
log.warn(`Ran into problem getting target SDK version; ignoring...`);
}
if (apiLevel >= 23 && targetSdk >= 23) {
/**
* If the device is running Android 6.0(API 23) or higher, and your app's target SDK is 23 or higher:
* The app has to list the permissions in the manifest.
* refer: https://developer.android.com/training/permissions/requesting.html
*/
dumpsysOutput = dumpsysOutput || await this.shell(['dumpsys', 'package', pkg]);
const requestedPermissions = await this.getReqPermissions(pkg, dumpsysOutput);
const grantedPermissions = await this.getGrantedPermissions(pkg, dumpsysOutput);
const permissionsToGrant = _.difference(requestedPermissions, grantedPermissions);
if (_.isEmpty(permissionsToGrant)) {
log.info(`${pkg} contains no permissions available for granting`);
} else {
await this.grantPermissions(pkg, permissionsToGrant);
}
}
};
/**
* Grant multiple permissions for the particular package.
* This call is more performant than `grantPermission` one, since it combines
* multiple `adb shell` calls into a single command.
*
* @param {string} pkg - The package name to be processed.
* @param {Array<string>} permissions - The list of permissions to be granted.
* @throws {Error} If there was an error while changing permissions.
*/
methods.grantPermissions = async function grantPermissions (pkg, permissions) {
// As it consumes more time for granting each permission,
// trying to grant all permission by forming equivalent command.
// Also, it is necessary to split long commands into chunks, since the maximum length of
// adb shell buffer is limited
log.debug(`Granting permissions ${JSON.stringify(permissions)} to '${pkg}'`);
const commands = [];
let cmdChunk = [];
for (const permission of permissions) {
const nextCmd = ['pm', 'grant', pkg, permission, ';'];
if (nextCmd.join(' ').length + cmdChunk.join(' ').length >= MAX_SHELL_BUFFER_LENGTH) {
commands.push(cmdChunk);
cmdChunk = [];
}
cmdChunk = [...cmdChunk, ...nextCmd];
}
if (!_.isEmpty(cmdChunk)) {
commands.push(cmdChunk);
}
log.debug(`Got the following command chunks to execute: ${JSON.stringify(commands)}`);
let lastError = null;
for (const cmd of commands) {
try {
await this.shell(cmd);
} catch (e) {
// this is to give the method a chance to assign all the requested permissions
// before to quit in case we'd like to ignore the error on the higher level
if (!IGNORED_PERM_ERRORS.some((msgRegex) => msgRegex.test(e.stderr || e.message))) {
lastError = e;
}
}
}
if (lastError) {
throw lastError;
}
};
/**
* Grant single permission for the particular package.
*
* @param {string} pkg - The package name to be processed.
* @param {string} permission - The full name of the permission to be granted.
* @throws {Error} If there was an error while changing permissions.
*/
methods.grantPermission = async function grantPermission (pkg, permission) {
try {
await this.shell(['pm', 'grant', pkg, permission]);
} catch (e) {
if (!NOT_CHANGEABLE_PERM_ERROR.test(e.stderr || e.message)) {
throw e;
}
}
};
/**
* Revoke single permission from the particular package.
*
* @param {string} pkg - The package name to be processed.
* @param {string} permission - The full name of the permission to be revoked.
* @throws {Error} If there was an error while changing permissions.
*/
methods.revokePermission = async function revokePermission (pkg, permission) {
try {
await this.shell(['pm', 'revoke', pkg, permission]);
} catch (e) {
if (!NOT_CHANGEABLE_PERM_ERROR.test(e.stderr || e.message)) {
throw e;
}
}
};
/**
* Retrieve the list of granted permissions for the particular package.
*
* @param {string} pkg - The package name to be processed.
* @param {string} cmdOutput [null] - Optional parameter containing command output of
* _dumpsys package_ command. It may speed up the method execution.
* @return {Array<String>} The list of granted permissions or an empty list.
* @throws {Error} If there was an error while changing permissions.
*/
methods.getGrantedPermissions = async function getGrantedPermissions (pkg, cmdOutput = null) {
log.debug('Retrieving granted permissions');
const stdout = cmdOutput || await this.shell(['dumpsys', 'package', pkg]);
return extractMatchingPermissions(stdout, ['install', 'runtime'], true);
};
/**
* Retrieve the list of denied permissions for the particular package.
*
* @param {string} pkg - The package name to be processed.
* @param {string} cmdOutput [null] - Optional parameter containing command output of
* _dumpsys package_ command. It may speed up the method execution.
* @return {Array<String>} The list of denied permissions or an empty list.
*/
methods.getDeniedPermissions = async function getDeniedPermissions (pkg, cmdOutput = null) {
log.debug('Retrieving denied permissions');
const stdout = cmdOutput || await this.shell(['dumpsys', 'package', pkg]);
return extractMatchingPermissions(stdout, ['install', 'runtime'], false);
};
/**
* Retrieve the list of requested permissions for the particular package.
*
* @param {string} pkg - The package name to be processed.
* @param {string} cmdOutput [null] - Optional parameter containing command output of
* _dumpsys package_ command. It may speed up the method execution.
* @return {Array<String>} The list of requested permissions or an empty list.
*/
methods.getReqPermissions = async function getReqPermissions (pkg, cmdOutput = null) {
log.debug('Retrieving requested permissions');
const stdout = cmdOutput || await this.shell(['dumpsys', 'package', pkg]);
return extractMatchingPermissions(stdout, ['requested']);
};
/**
* Retrieve the list of location providers for the device under test.
*
* @return {Array.<String>} The list of available location providers or an empty list.
*/
methods.getLocationProviders = async function getLocationProviders () {
let stdout = await this.getSetting('secure', 'location_providers_allowed');
return stdout.trim().split(',')
.map((p) => p.trim())
.filter(Boolean);
};
/**
* Toggle the state of GPS location provider.
*
* @param {boolean} enabled - Whether to enable (true) or disable (false) the GPS provider.
*/
methods.toggleGPSLocationProvider = async function toggleGPSLocationProvider (enabled) {
await this.setSetting('secure', 'location_providers_allowed', `${enabled ? '+' : '-'}gps`);
};
/**
* Set hidden api policy to manage access to non-SDK APIs.
* https://developer.android.com/preview/restrictions-non-sdk-interfaces
*
* @param {number|string} value - The API enforcement policy.
* For Android P
* 0: Disable non-SDK API usage detection. This will also disable logging, and also break the strict mode API,
* detectNonSdkApiUsage(). Not recommended.
* 1: "Just warn" - permit access to all non-SDK APIs, but keep warnings in the log.
* The strict mode API will keep working.
* 2: Disallow usage of dark grey and black listed APIs.
* 3: Disallow usage of blacklisted APIs, but allow usage of dark grey listed APIs.
*
* For Android Q
* https://developer.android.com/preview/non-sdk-q#enable-non-sdk-access
* 0: Disable all detection of non-SDK interfaces. Using this setting disables all log messages for non-SDK interface usage
* and prevents you from testing your app using the StrictMode API. This setting is not recommended.
* 1: Enable access to all non-SDK interfaces, but print log messages with warnings for any non-SDK interface usage.
* Using this setting also allows you to test your app using the StrictMode API.
* 2: Disallow usage of non-SDK interfaces that belong to either the black list
* or to a restricted greylist for your target API level.
*/
methods.setHiddenApiPolicy = async function setHiddenApiPolicy (value) {
await this.setSetting('global', 'hidden_api_policy_pre_p_apps', value);
await this.setSetting('global', 'hidden_api_policy_p_apps', value);
await this.setSetting('global', 'hidden_api_policy', value);
};
/**
* Reset access to non-SDK APIs to its default setting.
* https://developer.android.com/preview/restrictions-non-sdk-interfaces
*/
methods.setDefaultHiddenApiPolicy = async function setDefaultHiddenApiPolicy () {
await this.shell(['settings', 'delete', 'global', 'hidden_api_policy_pre_p_apps']);
await this.shell(['settings', 'delete', 'global', 'hidden_api_policy_p_apps']);
await this.shell(['settings', 'delete', 'global', 'hidden_api_policy']);
};
/**
* Stop the particular package if it is running and clears its application data.
*
* @param {string} pkg - The package name to be processed.
*/
methods.stopAndClear = async function stopAndClear (pkg) {
try {
await this.forceStop(pkg);
await this.clear(pkg);
} catch (e) {
throw new Error(`Cannot stop and clear ${pkg}. Original error: ${e.message}`);
}
};
/**
* Retrieve the list of available input methods (IMEs) for the device under test.
*
* @return {Array.<String>} The list of IME names or an empty list.
*/
methods.availableIMEs = async function availableIMEs () {
try {
return getIMEListFromOutput(await this.shell(['ime', 'list', '-a']));
} catch (e) {
throw new Error(`Error getting available IME's. Original error: ${e.message}`);
}
};
/**
* Retrieve the list of enabled input methods (IMEs) for the device under test.
*
* @return {Array.<String>} The list of enabled IME names or an empty list.
*/
methods.enabledIMEs = async function enabledIMEs () {
try {
return getIMEListFromOutput(await this.shell(['ime', 'list']));
} catch (e) {
throw new Error(`Error getting enabled IME's. Original error: ${e.message}`);
}
};
/**
* Enable the particular input method on the device under test.
*
* @param {string} imeId - One of existing IME ids.
*/
methods.enableIME = async function enableIME (imeId) {
await this.shell(['ime', 'enable', imeId]);
};
/**
* Disable the particular input method on the device under test.
*
* @param {string} imeId - One of existing IME ids.
*/
methods.disableIME = async function disableIME (imeId) {
await this.shell(['ime', 'disable', imeId]);
};
/**
* Set the particular input method on the device under test.
*
* @param {string} imeId - One of existing IME ids.
*/
methods.setIME = async function setIME (imeId) {
await this.shell(['ime', 'set', imeId]);
};
/**
* Get the default input method on the device under test.
*
* @return {?string} The name of the default input method
*/
methods.defaultIME = async function defaultIME () {
try {
let engine = await this.getSetting('secure', 'default_input_method');
if (engine === 'null') {
return null;
}
return engine.trim();
} catch (e) {
throw new Error(`Error getting default IME. Original error: ${e.message}`);
}
};
/**
* Send the particular keycode to the device under test.
*
* @param {string|number} keycode - The actual key code to be sent.
*/
methods.keyevent = async function keyevent (keycode) {
// keycode must be an int.
let code = parseInt(keycode, 10);
await this.shell(['input', 'keyevent', code]);
};
/**
* Send the particular text to the device under test.
*
* @param {string} text - The actual text to be sent.
*/
methods.inputText = async function inputText (text) {
/* eslint-disable no-useless-escape */
// need to escape whitespace and ( ) < > | ; & * \ ~ " '
text = text
.replace(/\\/g, '\\\\')
.replace(/\(/g, '\(')
.replace(/\)/g, '\)')
.replace(/</g, '\<')
.replace(/>/g, '\>')
.replace(/\|/g, '\|')
.replace(/;/g, '\;')
.replace(/&/g, '\&')
.replace(/\*/g, '\*')
.replace(/~/g, '\~')
.replace(/"/g, '\"')
.replace(/'/g, "\'")
.replace(/ /g, '%s');
/* eslint-disable no-useless-escape */
await this.shell(['input', 'text', text]);
};
/**
* Clear the active text field on the device under test by sending
* special keyevents to it.
*
* @param {number} length [100] - The maximum length of the text in the field to be cleared.
*/
methods.clearTextField = async function clearTextField (length = 100) {
// assumes that the EditText field already has focus
log.debug(`Clearing up to ${length} characters`);
if (length === 0) {
return;
}
let args = ['input', 'keyevent'];
for (let i = 0; i < length; i++) {
// we cannot know where the cursor is in the text field, so delete both before
// and after so that we get rid of everything
// https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_DEL
// https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_FORWARD_DEL
args.push('67', '112');
}
await this.shell(args);
};
/**
* Send the special keycode to the device under test in order to lock it.
*/
methods.lock = async function lock () {
if (await this.isScreenLocked()) {
log.debug('Screen is already locked. Doing nothing.');
return;
}
log.debug('Pressing the KEYCODE_POWER button to lock screen');
await this.keyevent(26);
const timeoutMs = 5000;
try {
await waitForCondition(async () => await this.isScreenLocked(), {
waitMs: timeoutMs,
intervalMs: 500,
});
} catch (e) {
throw new Error(`The device screen is still locked after ${timeoutMs}ms timeout`);
}
};
/**
* Send the special keycode to the device under test in order to emulate
* Back button tap.
*/
methods.back = async function back () {
log.debug('Pressing the BACK button');
await this.keyevent(4);
};
/**
* Send the special keycode to the device under test in order to emulate
* Home button tap.
*/
methods.goToHome = async function goToHome () {
log.debug('Pressing the HOME button');
await this.keyevent(3);
};
/**
* @return {string} the actual path to adb executable.
*/
methods.getAdbPath = function getAdbPath () {
return this.executable.path;
};
/**
* Retrieve current screen orientation of the device under test.
*
* @return {number} The current orientation encoded as an integer number.
*/
methods.getScreenOrientation = async function getScreenOrientation () {
let stdout = await this.shell(['dumpsys', 'input']);
return getSurfaceOrientation(stdout);
};
/**
* Retrieve the screen lock state of the device under test.
*
* @return {boolean} True if the device is locked.
*/
methods.isScreenLocked = async function isScreenLocked () {
let stdout = await this.shell(['dumpsys', 'window']);
if (process.env.APPIUM_LOG_DUMPSYS) {
// optional debugging
// if the method is not working, turn it on and send us the output
let dumpsysFile = path.resolve(process.cwd(), 'dumpsys.log');
log.debug(`Writing dumpsys output to ${dumpsysFile}`);
await fs.writeFile(dumpsysFile, stdout);
}
return (isShowingLockscreen(stdout) || isCurrentFocusOnKeyguard(stdout) ||
!isScreenOnFully(stdout));
};
/**
* @typedef {Object} KeyboardState
* @property {boolean} isKeyboardShown - Whether soft keyboard is currently visible.
* @property {boolean} canCloseKeyboard - Whether the keyboard can be closed.
*/
/**
* Retrieve the state of the software keyboard on the device under test.
*
* @return {KeyboardState} The keyboard state.
*/
methods.isSoftKeyboardPresent = async function isSoftKeyboardPresent () {
try {
const stdout = await this.shell(['dumpsys', 'input_method']);
const inputShownMatch = /mInputShown=(\w+)/.exec(stdout);
const inputViewShownMatch = /mIsInputViewShown=(\w+)/.exec(stdout);
return {
isKeyboardShown: !!(inputShownMatch && inputShownMatch[1] === 'true'),
canCloseKeyboard: !!(inputViewShownMatch && inputViewShownMatch[1] === 'true'),
};
} catch (e) {
throw new Error(`Error finding softkeyboard. Original error: ${e.message}`);
}
};
/**
* Send an arbitrary Telnet command to the device under test.
*
* @param {string} command - The command to be sent.
*
* @return {string} The actual output of the given command.
*/
methods.sendTelnetCommand = async function sendTelnetCommand (command) {
log.debug(`Sending telnet command to device: ${command}`);
let port = await this.getEmulatorPort();
return await new B((resolve, reject) => {
let conn = net.createConnection(port, 'localhost'),
connected = false,
readyRegex = /^OK$/m,
dataStream = '',
res = null;
conn.on('connect', () => {
log.debug('Socket connection to device created');
});
conn.on('data', (data) => {
data = data.toString('utf8');
if (!connected) {
if (readyRegex.test(data)) {
connected = true;
log.debug('Socket connection to device ready');
conn.write(`${command}\n`);
}
} else {
dataStream += data;
if (readyRegex.test(data)) {
res = dataStream.replace(readyRegex, '').trim();
res = _.last(res.trim().split('\n'));
log.debug(`Telnet command got response: ${res}`);
conn.write('quit\n');
}
}
});
conn.on('error', (err) => { // eslint-disable-line promise/prefer-await-to-callbacks
log.debug(`Telnet command error: ${err.message}`);
reject(err);
});
conn.on('close', () => {
if (res === null) {
reject(new Error('Never got a response from command'));
} else {
resolve(res);
}
});
});
};
/**
* Check the state of Airplane mode on the device under test.
*
* @return {boolean} True if Airplane mode is enabled.
*/
methods.isAirplaneModeOn = async function isAirplaneModeOn () {
let stdout = await this.getSetting('global', 'airplane_mode_on');
return parseInt(stdout, 10) !== 0;
};
/**
* Change the state of Airplane mode in Settings on the device under test.
*
* @param {boolean} on - True to enable the Airplane mode in Settings and false to disable it.
*/
methods.setAirplaneMode = async function setAirplaneMode (on) {
await this.setSetting('global', 'airplane_mode_on', on ? 1 : 0);
};
/**
* Broadcast the state of Airplane mode on the device under test.
* This method should be called after {@link #setAirplaneMode}, otherwise
* the mode change is not going to be applied for the device.
*
* @param {boolean} on - True to broadcast enable and false to broadcast disable.
*/
methods.broadcastAirplaneMode = async function broadcastAirplaneMode (on) {
await this.shell([
'am', 'broadcast',
'-a', 'android.intent.action.AIRPLANE_MODE',
'--ez', 'state', on ? 'true' : 'false'
]);
};
/**
* Check the state of WiFi on the device under test.
*
* @return {boolean} True if WiFi is enabled.
*/
methods.isWifiOn = async function isWifiOn () {
let stdout = await this.getSetting('global', 'wifi_on');
return (parseInt(stdout, 10) !== 0);
};
/**
* Change the state of WiFi on the device under test.
*
* @param {boolean} on - True to enable and false to disable it.
* @param {boolean} isEmulator [false] - Set it to true if the device under test
* is an emulator rather than a real device.
*/
methods.setWifiState = async function setWifiState (on, isEmulator = false) {
if (isEmulator) {
await this.shell(['svc', 'wifi', on ? 'enable' : 'disable'], {
privileged: true,
});
} else {
await this.shell([
'am', 'broadcast',
'-a', WIFI_CONNECTION_SETTING_ACTION,
'-n', WIFI_CONNECTION_SETTING_RECEIVER,
'--es', 'setstatus', on ? 'enable' : 'disable'
]);
}
};
/**
* Check the state of Data transfer on the device under test.
*
* @return {boolean} True if Data transfer is enabled.
*/
methods.isDataOn = async function isDataOn () {
let stdout = await this.getSetting('global', 'mobile_data');
return (parseInt(stdout, 10) !== 0);
};
/**
* Change the state of Data transfer on the device under test.
*
* @param {boolean} on - True to enable and false to disable it.
* @param {boolean} isEmulator [false] - Set it to true if the device under test
* is an emulator rather than a real device.
*/
methods.setDataState = async function setDataState (on, isEmulator = false) {
if (isEmulator) {
await this.shell(['svc', 'data', on ? 'enable' : 'disable'], {
privileged: true,
});
} else {
await this.shell([
'am', 'broadcast',
'-a', DATA_CONNECTION_SETTING_ACTION,
'-n', DATA_CONNECTION_SETTING_RECEIVER,
'--es', 'setstatus', on ? 'enable' : 'disable'
]);
}
};
/**
* Change the state of WiFi and/or Data transfer on the device under test.
*
* @param {boolean} wifi - True to enable and false to disable WiFi.
* @param {boolean} data - True to enable and false to disable Data transfer.
* @param {boolean} isEmulator [false] - Set it to true if the device under test
* is an emulator rather than a real device.
*/
methods.setWifiAndData = async function setWifiAndData ({wifi, data}, isEmulator = false) {
if (util.hasValue(wifi)) {
await this.setWifiState(wifi, isEmulator);
}
if (util.hasValue(data)) {
await this.setDataState(data, isEmulator);
}
};
/**
* Change the state of animation on the device under test.
* Animation on the device is controlled by the following global properties:
* [ANIMATOR_DURATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#ANIMATOR_DURATION_SCALE},
* [TRANSITION_ANIMATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#TRANSITION_ANIMATION_SCALE},
* [WINDOW_ANIMATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#WINDOW_ANIMATION_SCALE}.
* This method sets all this properties to 0.0 to disable (1.0 to enable) animation.
*
* Turning off animation might be useful to improve stability
* and reduce tests execution time.
*
* @param {boolean} on - True to enable and false to disable it.
*/
methods.setAnimationState = async function setAnimationState (on) {
await this.shell([
'am', 'broadcast',
'-a', ANIMATION_SETTING_ACTION,
'-n', ANIMATION_SETTING_RECEIVER,
'--es', 'setstatus', on ? 'enable' : 'disable'
]);
};
/**
* Check the state of animation on the device under test.
*
* @return {boolean} True if at least one of animation scale settings
* is not equal to '0.0'.
*/
methods.isAnimationOn = async function isAnimationOn () {
let animator_duration_scale = await this.getSetting('global', 'animator_duration_scale');
let transition_animation_scale = await this.getSetting('global', 'transition_animation_scale');
let window_animation_scale = await this.getSetting('global', 'window_animation_scale');
return _.some([animator_duration_scale, transition_animation_scale, window_animation_scale],
(setting) => setting !== '0.0');
};
/**
* Change the locale on the device under test. Don't need to reboot the device after changing the locale.
* This method sets an arbitrary locale following:
* https://developer.android.com/reference/java/util/Locale.html
* https://developer.android.com/reference/java/util/Locale.html#Locale(java.lang.String,%20java.lang.String)
*
* @param {string} language - Language. e.g. en, ja
* @param {string} country - Country. e.g. US, JP
* @param {?string} script - Script. e.g. Hans in `zh-Hans-CN`
*/
methods.setDeviceSysLocaleViaSettingApp = async function setDeviceSysLocaleViaSettingApp (language, country, script = null) {
const params = [
'am', 'broadcast',
'-a', LOCALE_SETTING_ACTION,
'-n', LOCALE_SETTING_RECEIVER,
'--es', 'lang', language.toLowerCase(),
'--es', 'country', country.toUpperCase()
];
if (script) {
params.push('--es', 'script', script);
}
await this.shell(params);
};
/**
* @typedef {Object} Location
* @property {number|string} longitude - Valid longitude value.
* @property {number|string} latitude - Valid latitude value.
* @property {?number|string} altitude - Valid altitude value.
*/
/**
* Emulate geolocation coordinates on the device under test.
*
* @param {Location} location - Location object. The `altitude` value is ignored
* while mocking the position.
* @param {boolean} isEmulator [false] - Set it to true if the device under test
* is an emulator rather than a real device.
*/
methods.setGeoLocation = async function setGeoLocation (location, isEmulator = false) {
const formatLocationValue = (valueName, isRequired = true) => {
if (!util.hasValue(location[valueName])) {
if (isRequired) {
throw new Error(`${valueName} must be provided`);
}
return null;
}
const floatValue = parseFloat(location[valueName]);
if (!isNaN(floatValue)) {
return `${_.ceil(floatValue, 5)}`;
}
if (isRequired) {
throw new Error(`${valueName} is expected to be a valid float number. ` +
`'${location[valueName]}' is given instead`);
}
return null;
};
const longitude = formatLocationValue('longitude');
const latitude = formatLocationValue('latitude');
const altitude = formatLocationValue('altitude', false);
if (isEmulator) {
await this.resetTelnetAuthToken();
await this.adbExec(['emu', 'geo', 'fix', longitude, latitude]);
// A workaround for https://code.google.com/p/android/issues/detail?id=206180
await this.adbExec(['emu', 'geo', 'fix', longitude.replace('.', ','), latitude.replace('.', ',')]);
} else {
const args = [
'am', 'startservice',
'-e', 'longitude', longitude,
'-e', 'latitude', latitude,
];
if (util.hasValue(altitude)) {
args.push('-e', 'altitude', altitude);
}
args.push(LOCATION_SERVICE);
await this.shell(args);
}
};
/**
* Get the current geo location from the device under test.
*
* @returns {Location} The current location
* @throws {Error} If the current location cannot be retrieved
*/
methods.getGeoLocation = async function getGeoLocation () {
let output;
try {
output = await this.shell([
'am', 'broadcast',
'-n', LOCATION_RECEIVER,
'-a', LOCATION_RETRIEVAL_ACTION,
]);
} catch (err) {
throw new Error(`Cannot retrieve the current geo coordinates from the device. ` +
`Make sure the Appium Settings application is up to date and has location permissions. Also the location ` +
`services must be enabled on the device. Original error: ${err.message}`);
}
const match = /data="(-?[\d\.]+)\s+(-?[\d\.]+)\s+(-?[\d\.]+)"/.exec(output);
if (!match) {
throw new Error(`Cannot parse the actual location values from the command output: ${output}`);
}
const location = {
latitude: match[1],
longitude: match[2],
altitude: match[3],
};
log.debug(`Got geo coordinates: ${JSON.stringify(location)}`);
return location;
};
/**
* Forcefully recursively remove a path on the device under test.
* Be careful while calling this method.
*
* @param {string} path - The path to be removed recursively.
*/
methods.rimraf = async function rimraf (path) {
await this.shell(['rm', '-rf', path]);
};
/**