Best JavaScript code snippet using appium-android-driver
selendroid.js
Source:selendroid.js
1"use strict";2var Device = require('../device.js')3 , mkdirp = require('mkdirp')4 , _ = require('underscore')5 , deviceCommon = require('../common.js')6 , androidController = require('./android-controller.js')7 , androidContextController = require('./android-context-controller.js')8 , proxyTo = deviceCommon.proxyTo9 , doRequest = deviceCommon.doRequest10 , logger = require('../../server/logger.js').get('appium')11 , status = require("../../server/status.js")12 , fs = require('fs')13 , async = require('async')14 , androidCommon = require('./android-common.js')15 , androidHybrid = require('./android-hybrid.js')16 , path = require('path')17 , md5 = require('md5calculator')18 , utf7 = require('utf7').imap;19var Selendroid = function () {20 this.init();21};22_.extend(Selendroid.prototype, Device.prototype);23Selendroid.prototype._deviceInit = Device.prototype.init;24Selendroid.prototype.init = function () {25 this._deviceInit();26 this.selendroidHost = 'localhost';27 this.selendroidPort = 8080;28 this.selendroidSessionId = null;29 this.appExt = ".apk";30 this.args.devicePort = this.selendroidPort;31 this.serverApk = null;32 this.onStop = function () {};33 this.adb = null;34 this.isProxy = true;35 this.mobileMethodsSupported = [36 'setLocation'37 , 'setCommandTimeout'38 , 'reset'39 , 'lock'40 , 'background'41 , 'keyevent'42 , 'currentActivity'43 , 'installApp'44 , 'uninstallApp'45 , 'removeApp'46 , 'closeApp'47 , 'isAppInstalled'48 , 'launchApp'49 , 'toggleData'50 , 'toggleFlightMode'51 , 'toggleWiFi'52 , 'toggleLocationServices'53 , 'getStrings'54 ];55 this.proxyHost = this.selendroidHost;56 this.avoidProxy = [57 ['GET', new RegExp('^/wd/hub/session/[^/]+/log/types$')]58 , ['POST', new RegExp('^/wd/hub/session/[^/]+/log')]59 , ['POST', new RegExp('^/wd/hub/session/[^/]+/location')]60 , ['POST', new RegExp('^/wd/hub/session/[^/]+/appium')]61 , ['GET', new RegExp('^/wd/hub/session/[^/]+/appium')]62 , ['POST', new RegExp('^/wd/hub/session/[^/]+/context')]63 , ['GET', new RegExp('^/wd/hub/session/[^/]+/context')]64 , ['GET', new RegExp('^/wd/hub/session/[^/]+/contexts')]65 , ['POST', new RegExp('^/wd/hub/session/[^/]+/element/[^/]+/value')]66 , ['GET', new RegExp('^/wd/hub/session/[^/]+/network_connection')]67 , ['POST', new RegExp('^/wd/hub/session/[^/]+/network_connection')]68 , ['POST', new RegExp('^/wd/hub/session/[^/]+/ime')]69 , ['GET', new RegExp('^/wd/hub/session/[^/]+/ime')]70 ];71 this.curContext = this.defaultContext();72};73Selendroid.prototype.getSettings = deviceCommon.getSettings;74Selendroid.prototype.updateSettings = deviceCommon.updateSettings;75Selendroid.prototype.pushUnlock = androidController.pushUnlock;76Selendroid.prototype.unlock = androidController.unlock;77Selendroid.prototype.installApp = androidController.installApp;78Selendroid.prototype.isAppInstalled = androidController.isAppInstalled;79Selendroid.prototype.removeApp = androidController.removeApp;80_.extend(Selendroid.prototype, androidCommon);81Selendroid.prototype._deviceConfigure = Device.prototype.configure;82Selendroid.prototype._setAndroidArgs = androidCommon.setAndroidArgs;83Selendroid.prototype.setAndroidArgs = function () {84 this._setAndroidArgs();85 this.args.systemPort = this.args.selendroidPort;86 this.proxyPort = this.args.systemPort;87};88Selendroid.prototype.start = function (cb) {89 logger.debug("Starting selendroid server");90 var modServerExists = false91 , modAppPkg = null92 , resignedServerMd5Hash = null;93 var checkModServerExists = function (cb) {94 this.selendroidServerPath = path.resolve(this.args.tmpDir,95 'selendroid.' + this.args.appPackage + '.apk');96 modAppPkg = this.args.appPackage + '.selendroid';97 fs.exists(this.selendroidServerPath, function (exists) {98 modServerExists = exists;99 cb();100 });101 }.bind(this);102 var checkServerResigned = function (cb) {103 if (modServerExists) {104 md5(this.selendroidServerPath, function (err, md5Hash) {105 if (err) return cb(err);106 logger.debug("MD5 for selendroid server is " + md5Hash);107 if (resignedServerMd5Hash !== md5Hash) {108 resignedServerMd5Hash = md5Hash;109 modServerExists = false;110 }111 }.bind(this));112 }113 cb();114 }.bind(this);115 var conditionalUninstallSelendroid = function (cb) {116 if (!modServerExists) {117 logger.debug("Rebuilt selendroid apk does not exist, uninstalling " +118 "any instances of it on device to make way for new one");119 this.adb.uninstallApk(modAppPkg, cb);120 } else {121 logger.debug("Rebuilt selendroid apk exists, doing nothing");122 cb();123 }124 }.bind(this);125 var conditionalInsertManifest = function (cb) {126 if (!modServerExists) {127 logger.debug("Rebuilt selendroid server does not exist, inserting " +128 "modified manifest");129 this.insertSelendroidManifest(this.serverApk, cb);130 } else {131 logger.debug("Rebuilt selendroid server already exists, no need to " +132 "rebuild it with a new manifest");133 cb();134 }135 }.bind(this);136 var conditionalInstallSelendroid = function (cb) {137 this.adb.isAppInstalled(modAppPkg, function (e, installed) {138 if (!installed) {139 logger.debug("Rebuilt selendroid is not installed, installing it");140 this.adb.install(this.selendroidServerPath, cb);141 } else {142 logger.debug("Rebuilt selendroid is already installed");143 cb();144 }145 }.bind(this));146 }.bind(this);147 async.series([148 this.initJavaVersion.bind(this),149 this.initAdb.bind(this),150 this.ensureServerExists.bind(this),151 this.prepareDevice.bind(this),152 this.checkInternetPermissionForApp.bind(this),153 this.packageAndLaunchActivityFromManifest.bind(this),154 checkModServerExists,155 conditionalInsertManifest,156 this.checkSelendroidCerts.bind(this),157 checkServerResigned,158 conditionalUninstallSelendroid,159 conditionalInstallSelendroid,160 this.extractStringsSelendroid.bind(this),161 this.uninstallApp.bind(this),162 this.installAppForTest.bind(this),163 this.forwardPort.bind(this),164 this.initUnicode.bind(this),165 this.pushSettingsApp.bind(this),166 this.pushUnlock.bind(this),167 this.unlock.bind(this),168 this.pushSelendroid.bind(this),169 this.waitForServer.bind(this)170 ], function (err) {171 if (err) return cb(err);172 async.series([173 this.createSession.bind(this),174 this.initAutoWebview.bind(this)175 ], function (err, res) {176 if (err) return cb(err);177 // `createSession` returns session id, so send that along178 cb(null, res[0]);179 });180 }.bind(this));181};182Selendroid.prototype.pushSelendroid = function (cb) {183 var instrumentWith = this.args.appPackage + ".selendroid/" +184 "io.selendroid.server.ServerInstrumentation";185 this.adb.instrument(this.args.appPackage, this.args.appActivity, instrumentWith, cb);186};187Selendroid.prototype.checkInternetPermissionForApp = function (cb) {188 var apk = this.args.app;189 this.adb.hasInternetPermissionFromManifest(apk, function (err, hasInternetPermission) {190 if (err) return cb(err);191 if (hasInternetPermission) {192 return cb();193 }194 else {195 var errorMessg = "apk does not have INTERNET permissions. Selendroid needs internet " +196 "permission to proceed, please check if you have <uses-permission " +197 "android:name=\"android.**permission.INTERNET\"/> in your " +198 "AndroidManifest.xml";199 cb(new Error(errorMessg));200 }201 });202};203Selendroid.prototype.checkSelendroidCerts = function (cb) {204 var alreadyReturned = false205 , checks = 0;206 var onDoneSigning = function () {207 checks++;208 if (checks === 2 && !alreadyReturned) {209 cb();210 }211 };212 // these run in parallel213 var apks = [this.selendroidServerPath, this.args.app];214 _.each(apks, function (apk) {215 logger.debug("Checking signed status of " + apk);216 this.adb.checkApkCert(apk, this.args.appPackage, function (err, isSigned) {217 if (err) return cb(err);218 if (isSigned) return onDoneSigning();219 this.adb.sign(apk, function (err) {220 if (err && !alreadyReturned) {221 alreadyReturned = true;222 return cb(err);223 }224 onDoneSigning();225 });226 }.bind(this));227 }.bind(this));228};229Selendroid.prototype.stop = function (ocb) {230 var completeShutdown = function (cb) {231 if (this.args.unicodeKeyboard && this.args.resetKeyboard && this.defaultIME) {232 logger.debug('Resetting IME to \'' + this.defaultIME + '\'');233 this.adb.setIME(this.defaultIME, function (err) {234 if (err) {235 // simply warn on error here, because we don't want to stop the shutdown236 // process237 logger.warn(err);238 }239 logger.debug("Stopping selendroid server");240 this.deleteSession(cb);241 }.bind(this));242 } else {243 logger.debug("Stopping selendroid server");244 this.deleteSession(cb);245 }246 }.bind(this);247 completeShutdown(function (err) {248 if (err) return ocb(err);249 // Remove the app _after_ stopping Selendroid, or Selendroid will fail250 if (this.args.fullReset) {251 logger.debug("Removing app from device");252 this.uninstallApp(function (err) {253 if (err) {254 // simply warn on error here, because we don't want to stop the shutdown255 // process256 logger.warn(err);257 }258 ocb();259 });260 } else {261 ocb();262 }263 }.bind(this));264};265Selendroid.prototype.keyevent = function (keycode, metastate, cb) {266 this.adb.keyevent(keycode, function () {267 cb(null, {268 status: status.codes.Success.code269 , value: null270 });271 });272};273/*274 * Execute an arbitrary function and handle potential ADB disconnection before275 * proceeding276 */277Selendroid.prototype.wrapActionAndHandleADBDisconnect = function (action, ocb) {278 async.series([279 function (cb) {280 action(cb);281 }.bind(this)282 , this.adb.restart.bind(this.adb)283 , this.forwardPort.bind(this)284 ], function (err) {285 ocb(err);286 }.bind(this));287};288Selendroid.prototype.ensureServerExists = function (cb) {289 logger.debug("Checking whether selendroid is built yet");290 var selBin = path.resolve(__dirname, "..", "..", "..", "build", "selendroid",291 "selendroid.apk");292 fs.stat(selBin, function (err) {293 if (err) {294 logger.debug("Selendroid needs to be built; please run ./reset.sh " +295 "--selendroid");296 return cb(err);297 }298 logger.debug("Selendroid server exists!");299 this.serverApk = selBin;300 cb(null);301 }.bind(this));302};303Selendroid.prototype.waitForServer = function (cb) {304 var waitMs = 20000305 , intMs = 800306 , start = Date.now();307 var pingServer = function () {308 this.proxyTo('/wd/hub/status', 'GET', null, function (err, res, body) {309 if (body === null || typeof body === "undefined" || !body.trim()) {310 if (Date.now() - start < waitMs) {311 setTimeout(pingServer, intMs);312 } else {313 cb(new Error("Waited " + (waitMs / 1000) + " secs for " +314 "selendroid server and it never showed up"));315 }316 } else {317 logger.debug("Selendroid server is alive!");318 cb(null);319 }320 });321 }.bind(this);322 pingServer();323};324Selendroid.prototype.createSession = function (cb) {325 logger.debug("Listening for Selendroid logs");326 this.adb.logcat.on('log', function (logObj) {327 if (/System/.test(logObj.message)) {328 var type = "";329 if (/System\.err/.test(logObj.message)) {330 type = " ERR";331 }332 var msg = logObj.message.replace(/^.+: /, '');333 logger.debug("[SELENDROID" + type + "] " + msg);334 }335 }.bind(this));336 logger.debug("Creating Selendroid session");337 var data = {desiredCapabilities: this.capabilities};338 this.proxyTo('/wd/hub/session', 'POST', data, function (err, res, body) {339 if (err) return cb(err);340 if (res.statusCode === 200 && body.sessionId) {341 logger.debug("Successfully started selendroid session");342 this.selendroidSessionId = body.sessionId;343 this.proxySessionId = this.selendroidSessionId;344 this.adb.waitForActivity(this.args.appWaitPackage, this.args.appWaitActivity, 1800,345 function (err) {346 if (err) {347 logger.debug("Selendroid hasn't started app yet, let's do it " +348 "manually with adb.startApp");349 var onStart = function (err) {350 if (err) return cb(err);351 return cb(null, body.sessionId);352 }.bind(this);353 return this.adb.startApp({354 pkg: this.args.appPackage,355 activity: this.args.appActivity,356 action: this.args.intentAction,357 category: this.args.intentCategory,358 flags: this.args.intentFlags,359 waitPkg: this.args.appWaitPackage,360 waitActivity: this.args.appWaitActivity,361 optionalIntentArguments: this.args.optionalIntentArguments,362 stopApp: this.args.stopAppOnReset,363 retry: false364 }, onStart);365 }366 return cb(null, body.sessionId);367 }.bind(this), 1800);368 } else {369 logger.error("Selendroid create session did not work. Status was " +370 res.statusCode + " and body was " + body);371 cb(new Error("Selendroid session creation did not work."));372 }373 }.bind(this));374};375Selendroid.prototype.deleteSession = function (cb) {376 var url = '/wd/hub/session/' + this.selendroidSessionId;377 this.proxyTo(url, 'DELETE', null, function (err, res) {378 if (err) return cb(err);379 if (res.statusCode !== 200) return cb(new Error("Status was not 200"));380 this.adb.forceStop(this.args.appPackage, function (err) {381 if (err) return cb(err);382 this.adb.stopLogcat(cb);383 }.bind(this));384 }.bind(this));385};386Selendroid.prototype.proxyTo = proxyTo;387Selendroid.prototype.insertSelendroidManifest = function (serverPath, cb) {388 logger.debug("Inserting selendroid manifest");389 var newServerPath = this.selendroidServerPath390 , newPackage = this.args.appPackage + '.selendroid'391 , srcManifest = path.resolve(__dirname, '..', '..', '..', 'build',392 'selendroid', 'AndroidManifest.xml')393 , dstDir = path.resolve(this.args.tmpDir, this.args.appPackage)394 , dstManifest = path.resolve(dstDir, 'AndroidManifest.xml');395 try {396 fs.mkdirSync(dstDir);397 } catch (e) {398 if (e.message.indexOf("EEXIST") === -1) {399 throw e;400 }401 }402 fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8");403 async.series([404 function (cb) { mkdirp(dstDir, cb); }.bind(this),405 function (cb) { this.adb.checkSdkBinaryPresent("aapt", cb); }.bind(this),406 function (cb) {407 this.adb.compileManifest(dstManifest, newPackage,408 this.args.appPackage, cb);409 }.bind(this),410 function (cb) {411 this.adb.insertManifest(dstManifest, serverPath,412 newServerPath, cb);413 }.bind(this)414 ], cb);415};416Selendroid.prototype.setLocation = androidController.setLocation;417Selendroid.prototype.removeApp = androidController.removeApp;418Selendroid.prototype.unpackApp = androidController.unpackApp;419Selendroid.prototype.translatePath = function (req) {420 var path = req.originalUrl;421 if (path.indexOf("contexts") !== -1) {422 logger.debug("Temporarily translating 'contexts' to 'window_handles");423 path = path.replace("contexts", "window_handles");424 } else if (path.indexOf("context") !== -1) {425 logger.debug("Temporarily translating 'context' to 'window'");426 path = path.replace("context", "window");427 }428 req.originalUrl = path;429};430Selendroid.prototype.extractStringsSelendroid = function (cb) {431 this.extractStrings(function () {432 cb();433 });434};435Selendroid.prototype.getStrings = function (language, stringFile, cb) {436 if (this.language && this.language === language) {437 // Return last strings438 return cb(null, {439 status: status.codes.Success.code,440 value: this.apkStrings441 });442 }443 // Extract and return strings444 return this.extractStrings(function () {445 cb(null, {446 status: status.codes.Success.code,447 value: this.apkStrings448 });449 }.bind(this), language);450};451_.extend(Selendroid.prototype, androidHybrid);452_.extend(Selendroid.prototype, androidContextController);453Selendroid.prototype.isChromedriverContext = function (windowName) {454 return windowName === this.CHROMIUM_WIN;455};456Selendroid.prototype.getContexts = function (cb) {457 var chromiumViews = [];458 this.listWebviews(function (err, webviews) {459 if (err) return cb(err);460 if (_.contains(webviews, this.CHROMIUM_WIN)) {461 chromiumViews = [this.CHROMIUM_WIN];462 } else {463 chromiumViews = [];464 }465 var selendroidViews = [];466 var reqUrl = this.selendroidHost + ':' + this.args.selendroidPort + '/wd/hub/session/' + this.selendroidSessionId;467 doRequest(reqUrl + '/window_handles', 'GET', {}, null, function (err, res) {468 if (err) return cb(err);469 selendroidViews = JSON.parse(res.body).value;470 this.contexts = _.union(selendroidViews, chromiumViews);471 logger.debug("Available contexts: " + JSON.stringify(this.contexts));472 cb(null, {sessionId: this.selendroidSessionId, status: status.codes.Success.code, value: this.contexts});473 }.bind(this));474 }.bind(this));475};476Selendroid.prototype.defaultWebviewName = function () {477 return this.WEBVIEW_WIN + "_0";478};479Selendroid.prototype.setValue = function (elementId, value, cb) {480 logger.debug('Setting text on element \'' + elementId + '\': \'' + value + '\'');481 for (var i = 0; i < value.length; i++) {482 var c = value.charCodeAt(i);483 // if we're using the unicode keyboard, and this is unicode, maybe encode484 if (this.args.unicodeKeyboard && (c > 127 || c === 38)) {485 // this is not simple ascii, or it is an ampersand (`&`)486 if (c >= parseInt("E000", 16) && c <= parseInt("E040", 16)) {487 // Selenium uses a Unicode PUA to cover certain special characters488 // see https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/Keys.java489 } else {490 // encode the text491 value = utf7.encode(value);492 break;493 }494 }495 }496 var reqUrl = this.proxyHost + ':' + this.proxyPort +497 '/wd/hub/session/' + this.proxySessionId +498 '/element/' + elementId + '/value';499 doRequest(reqUrl, 'POST', { value: [value] }, null, function (err) {500 if (err) return cb(err);501 cb(null, {502 status: status.codes.Success.code,503 value: ''504 });505 });506};507Selendroid.prototype.back = function (cb) {508 this.keyevent(4, null, cb);509};...
android.js
Source:android.js
...211 if (ok) {212 uninstall();213 } else {214 logger.debug(err);215 this.adb.restart(function (err) {216 if (err) {217 logger.debug(err);218 }219 if (this.uiautomatorRestartOnExit) {220 this.uiautomatorRestartOnExit = false;221 this.restartUiautomator(function (err) {222 if (err) {223 logger.debug(err);224 uninstall();225 }226 }.bind(this));227 } else {228 uninstall();229 }...
chromedriver.js
Source:chromedriver.js
1"use strict";2var proxyTo = require('../common.js').proxyTo3 , _ = require('underscore')4 , logger = require('../../server/logger.js').get('appium')5 , exec = require('child_process').exec6 , spawn = require('child_process').spawn7 , async = require('async')8 , through = require('through')9 , system = require('appium-support').system10 , isWindows = system.isWindows()11 , isLinux = system.isLinux()12 , path = require('path')13 , fs = require('fs')14 , ADB = require('./adb.js');15var Chromedriver = function (args, adb, onDie) {16 this.proxyHost = '127.0.0.1';17 this.proxyPort = args.port || 9515;18 this.deviceId = args.deviceId;19 this.enablePerformanceLogging = args.enablePerformanceLogging;20 this.proc = null;21 this.onChromedriverStart = null;22 this.onDie = onDie;23 this.exitCb = null;24 this.shuttingDown = false;25 this.executable = args.executable;26 this.adb = adb;27};28Chromedriver.prototype.initChromedriverPath = function (cb) {29 if (this.executable) {30 this.chromedriver = this.executable;31 cb();32 } else {33 var setPath = function (platform, executable) {34 this.chromedriver = path.resolve(__dirname, "..", "..", "..", "build",35 "chromedriver", platform, executable);36 logger.debug("Set chromedriver binary as: " + this.chromedriver);37 }.bind(this);38 if (isLinux) {39 logger.debug("Determining linux architecture");40 exec("uname -m", function (err, stdout) {41 var executable;42 if (err) return cb(err);43 if (stdout.trim() === "i686") {44 executable = "chromedriver32";45 } else {46 executable = "chromedriver64";47 }48 setPath("linux", executable);49 cb();50 });51 } else {52 var executable = isWindows ? "chromedriver.exe" : "chromedriver";53 var platform = isWindows ? "windows" : "mac";54 setPath(platform, executable);55 cb();56 }57 }58};59Chromedriver.prototype.ensureChromedriverExists = function (cb) {60 logger.debug("Ensuring Chromedriver exists");61 fs.exists(this.chromedriver, function (exists) {62 if (!exists) return cb(new Error("Could not find chromedriver. Need to run reset script?"));63 cb();64 });65};66Chromedriver.prototype.killOldChromedrivers = function (cb) {67 var cmd;68 if (isWindows) {69 cmd = "FOR /F \"usebackq tokens=5\" %%a in (`netstat -nao ^| findstr /R /C:\"" + this.proxyPort + " \"`) do (" +70 "FOR /F \"usebackq\" %%b in (`TASKLIST /FI \"PID eq %%a\" ^| findstr /I chromedriver.exe`) do (" +71 "IF NOT %%b==\"\" TASKKILL /F /PID %%b" +72 ")" +73 ")";74 } else {75 cmd = "ps -ef | grep " + this.chromedriver + " | grep -v grep |" +76 "grep -e '--port=" + this.proxyPort + "\\(\\s.*\\)\\?$' | awk '{ print $2 }' | " +77 "xargs kill -15";78 }79 logger.debug("Killing any old chromedrivers, running: " + cmd);80 exec(cmd, function (err) {81 if (err) {82 logger.debug("No old chromedrivers seemed to exist");83 } else {84 logger.debug("Successfully cleaned up old chromedrivers");85 }86 cb();87 });88};89Chromedriver.prototype.start = function (cb) {90 this.onChromedriverStart = cb;91 logger.debug("Spawning chromedriver with: " + this.chromedriver);92 var alreadyReturned = false;93 var args = ["--url-base=wd/hub", "--port=" + this.proxyPort, "--adb-port=" + ADB.getAdbServerPort()];94 this.proc = spawn(this.chromedriver, args);95 this.proc.stdout.setEncoding('utf8');96 this.proc.stderr.setEncoding('utf8');97 this.proc.on('error', function (err) {98 logger.error('Chromedriver process failed with error: ' + err.message);99 alreadyReturned = true;100 this.shuttingDown = true;101 logger.error('Killing chromedriver');102 this.proc.kill();103 this.onDie();104 }.bind(this));105 this.proc.stdout.pipe(through(function (data) {106 logger.debug('[CHROMEDRIVER] ' + data.trim());107 if (!alreadyReturned && data.indexOf('Starting ') === 0) {108 this.chromedriverStarted = true;109 alreadyReturned = true;110 return cb();111 }112 }.bind(this)));113 this.proc.stderr.pipe(through(function (data) {114 logger.debug('[CHROMEDRIVER STDERR] ' + data.trim());115 }));116 this.proc.on('exit', this.onClose.bind(this));117 this.proc.on('close', this.onClose.bind(this));118};119Chromedriver.prototype.onClose = function (code, signal) {120 if (!this.shuttingDown) {121 this.shuttingDown = true;122 logger.debug("Chromedriver exited with code " + code);123 if (signal) {124 logger.debug("(killed by signal " + signal + ")");125 }126 if (!this.chromedriverStarted) {127 return this.onChromedriverStart(128 new Error("Chromedriver quit before it was available"));129 }130 if (this.exitCb !== null) {131 return this.exitCb();132 }133 this.onDie();134 }135};136Chromedriver.prototype.createSession = function (caps, cb) {137 logger.debug("Creating Chrome session");138 caps.chromeOptions.androidDeviceSerial = this.deviceId;139 if (this.enablePerformanceLogging) {140 caps.loggingPrefs = {performance: 'ALL'};141 }142 var data = {143 sessionId: null,144 desiredCapabilities: caps145 };146 async.waterfall([147 this.initChromedriverPath.bind(this),148 this.ensureChromedriverExists.bind(this),149 this.killOldChromedrivers.bind(this),150 this.start.bind(this),151 _.partial(this.proxyNewSession.bind(this), data)152 ], cb);153};154Chromedriver.prototype.proxyNewSession = function (data, cb) {155 var maxRetries = 5;156 var curRetry = 0;157 var retryInt = 500;158 var doProxy = function (alreadyRestarted) {159 this.proxyTo('/wd/hub/session', 'POST', data, function (err, res, body) {160 if (err) {161 if (/ECONNREFUSED/.test(err.message) && curRetry < maxRetries) {162 logger.debug("Could not connect yet; retrying");163 curRetry++;164 setTimeout(doProxy, retryInt);165 return;166 }167 return cb(err);168 }169 // first checking if we get a well formed success response170 this.chromeSessionId = null;171 try {172 if (body.status === 0 && body.sessionId) {173 logger.debug("Successfully started chrome session " + body.sessionId);174 this.chromeSessionId = body.sessionId;175 }176 } catch (ignore) {}177 if (this.chromeSessionId) return cb(null, this.chromeSessionId);178 // then check redirect success case179 try {180 if (res.statusCode === 303 && res.headers.location) {181 logger.debug("Successfully started chrome session");182 var loc = res.headers.location;183 this.chromeSessionId = /\/([^\/]+)$/.exec(loc)[1];184 }185 } catch (ignore) {}186 if (this.chromeSessionId) return cb(null, this.chromeSessionId);187 // those are error cases188 if (typeof body !== "undefined" &&189 typeof body.value !== "undefined" &&190 typeof body.value.message !== "undefined" &&191 body.value.message.indexOf("Failed to run adb command") !== -1) {192 logger.error("Chromedriver had trouble running adb");193 if (!alreadyRestarted) {194 logger.error("Restarting adb for chromedriver");195 return this.adb.restartAdb(function () {196 this.adb.getConnectedDevices(function () {197 doProxy(true);198 }.bind(this));199 }.bind(this));200 } else {201 cb(new Error("Chromedriver wasn't able to use adb. Is the server up?"));202 }203 } else {204 logger.error("Chromedriver create session did not work. Status was " +205 res.statusCode + " and body was " +206 JSON.stringify(body));207 cb(new Error("Did not get session redirect from Chromedriver"));208 }209 }.bind(this));210 }.bind(this);211 doProxy();212};213Chromedriver.prototype.deleteSession = function (cb) {214 logger.debug("Deleting Chrome session");215 var url = '/wd/hub/session/' + this.chromeSessionId;216 this.proxyTo(url, 'DELETE', null, function (err, res) {217 if (err) return cb(err);218 if (res.statusCode !== 200) return cb(new Error("Status was not 200"));219 cb();220 }.bind(this));221};222Chromedriver.prototype.stop = function (cb) {223 logger.debug('Killing chromedriver and waiting for close');224 this.exitCb = cb;225 this.proc.kill('SIGINT');226};227Chromedriver.prototype.proxyTo = proxyTo;...
network.js
Source:network.js
...156helpers.wrapBootstrapDisconnect = async function (wrapped) {157 this.bootstrap.ignoreUnexpectedShutdown = true;158 try {159 await wrapped();160 await this.adb.restart();161 await this.bootstrap.start(this.opts.appPackage, this.opts.disableAndroidWatchers, this.opts.acceptSslCerts);162 } finally {163 this.bootstrap.ignoreUnexpectedShutdown = false;164 }165};166Object.assign(extensions, commands, helpers);167export { commands, helpers };...
commands.js
Source:commands.js
...105// have a bootstrap; instead we just restart adb and re-forward the Selendroid106// port107helpers.wrapBootstrapDisconnect = async function wrapBootstrapDisconnect (wrapped) {108 await wrapped();109 await this.adb.restart();110 await this.adb.forwardPort(this.opts.systemPort, DEVICE_PORT);111};112Object.assign(extensions, commands, helpers);...
Using AI Code Generation
1this.adb.restart();2this.adb.restartAdb();3this.adb.restartInput();4this.adb.restartUiAutomator();5this.adb.setDeviceProperty("propName","propValue");6this.adb.setDeviceSysLanguage("lang");7this.adb.setDeviceSysLocale("locale");8this.adb.setDeviceSysRegion("region");9this.adb.setDeviceSysTimeZone("timezone");10this.adb.setDeviceSysVolume("volume");11this.adb.setDeviceTime("time");12this.adb.setDeviceWifi("wifiState");13this.adb.setDeviceWifiData("wifiDataState");14this.adb.setDeviceWifiTethering("wifiTetheringState");15this.adb.setIME("ime");
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5var should = chai.should();6var expect = chai.expect;7var AndroidController = require('appium-android-driver');8chai.use(chaiAsPromised);9var driver = wd.promiseChainRemote('localhost', 4723);10driver.on('status', function(info) {11 console.log('\x1b[36m%s\x1b[0m', info);12});13driver.on('command', function(meth, path, data) {14 console.log(' > \x1b[33m%s\x1b[36m%s\x1b[0m', meth, path, data || '');15});16driver.on('http', function(meth, path, data) {17 console.log(' > \x1b[90m%s\x1b[36m%s\x1b[0m', meth, path, data || '');18});19var desired = {20};21 .init(desired)22 .setImplicitWaitTimeout(20000)23 .then(() => {24 return driver.startActivity({25 });26 })27 .sleep(5000)28 .then(() => {29 return driver.elementById('io.appium.android.apis:id/two').click();30 })31 .sleep(5000)32 .then(() => {33 return driver.elementById('io.appium.android.apis:id/edit').click();34 })35 .sleep(5000)36 .then(() => {37 return driver.elementById('io.appium.android.apis:id/edit').sendKeys('Hello');38 })39 .sleep(5000)40 .then(() => {41 return driver.elementById('io.appium.android.apis:id/edit').clear();42 })43 .sleep(5000)44 .then(() => {45 return driver.elementById('io.appium.android.apis:id/edit').sendKeys('Hello');46 })47 .sleep(5000)48 .then(() => {
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5 .init(desired)6 .then(function() {7 })8 .then(function() {9 return driver.elementById('i am a link');10 })11 .then(function(el) {12 return el.click();13 })14 .then(function() {15 return driver.sleep(3000);16 })17 .then(function() {18 return driver.adb.restart();19 })20 .then(function() {21 return driver.sleep(3000);22 })23 .then(function() {24 return driver.title();25 })26 .then(function(title) {27 assert.ok(title === "I am another page title - Sauce Labs");28 })29 .fin(function() { return driver.quit(); })30 .done();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var _ = require('underscore');4var Q = require('q');5var AndroidDriver = require('appium-android-driver');6var ADB = require('appium-adb');7var desired = {8};9var driver = wd.promiseChainRemote('localhost', 4723);10var androidDriver = new AndroidDriver();11var adb = new ADB();12androidDriver.adb = adb;13 .init(desired)14 .then(function () {15 return androidDriver.restart();16 })17 .then(function () {18 return driver.quit();19 })20 .done();21var wd = require('wd');22var assert = require('assert');23var _ = require('underscore');24var Q = require('q');25var AndroidDriver = require('appium-android-driver');26var ADB = require('appium-adb');27var desired = {28};29var driver = wd.promiseChainRemote('localhost', 4723);30var androidDriver = new AndroidDriver();31var adb = new ADB();32androidDriver.adb = adb;33 .init(desired)34 .then(function () {35 return androidDriver.restart();36 })37 .then(function () {38 return driver.quit();39 })40 .done();
Using AI Code Generation
1var appium = require('appium');2var AndroidDriver = appium.AndroidDriver;3var driver = new AndroidDriver();4driver.adb.restart();5AndroidDriver.prototype.restart = function() {6 var adb = this.adb;7 return adb.restart();8};9ADB.prototype.restart = function(cb) {10 this.shell("stop", function(err) {11 if (err) return cb(err);12 this.shell("start", cb);13 }.bind(this));14};15ADB.prototype.shell = function(cmd, cb) {16 cmd = "shell " + cmd;17 this.exec(cmd, cb);18};19ADB.prototype.exec = function(cmd, cb) {20 this.adbCmd(cmd, cb);21};22ADB.prototype.adbCmd = function(cmd, cb) {23 this.getAdbWithCorrectAdbPath(function(err, adb) {24 if (err) return cb(err);25 logger.debug("Executing: " + adb + " " + cmd);26 exec(adb + " " + cmd, { maxBuffer: 524288 }, function(err, stdout, stderr) {27 if (err) {28 logger.error("Error executing adbExec. Original error: '" + err.message +29 "'; Stderr: '" + stderr + "' Stdout: '" + stdout + "'");30 err.stdout = stdout;31 err.stderr = stderr;32 cb(err);33 } else {34 cb(null, stdout);35 }36 });37 }.bind(this));38};39ADB.prototype.getAdbWithCorrectAdbPath = function(cb) {40 if (this.adb !== "adb") {41 if (this.isValidClass(this.adb)) {42 var adb = new this.adb({adb: this.adb});43 adb.checkAdbPresent(function(err) {44 if (err) return cb(err);45 cb(null, adb.executable.path);46 });47 } else {48 cb(null, this.adb);49 }50 } else {51 this.checkAdbPresent(cb);52 }53};54ADB.prototype.checkAdbPresent = function(cb) {55 this.exec("version", function(err, stdout) {56 if (err) {57 logger.error("ADB quit before it successfully launched");
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12client.adb.restart(function(err) {13 if (err) {14 console.log(err);15 }16});17client.adb.restart({18}, function(err) {19 if (err) {20 console.log(err);21 }22});23client.adb.restart({24}).then(function() {25 console.log('Server restarted successfully');26}, function(err) {27 console.log(err);28});29client.adb.restart().then(function() {30 console.log('Server restarted successfully');31}, function(err) {32 console.log(err);33});34client.adb.restart([options], callback(err))35client.adb.restart([options]).then(function() {}, function(err) {})36client.adb.restart().then(function() {}, function(err) {})
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!!