How to use this.remote.connect method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

macaca-ios.js

Source: macaca-ios.js Github

copy
1'use strict';
2
3const co = require('co');
4const Device = require('ios-device');
5const XCTestWD = require('xctestwd');
6const iOSUtils = require('ios-utils');
7const {
8  errors
9} = require('webdriver-dfn-error-code');
10const DriverBase = require('driver-base');
11const Simulator = require('ios-simulator');
12const RemoteDebugger = require('remote-debugger');
13
14const _ = require('./helper');
15const logger = require('./logger');
16const actionHandler = require('./actions');
17const controllers = require('./controllers');
18
19const WINDOW = 'WINDOW';
20const WEBVIEW = 'WEBVIEW';
21const NATIVE = 'NATIVE_APP';
22const WINDOW_PREFIX = `${WINDOW}_`;
23const WEBVIEW_PREFIX = `${WEBVIEW}_`;
24
25_.sudoUserPermissionDenied();
26
27class IOS extends DriverBase {
28  constructor() {
29    super();
30    this.iOSSDKVersion = null;
31    this.xctest = null;
32    this.args = null;
33    this.device = null;
34    this.atoms = [];
35    this.bundleId = null;
36    this.context = null;
37    this.contexts = [];
38    this.frame = null;
39    this.implicitWaitMs = 5000;
40    this.proxy = null;
41    this.remote = null;
42    this.udid = null;
43    this.isSafari = false;
44    this.proxyPort = 8001;
45  }
46}
47
48IOS.prototype.whiteList = function(context) {
49  const wdUrl = context.url;
50  const whiteList = [
51    'url',
52    'context',
53    'contexts',
54    'screenshot',
55    'implicit_wait',
56    'actions',
57    'keys'
58  ];
59  return whiteList.some(word => !!~wdUrl.indexOf(word));
60};
61
62IOS.prototype.isProxy = function() {
63  return !!this.proxy;
64};
65
66const autoAcceptAlerts = function() {
67  const acceptUrl = '/wd/hub/session/:sessionId/accept_alert';
68  return this.xctest.sendCommand(acceptUrl, 'POST', {});
69};
70
71const autoDismissAlerts = function() {
72  const dismissUrl = '/wd/hub/session/:sessionId/dismiss_alert';
73  return this.xctest.sendCommand(dismissUrl, 'POST', {});
74};
75
76IOS.prototype.autoHandleAlerts = function * () {
77  if (this.xctest) {
78    if (this.autoAcceptAlerts) {
79      this.autoHandleAlerts = autoAcceptAlerts;
80    } else if (this.autoDismissAlerts) {
81      this.autoHandleAlerts = autoDismissAlerts;
82    } else {
83      this.autoHandleAlerts = () => [];
84    }
85  } else {
86    this.autoHandleAlerts = () => [];
87  }
88};
89
90IOS.prototype.proxyCommand = function * (url, method, body) {
91  yield this.autoHandleAlerts();
92  return this.proxy.sendCommand(url, method, body);
93};
94
95IOS.prototype.startDevice = function * (caps) {
96  this.args = _.clone(caps);
97  let reuse = parseInt(this.args.reuse, 10);
98
99  if (!reuse && reuse !== 0) {
100    reuse = 1;
101  }
102  this.args.reuse = reuse;
103
104  this.autoAcceptAlerts = Boolean(caps.autoAcceptAlerts);
105  this.autoDismissAlerts = Boolean(caps.autoDismissAlerts);
106  this.iOSSDKVersion = yield iOSUtils.getIOSSDKVersion();
107
108  if (!this.args.udid && this.args.deviceName) {
109    this.args.udid = yield this.getSimulatorUdid();
110  }
111
112  const deviceInfo = _.getDeviceInfo(this.args.udid);
113
114  this.udid = this.args.udid;
115
116  if (this.args.proxyPort) {
117    this.proxyPort = this.args.proxyPort;
118  }
119  const app = this.args.app;
120  const bundleId = this.args.bundleId;
121
122  if (!bundleId && !app && !this.args.browserName) {
123    throw new errors.UnknownError('Neither \'app\' nor \'bundleId\' is provided!');
124  }
125
126  if (bundleId) {
127    this.bundleId = bundleId;
128  } else if (app) {
129    this.bundleId = yield iOSUtils.getBundleId(app);
130  } else if (this.args.browserName === 'Safari') {
131    this.isSafari = true;
132    this.bundleId = 'com.apple.mobilesafari';
133  }
134
135  if (deviceInfo.isRealIOS) {
136    this.device = new Device({
137      deviceId: this.udid
138    });
139
140    yield this.startRealDevice();
141  } else {
142    this.device = new Simulator({
143      deviceId: this.udid
144    });
145
146    yield this.startSimulator();
147  }
148
149  if (this.xctest) {
150    this.xctest.stop();
151  }
152  yield this.device.uninstall(XCTestWD.XCTestWD.BUNDLE_ID);
153
154  const desCaps = _.validateAndFilterDesiredCaps(_.merge({
155    bundleId: this.bundleId
156  }, this.args));
157
158  if (deviceInfo.isRealIOS) {
159    delete desCaps.app;
160  }
161
162  logger.debug(JSON.stringify(desCaps, null, '\t'));
163
164  this.initXCTest();
165
166  if (!this.isSafari) {
167    this.proxy = this.xctest;
168  }
169  const that = this;
170  yield _.retry(co.wrap(function * () {
171    logger.debug('Trying to start xctestwd server...');
172    return yield that.xctest.start({
173      desiredCapabilities: desCaps
174    });
175  }), 20 * 1000, 3);
176
177  if (this.isSafari) {
178    yield this.startSafari(desCaps);
179  }
180};
181
182IOS.prototype.initXCTest = function() {
183  this.xctest = new XCTestWD({
184    device: this.device,
185    proxyPort: this.proxyPort
186  });
187};
188
189IOS.prototype.startSafari = function * (caps) {
190  this.remote = new RemoteDebugger({
191    deviceId: this.udid
192  });
193
194  yield this.remote.start();
195
196  let availablePages = [];
197
198  const pageAvailable = () => {
199    return this.remote
200      .getPages()
201      .then(pages => {
202        availablePages = pages;
203        return !!pages.length;
204      });
205  };
206
207  yield _.waitForCondition(pageAvailable);
208
209  let latestPage = _.last(availablePages);
210  let pageId = latestPage.id;
211  yield this.remote.connect(pageId);
212  this.context = pageId;
213  yield this.deleteWindow();
214  return caps;
215};
216
217IOS.prototype.getSimulatorUdid = function * () {
218  const devices = yield Simulator.getDevices();
219  const availableDevices = devices.filter(device => device.available);
220  let matchedDevice = null;
221
222  logger.debug(`Get available devices ${JSON.stringify(availableDevices)}`);
223
224  const deviceString = this.args.deviceName;
225
226  _.each(availableDevices, device => {
227    if (device.name === deviceString) {
228      matchedDevice = device;
229    }
230  });
231
232  if (!matchedDevice) {
233    throw new Error(`Device ${deviceString} is not available!`);
234  }
235
236  return matchedDevice.udid;
237};
238
239IOS.prototype.startRealDevice = function * () {
240  const bundleId = this.bundleId;
241  const isInstalled = yield this.device.exists(bundleId);
242  const app = this.args.app;
243  const reuse = this.args.reuse;
244
245  if (!app && !isInstalled) {
246    throw new errors.UnknownError(`App '${bundleId}' is neither installed, nor provided!`);
247  }
248
249  if (isInstalled) {
250    logger.debug(`App "${bundleId}" is already installed.`);
251    logger.debug(`Adopting app reuse strategy: ${reuse}.`);
252    switch (reuse) {
253    case 0:
254    case 1:
255      if (app) {
256        try {
257          yield this.device.uninstall(bundleId);
258          logger.debug(`Uninstall app "${bundleId}".`);
259          yield this.device.installUntilReady(app, bundleId);
260          logger.debug(`Install app '${bundleId}' successfully.`);
261        } catch (err) {
262          logger.debug(err.message);
263          throw new errors.UnknownError(`Failed to install app '${bundleId}', please install the app manually.`);
264        }
265      }
266      break;
267    case 2:
268      if (app) {
269        try {
270          yield this.device.installUntilReady(app, bundleId);
271          logger.debug(`Install app '${bundleId}' successfully.`);
272        } catch (err) {
273          logger.debug(err.message);
274          throw new errors.UnknownError(`Failed to install app '${bundleId}', please install the app manually.`);
275        }
276      }
277      break;
278    case 3:
279      // Keep app state. Do nothing.
280      break;
281    }
282  } else {
283    logger.debug(`App '${bundleId}' is not installed.`);
284    try {
285      yield this.device.installUntilReady(app, bundleId);
286      logger.debug(`Install app '${bundleId}' successfully.`);
287    } catch (err) {
288      logger.debug(err.message);
289      throw new errors.UnknownError(`Failed to install app '${bundleId}', please install the app manually.`);
290    }
291  }
292};
293
294IOS.prototype.startSimulator = function * () {
295  const isBooted = yield this.device.isBooted();
296  const app = this.args.app;
297  const bundleId = this.bundleId;
298  const reuse = this.args.reuse;
299
300  if (reuse && isBooted) {
301    const isInstalled = yield this.device.exists(bundleId);
302    if (!isInstalled && !app) {
303      throw new errors.UnknownError(`App '${bundleId}' is neither installed, nor provided!`);
304    }
305
306    if (reuse === 1 && app) {
307      yield this.device.uninstall(this.bundleId);
308      yield this.device.installUntilReady(app, this.bundleId);
309    }
310
311    if (reuse === 2) {
312      if (!isInstalled && app) {
313        yield this.device.installUntilReady(app, this.bundleId);
314      }
315    }
316
317    if (reuse === 3) {
318      if (isInstalled) {
319        this.args.app = '';
320      }
321    }
322    return;
323  }
324
325  try {
326    yield Simulator.killAll();
327  } catch (e) {
328    logger.debug(`Kill simulator failed ${e}`);
329  }
330
331  try {
332    yield this.device.shutdown();
333  } catch (e) {
334    logger.debug(`Shutdown simulator ${this.device.deviceId} failed ${e}`);
335  }
336
337  if (!reuse) {
338    yield this.device.erase();
339  }
340
341  yield this.device.open();
342
343  yield _.retry(() => {
344    return new Promise((resolve, reject) => {
345      this.device
346        .isBooted()
347        .then(isBooted => {
348          if (isBooted) {
349            resolve();
350          } else {
351            reject(new errors.UnknownError(`Simulator ${this.device.deviceId} is not booted.`));
352          }
353        });
354    });
355  }, 3000, 10);
356
357  const isInstalled = yield this.device.exists(bundleId);
358
359  if (!isInstalled && !app) {
360    throw new errors.UnknownError(`App '${bundleId}' is neither installed, nor provided!`);
361  }
362
363  // after device resume, should also based on app info and reuse to uninstall/install app
364  if (reuse === 1 && app) {
365    yield this.device.uninstall(this.bundleId);
366    yield this.device.installUntilReady(app, this.bundleId);
367  }
368
369  if (reuse === 2) {
370    if (!isInstalled && app) {
371      yield this.device.installUntilReady(app, this.bundleId);
372    }
373  }
374};
375
376IOS.prototype.getDeviceString = function() {
377  return this.args.deviceName + ' (' + this.args.platformVersion + ')';
378};
379
380IOS.prototype.stopDevice = function * () {
381  logger.debug('Stoping iOS driver...');
382
383  if (this.xctest) {
384    this.xctest.stop();
385  }
386
387  if (this.remote) {
388    this.remote.stop();
389  }
390
391  if (this.device && !this.args.reuse) {
392    try {
393      yield this.device.shutdown();
394    } catch (e) {
395      logger.debug(`Shutdown simulator ${this.device.deviceId} failed ${e}`);
396    }
397
398    try {
399      yield Simulator.killAll();
400    } catch (e) {
401      logger.debug(`Kill simulator failed ${e}`);
402    }
403  }
404
405  logger.debug('iOS driver cleaned up.');
406};
407
408IOS.prototype.isWebContext = function() {
409  return this.context !== null && this.context !== 'NATIVE';
410};
411
412IOS.prototype.getContext = function * () {
413
414  yield this.getContexts();
415
416  if (!_.includes(this.contexts, String(this.context))) {
417    logger.debug(`We dont have this context ${this.context}`);
418    throw new errors.NoSuchWindow();
419  }
420
421  if (this.context && this.context !== NATIVE) {
422    return `${WEBVIEW_PREFIX}${this.context}`;
423  } else {
424    return NATIVE;
425  }
426};
427
428IOS.prototype.getContexts = function * () {
429  const webviews = yield this.getWebviews();
430  const ctx = webviews.map(page => page.id.toString());
431  ctx.unshift(NATIVE);
432  this.contexts = ctx;
433  const names = webviews.map(page => `${WEBVIEW_PREFIX}${page.id}`);
434  names.unshift(NATIVE);
435  return names;
436};
437
438IOS.prototype.getWebviews = function * () {
439
440  if (!this.remote) {
441    this.remote = new RemoteDebugger({
442      deviceId: this.udid
443    });
444    yield this.remote.start();
445  }
446  const pages = yield this.remote.getPages();
447
448  if (pages.length === 0) {
449    logger.debug('Cannot find any Webview');
450  }
451  return pages;
452};
453
454IOS.prototype.setContext = function * (name) {
455  if ((name === this.context) ||
456    (!name && NATIVE === this.context) ||
457    (name === NATIVE && this.context === null)) {
458    return null;
459  } else if (name === NATIVE || !name) {
460    this.proxy = this.xctest;
461    this.context = null;
462    this.frame = null;
463    this.remote && this.remote.disconnect();
464  } else {
465    this.proxy = null;
466    const index = name.replace(WEBVIEW_PREFIX, '');
467
468    yield this.getContexts();
469
470    if (!_.includes(this.contexts, index)) {
471      logger.debug(`We dont have this context ${index}`);
472      throw new errors.NoSuchWindow();
473    }
474
475    const pageId = parseInt(index, 10);
476
477    if (this.context === pageId) {
478      return null;
479    }
480
481    if (this.remote) {
482      this.remote.disconnect();
483    }
484
485    yield this.remote.connect(pageId);
486    this.context = pageId;
487    this.frame = null;
488    return null;
489  }
490};
491
492IOS.prototype.get = function * (url) {
493  if (this.isSafari || this.proxy) {
494    yield this.device.openURL(url);
495    yield _.sleep(2000);
496    if (!this.remote) {
497      this.remote = new RemoteDebugger({
498        deviceId: this.udid
499      });
500      yield this.remote.start();
501    }
502    const availablePages = yield this.remote.getPages();
503    const latestPage = _.last(availablePages);
504    if (latestPage) {
505      const pageId = latestPage.id;
506      yield this.remote.connect(pageId);
507      this.context = pageId;
508    }
509    this.frame = null;
510    return null;
511  } else {
512    this.frame = null;
513    return yield this.remote.navigateTo(url);
514  }
515};
516
517IOS.prototype.getWindows = function * () {
518  if (!this.isSafari) {
519    throw new errors.NoSuchWindow();
520  }
521  const webviews = yield this.getWebviews();
522  const ctx = webviews.map(page => page.id.toString());
523  this.contexts = ctx;
524  const names = webviews.map(page => `${WINDOW_PREFIX}${page.id}`);
525  return names;
526};
527
528IOS.prototype.setWindow = function * (name) {
529  if (name === this.context) {
530    return null;
531  } else {
532    const index = name.replace(WINDOW_PREFIX, '');
533
534    if (!_.includes(this.contexts, index)) {
535      logger.debug(`We dont have this window ${index}`);
536      throw new errors.NoSuchWindow();
537    }
538
539    const pageId = parseInt(index, 10);
540
541    if (this.context === pageId) {
542      return null;
543    }
544
545    if (this.remote) {
546      this.remote.disconnect();
547    }
548
549    yield this.remote.connect(pageId);
550    this.context = pageId;
551    this.frame = null;
552    return null;
553  }
554};
555
556IOS.prototype.getScreenshot = function * (context) {
557  const data = yield this.xctest.sendCommand(context.url, context.method, context.body);
558  try {
559    const result = typeof data === 'string' ? JSON.parse(data) : data;
560    return result.value;
561  } catch (e) {
562    logger.debug(e);
563    throw new errors.JavaScriptError(e.message);
564  }
565};
566
567IOS.prototype.keys = function * (value) {
568  // https://github.com/macacajs/webdriver-keycode/blob/master/lib/webdriver-keycode.js
569  const keyMap = {
570    '\uE105': 'homescreen'
571  };
572
573  value = value.join('');
574  var arrText = [];
575
576  for (var i = 0; i < value.length; i++) {
577    var key = value.charAt(i);
578
579    const keyEvent = keyMap[key];
580
581    if (keyEvent) {
582      // send at last
583      if (arrText.length) {
584        yield this.proxyCommand('/wd/hub/session/:sessionId/keys', 'POST', {
585          value: [arrText.join('')]
586        });
587        arrText = [];
588      }
589      if (keyEvent === 'homescreen') {
590        yield this.proxyCommand('/wd/hub/session/:sessionId/homeScreen', 'POST', {});
591      }
592    } else {
593      arrText.push(key);
594    }
595  }
596  if (arrText.length) {
597    yield this.proxyCommand('/wd/hub/session/:sessionId/keys', 'post', {
598      value: [arrText.join('')]
599    });
600  }
601  return null;
602};
603
604IOS.prototype.handleActions = function * (actions) {
605  if (!actions) {
606    throw new errors.UnknownError('Missing \'actions\' in parameters.');
607  }
608  const futureActions = actions.map(action => actionHandler.bind(this, action));
609  return yield _.serialTasks.apply(null, futureActions);
610};
611
612for (let name in controllers) {
613  IOS.prototype[name] = function * () {
614    if (this.isSafari) {
615      yield this.getWindows();
616    } else {
617      yield this.getContexts();
618    }
619    if (!_.includes(this.contexts, String(this.context))) {
620      logger.debug(`We dont have this context ${this.context}`);
621      throw new errors.NoSuchWindow();
622    }
623    yield this.autoHandleAlerts();
624    return yield controllers[name].apply(this, arguments);
625  };
626}
627
628module.exports = IOS;
629
Full Screen

