-
-
Notifications
You must be signed in to change notification settings - Fork 425
/
Copy pathdriver.js
2191 lines (1947 loc) · 77.7 KB
/
driver.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 IDB from 'appium-idb';
import {getSimulator} from 'appium-ios-simulator';
import {WebDriverAgent} from 'appium-webdriveragent';
import {BaseDriver, DeviceSettings} from 'appium/driver';
import {fs, mjpeg, util} from 'appium/support';
import AsyncLock from 'async-lock';
import {retry, retryInterval} from 'asyncbox';
import B from 'bluebird';
import _ from 'lodash';
import LRU from 'lru-cache';
import EventEmitter from 'node:events';
import path from 'node:path';
import url from 'node:url';
import {
APP_EXT,
IPA_EXT,
SAFARI_BUNDLE_ID,
extractBundleId,
extractBundleVersion,
fetchSupportedAppPlatforms,
findApps,
isAppBundle,
isolateAppBundle,
verifyApplicationPlatform,
} from './app-utils';
import commands from './commands';
import {PLATFORM_NAME_IOS, PLATFORM_NAME_TVOS, desiredCapConstraints} from './desired-caps';
import DEVICE_CONNECTIONS_FACTORY from './device-connections-factory';
import {executeMethodMap} from './execute-method-map';
import {newMethodMap} from './method-map';
import Pyidevice from './py-ios-device-client';
import {
getConnectedDevices,
getRealDeviceObj,
installToRealDevice,
runRealDeviceReset,
} from './real-device-management';
import {
createSim,
getExistingSim,
installToSimulator,
runSimulatorReset,
setLocalizationPrefs,
setSafariPrefs,
shutdownOtherSimulators,
shutdownSimulator,
} from './simulator-management';
import {
DEFAULT_TIMEOUT_KEY,
checkAppPresent,
clearSystemFiles,
detectUdid,
getAndCheckIosSdkVersion,
getAndCheckXcodeVersion,
getDriverInfo,
isLocalHost,
markSystemFilesForCleanup,
normalizeCommandTimeouts,
normalizePlatformVersion,
printUser,
removeAllSessionWebSocketHandlers,
translateDeviceName,
} from './utils';
const SHUTDOWN_OTHER_FEAT_NAME = 'shutdown_other_sims';
const CUSTOMIZE_RESULT_BUNDPE_PATH = 'customize_result_bundle_path';
const SUPPORTED_EXTENSIONS = [IPA_EXT, APP_EXT];
const MAX_ARCHIVE_SCAN_DEPTH = 1;
const defaultServerCaps = {
webStorageEnabled: false,
locationContextEnabled: false,
browserName: '',
platform: 'MAC',
javascriptEnabled: true,
databaseEnabled: false,
takesScreenshot: true,
networkConnectionEnabled: false,
};
const WDA_SIM_STARTUP_RETRIES = 2;
const WDA_REAL_DEV_STARTUP_RETRIES = 1;
const WDA_REAL_DEV_TUTORIAL_URL =
'https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md';
const WDA_STARTUP_RETRY_INTERVAL = 10000;
const DEFAULT_SETTINGS = {
nativeWebTap: false,
nativeWebTapStrict: false,
useJSONSource: false,
shouldUseCompactResponses: true,
elementResponseAttributes: 'type,label',
// Read https://github.com/appium/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBConfiguration.m for following settings' values
mjpegServerScreenshotQuality: 25,
mjpegServerFramerate: 10,
screenshotQuality: 1,
mjpegScalingFactor: 100,
// set `reduceMotion` to `null` so that it will be verified but still set either true/false
reduceMotion: null,
};
// This lock assures, that each driver session does not
// affect shared resources of the other parallel sessions
const SHARED_RESOURCES_GUARD = new AsyncLock();
const WEB_ELEMENTS_CACHE_SIZE = 500;
const SUPPORTED_ORIENATIONS = ['LANDSCAPE', 'PORTRAIT'];
/* eslint-disable no-useless-escape */
/** @type {import('@appium/types').RouteMatcher[]} */
const NO_PROXY_NATIVE_LIST = [
['DELETE', /window/],
['GET', /^\/session\/[^\/]+$/],
['GET', /alert_text/],
['GET', /alert\/[^\/]+/],
['GET', /appium/],
['GET', /attribute/],
['GET', /context/],
['GET', /location/],
['GET', /log/],
['GET', /screenshot/],
['GET', /size/],
['GET', /source/],
['GET', /timeouts$/],
['GET', /url/],
['GET', /window/],
['POST', /accept_alert/],
['POST', /actions$/],
['DELETE', /actions$/],
['POST', /alert_text/],
['POST', /alert\/[^\/]+/],
['POST', /appium/],
['POST', /appium\/device\/is_locked/],
['POST', /appium\/device\/lock/],
['POST', /appium\/device\/unlock/],
['POST', /back/],
['POST', /clear/],
['POST', /context/],
['POST', /dismiss_alert/],
['POST', /element\/active/], // MJSONWP get active element should proxy
['POST', /element$/],
['POST', /elements$/],
['POST', /execute/],
['POST', /keys/],
['POST', /log/],
['POST', /moveto/],
['POST', /receive_async_response/], // always, in case context switches while waiting
['POST', /session\/[^\/]+\/location/], // geo location, but not element location
['POST', /shake/],
['POST', /timeouts/],
['POST', /touch/],
['POST', /url/],
['POST', /value/],
['POST', /window/],
['DELETE', /cookie/],
['GET', /cookie/],
['POST', /cookie/],
];
const NO_PROXY_WEB_LIST = /** @type {import('@appium/types').RouteMatcher[]} */ ([
['GET', /attribute/],
['GET', /element/],
['GET', /text/],
['GET', /title/],
['POST', /clear/],
['POST', /click/],
['POST', /element/],
['POST', /forward/],
['POST', /frame/],
['POST', /keys/],
['POST', /refresh/],
]).concat(NO_PROXY_NATIVE_LIST);
/* eslint-enable no-useless-escape */
const MEMOIZED_FUNCTIONS = ['getStatusBarHeight', 'getDevicePixelRatio', 'getScreenInfo'];
const BUNDLE_VERSION_PATTERN = /CFBundleVersion\s+=\s+"?([^(;|")]+)/;
/**
* @implements {ExternalDriver<XCUITestDriverConstraints, FullContext|string>}
* @extends {BaseDriver<XCUITestDriverConstraints>}
* @privateRemarks **This class should be considered "final"**. It cannot be extended
* due to use of public class field assignments. If extending this class becomes a hard requirement, refer to the implementation of `BaseDriver` on how to do so.
*/
class XCUITestDriver extends BaseDriver {
static newMethodMap = newMethodMap;
static executeMethodMap = executeMethodMap;
/** @type {string|null|undefined} */
curWindowHandle;
/**
* @type {boolean|undefined}
*/
selectingNewPage;
/** @type {string[]} */
contexts;
/** @type {string|null} */
curContext;
/**
* @type {import('@appium/types').Position|null}
*/
curWebCoords;
/**
* @type {import('@appium/types').Position|null}
*/
curCoords;
/** @type {string[]} */
curWebFrames;
/**
* @type {import('./types').Page[]|undefined}
*/
windowHandleCache;
/** @type {import('./types').AsyncPromise|undefined} */
asyncPromise;
/** @type {number|undefined} */
asyncWaitMs;
/** @type {((logRecord: {message: string}) => void)|null} */
_syslogWebsocketListener;
/** @type {import('./commands/performance').PerfRecorder[]} */
_perfRecorders;
/** @type {LRU} */
webElementsCache;
/**
* @type {any|null}
* @privateRemarks needs types
**/
_conditionInducerService;
/** @type {boolean|undefined} */
_isSafariIphone;
/** @type {boolean|undefined} */
_isSafariNotched;
/** @type {import('./commands/types').WaitingAtoms} */
_waitingAtoms;
/** @type {import('./types').LifecycleData} */
lifecycleData;
/** @type {XCUITestDriverOpts} */
opts;
/** @type {import('./commands/record-audio').AudioRecorder|null} */
_audioRecorder;
/** @type {import('./commands/pcap').TrafficCapture|null} */
_trafficCapture;
/**
*
* @param {XCUITestDriverOpts} opts
* @param {boolean} shouldValidateCaps
*/
constructor(opts = /** @type {XCUITestDriverOpts} */ ({}), shouldValidateCaps = true) {
super(opts, shouldValidateCaps);
this.locatorStrategies = [
'xpath',
'id',
'name',
'class name',
'-ios predicate string',
'-ios class chain',
'accessibility id',
'css selector',
];
this.webLocatorStrategies = [
'link text',
'css selector',
'tag name',
'link text',
'partial link text',
];
this.curWebFrames = [];
this._perfRecorders = [];
this.desiredCapConstraints = desiredCapConstraints;
this.webElementsCache = new LRU({
max: WEB_ELEMENTS_CACHE_SIZE,
});
this._waitingAtoms = {
count: 0,
alertNotifier: new EventEmitter(),
alertMonitor: B.resolve(),
};
this.resetIos();
this.settings = new DeviceSettings(DEFAULT_SETTINGS, this.onSettingsUpdate.bind(this));
this.logs = {};
this._trafficCapture = null;
// memoize functions here, so that they are done on a per-instance basis
for (const fn of MEMOIZED_FUNCTIONS) {
this[fn] = _.memoize(this[fn]);
}
this.lifecycleData = {};
this._audioRecorder = null;
}
async onSettingsUpdate(key, value) {
if (key !== 'nativeWebTap' && key !== 'nativeWebTapStrict') {
return await this.proxyCommand('/appium/settings', 'POST', {
settings: {[key]: value},
});
}
this.opts[key] = !!value;
}
resetIos() {
this.opts = this.opts || {};
this.wda = null;
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.device = null;
this.jwpProxyActive = false;
this.proxyReqRes = null;
this.safari = false;
this.cachedWdaStatus = null;
this.curWebFrames = [];
this._currentUrl = null;
this.curContext = null;
this.xcodeVersion = {};
this.contexts = [];
this.implicitWaitMs = 0;
this.asynclibWaitMs = 0;
this.pageLoadMs = 6000;
this.landscapeWebCoordsOffset = 0;
this.remote = null;
this._conditionInducerService = null;
this.webElementsCache = new LRU({
max: WEB_ELEMENTS_CACHE_SIZE,
});
this._waitingAtoms = {
count: 0,
alertNotifier: new EventEmitter(),
alertMonitor: B.resolve(),
};
}
get driverData() {
// TODO fill out resource info here
return {};
}
async getStatus() {
if (typeof this.driverInfo === 'undefined') {
this.driverInfo = await getDriverInfo();
}
let status = {build: {version: this.driverInfo.version}};
if (this.cachedWdaStatus) {
status.wda = this.cachedWdaStatus;
}
return status;
}
mergeCliArgsToOpts() {
let didMerge = false;
// this.cliArgs should never include anything we do not expect.
for (const [key, value] of Object.entries(this.cliArgs ?? {})) {
if (_.has(this.opts, key)) {
this.log.info(
`CLI arg '${key}' with value '${value}' overwrites value '${this.opts[key]}' sent in via caps)`
);
didMerge = true;
}
this.opts[key] = value;
}
return didMerge;
}
async createSession(w3cCaps1, w3cCaps2, w3cCaps3, driverData) {
try {
let [sessionId, caps] = await super.createSession(w3cCaps1, w3cCaps2, w3cCaps3, driverData);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.sessionId = sessionId;
// merge cli args to opts, and if we did merge any, revalidate opts to ensure the final set
// is also consistent
if (this.mergeCliArgsToOpts()) {
this.validateDesiredCaps({...caps, ...this.cliArgs});
}
await this.start();
// merge server capabilities + desired capabilities
caps = Object.assign({}, defaultServerCaps, caps);
// update the udid with what is actually used
caps.udid = this.opts.udid;
// ensure we track nativeWebTap capability as a setting as well
if (_.has(this.opts, 'nativeWebTap')) {
await this.updateSettings({nativeWebTap: this.opts.nativeWebTap});
}
// ensure we track nativeWebTapStrict capability as a setting as well
if (_.has(this.opts, 'nativeWebTapStrict')) {
await this.updateSettings({nativeWebTapStrict: this.opts.nativeWebTapStrict});
}
// ensure we track useJSONSource capability as a setting as well
if (_.has(this.opts, 'useJSONSource')) {
await this.updateSettings({useJSONSource: this.opts.useJSONSource});
}
let wdaSettings = {
elementResponseAttributes: DEFAULT_SETTINGS.elementResponseAttributes,
shouldUseCompactResponses: DEFAULT_SETTINGS.shouldUseCompactResponses,
};
if (_.has(this.opts, 'elementResponseAttributes')) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
wdaSettings.elementResponseAttributes = this.opts.elementResponseAttributes;
}
if (_.has(this.opts, 'shouldUseCompactResponses')) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
wdaSettings.shouldUseCompactResponses = this.opts.shouldUseCompactResponses;
}
if (_.has(this.opts, 'mjpegServerScreenshotQuality')) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
wdaSettings.mjpegServerScreenshotQuality = this.opts.mjpegServerScreenshotQuality;
}
if (_.has(this.opts, 'mjpegServerFramerate')) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
wdaSettings.mjpegServerFramerate = this.opts.mjpegServerFramerate;
}
if (_.has(this.opts, 'screenshotQuality')) {
this.log.info(`Setting the quality of phone screenshot: '${this.opts.screenshotQuality}'`);
wdaSettings.screenshotQuality = this.opts.screenshotQuality;
}
// ensure WDA gets our defaults instead of whatever its own might be
await this.updateSettings(wdaSettings);
// turn on mjpeg stream reading if requested
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 /** @type {[string, import('@appium/types').DriverCaps<XCUITestDriverConstraints>]} */ ([
sessionId,
caps,
]);
} catch (e) {
this.log.error(JSON.stringify(e));
await this.deleteSession();
throw e;
}
}
/**
* Returns the default URL for Safari browser
* @returns {string} The default URL
*/
getDefaultUrl() {
// Setting this to some external URL slows down Appium startup
return this.isRealDevice()
? `http://127.0.0.1:${this.opts.wdaLocalPort || 8100}/health`
: `http://${this.opts.address.includes(':') ? `[${this.opts.address}]` : this.opts.address}:${
this.opts.port
}/welcome`;
}
async start() {
this.opts.noReset = !!this.opts.noReset;
this.opts.fullReset = !!this.opts.fullReset;
await printUser();
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.iosSdkVersion = null; // For WDA and xcodebuild
const {device, udid, realDevice} = await this.determineDevice();
this.log.info(
`Determining device to run tests on: udid: '${udid}', real device: ${realDevice}`
);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.device = device;
this.opts.udid = udid;
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.realDevice = realDevice;
if (this.opts.simulatorDevicesSetPath) {
if (realDevice) {
this.log.info(
`The 'simulatorDevicesSetPath' capability is only supported for Simulator devices`
);
} else {
this.log.info(
`Setting simulator devices set path to '${this.opts.simulatorDevicesSetPath}'`
);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.device.devicesSetPath = this.opts.simulatorDevicesSetPath;
}
}
// at this point if there is no platformVersion, get it from the device
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
if (!this.opts.platformVersion && this.opts.device) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.platformVersion = await this.opts.device.getPlatformVersion();
this.log.info(
`No platformVersion specified. Using device version: '${this.opts.platformVersion}'`
);
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
const normalizedVersion = normalizePlatformVersion(this.opts.platformVersion);
if (this.opts.platformVersion !== normalizedVersion) {
this.log.info(
`Normalized platformVersion capability value '${this.opts.platformVersion}' to '${normalizedVersion}'`
);
this.opts.platformVersion = normalizedVersion;
}
if (util.compareVersions(this.opts.platformVersion, '<', '9.3')) {
throw new Error(
`Platform version must be 9.3 or above. '${this.opts.platformVersion}' is not supported.`
);
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
if (_.isEmpty(this.xcodeVersion) && (!this.opts.webDriverAgentUrl || !this.opts.realDevice)) {
// no `webDriverAgentUrl`, or on a simulator, so we need an Xcode version
this.xcodeVersion = await getAndCheckXcodeVersion();
}
this.logEvent('xcodeDetailsRetrieved');
if (_.toLower(this.opts.browserName) === 'safari') {
this.log.info('Safari test requested');
this.safari = true;
this.opts.app = undefined;
this.opts.processArguments = this.opts.processArguments || {};
this.opts.bundleId = SAFARI_BUNDLE_ID;
this._currentUrl = this.opts.safariInitialUrl || this.getDefaultUrl();
} else if (this.opts.app || this.opts.bundleId) {
await this.configureApp();
}
this.logEvent('appConfigured');
// fail very early if the app doesn't actually exist
// or if bundle id doesn't point to an installed app
if (this.opts.app) {
await checkAppPresent(this.opts.app);
if (!this.opts.bundleId) {
this.opts.bundleId = await extractBundleId.bind(this)(this.opts.app);
}
}
await this.runReset();
this.wda = new WebDriverAgent(this.xcodeVersion, this.opts, this.log);
// Derived data path retrieval is an expensive operation
// We could start that now in background and get the cached result
// whenever it is needed
// eslint-disable-next-line promise/prefer-await-to-then
this.wda.retrieveDerivedDataPath().catch((e) => this.log.debug(e));
const memoizedLogInfo = _.memoize(() => {
this.log.info(
"'skipLogCapture' is set. Skipping starting logs such as crash, system, safari console and safari network."
);
});
const startLogCapture = async () => {
if (this.opts.skipLogCapture) {
memoizedLogInfo();
return false;
}
const result = await this.startLogCapture();
if (result) {
this.logEvent('logCaptureStarted');
}
return result;
};
const isLogCaptureStarted = await startLogCapture();
this.log.info(`Setting up ${this.isRealDevice() ? 'real device' : 'simulator'}`);
if (this.isSimulator()) {
if (this.opts.shutdownOtherSimulators) {
this.ensureFeatureEnabled(SHUTDOWN_OTHER_FEAT_NAME);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await shutdownOtherSimulators(this.opts.device);
}
await this.startSim();
if (this.opts.customSSLCert) {
// Simulator must be booted in order to call this helper
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device.addCertificate(this.opts.customSSLCert);
this.logEvent('customCertInstalled');
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
if (await setSafariPrefs(this.opts.device, this.opts)) {
this.log.debug('Safari preferences have been updated');
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
if (await setLocalizationPrefs(this.opts.device, this.opts)) {
this.log.debug('Localization preferences have been updated');
}
if (_.isBoolean(this.opts.reduceMotion)) {
this.log.info(`Setting reduceMotion to ${this.opts.reduceMotion}`);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device.setReduceMotion(this.opts.reduceMotion);
}
if (_.isBoolean(this.opts.reduceTransparency)) {
this.log.info(`Setting reduceTransparency to ${this.opts.reduceTransparency}`);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device.setReduceTransparency(this.opts.reduceTransparency);
}
if (this.opts.launchWithIDB) {
try {
const idb = new IDB({udid});
await idb.connect();
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
this.opts.device.idb = idb;
} catch (e) {
this.log.debug(e.stack);
this.log.warn(
`idb will not be used for Simulator interaction. Original error: ${e.message}`
);
}
}
this.logEvent('simStarted');
if (!isLogCaptureStarted) {
// Retry log capture if Simulator was not running before
await startLogCapture();
}
} else if (this.opts.customSSLCert) {
await new Pyidevice(udid).installProfile({payload: this.opts.customSSLCert});
this.logEvent('customCertInstalled');
}
if (this.opts.app) {
await this.installAUT();
this.logEvent('appInstalled');
}
// if we only have bundle identifier and no app, fail if it is not already installed
if (
!this.opts.app &&
this.opts.bundleId &&
!this.isSafari() &&
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
!(await this.opts.device.isAppInstalled(this.opts.bundleId))
) {
this.log.errorAndThrow(`App with bundle identifier '${this.opts.bundleId}' unknown`);
}
if (this.isSimulator()) {
if (this.opts.permissions) {
this.log.debug('Setting the requested permissions before WDA is started');
for (const [bundleId, permissionsMapping] of _.toPairs(JSON.parse(this.opts.permissions))) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device.setPermissions(bundleId, permissionsMapping);
}
}
// TODO: Deprecate and remove this block together with calendarAccessAuthorized capability
if (_.isBoolean(this.opts.calendarAccessAuthorized)) {
this.log.warn(
`The 'calendarAccessAuthorized' capability is deprecated and will be removed soon. ` +
`Consider using 'permissions' one instead with 'calendar' key`
);
const methodName = `${
this.opts.calendarAccessAuthorized ? 'enable' : 'disable'
}CalendarAccess`;
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device[methodName](this.opts.bundleId);
}
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.startWda(this.opts.sessionId, realDevice);
if (this.opts.orientation) {
await this.setInitialOrientation(this.opts.orientation);
this.logEvent('orientationSet');
}
if (this.isSafari() || this.opts.autoWebview) {
await this.activateRecentWebview();
}
if (this.isSafari()) {
if (
!(
this.opts.safariInitialUrl === '' ||
(this.opts.noReset && _.isNil(this.opts.safariInitialUrl))
)
) {
this.log.info(
`About to set the initial Safari URL to '${this.getCurrentUrl()}'.` +
`Use 'safariInitialUrl' capability in order to customize it`
);
await this.setUrl(this.getCurrentUrl());
} else {
this.setCurrentUrl(await this.getUrl());
}
}
}
/**
* Start WebDriverAgentRunner
* @param {string} sessionId - The id of the target session to launch WDA with.
* @param {boolean} realDevice - Equals to true if the test target device is a real device.
*/
async startWda(sessionId, realDevice) {
// Don't cleanup the processes if webDriverAgentUrl is set
if (!util.hasValue(this.wda.webDriverAgentUrl)) {
await this.wda.cleanupObsoleteProcesses();
}
const usePortForwarding =
this.isRealDevice() && !this.wda.webDriverAgentUrl && isLocalHost(this.wda.wdaBaseUrl);
await DEVICE_CONNECTIONS_FACTORY.requestConnection(this.opts.udid, this.wda.url.port, {
devicePort: usePortForwarding ? this.wda.wdaRemotePort : null,
usePortForwarding,
});
// Let multiple WDA binaries with different derived data folders be built in parallel
// Concurrent WDA builds from the same source will cause xcodebuild synchronization errors
let synchronizationKey = XCUITestDriver.name;
if (this.opts.useXctestrunFile || !(await this.wda.isSourceFresh())) {
// First-time compilation is an expensive operation, which is done faster if executed
// sequentially. Xcodebuild spreads the load caused by the clang compiler to all available CPU cores
const derivedDataPath = await this.wda.retrieveDerivedDataPath();
if (derivedDataPath) {
synchronizationKey = path.normalize(derivedDataPath);
}
}
this.log.debug(
`Starting WebDriverAgent initialization with the synchronization key '${synchronizationKey}'`
);
if (SHARED_RESOURCES_GUARD.isBusy() && !this.opts.derivedDataPath && !this.opts.bootstrapPath) {
this.log.debug(
`Consider setting a unique 'derivedDataPath' capability value for each parallel driver instance ` +
`to avoid conflicts and speed up the building process`
);
}
return await SHARED_RESOURCES_GUARD.acquire(synchronizationKey, async () => {
if (this.opts.useNewWDA) {
this.log.debug(`Capability 'useNewWDA' set to true, so uninstalling WDA before proceeding`);
await this.wda.quitAndUninstall();
this.logEvent('wdaUninstalled');
} else if (!util.hasValue(this.wda.webDriverAgentUrl)) {
await this.wda.setupCaching();
}
// local helper for the two places we need to uninstall wda and re-start it
const quitAndUninstall = async (msg) => {
this.log.debug(msg);
if (this.opts.webDriverAgentUrl) {
this.log.debug(
'Not quitting/uninstalling WebDriverAgent since webDriverAgentUrl capability is provided'
);
throw new Error(msg);
}
this.log.warn('Quitting and uninstalling WebDriverAgent');
await this.wda.quitAndUninstall();
throw new Error(msg);
};
// Used in the following WDA build
if (this.opts.resultBundlePath) {
this.ensureFeatureEnabled(CUSTOMIZE_RESULT_BUNDPE_PATH);
}
const startupRetries =
this.opts.wdaStartupRetries ||
(this.isRealDevice() ? WDA_REAL_DEV_STARTUP_RETRIES : WDA_SIM_STARTUP_RETRIES);
const startupRetryInterval = this.opts.wdaStartupRetryInterval || WDA_STARTUP_RETRY_INTERVAL;
this.log.debug(
`Trying to start WebDriverAgent ${startupRetries} times with ${startupRetryInterval}ms interval`
);
if (
!util.hasValue(this.opts.wdaStartupRetries) &&
!util.hasValue(this.opts.wdaStartupRetryInterval)
) {
this.log.debug(
`These values can be customized by changing wdaStartupRetries/wdaStartupRetryInterval capabilities`
);
}
let retryCount = 0;
await retryInterval(startupRetries, startupRetryInterval, async () => {
this.logEvent('wdaStartAttempted');
if (retryCount > 0) {
this.log.info(`Retrying WDA startup (${retryCount + 1} of ${startupRetries})`);
}
try {
// on xcode 10 installd will often try to access the app from its staging
// directory before fully moving it there, and fail. Retrying once
// immediately helps
const retries = this.xcodeVersion.major >= 10 ? 2 : 1;
this.cachedWdaStatus = await retry(
retries,
this.wda.launch.bind(this.wda),
sessionId,
realDevice
);
} catch (err) {
this.logEvent('wdaStartFailed');
retryCount++;
let errorMsg = `Unable to launch WebDriverAgent because of xcodebuild failure: ${err.message}`;
if (this.isRealDevice()) {
errorMsg +=
`. Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +
`Try to remove the WebDriverAgentRunner application from the device if it is installed ` +
`and reboot the device.`;
}
await quitAndUninstall(errorMsg);
}
this.proxyReqRes = this.wda.proxyReqRes.bind(this.wda);
this.jwpProxyActive = true;
let originalStacktrace = null;
try {
await retryInterval(15, 1000, async () => {
this.logEvent('wdaSessionAttempted');
this.log.debug('Sending createSession command to WDA');
try {
this.cachedWdaStatus =
this.cachedWdaStatus || (await this.proxyCommand('/status', 'GET'));
await this.startWdaSession(this.opts.bundleId, this.opts.processArguments);
} catch (err) {
originalStacktrace = err.stack;
this.log.debug(`Failed to create WDA session (${err.message}). Retrying...`);
throw err;
}
});
this.logEvent('wdaSessionStarted');
} catch (err) {
if (originalStacktrace) {
this.log.debug(originalStacktrace);
}
let errorMsg = `Unable to start WebDriverAgent session because of xcodebuild failure: ${err.message}`;
if (this.isRealDevice()) {
errorMsg +=
` Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +
`Try to remove the WebDriverAgentRunner application from the device if it is installed ` +
`and reboot the device.`;
}
await quitAndUninstall(errorMsg);
}
if (this.opts.clearSystemFiles && !this.opts.webDriverAgentUrl) {
await markSystemFilesForCleanup(this.wda);
}
// we expect certain socket errors until this point, but now
// mark things as fully working
this.wda.fullyStarted = true;
this.logEvent('wdaStarted');
});
});
}
/**
*
* @param {XCUITestDriverOpts} [opts]
*/
async runReset(opts) {
this.logEvent('resetStarted');
if (this.isRealDevice()) {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await runRealDeviceReset(this.opts.device, opts || this.opts);
} else {
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await runSimulatorReset(this.opts.device, opts || this.opts);
}
this.logEvent('resetComplete');
}
async deleteSession() {
await removeAllSessionWebSocketHandlers(this.server, this.sessionId);
for (const recorder of _.compact([
this._recentScreenRecorder,
this._audioRecorder,
this._trafficCapture,
])) {
await recorder.interrupt(true);
await recorder.cleanup();
}
if (!_.isEmpty(this._perfRecorders)) {
await B.all(this._perfRecorders.map((x) => x.stop(true)));
this._perfRecorders = [];
}
if (this._conditionInducerService) {
this.disableConditionInducer();
}
await this.stop();
if (this.wda && !this.opts.webDriverAgentUrl) {
if (this.opts.clearSystemFiles) {
let synchronizationKey = XCUITestDriver.name;
const derivedDataPath = await this.wda.retrieveDerivedDataPath();
if (derivedDataPath) {
synchronizationKey = path.normalize(derivedDataPath);
}
await SHARED_RESOURCES_GUARD.acquire(synchronizationKey, async () => {
await clearSystemFiles(this.wda);
});
} else {
this.log.debug('Not clearing log files. Use `clearSystemFiles` capability to turn on.');
}
}
if (this.remote) {
this.log.debug('Found a remote debugger session. Removing...');
await this.stopRemote();
}
if (this.opts.resetOnSessionStartOnly === false) {
await this.runReset(
Object.assign({}, this.opts, {
enforceSimulatorShutdown: true,
})
);
}
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
if (this.isSimulator() && !this.opts.noReset && !!this.opts.device) {
if (this.lifecycleData.createSim) {
this.log.debug(`Deleting simulator created for this run (udid: '${this.opts.udid}')`);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await shutdownSimulator(this.opts.device);
// @ts-expect-error - do not assign arbitrary properties to `this.opts`
await this.opts.device.delete();
}
}
const shouldResetLocationServivce = this.isRealDevice() && !!this.opts.resetLocationService;
if (shouldResetLocationServivce) {
try {
await this.mobileResetLocationService();
} catch (ignore) {
/* Ignore this error since mobileResetLocationService already logged the error */
}
}
if (!_.isEmpty(this.logs)) {
await this.logs.syslog.stopCapture();
this.logs = {};
}
if (this.mjpegStream) {
this.log.info('Closing MJPEG stream');
this.mjpegStream.stop();
}
this.resetIos();
await super.deleteSession();
}
async stop() {
this.jwpProxyActive = false;
this.proxyReqRes = null;
if (this.wda && this.wda.fullyStarted) {
if (this.wda.jwproxy) {
try {
await this.proxyCommand(`/session/${this.sessionId}`, 'DELETE');
} catch (err) {
// an error here should not short-circuit the rest of clean up
this.log.debug(`Unable to DELETE session on WDA: '${err.message}'. Continuing shutdown.`);
}
}
if (!this.wda.webDriverAgentUrl && this.opts.useNewWDA) {
await this.wda.quit();
}
}
DEVICE_CONNECTIONS_FACTORY.releaseConnection(this.opts.udid);
}
/**
*
* @param {string} cmd
* @param {...any} args
* @returns {Promise<any>}
*/
async executeCommand(cmd, ...args) {
this.log.debug(`Executing command '${cmd}'`);
if (cmd === 'receiveAsyncResponse') {