How to use quitAndUninstall method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

driver.js

Source:driver.js Github

copy

Full Screen

...374 this.wda = new WebDriverAgent(this.xcodeVersion, this.opts);375 await this.wda.cleanupObsoleteProcesses();376 if (this.opts.useNewWDA) {377 log.debug(`Capability 'useNewWDA' set to true, so uninstalling WDA before proceeding`);378 await this.wda.quitAndUninstall();379 this.logEvent('wdaUninstalled');380 } else if (!util.hasValue(this.wda.webDriverAgentUrl)) {381 await this.wda.setupCaching(this.opts.updatedWDABundleId);382 }383 // local helper for the two places we need to uninstall wda and re-start it384 const quitAndUninstall = async (msg) => {385 log.debug(msg);386 if (this.opts.webDriverAgentUrl) {387 log.debug('Not quitting and unsinstalling WebDriverAgent as webDriverAgentUrl is provided');388 throw new Error(msg);389 }390 log.warn('Quitting and uninstalling WebDriverAgent, then retrying');391 await this.wda.quitAndUninstall();392 throw new Error(msg);393 };394 const startupRetries = this.opts.wdaStartupRetries || (this.isRealDevice() ? WDA_REAL_DEV_STARTUP_RETRIES : WDA_SIM_STARTUP_RETRIES);395 const startupRetryInterval = this.opts.wdaStartupRetryInterval || WDA_STARTUP_RETRY_INTERVAL;396 log.debug(`Trying to start WebDriverAgent ${startupRetries} times with ${startupRetryInterval}ms interval`);397 await retryInterval(startupRetries, startupRetryInterval, async () => {398 this.logEvent('wdaStartAttempted');399 try {400 // on xcode 10 installd will often try to access the app from its staging401 // directory before fully moving it there, and fail. Retrying once402 // immediately helps403 const retries = this.xcodeVersion.major >= 10 ? 2 : 1;404 this.cachedWdaStatus = await retry(retries, this.wda.launch.bind(this.wda), sessionId, realDevice);405 // this.cachedWdaStatus = await this.wda.launch(sessionId, realDevice);406 } catch (err) {407 this.logEvent('wdaStartFailed');408 let errorMsg = `Unable to launch WebDriverAgent because of xcodebuild failure: "${err.message}".`;409 if (this.isRealDevice()) {410 errorMsg += ` Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +411 `Try to remove the WebDriverAgentRunner application from the device if it is installed ` +412 `and reboot the device.`;413 }414 await quitAndUninstall(errorMsg);415 }416 this.proxyReqRes = this.wda.proxyReqRes.bind(this.wda);417 this.jwpProxyActive = true;418 try {419 await retryInterval(15, 1000, async () => {420 this.logEvent('wdaSessionAttempted');421 log.debug('Sending createSession command to WDA');422 try {423 this.cachedWdaStatus = this.cachedWdaStatus || await this.proxyCommand('/status', 'GET');424 await this.startWdaSession(this.opts.bundleId, this.opts.processArguments);425 } catch (err) {426 log.debug(`Failed to create WDA session (${err.message}). Retrying...`);427 throw err;428 }429 });430 this.logEvent('wdaSessionStarted');431 } catch (err) {432 let errorMsg = `Unable to start WebDriverAgent session because of xcodebuild failure: ${err.message}`;433 if (this.isRealDevice()) {434 errorMsg += ` Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +435 `Try to remove the WebDriverAgentRunner application from the device if it is installed ` +436 `and reboot the device.`;437 }438 await quitAndUninstall(errorMsg);439 }440 if (!util.hasValue(this.opts.preventWDAAttachments)) {441 // XCTest prior to Xcode 9 SDK has no native way to disable attachments442 this.opts.preventWDAAttachments = this.xcodeVersion.major < 9;443 if (this.opts.preventWDAAttachments) {444 log.info('Enabled WDA attachments prevention by default to save the disk space. ' +445 `Set 'preventWDAAttachments' capability to false if this is an undesired behavior.`);446 }447 }448 if (this.opts.preventWDAAttachments) {449 await adjustWDAAttachmentsPermissions(this.wda, this.opts.preventWDAAttachments ? '555' : '755');450 this.logEvent('wdaPermsAdjusted');451 }452 if (this.opts.clearSystemFiles) {...

