Best JavaScript code snippet using appium-android-driver
android-common.js
Source:android-common.js
...471 }.bind(this);472 if (appExists) {473 install();474 } else {475 this.adb.push(this.args.app, remoteApk, install);476 }477 }.bind(this));478 }.bind(this));479 }.bind(this));480 } else {481 cb();482 }483 }.bind(this));484 }.bind(this));485 }.bind(this);486 // Skipping sign apk for noSign true487 if (this.args.noSign) {488 logger.debug('noSign capability set to true, skipping checking and signing of app');489 afterSigning();490 } else {491 this.adb.checkAndSignApk(this.args.app, this.args.appPackage, afterSigning);492 }493};494androidCommon.installRemoteWithRetry = function (remoteApk, cb) {495 this.adb.uninstallApk(this.args.appPackage, function (err) {496 if (err) logger.warn("Uninstalling apk failed, continuing");497 this.adb.installRemote(remoteApk, function (err) {498 if (err) {499 logger.warn("Installing remote apk failed, going to uninstall and try " +500 "again");501 this.removeTempApks([], function () {502 this.adb.push(this.args.app, remoteApk, function (err) {503 if (err) return cb(err);504 logger.debug("Attempting to install again for the last time");505 this.adb.installRemote(remoteApk, cb);506 }.bind(this));507 }.bind(this));508 } else {509 cb();510 }511 }.bind(this));512 }.bind(this));513};514androidCommon.getAppMd5 = function (cb) {515 try {516 md5(this.args.app, function (err, md5Hash) {...
android-controller.js
Source:android-controller.js
...438 var fd = fs.openSync(localFile, 'w');439 fs.writeSync(fd, content, 0, content.length, 0);440 fs.closeSync(fd);441 // adb push creates folders and overwrites existing files.442 this.adb.push(localFile, remotePath, cb);443 }.bind(this),444 ],445 function (err) {446 if (fs.existsSync(localFile)) fs.unlinkSync(localFile);447 if (err) return cb(err);448 cb(null, {449 status: status.codes.Success.code450 });451 });452};453androidController.pullFolder = function (remotePath, cb) {454 var localFolder = temp.path({prefix: 'appium'});455 var bufferOnSuccess = function (buffer) {456 logger.debug("Converting in-memory zip file to base64 encoded string");...
driver.js
Source:driver.js
...437 builder.toFile(localPath);438 log.info(`Creating shared_prefs remote folder: ${remotePath}`);439 await this.adb.shell(['mkdir', '-p', remotePath]);440 log.info(`Pushing shared_prefs to ${remoteFile}`);441 await this.adb.push(localPath, remoteFile);442 try {443 log.info(`Trying to remove shared preferences temporary file`);444 if (await fs.exists(localPath)) {445 await fs.unlink(localPath);446 }447 } catch (e) {448 log.warn(`Error trying to remove temporary file ${localPath}`);449 }450 return true;451 }452 getPrefsBuilder () {453 /* Add this method to create a new SharedPrefsBuilder instead of454 * directly creating the object on setSharedPreferences for testing purposes455 */...
android.js
Source:android.js
...315 return this.adb.shell("echo '{}' > " + remoteFile, cb);316 }317 }318 var jsonFile = path.resolve(outputPath, stringsJson);319 this.adb.push(jsonFile, remotePath, function (err) {320 if (err) return cb(new Error("Could not push strings.json"));321 cb();322 });323 }.bind(this), language);324};325Android.prototype.getStrings = function (language, stringFile, cb) {326 if (this.language && this.language === language) {327 // Return last strings328 return cb(null, {329 status: status.codes.Success.code,330 value: this.apkStrings331 });332 }333 // Extract, push and return strings334 return this.pushStrings(function () {335 this.proxy(["updateStrings", {}], function (err, res) {336 if (err || res.status !== status.codes.Success.code) return cb(err, res);337 cb(null, {338 status: status.codes.Success.code,339 value: this.apkStrings340 });341 }.bind(this));342 }.bind(this), language);343};344Android.prototype.pushAppium = function (cb) {345 logger.debug("Pushing appium bootstrap to device...");346 var binPath = path.resolve(__dirname, "..", "..", "..", "build",347 "android_bootstrap", "AppiumBootstrap.jar");348 fs.stat(binPath, function (err) {349 if (err) {350 cb(new Error("Could not find AppiumBootstrap.jar; please run " +351 "'grunt buildAndroidBootstrap'"));352 } else {353 this.adb.push(binPath, this.remoteTempPath(), cb);354 }355 }.bind(this));356};357Android.prototype.startAppUnderTest = function (cb) {358 this.startApp(this.args, cb);359};360Android.prototype.startApp = function (args, cb) {361 if (args.androidCoverage) {362 this.adb.androidCoverage(args.androidCoverage, args.appWaitPackage,363 args.appWaitActivity, cb);364 } else {365 this.adb.startApp({366 pkg: args.appPackage,367 activity: args.appActivity,...
actions.js
Source:actions.js
...178 ['run-as', packageId, `mkdir -p '${path.posix.dirname(pathInContainer).replace(/'/g, '\\\'')}'`]179 );180 await this.adb.shell(['run-as', packageId, `touch '${pathInContainer.replace(/'/g, '\\\'')}'`]);181 await this.adb.shell(['run-as', packageId, `chmod 777 '${pathInContainer.replace(/'/g, '\\\'')}'`]);182 await this.adb.push(localFile, tmpDestination);183 await this.adb.shell(['cp', '-f', tmpDestination, pathInContainer]);184 } catch (e) {185 log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +186 `Is the application installed and has 'debuggable' build option set to true? ` +187 `Original error: ${e.message}`);188 }189 } else {190 // adb push creates folders and overwrites existing files.191 await this.adb.push(localFile, remotePath);192 }193 } finally {194 if (await fs.exists(localFile)) {195 await fs.unlink(localFile);196 }197 if (_.isString(tmpDestination)) {198 await this.adb.shell(['rm', '-f', tmpDestination]);199 }200 }201};202commands.pullFolder = async function (remotePath) {203 let localFolder = temp.path({prefix: 'appium'});204 await this.adb.pull(remotePath, localFolder);205 return (await zip.toInMemoryZip(localFolder)).toString('base64');...
api.js
Source:api.js
1/**2 * API used by the cli to push and manage files.3 * @noflow4 */5/*eslint-disable no-console*/6import {exec, spawn} from 'child_process';7import fs from 'mz/fs';8import os from 'os';9import path from 'path';10import readline from 'readline';11import which from 'which';12const SYSTEM_MODULE_ROOT = process.env.SILK_SYSTEM_MODULE_ROOT || '/system/silk/node_modules';13const DATA_MODULE_ROOT = process.env.SILK_DATA_MODULE_ROOT || '/data/node_modules';14const ACTIVATE_PROP = 'persist.silk.main';15const MODULE_PUSH_PROP = 'silk.module.push';16const WIFI_SETUP_SCRIPT = 'wifi_setup.sh';17async function execWithPaths(18 cmd,19 additionalPaths,20 timeout = 10000,21) {22 const env = process.env;23 const PATH = env.PATH.split(':');24 const newPath = additionalPaths.concat(PATH).join(':');25 const cmdEnv = {};26 for (let key in env) {27 cmdEnv[key] = env[key];28 }29 cmdEnv.PATH = newPath;30 return new Promise((resolve, reject) => {31 const childProcess = exec(32 cmd,33 {34 env: cmdEnv,35 maxBuffer: 1024 * 1024 * 10, // 10MB - |adb push| can be verbose36 timeout,37 },38 (err, stdout, stderr) => {39 if (rl) {40 process.stdout.write('\n');41 rl.close();42 }43 if (err) {44 reject(err);45 } else {46 resolve([stdout, stderr]);47 }48 }49 );50 let lastMatch = null;51 const rl = readline.createInterface({52 input: childProcess.stdout,53 });54 rl.on('line', (data) => {55 // Read line doesn't split lines with \r between them so split again56 const lines = data.split(os.EOL);57 lines.forEach((line) => {58 const progressRegex = /\[\s*\d+%\]\s*(.*):\s*\d+%/;59 const match = progressRegex.exec(line);60 if (match && match.length > 1) {61 if (lastMatch === match[1]) {62 // Progress reported for the same file so clear the current line to63 // show output on the same line64 readline.clearLine(process.stdout, 0);65 readline.cursorTo(process.stdout, 0);66 } else {67 process.stdout.write('\n');68 }69 lastMatch = match[1];70 }71 process.stdout.write(line);72 });73 });74 });75}76export class SDKApi {77 device = null;78 additionalPaths = [];79 _adbPath = null;80 constructor(opts) {81 for (let key in opts) {82 this[key] = opts[key];83 }84 }85 async adb(adbCmd, timeout = 10000) {86 let cmd = `adb`;87 if (this.device) {88 cmd += ` -s ${this.device}`;89 }90 return execWithPaths(`${cmd} ${adbCmd}`, this.additionalPaths, timeout);91 }92 async restart() {93 await this.stop();94 await this.start();95 }96 async start() {97 await this.adb(`shell start`);98 }99 async stop() {100 await this.adb(`shell stop`);101 }102 async activate(name) {103 if (!name) {104 this.setprop(ACTIVATE_PROP, '\\"\\"');105 } else {106 this.setprop(ACTIVATE_PROP, name);107 }108 }109 logcat(logcatArgs) {110 if (!this._adbPath) {111 this._adbPath = which.sync('adb');112 }113 const args = [];114 if (this.device) {115 args.push('-s', this.device);116 }117 args.push('logcat');118 args.push(...logcatArgs);119 return spawn(this._adbPath, args, {120 // XXX: May be better to use inherit.121 stdio: 'pipe',122 });123 }124 async pushModule(name, directory, system = false) {125 const dest = path.join(system ? SYSTEM_MODULE_ROOT : DATA_MODULE_ROOT, name);126 await this.adb('root');127 await this.adb('wait-for-device');128 if (system) {129 let [stdout] = await this.adb('shell getprop partition.system.verified');130 let verified = stdout.replace(/\r?\n$/, '');131 if (verified === '1') {132 throw new Error('Verity enabled. Run |adb disable-verity && adb reboot| to continue');133 }134 await this.adb('remount');135 }136 // XXX: This potentially makes things slower but ensures we don't leave137 // around files between pushes which is a common source of bugs.138 console.log('Updating', dest);139 await this.adb(`shell rm -rf ${dest}`);140 await this.adb(`push ${directory} ${dest}`, /*timeout = */ 300 * 1000);141 this.setprop(MODULE_PUSH_PROP, dest);142 }143 async setprop(key, value) {144 await this.adb(`shell setprop ${key} ${value}`);145 }146 async listDevices() {147 const [stdout] = await this.adb(`devices -l`, this.additionalPaths);148 const devices = [];149 // first newline marks the start of the device list.150 let newLine = stdout.indexOf('\n');151 if (newLine === -1) {152 return [];153 }154 let deviceList = stdout.slice(newLine).split('\n');155 // see transports.c in adb for the logic of the parser.156 for (let potentialDevice of deviceList) {157 if (!potentialDevice) {158 continue;159 }160 potentialDevice = potentialDevice.trim();161 const serial = potentialDevice.slice(0, 22).trim();162 const details = potentialDevice.slice(23).split(' ');163 const state = details.shift();164 const extra = {};165 for (let item of details) {166 const [name, value] = item.split(':');167 extra[name] = value;168 }169 devices.push({serial, state, extra});170 }171 return devices;172 }173 async setupWifi(ssid, password, keepExistingNetworks = false) {174 if (this.device === 'sim') {175 return true; // Nothing to update on simulator176 }177 console.log(`Setup Wi-Fi network: ${ssid} ${password} ...`);178 let result = false;179 // Generate wifi setup script180 try {181 const data = `182 set -ex183 iface=$(wpa_cli ifname | busybox tail -n1)184 if [ "$iface" = "UNKNOWN COMMAND" ]; then185 iface="$(getprop wifi.interface)";186 # gonks older than N need an additional IFNAME=187 ifaceArgs="-i$iface IFNAME=$iface";188 else189 ifaceArgs="-i$iface";190 fi191 echo "wifi interface: $iface"192 w="wpa_cli $ifaceArgs"193 set -x194 $w ping195 # Ok if this next command fails, it is only needed by a few devices196 $w update_config 1 || true197 if [ ${keepExistingNetworks} != true ]; then198 $w remove_network all199 $w save_config200 $w disconnect201 fi202 id=$($w add_network)203 $w set_network $id ssid '"${ssid}"'204 if [ -n "${password}" ]; then205 $w set_network $id psk '"${password}"'206 else207 $w set_network $id key_mgmt NONE208 fi209 $w enable_network $id210 $w save_config211 $w reconnect212 $w status213 `;214 await fs.writeFile(WIFI_SETUP_SCRIPT, data);215 await fs.chmod(WIFI_SETUP_SCRIPT, '400');216 // Push the script on the device217 await this.adb('root');218 await this.adb('wait-for-device');219 await this.adb(`push ${WIFI_SETUP_SCRIPT} /data/`);220 // Run the script on the device or simulator221 let [stdout] = await this.adb(`shell sh /data/${WIFI_SETUP_SCRIPT}`);222 console.log(stdout);223 result = true;224 } catch (err) {225 console.log(`Failed to configure wifi ${err}`);226 }227 // Delete the script228 try {229 await fs.unlink(WIFI_SETUP_SCRIPT);230 await this.adb(`shell rm /data/${WIFI_SETUP_SCRIPT}`);231 await this.adb(`shell sync`);232 } catch (err) {233 console.log(`Failed to cleanup ${err}`);234 }235 return result;236 }...
uiautomator.js
Source:uiautomator.js
...17 this.changeState(UiAutomator.STATE_STARTING);18 log.debug("Parsing uiautomator jar");19 // expecting a path like /ads/ads/foo.jar or \asd\asd\foo.jar20 let jarName = this.parseJarNameFromPath(uiAutomatorBinaryPath);21 await this.adb.push(uiAutomatorBinaryPath, this.tempPath);22 // killing any uiautomator existing processes23 await this.killUiAutomatorOnDevice();24 log.debug('Starting UIAutomator');25 let args = ["shell", "uiautomator", "runtest", jarName, "-c", className, ...extraParams];26 this.proc = this.adb.createSubProcess(args);27 // handle out-of-bound exit by simply emitting a stopped state28 this.proc.on('exit', (code, signal) => {29 processIsAlive = false;30 // cleanup31 if (this.state !== UiAutomator.STATE_STOPPED &&32 this.state !== UiAutomator.STATE_STOPPING) {33 let msg = `UiAutomator exited unexpectedly with code ${code}, ` +34 `signal ${signal}`;35 log.error(msg);...
Using AI Code Generation
1driver.pushFile('/sdcard/Download', 'test.txt', 'Hello World!');2driver.pullFile('/sdcard/Download/test.txt');3driver.shell(['ls', '-l', '/sdcard/Download']);4driver.isScreenLocked();5driver.isKeyboardShown();6driver.rotateScreen('LANDSCAPE');7driver.getOrientation();8driver.setOrientation('LANDSCAPE');9driver.getApiLevel();10driver.getDevicePixelRatio();11driver.getDisplayDensity();12driver.getDisplaySize();13driver.getDeviceSysLanguage();14driver.getDeviceSysCountry();15driver.getDeviceTime();16driver.getDeviceTimeZone();17driver.getDeviceTime();
Using AI Code Generation
1var path = require('path');2var fs = require('fs');3var ADB = require('appium-adb');4var adb = new ADB();5var srcPath = path.resolve(__dirname, 'src_file.txt');6var destPath = '/data/local/tmp/src_file.txt';7adb.push(srcPath, destPath, function(err) {8 if (err) {9 console.log(err);10 }11 else {12 console.log('File pushed successfully');13 }14});15var path = require('path');16var fs = require('fs');17var ADB = require('appium-adb');18var adb = new ADB();19var srcPath = '/data/local/tmp/src_file.txt';20var destPath = path.resolve(__dirname, 'src_file.txt');21adb.pull(srcPath, destPath, function(err) {22 if (err) {23 console.log(err);24 }25 else {26 console.log('File pulled successfully');27 }28});29var exec = require('child_process').exec;30var adb = 'adb -s emulator-5554';31exec(adb + ' shell ls /sdcard', function(err, stdout, stderr) {32 if (err) {33 console.log(err);34 }35 else {36 console.log(stdout);37 }38});
Using AI Code Generation
1var fs = require('fs');2var path = require('path');3var appium = require('appium');4var wd = require('wd');5var chai = require('chai');6var chaiAsPromised = require('chai-as-promised');7chai.use(chaiAsPromised);8var should = chai.should();9var assert = chai.assert;10var _ = require('underscore');11var Q = require('q');12var AdmZip = require('adm-zip');13var zip = new AdmZip();14var zipFile = path.resolve(__dirname, 'test.zip');15var zipFile2 = path.resolve(__dirname, 'test2.zip');16var zipFile3 = path.resolve(__dirname, 'test3.zip');17var zipFile4 = path.resolve(__dirname, 'test4.zip');18var zipFile5 = path.resolve(__dirname, 'test5.zip');19var zipFile6 = path.resolve(__dirname, 'test6.zip');20var zipFile7 = path.resolve(__dirname, 'test7.zip');21var zipFile8 = path.resolve(__dirname, 'test8.zip');22var zipFile9 = path.resolve(__dirname, 'test9.zip');23var zipFile10 = path.resolve(__dirname, 'test10.zip');24var zipFile11 = path.resolve(__dirname, 'test11.zip');25var zipFile12 = path.resolve(__dirname, 'test12.zip');26var zipFile13 = path.resolve(__dirname, 'test13.zip');27var zipFile14 = path.resolve(__dirname, 'test14.zip');28var zipFile15 = path.resolve(__dirname, 'test15.zip');29var zipFile16 = path.resolve(__dirname, 'test16.zip');30var zipFile17 = path.resolve(__dirname, 'test17.zip');31var zipFile18 = path.resolve(__dirname, 'test18.zip');32var zipFile19 = path.resolve(__dirname, 'test19.zip');33var zipFile20 = path.resolve(__dirname, 'test20.zip');34var zipFile21 = path.resolve(__dirname, 'test21.zip');35var zipFile22 = path.resolve(__dirname, 'test22.zip');36var zipFile23 = path.resolve(__dirname, 'test23.zip');37var zipFile24 = path.resolve(__dirname, 'test24.zip');38var zipFile25 = path.resolve(__dirname, 'test25.zip');39var zipFile26 = path.resolve(__dirname,
Using AI Code Generation
1var wd = require('wd');2var path = require('path');3var assert = require('assert');4var fs = require('fs');5var desired = {6};7var driver = wd.promiseChainRemote("localhost", 4723);8driver.init(desired).then(function() {9 return driver.pushFile('/sdcard/test.txt', 'hello world');10}).then(function() {11 return driver.pullFile('/sdcard/test.txt');12}).then(function(data) {13 console.log(data);14 assert.equal(data, 'hello world');15}).fin(function() {16 return driver.quit();17}).done();18Error: Error executing adbExec. Original error: 'Command '/Users/xxxxxx/Android/Sdk/platform-tools/adb -P 5037 -s emulator-5554 push /var/folders/2y/1jv8z5_11lq1x1l7l9g9x8x00000gn/T/115-448-1c3qj8w.k5h5m5e5.tmp /sdcard/test.txt' exited with code 1'; Stderr: 'adb: error: failed to copy '/var/folders/2y/1jv8z5_11lq1x1l7l9g9x8x00000gn/T/115-448-1c3qj8w.k5h5m5e5.tmp' to '/sdcard/test.txt': Permission denied19var wd = require('wd');20var path = require('path');21var assert = require('assert');22var fs = require('fs');23var desired = {
Using AI Code Generation
1var adb = new ADB();2adb.push("C:\\Users\\test\\Desktop\\test.apk", "/data/local/tmp/test.apk", function(err, stdout) {3 console.log(stdout);4});5var adb = new ADB();6adb.shell("pm install -r /data/local/tmp/test.apk", function(err, stdout) {7 console.log(stdout);8});9var adb = new ADB();10adb.shell("am start -n com.test/.MainActivity", function(err, stdout) {11 console.log(stdout);12});13var adb = new ADB();14adb.shell("am force-stop com.test", function(err, stdout) {15 console.log(stdout);16});17var adb = new ADB();18adb.shell("rm /data/local/tmp/test.apk", function(err, stdout) {19 console.log(stdout);20});21var adb = new ADB();22adb.shell("pm uninstall com.test", function(err, stdout) {23 console.log(stdout);24});25var adb = new ADB();26adb.shell("pm clear com.test", function(err, stdout) {27 console.log(stdout);28});29var adb = new ADB();30adb.shell("am instrument -w -r -e debug false -e class com.test.MainActivityTest#test1 com.test.test/android.support.test.runner.AndroidJUnitRunner", function(err, stdout) {31 console.log(stdout);32});33var adb = new ADB();34adb.shell("am instrument -w -r -e debug false -e class com.test.MainActivityTest#test2 com.test.test/android.support.test.runner.AndroidJUnitRunner", function(err, stdout) {35 console.log(stdout);36});37var adb = new ADB();38adb.shell("am instrument -w -r -e debug false -e class com.test.MainActivityTest#test3 com.test.test/android
Using AI Code Generation
1var fs = require('fs');2var path = require('path');3var adb = require('appium-adb');4var adbPath = '/Users/xyz/Library/Android/sdk/platform-tools/adb';5var adb = new adb.ADB(adbPath);6var src = '/Users/xyz/Downloads/test.txt';7var dst = '/sdcard/test.txt';8adb.push(src, dst, function (err) {9 if (err) {10 console.log(err);11 } else {12 console.log('pushed');13 }14});15var fs = require('fs');16var path = require('path');17var adb = require('appium-adb');18var adbPath = '/Users/xyz/Library/Android/sdk/platform-tools/adb';19var adb = new adb.ADB(adbPath);20var src = '/Users/xyz/Downloads/test.txt';21var dst = '/sdcard/test.txt';22adb.push(src, dst, function (err) {23 if (err) {24 console.log(err);25 } else {26 console.log('pushed');27 }28});29var fs = require('fs');30var path = require('path');31var adb = require('appium-adb');32var adbPath = '/Users/xyz/Library/Android/sdk/platform-tools/adb';33var adb = new adb.ADB(adbPath);34var src = '/Users/xyz/Downloads/test.txt';35var dst = '/sdcard/test.txt';36adb.push(src, dst, function (err) {37 if (err) {38 console.log(err);39 } else {40 console.log('pushed');41 }42});43var fs = require('fs');44var path = require('path');
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!!