Best JavaScript code snippet using appium-android-driver
android-common.js
Source:android-common.js
...583 function (apks, cb) { removeApks(apks, cb); }584 ], function (err, matchingApkFound) { cb(null, matchingApkFound); });585};586androidCommon.forwardPort = function (cb) {587 this.adb.forwardPort(this.args.systemPort, this.args.devicePort, cb);588};589androidCommon.pushUnicodeIME = function (cb) {590 logger.debug("Pushing unicode ime to device...");591 var imePath = path.resolve(__dirname, "..", "..", "..", "build",592 "unicode_ime_apk", "UnicodeIME-debug.apk");593 fs.stat(imePath, function (err) {594 if (err) {595 cb(new Error("Could not find Unicode IME apk; please run " +596 "'reset.sh --android' to build it."));597 } else {598 this.adb.install(imePath, false, cb);599 }600 }.bind(this));601};...
driver.js
Source:driver.js
...259 // set up the modified UiAutomator2 server etc260 await this.initUiAutomator2Server();261 // Further prepare the device by forwarding the UiAutomator2 port262 logger.debug(`Forwarding UiAutomator2 Server port ${DEVICE_PORT} to ${this.opts.systemPort}`);263 await this.adb.forwardPort(this.opts.systemPort, DEVICE_PORT);264 // Should be after installing io.appium.settings in helpers.initDevice265 if (this.opts.disableWindowAnimation && (await this.adb.getApiLevel() < 26)) { // API level 26 is Android 8.0.266 // Granting android.permission.SET_ANIMATION_SCALE is necessary to handle animations under API level 26267 // Read https://github.com/appium/appium/pull/11640#issuecomment-438260477268 // `--no-window-animation` works over Android 8 to disable all of animations269 if (await this.adb.isAnimationOn()) {270 logger.info('Disabling animation via io.appium.settings');271 await this.adb.setAnimationState(false);272 this._wasWindowAnimationDisabled = true;273 } else {274 logger.info('Window animation is already disabled');275 }276 }277 // If the user sets autoLaunch to false, they are responsible for initAUT() and startAUT()278 if (this.opts.autoLaunch) {279 // set up app under test280 // prepare our actual AUT, get it on the device, etc...281 await this.initAUT();282 }283 // Adding AUT package name in the capabilities if package name not exist in caps284 if (!this.caps.appPackage && appInfo) {285 this.caps.appPackage = appInfo.appPackage;286 }287 // launch UiAutomator2 and wait till its online and we have a session288 await this.uiautomator2.startSession(this.caps);289 await this.addDeviceInfoToCaps();290 // Unlock the device after the session is started.291 if (!this.opts.skipUnlock) {292 // unlock the device to prepare it for testing293 await helpers.unlock(this, this.adb, this.caps);294 } else {295 logger.debug(`'skipUnlock' capability set, so skipping device unlock`);296 }297 if (this.isChromeSession) { // start a chromedriver session298 await this.startChromeSession(this);299 } else if (this.opts.autoLaunch) { // rescue UiAutomator2 if it fails to start our AUT300 await this.ensureAppStarts();301 }302 // if the initial orientation is requested, set it303 if (util.hasValue(this.opts.orientation)) {304 logger.debug(`Setting initial orientation to '${this.opts.orientation}'`);305 await this.setOrientation(this.opts.orientation);306 }307 // if we want to immediately get into a webview, set our context308 // appropriately309 if (this.opts.autoWebview) {310 const viewName = this.defaultWebviewName();311 const timeout = this.opts.autoWebviewTimeout || 2000;312 logger.info(`Setting auto webview to context '${viewName}' with timeout ${timeout}ms`);313 await retryInterval(timeout / 500, 500, this.setContext.bind(this), viewName);314 }315 // now that everything has started successfully, turn on proxying so all316 // subsequent session requests go straight to/from uiautomator2317 this.jwpProxyActive = true;318 }319 async addDeviceInfoToCaps () {320 const {321 apiVersion,322 platformVersion,323 manufacturer,324 model,325 realDisplaySize,326 displayDensity,327 } = await this.mobileGetDeviceInfo();328 this.caps.deviceApiLevel = parseInt(apiVersion, 10);329 this.caps.platformVersion = platformVersion;330 this.caps.deviceScreenSize = realDisplaySize;331 this.caps.deviceScreenDensity = displayDensity;332 this.caps.deviceModel = model;333 this.caps.deviceManufacturer = manufacturer;334 }335 async initUiAutomator2Server () {336 // now that we have package and activity, we can create an instance of337 // uiautomator2 with the appropriate data338 this.uiautomator2 = new UiAutomator2Server({339 host: this.opts.remoteAdbHost || this.opts.host || 'localhost',340 systemPort: this.opts.systemPort,341 devicePort: DEVICE_PORT,342 adb: this.adb,343 apk: this.opts.app,344 tmpDir: this.opts.tmpDir,345 appPackage: this.opts.appPackage,346 appActivity: this.opts.appActivity,347 disableWindowAnimation: !!this.opts.disableWindowAnimation,348 });349 this.proxyReqRes = this.uiautomator2.proxyReqRes.bind(this.uiautomator2);350 if (this.opts.skipServerInstallation) {351 logger.info(`'skipServerInstallation' is set. Skipping UIAutomator2 server installation.`);352 } else {353 await this.uiautomator2.installServerApk(this.opts.uiautomator2ServerInstallTimeout);354 }355 }356 async initAUT () {357 // Install any "otherApps" that were specified in caps358 if (this.opts.otherApps) {359 let otherApps;360 try {361 otherApps = helpers.parseArray(this.opts.otherApps);362 } catch (e) {363 logger.errorAndThrow(`Could not parse "otherApps" capability: ${e.message}`);364 }365 otherApps = await B.all(otherApps366 .map((app) => this.helpers.configureApp(app, [APK_EXTENSION, APKS_EXTENSION])));367 await helpers.installOtherApks(otherApps, this.adb, this.opts);368 }369 if (!this.opts.app) {370 if (this.opts.fullReset) {371 logger.errorAndThrow('Full reset requires an app capability, use fastReset if app is not provided');372 }373 logger.debug('No app capability. Assuming it is already on the device');374 if (this.opts.fastReset) {375 await helpers.resetApp(this.adb, this.opts);376 }377 }378 if (!this.opts.skipUninstall) {379 await this.adb.uninstallApk(this.opts.appPackage);380 }381 if (this.opts.app) {382 if (!this.opts.noSign && !await this.adb.checkApkCert(this.opts.app, this.opts.appPackage)) {383 await helpers.signApp(this.adb, this.opts.app);384 }385 await helpers.installApk(this.adb, this.opts);386 }387 }388 async ensureAppStarts () {389 // make sure we have an activity and package to wait for390 let appWaitPackage = this.opts.appWaitPackage || this.opts.appPackage;391 let appWaitActivity = this.opts.appWaitActivity || this.opts.appActivity;392 logger.info(`UiAutomator2 did not start the activity we were waiting for, ` +393 `'${appWaitPackage}/${appWaitActivity}'. Starting it ourselves`);394 if (this.caps.androidCoverage) {395 logger.info(`androidCoverage is configured. ` +396 ` Starting instrumentation of '${this.caps.androidCoverage}'...`);397 await this.adb.androidCoverage(this.caps.androidCoverage, appWaitPackage, appWaitActivity);398 } else {399 await this.adb.startApp({400 pkg: this.opts.appPackage,401 activity: this.opts.appActivity,402 action: this.opts.intentAction,403 category: this.opts.intentCategory,404 flags: this.opts.intentFlags,405 waitPkg: this.opts.appWaitPackage,406 waitActivity: this.opts.appWaitActivity,407 optionalIntentArguments: this.opts.optionalIntentArguments,408 stopApp: !this.opts.dontStopAppOnReset,409 retry: true410 });411 }412 }413 async deleteSession () {414 logger.debug('Deleting UiAutomator2 session');415 await androidHelpers.removeAllSessionWebSocketHandlers(this.server, this.sessionId);416 if (this.uiautomator2) {417 try {418 await this.stopChromedriverProxies();419 } catch (err) {420 logger.warn(`Unable to stop ChromeDriver proxies: ${err.message}`);421 }422 if (this.jwpProxyActive) {423 try {424 await this.uiautomator2.deleteSession();425 } catch (err) {426 logger.warn(`Unable to proxy deleteSession to UiAutomator2: ${err.message}`);427 }428 }429 this.uiautomator2 = null;430 }431 this.jwpProxyActive = false;432 if (this.adb) {433 if (this.opts.unicodeKeyboard && this.opts.resetKeyboard && this.defaultIME) {434 logger.debug(`Resetting IME to '${this.defaultIME}'`);435 try {436 await this.adb.setIME(this.defaultIME);437 } catch (err) {438 logger.warn(`Unable to reset IME: ${err.message}`);439 }440 }441 if (this.caps.androidCoverage) {442 logger.info('Shutting down the adb process of instrumentation...');443 await this.adb.endAndroidCoverage();444 // Use this broadcast intent to notify it's time to dump coverage to file445 if (this.caps.androidCoverageEndIntent) {446 logger.info(`Sending intent broadcast '${this.caps.androidCoverageEndIntent}' at the end of instrumenting.`);447 await this.adb.broadcast(this.caps.androidCoverageEndIntent);448 } else {449 logger.warn('No androidCoverageEndIntent is configured in caps. Possibly you cannot get coverage file.');450 }451 }452 if (this.opts.appPackage) {453 try {454 await this.adb.forceStop(this.opts.appPackage);455 } catch (err) {456 logger.warn(`Unable to force stop app: ${err.message}`);457 }458 }459 if (this.opts.fullReset && !this.opts.skipUninstall && !this.appOnDevice) {460 logger.debug(`Capability 'fullReset' set to 'true', Uninstalling '${this.opts.appPackage}'`);461 try {462 await this.adb.uninstallApk(this.opts.appPackage);463 } catch (err) {464 logger.warn(`Unable to uninstall app: ${err.message}`);465 }466 }467 // This value can be true if test target device is <= 26468 if (this._wasWindowAnimationDisabled) {469 logger.info('Restoring window animation state');470 await this.adb.setAnimationState(true);471 }472 await this.adb.stopLogcat();473 if (util.hasValue(this.opts.systemPort)) {474 try {475 await this.adb.removePortForward(this.opts.systemPort);476 } catch (error) {477 logger.warn(`Unable to remove port forward '${error.message}'`);478 // Ignore, this block will also be called when we fall in catch block479 // and before even port forward.480 }481 }482 if (await this.adb.getApiLevel() >= 28) { // Android P483 logger.info('Restoring hidden api policy to the device default configuration');484 await this.adb.setDefaultHiddenApiPolicy();485 }486 if (this.opts.reboot) {487 let avdName = this.opts.avd.replace('@', '');488 logger.debug(`Closing emulator '${avdName}'`);489 try {490 await this.adb.killEmulator(avdName);491 } catch (err) {492 logger.warn(`Unable to close emulator: ${err.message}`);493 }494 }495 }496 if (this.mjpegStream) {497 logger.info('Closing MJPEG stream');498 this.mjpegStream.stop();499 }500 await super.deleteSession();501 }502 async checkAppPresent () {503 logger.debug('Checking whether app is actually present');504 if (!(await fs.exists(this.opts.app))) {505 logger.errorAndThrow(`Could not find app apk at '${this.opts.app}'`);506 }507 }508 async onSettingsUpdate () {509 // intentionally do nothing here, since commands.updateSettings proxies510 // settings to the uiauto2 server already511 }512 // Need to override android-driver's version of this since we don't actually513 // have a bootstrap; instead we just restart adb and re-forward the UiAutomator2514 // port515 async wrapBootstrapDisconnect (wrapped) {516 await wrapped();517 await this.adb.restart();518 await this.adb.forwardPort(this.opts.systemPort, DEVICE_PORT);519 }520 proxyActive (sessionId) {521 super.proxyActive(sessionId);522 // we always have an active proxy to the UiAutomator2 server523 return true;524 }525 canProxy (sessionId) {526 super.canProxy(sessionId);527 // we can always proxy to the uiautomator2 server528 return true;529 }530 getProxyAvoidList (sessionId) {531 super.getProxyAvoidList(sessionId);532 // we are maintaining two sets of NO_PROXY lists, one for chromedriver(CHROME_NO_PROXY)...
bootstrap.js
Source:bootstrap.js
...33 const rootDir = path.resolve(__dirname, '..', '..');34 const startDetector = (s) => { return /Appium Socket Server Ready/.test(s); };35 const bootstrapJar = path.resolve(rootDir, 'bootstrap', 'bin', 'AppiumBootstrap.jar');36 await this.init();37 await this.adb.forwardPort(this.systemPort, 4724);38 this.process = await this.uiAutomator.start(39 bootstrapJar, 'io.appium.android.bootstrap.Bootstrap',40 startDetector, '-e', 'pkg', appPackage,41 '-e', 'disableAndroidWatchers', disableAndroidWatchers,42 '-e', 'acceptSslCerts', acceptSslCerts);43 // process the output44 this.process.on('output', (stdout, stderr) => {45 const alertRe = /Emitting system alert message/;46 if (alertRe.test(stdout)) {47 log.debug('Emitting alert message...');48 if (this.webSocket) {49 this.webSocket.sockets.emit('alert', {message: stdout});50 }51 }...
commands.js
Source:commands.js
...106// 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.adbExec('reverse', ['tcp:4723', 'tcp:4724']);2this.adb.adbExec('reverse', ['tcp:4723', 'tcp:4725']);3this.adb.adbExec('reverse', ['tcp:4723', 'tcp:4726']);4this.adb.adbExec('reverse', ['tcp:4723', 'tcp:4727']);5this.adb.adbExec('reverse', ['tcp:4723', 'tcp:4728']);6this.adb.adbExec('reverse', ['tcp:4723', 'tcp:4729']);7for (let i = 0; i < 6; i++) {8 this.adb.adbExec('reverse', ['tcp:4723', `tcp:472${i + 4}`]);9}
Using AI Code Generation
1const ADB = require('appium-adb');2const AndroidDriver = require('appium-android-driver');3const driver = new AndroidDriver({});4driver.adb = new ADB();5driver.adb.forwardPort(8200, 8200);6driver.adb.forwardPort(8200, 8200);7driver.adb.forwardPort(8200, 8200);
Using AI Code Generation
1var wd = require('wd');2var AppiumDriver = require('appium-android-driver');3var driver = wd.promiseChainRemote('localhost', 4723);4var adb = new AppiumDriver.ADB();5var port = 4724;6var systemPort = 8200;7driver.init({8}).then(function() {9 return adb.forwardPort(port, systemPort);10}).then(function() {11 console.log('Port forwarding successful');12}).catch(function(err) {13 console.error(err);14});15var wd = require('wd');16var AppiumDriver = require('appium-android-driver');17var driver = wd.promiseChainRemote('localhost', 4723);18var adb = new AppiumDriver.ADB();19var port = 4724;20var systemPort = 8200;21driver.init({22}).then(function() {23 return adb.forwardPort(port, systemPort);24}).then(function() {25 console.log('Port forwarding successful');26}).catch(function(err) {27 console.error(err);28});29AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {30 return this.shell(['forward', 'tcp:' + port, 'tcp:' + systemPort]);31};32AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {33 return this.shell(['forward', 'tcp:' + port, 'tcp:' + systemPort]);34};35AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {36 return this.shell(['forward', 'tcp:' + port, 'tcp:' + systemPort]);37};38AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {39 return this.shell(['forward', 'tcp:' + port, 'tcp:' + systemPort]);40};41AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {42 return this.shell(['forward', 'tcp:' + port, 'tcp:' + systemPort]);43};44AppiumDriver.ADB.prototype.forwardPort = function (port, systemPort) {45 return this.shell(['forward', 'tcp:' + port, 'tcp
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!!