-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
Copy pathdriver.ts
1081 lines (984 loc) · 37.3 KB
/
driver.ts
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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type {
DefaultCreateSessionResult,
DriverData,
ExternalDriver,
InitialOpts,
Orientation,
RouteMatcher,
SingularSessionData,
StringRecord,
} from '@appium/types';
import {DEFAULT_ADB_PORT} from 'appium-adb';
import {AndroidDriver, utils} from 'appium-android-driver';
import {SETTINGS_HELPER_ID} from 'io.appium.settings';
import {BaseDriver, DeviceSettings} from 'appium/driver';
import {fs, mjpeg, util} from 'appium/support';
import {retryInterval} from 'asyncbox';
import B from 'bluebird';
import _ from 'lodash';
import os from 'node:os';
import path from 'node:path';
import {checkPortStatus, findAPortNotInUse} from 'portscanner';
import type {ExecError} from 'teen_process';
import UIAUTOMATOR2_CONSTRAINTS, {type Uiautomator2Constraints} from './constraints';
import {APKS_EXTENSION, APK_EXTENSION} from './extensions';
import {newMethodMap} from './method-map';
import { signApp } from './helpers';
import type { EmptyObject } from 'type-fest';
import type {
Uiautomator2Settings,
Uiautomator2DeviceDetails,
Uiautomator2DriverCaps,
Uiautomator2DriverOpts,
Uiautomator2SessionCaps,
Uiautomator2SessionInfo,
Uiautomator2StartSessionOpts,
W3CUiautomator2DriverCaps,
} from './types';
import {SERVER_PACKAGE_ID, SERVER_TEST_PACKAGE_ID, UiAutomator2Server} from './uiautomator2';
import {
mobileGetActionHistory,
mobileScheduleAction,
mobileUnscheduleAction,
performActions,
releaseActions,
} from './commands/actions';
import {
getAlertText,
mobileAcceptAlert,
mobileDismissAlert,
postAcceptAlert,
postDismissAlert,
} from './commands/alert';
import {
mobileInstallMultipleApks,
} from './commands/app-management';
import {
mobileGetBatteryInfo,
} from './commands/battery';
import {
getClipboard,
setClipboard,
} from './commands/clipboard';
import {
active,
getAttribute,
elementEnabled,
elementDisplayed,
elementSelected,
getName,
getLocation,
getSize,
getElementRect,
getElementScreenshot,
getText,
setValueImmediate,
doSetElementValue,
click,
clear,
mobileReplaceElementValue,
} from './commands/element';
import {
doFindElementOrEls,
} from './commands/find';
import {
mobileClickGesture,
mobileDoubleClickGesture,
mobileDragGesture,
mobileFlingGesture,
mobileLongClickGesture,
mobilePinchCloseGesture,
mobilePinchOpenGesture,
mobileScroll,
mobileScrollBackTo,
mobileScrollGesture,
mobileSwipeGesture,
} from './commands/gestures';
import {
pressKeyCode,
longPressKeyCode,
mobilePressKey,
mobileType,
doSendKeys,
keyevent,
} from './commands/keyboard';
import {
getPageSource,
getOrientation,
setOrientation,
openNotifications,
suspendChromedriverProxy,
mobileGetDeviceInfo,
} from './commands/misc';
import {
setUrl,
mobileDeepLink,
back,
} from './commands/navigation';
import {
mobileScreenshots,
mobileViewportScreenshot,
getScreenshot,
getViewportScreenshot,
} from './commands/screenshot';
import {
getStatusBarHeight,
getDevicePixelRatio,
getDisplayDensity,
getViewPortRect,
getWindowRect,
getWindowSize,
mobileViewPortRect,
} from './commands/viewport';
import { executeMethodMap } from './execute-method-map';
// The range of ports we can use on the system for communicating to the
// UiAutomator2 HTTP server on the device
const DEVICE_PORT_RANGE = [8200, 8299];
// The guard is needed to avoid dynamic system port allocation conflicts for
// parallel driver sessions
const DEVICE_PORT_ALLOCATION_GUARD = util.getLockFileGuard(
path.resolve(os.tmpdir(), 'uia2_device_port_guard'),
{timeout: 25, tryRecovery: true}
);
// This is the port that UiAutomator2 listens to on the device. We will forward
// one of the ports above on the system to this port on the device.
const DEVICE_PORT = 6790;
// This is the port that the UiAutomator2 MJPEG server listens to on the device.
// We will forward one of the ports above on the system to this port on the
// device.
const MJPEG_SERVER_DEVICE_PORT = 7810;
const LOCALHOST_IP4 = '127.0.0.1';
// NO_PROXY contains the paths that we never want to proxy to UiAutomator2 server.
// TODO: Add the list of paths that we never want to proxy to UiAutomator2 server.
// TODO: Need to segregate the paths better way using regular expressions wherever applicable.
// (Not segregating right away because more paths to be added in the NO_PROXY list)
const NO_PROXY: RouteMatcher[] = [
['DELETE', new RegExp('^/session/[^/]+/actions')],
['GET', new RegExp('^/session/(?!.*/)')],
['GET', new RegExp('^/session/[^/]+/alert_[^/]+')],
['GET', new RegExp('^/session/[^/]+/alert/[^/]+')],
['GET', new RegExp('^/session/[^/]+/appium/[^/]+/current_activity')],
['GET', new RegExp('^/session/[^/]+/appium/[^/]+/current_package')],
['GET', new RegExp('^/session/[^/]+/appium/app/[^/]+')],
['GET', new RegExp('^/session/[^/]+/appium/device/[^/]+')],
['GET', new RegExp('^/session/[^/]+/appium/settings')],
['GET', new RegExp('^/session/[^/]+/context')],
['GET', new RegExp('^/session/[^/]+/contexts')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/attribute')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/displayed')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/enabled')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/location_in_view')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/name')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/screenshot')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/selected')],
['GET', new RegExp('^/session/[^/]+/ime/[^/]+')],
['GET', new RegExp('^/session/[^/]+/location')],
['GET', new RegExp('^/session/[^/]+/network_connection')],
['GET', new RegExp('^/session/[^/]+/screenshot')],
['GET', new RegExp('^/session/[^/]+/timeouts')],
['GET', new RegExp('^/session/[^/]+/url')],
['POST', new RegExp('^/session/[^/]+/[^/]+_alert$')],
['POST', new RegExp('^/session/[^/]+/actions')],
['POST', new RegExp('^/session/[^/]+/alert/[^/]+')],
['POST', new RegExp('^/session/[^/]+/app/[^/]')],
['POST', new RegExp('^/session/[^/]+/appium/[^/]+/start_activity')],
['POST', new RegExp('^/session/[^/]+/appium/app/[^/]+')],
['POST', new RegExp('^/session/[^/]+/appium/compare_images')],
['POST', new RegExp('^/session/[^/]+/appium/device/(?!set_clipboard)[^/]+')],
['POST', new RegExp('^/session/[^/]+/appium/element/[^/]+/replace_value')],
['POST', new RegExp('^/session/[^/]+/appium/element/[^/]+/value')],
['POST', new RegExp('^/session/[^/]+/appium/getPerformanceData')],
['POST', new RegExp('^/session/[^/]+/appium/performanceData/types')],
['POST', new RegExp('^/session/[^/]+/appium/settings')],
['POST', new RegExp('^/session/[^/]+/appium/execute_driver')],
['POST', new RegExp('^/session/[^/]+/appium/start_recording_screen')],
['POST', new RegExp('^/session/[^/]+/appium/stop_recording_screen')],
['POST', new RegExp('^/session/[^/]+/appium/.*event')],
['POST', new RegExp('^/session/[^/]+/context')],
['POST', new RegExp('^/session/[^/]+/element')],
['POST', new RegExp('^/session/[^/]+/ime/[^/]+')],
['POST', new RegExp('^/session/[^/]+/keys')],
['POST', new RegExp('^/session/[^/]+/location')],
['POST', new RegExp('^/session/[^/]+/network_connection')],
['POST', new RegExp('^/session/[^/]+/timeouts')],
['POST', new RegExp('^/session/[^/]+/url')],
// MJSONWP commands
['GET', new RegExp('^/session/[^/]+/log/types')],
['POST', new RegExp('^/session/[^/]+/execute')],
['POST', new RegExp('^/session/[^/]+/execute_async')],
['POST', new RegExp('^/session/[^/]+/log')],
// W3C commands
// For Selenium v4 (W3C does not have this route)
['GET', new RegExp('^/session/[^/]+/se/log/types')],
['GET', new RegExp('^/session/[^/]+/window/rect')],
['POST', new RegExp('^/session/[^/]+/execute/async')],
['POST', new RegExp('^/session/[^/]+/execute/sync')],
// For Selenium v4 (W3C does not have this route)
['POST', new RegExp('^/session/[^/]+/se/log')],
];
// This is a set of methods and paths that we never want to proxy to Chromedriver.
const CHROME_NO_PROXY: RouteMatcher[] = [
['GET', new RegExp('^/session/[^/]+/appium')],
['GET', new RegExp('^/session/[^/]+/context')],
['GET', new RegExp('^/session/[^/]+/element/[^/]+/rect')],
['GET', new RegExp('^/session/[^/]+/orientation')],
['POST', new RegExp('^/session/[^/]+/appium')],
['POST', new RegExp('^/session/[^/]+/context')],
['POST', new RegExp('^/session/[^/]+/orientation')],
// this is needed to make the mobile: commands working in web context
['POST', new RegExp('^/session/[^/]+/execute$')],
['POST', new RegExp('^/session/[^/]+/execute/sync')],
// MJSONWP commands
['GET', new RegExp('^/session/[^/]+/log/types$')],
['POST', new RegExp('^/session/[^/]+/log$')],
// W3C commands
// For Selenium v4 (W3C does not have this route)
['GET', new RegExp('^/session/[^/]+/se/log/types$')],
// For Selenium v4 (W3C does not have this route)
['POST', new RegExp('^/session/[^/]+/se/log$')],
];
const MEMOIZED_FUNCTIONS = ['getStatusBarHeight', 'getDevicePixelRatio'] as const;
class AndroidUiautomator2Driver
extends AndroidDriver
implements
ExternalDriver<
Uiautomator2Constraints,
string,
StringRecord
>
{
static newMethodMap = newMethodMap;
static executeMethodMap = executeMethodMap;
uiautomator2: UiAutomator2Server;
systemPort: number | undefined;
_originalIme: string | null;
mjpegStream?: mjpeg.MJpegStream;
override caps: Uiautomator2DriverCaps;
override opts: Uiautomator2DriverOpts;
override desiredCapConstraints: Uiautomator2Constraints;
constructor(opts: InitialOpts = {} as InitialOpts, shouldValidateCaps = true) {
// `shell` overwrites adb.shell, so remove
// @ts-expect-error FIXME: what is this?
delete opts.shell;
super(opts, shouldValidateCaps);
this.locatorStrategies = [
'xpath',
'id',
'class name',
'accessibility id',
'css selector',
'-android uiautomator',
];
this.desiredCapConstraints = _.cloneDeep(UIAUTOMATOR2_CONSTRAINTS);
this.jwpProxyActive = false;
this.jwpProxyAvoid = NO_PROXY;
this._originalIme = null;
this.settings = new DeviceSettings(
{ignoreUnimportantViews: false, allowInvisibleElements: false},
this.onSettingsUpdate.bind(this)
);
// handle webview mechanics from AndroidDriver
this.sessionChromedrivers = {};
this.caps = {} as Uiautomator2DriverCaps;
this.opts = opts as Uiautomator2DriverOpts;
// memoize functions here, so that they are done on a per-instance basis
for (const fn of MEMOIZED_FUNCTIONS) {
this[fn] = _.memoize(this[fn]) as any;
}
}
override validateDesiredCaps(caps: any): caps is Uiautomator2DriverCaps {
return super.validateDesiredCaps(caps);
}
async createSession(
w3cCaps1: W3CUiautomator2DriverCaps,
w3cCaps2?: W3CUiautomator2DriverCaps,
w3cCaps3?: W3CUiautomator2DriverCaps,
driverData?: DriverData[]
): Promise<any> {
try {
// TODO handle otherSessionData for multiple sessions
const [sessionId, caps] = (await BaseDriver.prototype.createSession.call(
this,
w3cCaps1,
w3cCaps2,
w3cCaps3,
driverData
)) as DefaultCreateSessionResult<Uiautomator2Constraints>;
const startSessionOpts: Uiautomator2StartSessionOpts = {
...caps,
platform: 'LINUX',
webStorageEnabled: false,
takesScreenshot: true,
javascriptEnabled: true,
databaseEnabled: false,
networkConnectionEnabled: true,
locationContextEnabled: false,
warnings: {},
desired: caps,
};
const defaultOpts = {
fullReset: false,
autoLaunch: true,
adbPort: DEFAULT_ADB_PORT,
androidInstallTimeout: 90000,
};
_.defaults(this.opts, defaultOpts);
this.opts.adbPort = this.opts.adbPort || DEFAULT_ADB_PORT;
// get device udid for this session
const {udid, emPort} = await this.getDeviceInfoFromCaps();
this.opts.udid = udid;
// @ts-expect-error do not put random stuff on opts
this.opts.emPort = emPort;
// now that we know our java version and device info, we can create our
// ADB instance
this.adb = await this.createADB();
if (this.isChromeSession) {
this.log.info(`We're going to run a Chrome-based session`);
const {pkg, activity: defaultActivity} = utils.getChromePkg(this.opts.browserName!);
let activity: string = defaultActivity;
if (await this.adb.getApiLevel() >= 24) {
try {
activity = await this.adb.resolveLaunchableActivity(pkg);
} catch (e) {
this.log.warn(`Using the default ${pkg} activity ${activity}. Original error: ${e.message}`);
}
}
this.opts.appPackage = this.caps.appPackage = pkg;
this.opts.appActivity = this.caps.appActivity = activity;
this.log.info(`Chrome-type package and activity are ${pkg} and ${activity}`);
}
if (this.opts.app) {
// find and copy, or download and unzip an app url or path
this.opts.app = await this.helpers.configureApp(this.opts.app, [
APK_EXTENSION,
APKS_EXTENSION,
]);
await this.checkAppPresent();
} else if (this.opts.appPackage) {
// the app isn't an actual app file but rather something we want to
// assume is on the device and just launch via the appPackage
this.log.info(`Starting '${this.opts.appPackage}' directly on the device`);
} else {
this.log.info(
`Neither 'app' nor 'appPackage' was set. Starting UiAutomator2 ` +
'without the target application'
);
}
const result = await this.startUiAutomator2Session(startSessionOpts);
if (this.opts.mjpegScreenshotUrl) {
this.log.info(`Starting MJPEG stream reading URL: '${this.opts.mjpegScreenshotUrl}'`);
this.mjpegStream = new mjpeg.MJpegStream(this.opts.mjpegScreenshotUrl);
await this.mjpegStream.start();
}
return [sessionId, result];
} catch (e) {
await this.deleteSession();
throw e;
}
}
async getDeviceDetails(): Promise<Uiautomator2DeviceDetails> {
const [
pixelRatio,
statBarHeight,
viewportRect,
{apiVersion, platformVersion, manufacturer, model, realDisplaySize, displayDensity},
] = await B.all([
this.getDevicePixelRatio(),
this.getStatusBarHeight(),
this.getViewPortRect(),
this.mobileGetDeviceInfo(),
]);
return {
pixelRatio,
statBarHeight,
viewportRect,
deviceApiLevel: _.parseInt(apiVersion),
platformVersion,
deviceManufacturer: manufacturer,
deviceModel: model,
deviceScreenSize: realDisplaySize,
deviceScreenDensity: displayDensity,
};
}
override get driverData() {
// TODO fill out resource info here
return {};
}
override async getSession(): Promise<SingularSessionData<Uiautomator2Constraints>> {
const sessionData = await BaseDriver.prototype.getSession.call(this);
this.log.debug('Getting session details from server to mix in');
const uia2Data = (await this.uiautomator2!.jwproxy.command('/', 'GET', {})) as any;
return {...sessionData, ...uia2Data};
}
async allocateSystemPort() {
const forwardPort = async (localPort: number) => {
this.log.debug(
`Forwarding UiAutomator2 Server port ${DEVICE_PORT} to local port ${localPort}`
);
if ((await checkPortStatus(localPort, LOCALHOST_IP4)) === 'open') {
throw this.log.errorWithException(
`UiAutomator2 Server cannot start because the local port #${localPort} is busy. ` +
`Make sure the port you provide via 'systemPort' capability is not occupied. ` +
`This situation might often be a result of an inaccurate sessions management, e.g. ` +
`old automation sessions on the same device must always be closed before starting new ones.`
);
}
await this.adb!.forwardPort(localPort, DEVICE_PORT);
};
if (this.opts.systemPort) {
this.systemPort = this.opts.systemPort;
return await forwardPort(this.systemPort);
}
await DEVICE_PORT_ALLOCATION_GUARD(async () => {
const [startPort, endPort] = DEVICE_PORT_RANGE;
try {
this.systemPort = await findAPortNotInUse(startPort, endPort);
} catch {
throw this.log.errorWithException(
`Cannot find any free port in range ${startPort}..${endPort}}. ` +
`Please set the available port number by providing the systemPort capability or ` +
`double check the processes that are locking ports within this range and terminate ` +
`these which are not needed anymore`
);
}
await forwardPort(this.systemPort);
});
}
async releaseSystemPort() {
if (!this.systemPort || !this.adb) {
return;
}
if (this.opts.systemPort) {
// We assume if the systemPort is provided manually then it must be unique,
// so there is no need for the explicit synchronization
await this.adb.removePortForward(this.systemPort);
} else {
await DEVICE_PORT_ALLOCATION_GUARD(
async () => await this.adb!.removePortForward(this.systemPort!)
);
}
}
async allocateMjpegServerPort() {
if (this.opts.mjpegServerPort) {
this.log.debug(
`MJPEG broadcasting requested, forwarding MJPEG server port ${MJPEG_SERVER_DEVICE_PORT} ` +
`to local port ${this.opts.mjpegServerPort}`
);
await this.adb!.forwardPort(this.opts.mjpegServerPort, MJPEG_SERVER_DEVICE_PORT);
}
}
async releaseMjpegServerPort() {
if (this.opts.mjpegServerPort) {
await this.adb!.removePortForward(this.opts.mjpegServerPort);
}
}
async performSessionPreExecSetup(): Promise<StringRecord|undefined> {
const apiLevel = await this.adb.getApiLevel();
if (apiLevel < 21) {
throw this.log.errorWithException(
'UIAutomator2 is only supported since Android 5.0 (Lollipop). ' +
'You could still use other supported backends in order to automate older Android versions.'
);
}
const preflightPromises: Promise<any>[] = [];
if (apiLevel >= 28) {
// Android P
preflightPromises.push((async () => {
this.log.info('Relaxing hidden api policy');
try {
await this.adb.setHiddenApiPolicy('1', !!this.opts.ignoreHiddenApiPolicyError);
} catch (err) {
throw this.log.errorWithException(
'Hidden API policy (https://developer.android.com/guide/app-compatibility/restrictions-non-sdk-interfaces) cannot be enabled. ' +
'This might be happening because the device under test is not configured properly. ' +
'Please check https://github.com/appium/appium/issues/13802 for more details. ' +
'You could also set the "appium:ignoreHiddenApiPolicyError" capability to true in order to ' +
'ignore this error, which might later lead to unexpected crashes or behavior of ' +
`the automation server. Original error: ${err.message}`
);
}
})());
}
if (util.hasValue(this.opts.gpsEnabled)) {
preflightPromises.push((async () => {
this.log.info(
`Trying to ${this.opts.gpsEnabled ? 'enable' : 'disable'} gps location provider`
);
await this.adb.toggleGPSLocationProvider(Boolean(this.opts.gpsEnabled));
})());
}
if (this.opts.hideKeyboard) {
preflightPromises.push((async () => {
this._originalIme = await this.adb.defaultIME();
})());
}
let appInfo;
preflightPromises.push((async () => {
// get appPackage et al from manifest if necessary
appInfo = await this.getLaunchInfo();
})());
// start settings app, set the language/locale, start logcat etc...
preflightPromises.push(this.initDevice());
await B.all(preflightPromises);
this.opts = {...this.opts, ...(appInfo ?? {})};
return appInfo;
}
async performSessionExecution(capsWithSessionInfo: StringRecord): Promise<void> {
await B.all([
// Prepare the device by forwarding the UiAutomator2 port
// This call mutates this.systemPort if it is not set explicitly
this.allocateSystemPort(),
// Prepare the device by forwarding the UiAutomator2 MJPEG server port (if
// applicable)
this.allocateMjpegServerPort(),
]);
const [uiautomator2,] = await B.all([
// set up the modified UiAutomator2 server etc
this.initUiAutomator2Server(),
(async () => {
// Should be after installing io.appium.settings
if (this.opts.disableWindowAnimation && await this.adb.getApiLevel() < 26) {
// API level 26 is Android 8.0.
// Granting android.permission.SET_ANIMATION_SCALE is necessary to handle animations under API level 26
// Read https://github.com/appium/appium/pull/11640#issuecomment-438260477
// `--no-window-animation` works over Android 8 to disable all of animations
if (await this.adb.isAnimationOn()) {
this.log.info('Disabling animation via io.appium.settings');
await this.settingsApp.setAnimationState(false);
this._wasWindowAnimationDisabled = true;
} else {
this.log.info('Window animation is already disabled');
}
}
})(),
// set up app under test
// prepare our actual AUT, get it on the device, etc...
this.initAUT(),
]);
// launch UiAutomator2 and wait till its online and we have a session
await uiautomator2.startSession(capsWithSessionInfo);
// now that everything has started successfully, turn on proxying so all
// subsequent session requests go straight to/from uiautomator2
this.jwpProxyActive = true;
}
async performSessionPostExecSetup(): Promise<void> {
// Unlock the device after the session is started.
if (!this.opts.skipUnlock) {
// unlock the device to prepare it for testing
await this.unlock();
} else {
this.log.debug(`'skipUnlock' capability set, so skipping device unlock`);
}
if (this.isChromeSession) {
// start a chromedriver session
await this.startChromeSession();
} else if (this.opts.autoLaunch && this.opts.appPackage) {
await this.ensureAppStarts();
}
// if the initial orientation is requested, set it
if (util.hasValue(this.opts.orientation)) {
this.log.debug(`Setting initial orientation to '${this.opts.orientation}'`);
await this.setOrientation(this.opts.orientation as Orientation);
}
// if we want to immediately get into a webview, set our context
// appropriately
if (this.opts.autoWebview) {
const viewName = this.defaultWebviewName();
const timeout = this.opts.autoWebviewTimeout || 2000;
this.log.info(`Setting auto webview to context '${viewName}' with timeout ${timeout}ms`);
await retryInterval(timeout / 500, 500, this.setContext.bind(this), viewName);
}
// We would like to notify about the initial context setting
if (await this.getCurrentContext() === this.defaultContextName()) {
await this.notifyBiDiContextChange();
}
}
async startUiAutomator2Session(
caps: Uiautomator2StartSessionOpts
): Promise<Uiautomator2SessionCaps> {
const appInfo = await this.performSessionPreExecSetup();
// set actual device name, udid, platform version, screen size, screen density, model and manufacturer details
const sessionInfo: Uiautomator2SessionInfo = {
deviceName: this.adb.curDeviceId!,
deviceUDID: this.opts.udid!,
};
const capsWithSessionInfo = {
...caps,
...sessionInfo,
};
// Adding AUT info in the capabilities if it does not exist in caps
if (appInfo) {
for (const capName of ['appPackage', 'appActivity']) {
if (!capsWithSessionInfo[capName] && appInfo[capName]) {
capsWithSessionInfo[capName] = appInfo[capName];
}
}
}
await this.performSessionExecution(capsWithSessionInfo);
const deviceInfoPromise: Promise<Uiautomator2DeviceDetails|EmptyObject> = (async () => {
try {
return await this.getDeviceDetails();
} catch (e) {
this.log.warn(`Cannot fetch device details. Original error: ${e.message}`);
return {};
}
})();
await this.performSessionPostExecSetup();
return {...capsWithSessionInfo, ...(await deviceInfoPromise)};
}
async initUiAutomator2Server() {
// broken out for readability
const uiautomator2Opts = {
// @ts-expect-error FIXME: maybe `address` instead of `host`?
host: this.opts.remoteAdbHost || this.opts.host || LOCALHOST_IP4,
systemPort: this.systemPort as number,
devicePort: DEVICE_PORT,
adb: this.adb,
tmpDir: this.opts.tmpDir as string,
disableWindowAnimation: !!this.opts.disableWindowAnimation,
disableSuppressAccessibilityService: this.opts.disableSuppressAccessibilityService,
readTimeout: this.opts.uiautomator2ServerReadTimeout,
basePath: this.basePath,
};
// now that we have package and activity, we can create an instance of
// uiautomator2 with the appropriate options
this.uiautomator2 = new UiAutomator2Server(this.log, uiautomator2Opts);
this.proxyReqRes = this.uiautomator2.proxyReqRes.bind(this.uiautomator2);
this.proxyCommand = this.uiautomator2.proxyCommand.bind(
this.uiautomator2
) as typeof this.proxyCommand;
if (this.opts.skipServerInstallation) {
this.log.info(`'skipServerInstallation' is set. Skipping UIAutomator2 server installation.`);
} else {
await this.uiautomator2.installServerApk(this.opts.uiautomator2ServerInstallTimeout);
try {
await this.adb!.addToDeviceIdleWhitelist(
SETTINGS_HELPER_ID,
SERVER_PACKAGE_ID,
SERVER_TEST_PACKAGE_ID
);
} catch (e) {
const err = e as ExecError;
this.log.warn(
`Cannot add server packages to the Doze whitelist. Original error: ` +
(err.stderr || err.message)
);
}
}
return this.uiautomator2;
}
async initAUT() {
// Uninstall any uninstallOtherPackages which were specified in caps
if (this.opts.uninstallOtherPackages) {
await this.uninstallOtherPackages(
utils.parseArray(this.opts.uninstallOtherPackages),
[SETTINGS_HELPER_ID, SERVER_PACKAGE_ID, SERVER_TEST_PACKAGE_ID]
);
}
// Install any "otherApps" that were specified in caps
if (this.opts.otherApps) {
let otherApps;
try {
otherApps = utils.parseArray(this.opts.otherApps);
} catch (e) {
throw this.log.errorWithException(
`Could not parse "otherApps" capability: ${(e as Error).message}`
);
}
otherApps = await B.all(
otherApps.map((app) => this.helpers.configureApp(app, [APK_EXTENSION, APKS_EXTENSION]))
);
await this.installOtherApks(otherApps);
}
if (this.opts.app) {
if (
(this.opts.noReset && !(await this.adb!.isAppInstalled(this.opts.appPackage!))) ||
!this.opts.noReset
) {
if (
!this.opts.noSign &&
!(await this.adb!.checkApkCert(this.opts.app, this.opts.appPackage!, {
requireDefaultCert: false,
}))
) {
await signApp(this.adb!, this.opts.app);
}
if (!this.opts.skipUninstall) {
await this.adb!.uninstallApk(this.opts.appPackage!);
}
await this.installAUT();
} else {
this.log.debug(
'noReset has been requested and the app is already installed. Doing nothing'
);
}
} else {
if (this.opts.fullReset) {
throw this.log.errorWithException(
'Full reset requires an app capability, use fastReset if app is not provided'
);
}
this.log.debug('No app capability. Assuming it is already on the device');
if (this.opts.fastReset && this.opts.appPackage) {
await this.resetAUT();
}
}
}
async ensureAppStarts() {
// make sure we have an activity and package to wait for
const appWaitPackage = this.opts.appWaitPackage || this.opts.appPackage;
const appWaitActivity = this.opts.appWaitActivity || this.opts.appActivity;
this.log.info(
`Starting '${this.opts.appPackage}/${this.opts.appActivity}' ` +
`and waiting for '${appWaitPackage}/${appWaitActivity}'`
);
if (
this.opts.noReset &&
!this.opts.forceAppLaunch &&
(await this.adb!.processExists(this.opts.appPackage!))
) {
this.log.info(
`'${this.opts.appPackage}' is already running and noReset is enabled. ` +
`Set forceAppLaunch capability to true if the app must be forcefully restarted on session startup.`
);
return;
}
await this.adb!.startApp({
pkg: this.opts.appPackage!,
activity: this.opts.appActivity,
action: this.opts.intentAction || 'android.intent.action.MAIN',
category: this.opts.intentCategory || 'android.intent.category.LAUNCHER',
flags: this.opts.intentFlags || '0x10200000', // FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
waitPkg: this.opts.appWaitPackage,
waitActivity: this.opts.appWaitActivity,
waitForLaunch: this.opts.appWaitForLaunch,
waitDuration: this.opts.appWaitDuration,
optionalIntentArguments: this.opts.optionalIntentArguments,
stopApp: this.opts.forceAppLaunch || !this.opts.dontStopAppOnReset,
retry: true,
user: this.opts.userProfile,
});
}
async deleteSession() {
this.log.debug('Deleting UiAutomator2 session');
const screenRecordingStopTasks = [
async () => {
if (!_.isEmpty(this._screenRecordingProperties)) {
await this.stopRecordingScreen();
}
},
async () => {
if (await this.mobileIsMediaProjectionRecordingRunning()) {
await this.mobileStopMediaProjectionRecording();
}
},
async () => {
if (!_.isEmpty(this._screenStreamingProps)) {
await this.mobileStopScreenStreaming();
}
},
];
try {
await this.stopChromedriverProxies();
} catch (err) {
this.log.warn(`Unable to stop ChromeDriver proxies: ${(err as Error).message}`);
}
if (this.jwpProxyActive) {
try {
await this.uiautomator2.deleteSession();
} catch (err) {
this.log.warn(`Unable to proxy deleteSession to UiAutomator2: ${(err as Error).message}`);
}
this.jwpProxyActive = false;
}
if (this.adb) {
await B.all(
screenRecordingStopTasks.map((task) => {
(async () => {
try {
await task();
} catch {}
})();
})
);
if (this.opts.appPackage) {
if (
!this.isChromeSession &&
((!this.opts.dontStopAppOnReset && !this.opts.noReset) ||
(this.opts.noReset && this.opts.shouldTerminateApp))
) {
try {
await this.adb.forceStop(this.opts.appPackage);
} catch (err) {
this.log.warn(`Unable to force stop app: ${(err as Error).message}`);
}
}
if (this.opts.fullReset && !this.opts.skipUninstall) {
this.log.debug(
`Capability 'fullReset' set to 'true', Uninstalling '${this.opts.appPackage}'`
);
try {
await this.adb.uninstallApk(this.opts.appPackage);
} catch (err) {
this.log.warn(`Unable to uninstall app: ${(err as Error).message}`);
}
}
}
// This value can be true if test target device is <= 26
if (this._wasWindowAnimationDisabled) {
this.log.info('Restoring window animation state');
await this.settingsApp.setAnimationState(true);
}
if (this._originalIme) {
try {
await this.adb.setIME(this._originalIme);
} catch (e) {
this.log.warn(`Cannot restore the original IME: ${e.message}`);
}
}
try {
await this.releaseSystemPort();
} catch (error) {
this.log.warn(`Unable to remove system port forward: ${(error as Error).message}`);
// Ignore, this block will also be called when we fall in catch block
// and before even port forward.
}
try {
await this.releaseMjpegServerPort();
} catch (error) {
this.log.warn(`Unable to remove MJPEG server port forward: ${(error as Error).message}`);
// Ignore, this block will also be called when we fall in catch block
// and before even port forward.
}
if ((await this.adb.getApiLevel()) >= 28) {
// Android P
this.log.info('Restoring hidden api policy to the device default configuration');
await this.adb.setDefaultHiddenApiPolicy(!!this.opts.ignoreHiddenApiPolicyError);
}
}
if (this.mjpegStream) {
this.log.info('Closing MJPEG stream');
this.mjpegStream.stop();
}
await super.deleteSession();
}
async checkAppPresent() {
this.log.debug('Checking whether app is actually present');
if (!this.opts.app || !(await fs.exists(this.opts.app))) {
throw this.log.errorWithException(`Could not find app apk at '${this.opts.app}'`);
}
}
async onSettingsUpdate() {
// intentionally do nothing here, since commands.updateSettings proxies
// settings to the uiauto2 server already
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
proxyActive(sessionId: string): boolean {
// we always have an active proxy to the UiAutomator2 server
return true;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
canProxy(sessionId: string): boolean {
// we can always proxy to the uiautomator2 server
return true;
}
getProxyAvoidList(): RouteMatcher[] {
// we are maintaining two sets of NO_PROXY lists, one for chromedriver(CHROME_NO_PROXY)
// and one for uiautomator2(NO_PROXY), based on current context will return related NO_PROXY list
if (util.hasValue(this.chromedriver)) {
// if the current context is webview(chromedriver), then return CHROME_NO_PROXY list
this.jwpProxyAvoid = CHROME_NO_PROXY;
} else {
this.jwpProxyAvoid = NO_PROXY;
}
if (this.opts.nativeWebScreenshot) {
this.jwpProxyAvoid = [
...this.jwpProxyAvoid,
['GET', new RegExp('^/session/[^/]+/screenshot')],
];
}
return this.jwpProxyAvoid;
}
async updateSettings(settings: Uiautomator2Settings) {
await this.settings.update(settings);
await this.uiautomator2!.jwproxy.command('/appium/settings', 'POST', {settings});
}
async getSettings() {
const driverSettings = this.settings.getSettings();
const serverSettings = (await this.uiautomator2!.jwproxy.command(
'/appium/settings',
'GET'
)) as Partial<Uiautomator2Settings>;
return {...driverSettings, ...serverSettings} as any;
}
mobileGetActionHistory = mobileGetActionHistory;
mobileScheduleAction = mobileScheduleAction;