network.js

Source: network.js Github

copy
1/**
2 * NETWORK
3 *
4 * The network service is used to communicate with the Ripple network.
5 *
6 * It encapsulates a ripple.Remote instance.
7 */
8
9var module = angular.module('network', []);
10
11module.factory('rpNetwork', ['$rootScope', function($scope)
12{
13  /**
14   * Manage network state.
15   *
16   * This class is intended to manage the connection status to the
17   * Ripple network.
18   *
19   * Note that code in other places *is allowed* to call the Ripple
20   * library directly. This is not to be intended to be an abstraction
21   * layer on top of an abstraction layer.
22   */
23  var Network = function ()
24  {
25    this.remote = new ripple.Remote(Options.server, true);
26    this.remote.on('connected', this.handleConnect.bind(this));
27    this.remote.on('disconnected', this.handleDisconnect.bind(this));
28
29    // Set network max transaction fee from Options, or default to 12 drops of XRP
30    this.remote.max_fee = Options.max_tx_network_fee || 12;
31
32    this.connected = false;
33  };
34
35  Network.prototype.init = function ()
36  {
37    this.remote.connect();
38  };
39
40  /**
41   * Setup listeners for identity state.
42   *
43   * This function causes the network object to start listening to
44   * changes in the identity state and automatically subscribe to
45   * accounts accordingly.
46   */
47  Network.prototype.listenId = function (id)
48  {
49    var self = this;
50  };
51
52  Network.prototype.handleConnect = function (e)
53  {
54    var self = this;
55    $scope.$apply(function () {
56      self.connected = true;
57      $scope.connected = true;
58      $scope.$broadcast('$netConnected');
59    });
60  };
61
62  Network.prototype.handleDisconnect = function (e)
63  {
64    var self = this;
65    $scope.$apply(function () {
66      self.connected = false;
67      $scope.connected = false;
68      $scope.$broadcast('$netDisconnected');
69    });
70  };
71
72  return new Network();
73}]);
74
75
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Xcuitest Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)