Full Screen

Full Screen

webdriveragent.js

Source:webdriveragent.js Github

copy

Full Screen

1import _ from 'lodash';2import path from 'path';3import url from 'url';4import { JWProxy } from 'appium-base-driver';5import { fs, util } from 'appium-support';6import log from '../logger';7import { NoSessionProxy } from "./no-session-proxy";8import { checkForDependencies, WDA_RUNNER_BUNDLE_ID, getWDAUpgradeTimestamp } from './utils';9import { resetXCTestProcesses, getPIDsListeningOnPort } from '../utils';10import XcodeBuild from './xcodebuild';11import iProxy from './iproxy';12import { exec } from 'teen_process';13const BOOTSTRAP_PATH = path.resolve(__dirname, '..', '..', '..', 'WebDriverAgent');14const WDA_BUNDLE_ID = 'com.apple.test.WebDriverAgentRunner-Runner';15const WDA_LAUNCH_TIMEOUT = 60 * 1000;16const WDA_AGENT_PORT = 8100;17const WDA_BASE_URL = 'http://localhost';18class WebDriverAgent {19 constructor (xcodeVersion, args = {}) {20 this.xcodeVersion = xcodeVersion;21 this.args = _.clone(args);22 this.device = args.device;23 this.platformVersion = args.platformVersion;24 this.host = args.host;25 this.realDevice = !!args.realDevice;26 this.setWDAPaths(args.bootstrapPath, args.agentPath);27 this.wdaLocalPort = args.wdaLocalPort;28 this.prebuildWDA = args.prebuildWDA;29 this.webDriverAgentUrl = args.webDriverAgentUrl;30 this.started = false;31 this.wdaConnectionTimeout = args.wdaConnectionTimeout;32 this.useCarthageSsl = _.isBoolean(args.useCarthageSsl) && args.useCarthageSsl;33 this.useXctestrunFile = args.useXctestrunFile;34 this.xcodebuild = new XcodeBuild(this.xcodeVersion, this.device, {35 platformVersion: this.platformVersion,36 agentPath: this.agentPath,37 bootstrapPath: this.bootstrapPath,38 realDevice: this.realDevice,39 showXcodeLog: !!args.showXcodeLog,40 xcodeConfigFile: args.xcodeConfigFile,41 xcodeOrgId: args.xcodeOrgId,42 xcodeSigningId: args.xcodeSigningId,43 keychainPath: args.keychainPath,44 keychainPassword: args.keychainPassword,45 useSimpleBuildTest: args.useSimpleBuildTest,46 usePrebuiltWDA: args.usePrebuiltWDA,47 updatedWDABundleId: args.updatedWDABundleId,48 launchTimeout: args.wdaLaunchTimeout || WDA_LAUNCH_TIMEOUT,49 wdaRemotePort: this.realDevice ? WDA_AGENT_PORT : (this.wdaLocalPort || WDA_AGENT_PORT),50 useXctestrunFile: this.useXctestrunFile,51 derivedDataPath: args.derivedDataPath,52 mjpegServerPort: args.mjpegServerPort,53 });54 }55 setWDAPaths (bootstrapPath, agentPath) {56 // allow the user to specify a place for WDA. This is undocumented and57 // only here for the purposes of testing development of WDA58 this.bootstrapPath = bootstrapPath || BOOTSTRAP_PATH;59 log.info(`Using WDA path: '${this.bootstrapPath}'`);60 // for backward compatibility we need to be able to specify agentPath too61 this.agentPath = agentPath || path.resolve(this.bootstrapPath, 'WebDriverAgent.xcodeproj');62 log.info(`Using WDA agent: '${this.agentPath}'`);63 }64 async cleanupObsoleteProcesses () {65 const pids = await getPIDsListeningOnPort(this.url.port,66 (cmdLine) => (cmdLine.includes('/WebDriverAgentRunner') || cmdLine.includes('/iproxy')) &&67 !cmdLine.toLowerCase().includes(this.device.udid.toLowerCase()));68 if (!pids.length) {69 log.debug(`No obsolete cached processes from previous WDA sessions ` +70 `listening on port ${this.url.port} have been found`);71 return;72 }73 log.info(`Detected ${pids.length} obsolete cached process${pids.length === 1 ? '' : 'es'} ` +74 `from previous WDA sessions. Cleaning up...`);75 try {76 await exec('kill', pids);77 } catch (e) {78 log.warn(`Failed to kill obsolete cached process${pids.length === 1 ? '' : 'es'} '${pids}'. ` +79 `Original error: ${e.message}`);80 }81 }82 /**83 * Return boolean if WDA is running or not84 * @return {boolean} True if WDA is running85 * @throws {Error} If there was invalid response code or body86 */87 async isRunning () {88 return !!(await this.getStatus());89 }90 /**91 * Return current running WDA's status like below92 * {93 * "state": "success",94 * "os": {95 * "name": "iOS",96 * "version": "11.4",97 * "sdkVersion": "11.3"98 * },99 * "ios": {100 * "simulatorVersion": "11.4",101 * "ip": "172.254.99.34"102 * },103 * "build": {104 * "time": "Jun 24 2018 17:08:21",105 * "productBundleIdentifier": "com.facebook.WebDriverAgentRunner"106 * }107 * }108 *109 * @return {?object} State Object110 * @throws {Error} If there was invalid response code or body111 */112 async getStatus () {113 const noSessionProxy = new NoSessionProxy({114 server: this.url.hostname,115 port: this.url.port,116 base: '',117 timeout: 3000,118 });119 try {120 return await noSessionProxy.command('/status', 'GET');121 } catch (err) {122 log.debug(`WDA is not listening at '${this.url.href}'`);123 return null;124 }125 }126 async uninstall () {127 log.debug(`Removing WDA application from device`);128 try {129 await this.device.removeApp(WDA_BUNDLE_ID);130 } catch (e) {131 log.warn(`WebDriverAgent uninstall failed. Perhaps, it is already uninstalled? Original error: ${JSON.stringify(e)}`);132 }133 }134 async launch (sessionId) {135 if (this.webDriverAgentUrl) {136 log.info(`Using provided WebdriverAgent at '${this.webDriverAgentUrl}'`);137 this.url = this.webDriverAgentUrl;138 this.setupProxies(sessionId);139 return;140 }141 log.info('Launching WebDriverAgent on the device');142 this.setupProxies(sessionId);143 if (!this.useXctestrunFile && !await fs.exists(this.agentPath)) {144 throw new Error(`Trying to use WebDriverAgent project at '${this.agentPath}' but the ` +145 'file does not exist');146 }147 if (!this.useXctestrunFile) {148 // make sure that the WDA dependencies have been built149 const didPerformUpgrade = await checkForDependencies(this.bootstrapPath, this.useCarthageSsl);150 if (didPerformUpgrade) {151 // Only perform the cleanup after WDA upgrade152 await this.xcodebuild.cleanProject();153 }154 }155 // We need to provide WDA local port, because it might be occupied with156 // iproxy instance initiated by some preceeding run with a real device157 // (iproxy instances are not killed on session termination by default)158 await resetXCTestProcesses(this.device.udid, !this.realDevice, {wdaLocalPort: this.url.port});159 if (this.realDevice) {160 this.iproxy = new iProxy(this.device.udid, this.url.port, WDA_AGENT_PORT);161 await this.iproxy.start();162 }163 await this.xcodebuild.init(this.noSessionProxy);164 // Start the xcodebuild process165 if (this.prebuildWDA) {166 await this.xcodebuild.prebuild();167 }168 return await this.xcodebuild.start();169 }170 setupProxies (sessionId) {171 const proxyOpts = {172 server: this.url.hostname,173 port: this.url.port,174 base: '',175 timeout: this.wdaConnectionTimeout,176 };177 this.jwproxy = new JWProxy(proxyOpts);178 this.jwproxy.sessionId = sessionId;179 this.proxyReqRes = this.jwproxy.proxyReqRes.bind(this.jwproxy);180 this.noSessionProxy = new NoSessionProxy(proxyOpts);181 this.noSessionProxyReqRes = this.noSessionProxy.proxyReqRes.bind(this.noSessionProxy);182 }183 async quit () {184 log.info('Shutting down sub-processes');185 if (this.iproxy) {186 await this.iproxy.quit();187 }188 await this.xcodebuild.quit();189 await this.xcodebuild.reset();190 if (this.jwproxy) {191 this.jwproxy.sessionId = null;192 }193 this.started = false;194 if (!this.args.webDriverAgentUrl) {195 // if we populated the url ourselves (during `setupCaching` call, for instance)196 // then clean that up. If the url was supplied, we want to keep it197 this.webDriverAgentUrl = null;198 }199 }200 get url () {201 if (!this._url) {202 let port = this.wdaLocalPort || WDA_AGENT_PORT;203 this._url = url.parse(`${WDA_BASE_URL}:${port}`);204 }205 return this._url;206 }207 set url (_url) {208 this._url = url.parse(_url);209 }210 get fullyStarted () {211 return this.started;212 }213 set fullyStarted (started = false) {214 // before WDA is started we expect errors from iproxy, since it is not215 // communicating with anything yet216 this.started = started;217 if (this.iproxy) {218 this.iproxy.expectIProxyErrors = !started;219 }220 }221 async retrieveDerivedDataPath () {222 return await this.xcodebuild.retrieveDerivedDataPath();223 }224 /**225 * Reuse running WDA if it has the same bundle id with updatedWDABundleId.226 * Or reuse it if it has the default id without updatedWDABundleId.227 * Uninstall it if the method faces an exception for the above situation.228 *229 * @param {string} updatedWDABundleId BundleId you'd like to use230 */231 async setupCaching (updatedWDABundleId) {232 const status = await this.getStatus();233 if (!status || !status.build) {234 log.debug('WDA is currently not running. There is nothing to cache');235 return;236 }237 const {238 productBundleIdentifier,239 upgradedAt,240 } = status.build;241 if (util.hasValue(productBundleIdentifier) && util.hasValue(updatedWDABundleId) && updatedWDABundleId !== productBundleIdentifier) {242 log.info(`Will uninstall running WDA since it has different bundle id. The actual value is '${productBundleIdentifier}'.`);243 return await this.uninstall();244 }245 if (util.hasValue(productBundleIdentifier) && !util.hasValue(updatedWDABundleId) && WDA_RUNNER_BUNDLE_ID !== productBundleIdentifier) {246 log.info(`Will uninstall running WDA since its bundle id is not equal to the default value ${WDA_RUNNER_BUNDLE_ID}`);247 return await this.uninstall();248 }249 const actualUpgradeTimestamp = await getWDAUpgradeTimestamp(this.bootstrapPath);250 log.debug(`Upgrade timestamp of the currently bundled WDA: ${actualUpgradeTimestamp}`);251 log.debug(`Upgrade timestamp of the WDA on the device: ${upgradedAt}`);252 if (actualUpgradeTimestamp && upgradedAt && _.toLower(`${actualUpgradeTimestamp}`) !== _.toLower(`${upgradedAt}`)) {253 log.info('Will uninstall running WDA since it has different version in comparison to the one ' +254 `which is bundled with appium-xcuitest-driver module (${actualUpgradeTimestamp} != ${upgradedAt})`);255 return await this.uninstall();256 }257 const message = util.hasValue(productBundleIdentifier)258 ? `Will reuse previously cached WDA instance at '${this.url.href}' with '${productBundleIdentifier}'`259 : `Will reuse previously cached WDA instance at '${this.url.href}'`;260 log.info(`${message}. Set the wdaLocalPort capability to a value different from ${this.url.port} if this is an undesired behavior.`);261 this.webDriverAgentUrl = this.url.href;262 }263 async quitAndUninstall () {264 await this.quit();265 await this.uninstall();266 }267}268export default WebDriverAgent;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require("webdriverio");2const opts = {3 capabilities: {4 }5};6async function main() {7 const client = await wdio.remote(opts);8 await client.quitAndUninstall();9 await client.deleteSession();10}11main();12* Appium version (or git revision) that exhibits the issue: 1.18.013* Last Appium version that did not exhibit the issue (if applicable):14* Node.js version (unless using Appium.app|exe): 12.16.1

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const opts = {3 capabilities: {4 }5}6async function main() {7 const client = await wdio.remote(opts);8 await client.quitAndUninstall();9}10main();11const wdio = require('webdriverio');12const opts = {13 capabilities: {14 }15}16async function main() {17 const client = await wdio.remote(opts);18 await client.uninstallApp();19}20main();21const wdio = require('webdriverio');22const opts = {23 capabilities: {24 }25}26async function main() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .quitAndUninstall()9 .end();10var webdriverio = require('webdriverio');11var options = {12 desiredCapabilities: {13 }14};15 .remote(options)16 .init()17 .quitAndUninstall()18 .end();19var webdriverio = require('webdriverio');20var options = {21 desiredCapabilities: {22 }23};24 .remote(options)25 .init()26 .quitAndUninstall()27 .end();28var webdriverio = require('webdriverio');29var options = {30 desiredCapabilities: {31 }32};33 .remote(options)34 .init()35 .quitAndUninstall()36 .end();37var webdriverio = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1let driver = await wdio.remote(options);2await driver.quitAndUninstall();3let driver = await wdio.remote(options);4await driver.removeApp('com.example.app');5let driver = await wdio.remote(options);6await driver.installApp('path/to/app.apk');7let driver = await wdio.remote(options);8await driver.launchApp();9let driver = await wdio.remote(options);10await driver.terminateApp();11let driver = await wdio.remote(options);12await driver.activateApp('com.example.app');13let driver = await wdio.remote(options);14await driver.resetApp();15let driver = await wdio.remote(options);16await driver.backgroundApp(5);17let driver = await wdio.remote(options);18await driver.startRecordingScreen();19let driver = await wdio.remote(options);20await driver.stopRecordingScreen();21let driver = await wdio.remote(options);22await driver.getSystemBars();23let driver = await wdio.remote(options);24await driver.getDisplayDensity();25let driver = await wdio.remote(options);26await driver.getDisplaySize();27let driver = await wdio.remote(options);28await driver.getSettings();29let driver = await wdio.remote(options);30await driver.updateSettings({});31let driver = await wdio.remote(options);32await driver.setGeoLocation({});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const { exec } = require('child_process');3const assert = require('assert');4const path = require('path');5const fs = require('fs');6const { asyncify } = require('asyncbox');7const PORT = 4723;

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const should = chai.should();6const caps = {7};8driver.init(caps)9 .then(() => {10 return driver.quitAndUninstall();11 })12 .then(() => {13 console.log('Test Passed');14 })15 .catch((err) => {16 console.log('Test Failed: ' + err);17 });18const wd = require('wd');19const chai = require('chai');20const chaiAsPromised = require('chai-as-promised');21chai.use(chaiAsPromised);22const should = chai.should();23const caps = {24};25driver.init(caps)26 .then(() => {27 return driver.getLogTypes();28 })29 .then((logTypes) => {30 console.log('Log Types: ' + logTypes);31 })32 .catch((err) => {33 console.log('Test Failed: ' + err);34 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request-promise');2const { exec } = require('child_process');3const opts = {4 body: {},5};6request(opts)7 .then(function (response) {8 console.log(response);9 })10 .catch(function (err) {11 console.log(err);12 });13const opts = {14 body: {15 },16};17request(opts)18 .then(function (response) {19 console.log(response);20 })21 .catch(function (err) {22 console.log(err);23 });24const opts = {25 body: {26 },27};28request(opts)29 .then(function (response) {30 console.log(response);31 })32 .catch(function (err) {33 console.log(err);34 });35const opts = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5driver.init(desiredCaps)6 .then(function () {7 return driver.quitAndUninstall();8 })9 .then(function () {10 console.log("Quit and Uninstall successful");11 })12 .catch(function (err) {13 console.log("Quit and Uninstall failed with error: " + err);14 })15 .fin(function () {16 driver.quit();17 });18var wd = require('wd');19var assert = require('assert');20var desiredCaps = {21};22driver.init(desiredCaps)23 .then(function () {24 return driver.quitAndUninstall();25 })26 .then(function () {27 console.log("Quit and Uninstall successful");28 })29 .catch(function (err) {30 console.log("Quit and Uninstall failed with error: " + err);31 })32 .fin(function () {33 driver.quit();34 });35var wd = require('wd');36var assert = require('assert');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful