Best JavaScript code snippet using appium-base-driver
webdriveragent.js
Source:webdriveragent.js
1import _ from 'lodash';2import path from 'path';3import url from 'url';4import { JWProxy } from 'appium-base-driver';5import { fs } from 'appium-support';6import log from '../logger';7import { NoSessionProxy } from "./no-session-proxy";8import { checkForDependencies } from './utils';9import { resetXCTestProcesses, getPIDsListeningOnPort } from '../utils';10import XcodeBuild from './xcodebuild';11import iProxy from './iproxy';12import fkill from 'fkill';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.device = args.device;22 this.platformVersion = args.platformVersion;23 this.host = args.host;24 this.realDevice = !!args.realDevice;25 this.setWDAPaths(args.bootstrapPath, args.agentPath);26 this.wdaLocalPort = args.wdaLocalPort;27 this.prebuildWDA = args.prebuildWDA;28 this.webDriverAgentUrl = args.webDriverAgentUrl;29 this.started = false;30 this.wdaConnectionTimeout = args.wdaConnectionTimeout;31 this.useCarthageSsl = _.isBoolean(args.useCarthageSsl) && args.useCarthageSsl;32 this.useXctestrunFile = args.useXctestrunFile;33 this.xcodebuild = new XcodeBuild(this.xcodeVersion, this.device, {34 platformVersion: this.platformVersion,35 agentPath: this.agentPath,36 bootstrapPath: this.bootstrapPath,37 realDevice: this.realDevice,38 showXcodeLog: !!args.showXcodeLog,39 xcodeConfigFile: args.xcodeConfigFile,40 xcodeOrgId: args.xcodeOrgId,41 xcodeSigningId: args.xcodeSigningId,42 keychainPath: args.keychainPath,43 keychainPassword: args.keychainPassword,44 useSimpleBuildTest: args.useSimpleBuildTest,45 usePrebuiltWDA: args.usePrebuiltWDA,46 updatedWDABundleId: args.updatedWDABundleId,47 launchTimeout: args.wdaLaunchTimeout || WDA_LAUNCH_TIMEOUT,48 wdaRemotePort: this.realDevice ? WDA_AGENT_PORT : (this.wdaLocalPort || WDA_AGENT_PORT),49 useXctestrunFile : this.useXctestrunFile50 });51 }52 setWDAPaths (bootstrapPath, agentPath) {53 // allow the user to specify a place for WDA. This is undocumented and54 // only here for the purposes of testing development of WDA55 this.bootstrapPath = bootstrapPath || BOOTSTRAP_PATH;56 log.info(`Using WDA path: '${this.bootstrapPath}'`);57 // for backward compatibility we need to be able to specify agentPath too58 this.agentPath = agentPath || path.resolve(this.bootstrapPath, 'WebDriverAgent.xcodeproj');59 log.info(`Using WDA agent: '${this.agentPath}'`);60 }61 async cleanupObsoleteProcesses () {62 const pids = await getPIDsListeningOnPort(this.url.port,63 (cmdLine) => (cmdLine.includes('/WebDriverAgentRunner') || cmdLine.includes('/iproxy')) &&64 !cmdLine.toLowerCase().includes(this.device.udid.toLowerCase()));65 if (!pids.length) {66 log.debug(`No obsolete cached processes from previous WDA sessions ` +67 `listening on port ${this.url.port} have been found`);68 return;69 }70 log.info(`Detected ${pids.length} obsolete cached process${pids.length === 1 ? '' : 'es'} ` +71 `from previous WDA sessions. Cleaning up...`);72 try {73 await fkill(pids);74 } catch (e) {75 log.warn(`Failed to kill obsolete cached process${pids.length === 1 ? '' : 'es'} '${pids}'. ` +76 `Original error: ${e.message}`);77 }78 }79 async isRunning () {80 const noSessionProxy = new NoSessionProxy({81 server: this.url.hostname,82 port: this.url.port,83 base: '',84 timeout: 3000,85 });86 try {87 const status = await noSessionProxy.command('/status', 'GET');88 if (!status) {89 throw new Error(`WDA response to /status command should be defined.`);90 }91 return true;92 } catch (err) {93 log.debug(`WDA is not listening at '${this.url.href}'`);94 return false;95 }96 }97 async uninstall () {98 log.debug(`Removing WDA application from device`);99 try {100 await this.device.removeApp(WDA_BUNDLE_ID);101 } catch (e) {102 log.warn(`WebDriverAgent uninstall failed. Perhaps, it is already uninstalled? Original error: ${JSON.stringify(e)}`);103 }104 }105 async launch (sessionId) {106 if (this.webDriverAgentUrl) {107 log.info(`Using provided WebdriverAgent at '${this.webDriverAgentUrl}'`);108 this.url = this.webDriverAgentUrl;109 this.setupProxies(sessionId);110 return;111 }112 log.info('Launching WebDriverAgent on the device');113 this.setupProxies(sessionId);114 if (!this.useXctestrunFile && !await fs.exists(this.agentPath)) {115 throw new Error(`Trying to use WebDriverAgent project at '${this.agentPath}' but the ` +116 'file does not exist');117 }118 if (!this.useXctestrunFile) {119 // make sure that the WDA dependencies have been built120 await checkForDependencies(this.bootstrapPath, this.useCarthageSsl);121 }122 // We need to provide WDA local port, because it might be occupied with123 // iproxy instance initiated by some preceeding run with a real device124 // (iproxy instances are not killed on session termination by default)125 await resetXCTestProcesses(this.device.udid, !this.realDevice, {wdaLocalPort: this.url.port});126 if (this.realDevice) {127 this.iproxy = new iProxy(this.device.udid, this.url.port, WDA_AGENT_PORT);128 await this.iproxy.start();129 }130 await this.xcodebuild.init(this.noSessionProxy);131 // Start the xcodebuild process132 if (this.prebuildWDA) {133 await this.xcodebuild.prebuild();134 }135 return await this.xcodebuild.start();136 }137 setupProxies (sessionId) {138 const proxyOpts = {139 server: this.url.hostname,140 port: this.url.port,141 base: '',142 timeout: this.wdaConnectionTimeout,143 };144 this.jwproxy = new JWProxy(proxyOpts);145 this.jwproxy.sessionId = sessionId;146 this.proxyReqRes = this.jwproxy.proxyReqRes.bind(this.jwproxy);147 this.noSessionProxy = new NoSessionProxy(proxyOpts);148 this.noSessionProxyReqRes = this.noSessionProxy.proxyReqRes.bind(this.noSessionProxy);149 }150 async quit () {151 log.info('Shutting down sub-processes');152 if (this.iproxy) {153 await this.iproxy.quit();154 }155 await this.xcodebuild.quit();156 await this.xcodebuild.reset();157 if (this.jwproxy) {158 this.jwproxy.sessionId = null;159 }160 this.started = false;161 }162 get url () {163 if (!this._url) {164 let port = this.wdaLocalPort || WDA_AGENT_PORT;165 this._url = url.parse(`${WDA_BASE_URL}:${port}`);166 }167 return this._url;168 }169 set url (_url) {170 this._url = url.parse(_url);171 }172 get fullyStarted () {173 return this.started;174 }175 set fullyStarted (started = false) {176 // before WDA is started we expect errors from iproxy, since it is not177 // communicating with anything yet178 this.started = started;179 if (this.iproxy) {180 this.iproxy.expectIProxyErrors = !started;181 }182 }183 async retrieveDerivedDataPath () {184 return await this.xcodebuild.retrieveDerivedDataPath();185 }186}187export default WebDriverAgent;...
driver.js
Source:driver.js
1import _ from 'lodash';2import { BaseDriver } from '@appium/base-driver';3import SafariDriverServer from './safari';4import { desiredCapConstraints } from './desired-caps';5import commands from './commands/index';6import { formatCapsForServer } from './utils';7const NO_PROXY = [8 ['GET', new RegExp('^/session/[^/]+/appium')],9 ['POST', new RegExp('^/session/[^/]+/appium')],10 ['POST', new RegExp('^/session/[^/]+/element/[^/]+/elements?$')],11 ['POST', new RegExp('^/session/[^/]+/elements?$')],12 ['DELETE', new RegExp('^/session/[^/]+/cookie$')],13];14class SafariDriver extends BaseDriver {15 constructor (opts = {}) {16 super(opts);17 this.desiredCapConstraints = desiredCapConstraints;18 this.locatorStrategies = [19 'xpath',20 'tag name',21 'link text',22 'partial link text',23 'css selector',24 // Let these two reach Safari Driver and fail there with a proper error message25 'id',26 'name',27 ];28 this.resetState();29 for (const [cmd, fn] of _.toPairs(commands)) {30 SafariDriver.prototype[cmd] = fn;31 }32 }33 resetState () {34 this.safari = null;35 this.proxyReqRes = null;36 this.isProxyActive = false;37 this._screenRecorder = null;38 }39 proxyActive () {40 return this.isProxyActive;41 }42 getProxyAvoidList () {43 return NO_PROXY;44 }45 canProxy () {46 return true;47 }48 async createSession (...args) {49 const [sessionId, caps] = await super.createSession(...args);50 this.safari = new SafariDriverServer(this.log);51 try {52 await this.safari.start(formatCapsForServer(caps));53 } catch (e) {54 await this.deleteSession();55 throw e;56 }57 this.proxyReqRes = this.safari.proxy.proxyReqRes.bind(this.safari.proxy);58 this.isProxyActive = true;59 return [sessionId, caps];60 }61 async deleteSession () {62 this.log.info('Ending Safari session');63 await this._screenRecorder?.stop(true);64 await this.safari?.stop();65 this.resetState();66 await super.deleteSession();67 }68}...
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const { exec } = require('teen_process');5const { fs, util } = require('appium-support');6const { SubProcess } = require('teen_process');7const { retryInterval } = require('asyncbox');8const B = require('bluebird');9chai.should();10chai.use(chaiAsPromised);11const DEFAULT_SYSTEM_PORT = 8200;12const DEFAULT_DEVICE_PORT = 8201;13const startSystemServer = async function (systemPort = DEFAULT_SYSTEM_PORT) {14 const adb = await getAdbWithCorrectAdbPath();15 const adbName = await adb.defaultDevice();16 const args = ['reverse', `tcp:${systemPort}`, `tcp:${systemPort}`];17 await adb.shell(adbName, args);18};19const getAdbWithCorrectAdbPath = async function () {20 const adbPath = await fs.which('adb');21 return new ADB({adb: adbPath});22};23const getAdbDevicesWithRetry = B.method(function () {24 return retryInterval(10, 1000, async () => {25 try {26 return await getAdbWithCorrectAdbPath().getDevicesWithRetry();27 } catch (ign) {}28 });29});30const startDeviceServer = async function (systemPort = DEFAULT_SYSTEM_PORT, devicePort = DEFAULT_DEVICE_PORT) {31 const adbDevices = await getAdbDevicesWithRetry();32 if (_.isEmpty(adbDevices)) {33 throw new Error('No adb devices connected');34 }35 const device = adbDevices[0].udid;36 const server = new SubProcess('appium', ['--session-override', '--allow-insecure', 'chromedriver_autodownload', '--chromedriver-port', devicePort, '--device-name', device, '--system-port', systemPort]);37 await server.start(0);38 return server;39};40const startAppiumServer = async function (systemPort = DEFAULT_SYSTEM_PORT, devicePort = DEFAULT_DEVICE_PORT) {41 const adbDevices = await getAdbDevicesWithRetry();42 if (_.isEmpty(adbDevices)) {43 throw new Error('No adb devices connected');44 }45 const device = adbDevices[0].udid;46 const server = new SubProcess('appium', ['--session-override', '--allow-insecure',
Using AI Code Generation
1Appium.prototype.proxyReqRes = function (req, res, next) {2 return this.proxy.proxyReqRes(req, res, next);3};4Appium.prototype.proxyReqRes = function (req, res, next) {5 return this.proxy.proxyReqRes(req, res, next);6};7Appium.prototype.proxyReqRes = function (req, res, next) {8 return this.proxy.proxyReqRes(req, res, next);9};10Appium.prototype.proxyReqRes = function (req, res, next) {11 return this.proxy.proxyReqRes(req, res, next);12};13Appium.prototype.proxyReqRes = function (req, res, next) {14 return this.proxy.proxyReqRes(req, res, next);15};16Appium.prototype.proxyReqRes = function (req, res, next) {17 return this.proxy.proxyReqRes(req, res, next);18};19Appium.prototype.proxyReqRes = function (req, res, next) {20 return this.proxy.proxyReqRes(req, res, next);21};22Appium.prototype.proxyReqRes = function (req, res, next) {23 return this.proxy.proxyReqRes(req, res, next);24};25Appium.prototype.proxyReqRes = function (req, res, next) {26 return this.proxy.proxyReqRes(req, res, next);27};28Appium.prototype.proxyReqRes = function (req, res, next) {29 return this.proxy.proxyReqRes(req, res, next);30};
Using AI Code Generation
1const { BaseDriver } = require('appium-base-driver');2const { ProxyDriver } = require('appium-base-driver');3const { proxy } = new ProxyDriver();4class MyDriver extends BaseDriver {5 constructor (opts = {}) {6 super(opts);7 this.proxyReqRes = this.proxyReqRes.bind(this);8 }9 async proxyReqRes (driverOpts) {10 return await proxy.proxyReqRes(driverOpts);11 }12}13module.exports = MyDriver;14const { BaseDriver } = require('appium-base-driver');15const { ProxyDriver } = require('appium-base-driver');16const { proxy } = new ProxyDriver();17class MyDriver extends BaseDriver {18 constructor (opts = {}) {19 super(opts);20 this.proxyReqRes = this.proxyReqRes.bind(this);21 }22 async proxyReqRes (driverOpts) {23 return await proxy.proxyReqRes(driverOpts);24 }25}26module.exports = MyDriver;
Using AI Code Generation
1var wd = require('wd');2var wd = require('wd');3var asserters = wd.asserters;4var driver = wd.promiseChainRemote({5});6var desired = {7};8 .init(desired)9 .setImplicitWaitTimeout(10000)10 .title()11 .then(function(title) {12 console.log('title is: ' + title);13 })14 .quit();15 .init(desired)16 .setImplicitWaitTimeout(10000)17 .title()18 .then(function(title) {19 console.log('title is: ' + title);20 })21 .quit();22 .init(desired)23 .setImplicitWaitTimeout(10000)24 .title()25 .then(function(title) {26 console.log('title is: ' + title);27 })28 .quit();29 .init(desired)30 .setImplicitWaitTimeout(10000)31 .title()32 .then(function(title) {33 console.log('title is: ' + title);34 })35 .quit();36 .init(desired)37 .setImplicitWaitTimeout(10000)38 .title()39 .then(function(title) {40 console.log('title is: ' + title);
Using AI Code Generation
1var wd = require('wd');2driver.setProxy(proxy);3driver.init({4}).then(function () {5 return driver.elementByAccessibilityId('ComputeSumButton');6}).then(function (el) {7 return el.click();8}).then(function () {9 return driver.elementByClassName('UIAStaticText');10}).then(function (el) {11 return el.text();12}).then(function (text) {13 console.log('The sum is: ' + text);14}).fin(function () {15 return driver.quit();16}).done();17proxy.proxyReqRes = function (req, res, next) {18 var self = this;19 var data = '';20 var dest = self.proxyHost + ":" + self.proxyPort;21 req.on('data', function (chunk) {22 data += chunk.toString();23 });24 req.on('end', function () {25 var options = {26 };27 var proxyReq = http.request(options, function (proxyRes) {28 proxyRes.on('data', function (chunk) {29 res.write(chunk);30 });31 proxyRes.on('end', function () {32 res.end();33 });34 res.writeHead(proxyRes.statusCode, proxyRes.headers);35 });36 proxyReq.write(data);37 proxyReq.end();38 });39};
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!