How to use this.adb.shell method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

actions.js

Source:actions.js Github

copy

Full Screen

...136 const [packageId, pathInContainer] = parseContainerPath(remotePath);137 log.info(`Parsed package identifier '${packageId}' from '${remotePath}'. Will get the data from '${pathInContainer}'`);138 tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;139 try {140 await this.adb.shell(['run-as', packageId, `chmod 777 '${pathInContainer.replace(/'/g, '\\\'')}'`]);141 await this.adb.shell(['cp', '-f', pathInContainer, tmpDestination]);142 } catch (e) {143 log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +144 `Is the application installed and has 'debuggable' build option set to true? ` +145 `Original error: ${e.message}`);146 }147 }148 const localFile = temp.path({prefix: 'appium', suffix: '.tmp'});149 try {150 await this.adb.pull(_.isString(tmpDestination) ? tmpDestination : remotePath, localFile);151 const data = await fs.readFile(localFile);152 return new Buffer(data).toString('base64');153 } finally {154 if (await fs.exists(localFile)) {155 await fs.unlink(localFile);156 }157 if (_.isString(tmpDestination)) {158 await this.adb.shell(['rm', '-f', tmpDestination]);159 }160 }161};162commands.pushFile = async function (remotePath, base64Data) {163 if (remotePath.endsWith('/')) {164 log.errorAndThrow(`It is expected that remote path points to a file and not to a folder. ` +165 `'${remotePath}' is given instead`);166 }167 const localFile = temp.path({prefix: 'appium', suffix: '.tmp'});168 const content = new Buffer(base64Data, 'base64');169 let tmpDestination = null;170 try {171 await fs.writeFile(localFile, content.toString('binary'), 'binary');172 if (remotePath.startsWith(CONTAINER_PATH_MARKER)) {173 const [packageId, pathInContainer] = parseContainerPath(remotePath);174 log.info(`Parsed package identifier '${packageId}' from '${remotePath}'. Will put the data into '${pathInContainer}'`);175 tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;176 try {177 await this.adb.shell(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');206};207commands.fingerprint = async function (fingerprintId) {208 if (!this.isEmulator()) {209 log.errorAndThrow("fingerprint method is only available for emulators");210 }211 await this.adb.fingerprint(fingerprintId);212};...

Full Screen

Full Screen

browser_android_chrome.js

Source:browser_android_chrome.js Github

copy

Full Screen

1/******************************************************************************2Copyright (c) 2012, Google Inc.3All rights reserved.4Redistribution and use in source and binary forms, with or without5modification, are permitted provided that the following conditions are met:6 * Redistributions of source code must retain the above copyright notice,7 this list of conditions and the following disclaimer.8 * Redistributions in binary form must reproduce the above copyright notice,9 this list of conditions and the following disclaimer in the documentation10 and/or other materials provided with the distribution.11 * Neither the name of Google, Inc. nor the names of its contributors12 may be used to endorse or promote products derived from this software13 without specific prior written permission.14THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"15AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE16IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE17DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE18FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL19DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR20SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER21CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,22OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE23OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24******************************************************************************/25var adb = require('adb');26var fs = require('fs');27var logger = require('logger');28var process_utils = require('process_utils');29var video_hdmi = require('video_hdmi');30var DEVTOOLS_SOCKET = 'localabstract:chrome_devtools_remote';31var PAC_PORT = 80;32/**33 * Constructs a Chrome Mobile controller for Android.34 *35 * @param {webdriver.promise.Application} app the Application for scheduling.36 * @param {Object.<string>} args browser options with string values:37 * runNumber test run number. Install helpers on run 1.38 * deviceSerial the device to drive.39 * [chrome] Chrome.apk to install.40 * [devToolsPort] DevTools port.41 * [pac] PAC content42 * [captureDir] capture script dir.43 * [videoCard] the video card identifier.44 * @constructor45 */46function BrowserAndroidChrome(app, args) {47 'use strict';48 logger.info('BrowserAndroidChrome(%j)', args);49 if (!args.deviceSerial) {50 throw new Error('Missing deviceSerial');51 }52 this.app_ = app;53 this.deviceSerial_ = args.deviceSerial;54 this.shouldInstall_ = (1 === parseInt(args.runNumber || '1', 10));55 this.chrome_ = args.chrome; // Chrome.apk.56 this.adb_ = new adb.Adb(this.app_, this.deviceSerial_);57 this.chromePackage_ = 'com.google.android.apps.chrome_dev';58 this.chromeActivity_ = 'com.google.android.apps.chrome';59 this.devToolsPort_ = args.devToolsPort;60 this.devtoolsPortLock_ = undefined;61 this.devToolsUrl_ = undefined;62 this.pac_ = args.pac;63 this.pacFile_ = undefined;64 this.pacServer_ = undefined;65 this.videoCard_ = args.videoCard;66 function toDir(s) {67 return (s ? (s[s.length - 1] === '/' ? s : s + '/') : '');68 }69 var captureDir = toDir(args.captureDir);70 this.video_ = new video_hdmi.VideoHdmi(this.app_, captureDir + 'capture');71}72/** Public class. */73exports.BrowserAndroidChrome = BrowserAndroidChrome;74/**75 * Future webdriver impl.76 * TODO: ... implementation with chromedriver2.77 */78BrowserAndroidChrome.prototype.startWdServer = function() { //browserCaps79 'use strict';80 throw new Error('Soon: ' +81 'http://madteam.co/forum/avatars/Android/android-80-domokun.png');82};83/**84 * Launches the browser with about:blank, enables DevTools.85 */86BrowserAndroidChrome.prototype.startBrowser = function() {87 'use strict';88 if (this.shouldInstall_ && this.chrome_) {89 // Explicitly uninstall, as "install -r" fails if the installed package90 // was signed with different keys than the new apk being installed.91 this.adb_.adb(['uninstall', this.chromePackage_]).addErrback(function() {92 logger.debug('Ignoring failed uninstall');93 }.bind(this));94 // Chrome install on an emulator takes a looong time.95 this.adb_.adb(['install', '-r', this.chrome_], {}, /*timeout=*/120000);96 } else {97 // Stop Chrome at the start of each run.98 this.adb_.shell(['am', 'force-stop', this.chromePackage_]);99 }100 this.scheduleStartPacServer_();101 this.scheduleSetStartupFlags_();102 // Delete the prior run's tab(s) and start with "about:blank".103 //104 // If we only set "-d about:blank", Chrome will create a new tab.105 // If we only remove the tab files, Chrome will load the106 // "Mobile bookmarks" page107 //108 // We also tried a Page.navigate to "data:text/html;charset=utf-8,", which109 // helped but was insufficient by itself.110 this.adb_.shell(['su', '-c',111 'rm /data/data/com.google.android.apps.chrome_dev/files/tab*']);112 var activity = this.chromePackage_ + '/' + this.chromeActivity_ + '.Main';113 this.adb_.shell(['am', 'start', '-n', activity, '-d', 'about:blank']);114 // TODO(wrightt): check start error, use `pm list packages` to check pkg115 this.scheduleSelectDevToolsPort_();116 this.app_.schedule('Forward DevTools socket to local port', function() {117 this.adb_.adb(['forward', 'tcp:' + this.devToolsPort_, DEVTOOLS_SOCKET]);118 }.bind(this));119 this.app_.schedule('Set DevTools URL', function() {120 this.devToolsUrl_ = 'http://localhost:' + this.devToolsPort_ + '/json';121 }.bind(this));122};123/**124 * Sets the Chrome command-line flags.125 *126 * @private127 */128BrowserAndroidChrome.prototype.scheduleSetStartupFlags_ = function() {129 'use strict';130 var flagsFile = '/data/local/chrome-command-line';131 var flags = [132 '--disable-fre', '--metrics-recording-only', '--enable-remote-debugging'133 ];134 // TODO(wrightt): add flags to disable experimental chrome features, if any135 if (this.pac_) {136 flags.push('--proxy-pac-url=http://127.0.0.1:' + PAC_PORT + '/from_netcat');137 if (PAC_PORT != 80) {138 logger.warn('Non-standard PAC port might not work: ' + PAC_PORT);139 flags.push('--explicitly-allowed-ports=' + PAC_PORT);140 }141 }142 this.adb_.shell(['su', '-c', 'echo \\"chrome ' + flags.join(' ') +143 '\\" > ' + flagsFile]);144};145/**146 * Selects the DevTools port.147 *148 * @private149 */150BrowserAndroidChrome.prototype.scheduleSelectDevToolsPort_ = function() {151 'use strict';152 if (!this.devToolsPort_) {153 process_utils.scheduleAllocatePort(this.app_, 'Select DevTools port').then(154 function(alloc) {155 logger.debug('Selected DevTools port ' + alloc.port);156 this.devtoolsPortLock_ = alloc;157 this.devToolsPort_ = alloc.port;158 }.bind(this));159 }160};161/**162 * Releases the DevTools port.163 *164 * @private165 */166BrowserAndroidChrome.prototype.releaseDevToolsPort_ = function() {167 'use strict';168 if (this.devtoolsPortLock_) {169 this.devToolsPort_ = undefined;170 this.devtoolsPortLock_.release();171 this.devtoolsPortLock_ = undefined;172 }173};174/**175 * Starts the PAC server.176 *177 * @private178 */179BrowserAndroidChrome.prototype.scheduleStartPacServer_ = function() {180 'use strict';181 if (!this.pac_) {182 return;183 }184 // We use netcat to serve the PAC HTTP from on the device:185 // adb shell ... nc -l PAC_PORT < pacFile186 // Several other options were considered:187 // 1) 'data://' + base64-encoded-pac isn't supported188 // 2) 'file://' + path-on-device isn't supported189 // 3) 'http://' + desktop http.createServer assumes a route from the190 // device to the desktop, which won't work in general191 //192 // We copy our HTTP response to the device as a "pacFile". Ideally we'd193 // avoid this temp file, but the following alternatives don't work:194 // a) `echo RESPONSE | nc -l PAC_PORT` doesn't close the socket195 // b) `cat <<EOF | nc -l PAC_PORT\nRESPONSE\nEOF` can't create a temp196 // file; see http://stackoverflow.com/questions/15283220197 //198 // We must use port 80, otherwise Chrome silently blocks the PAC.199 // This can be seen by visiting the proxy URL on the device, which displays:200 // Error 312 (net::ERR_UNSAFE_PORT): Unknown error.201 //202 // Lastly, to verify that the proxy was set, visit:203 // chrome://net-internals/proxyservice.config#proxy204 var localPac = this.deviceSerial_ + '.pac_body';205 this.pacFile_ = '/data/local/tmp/pac_body';206 var response = 'HTTP/1.1 200 OK\n' +207 'Content-Length: ' + this.pac_.length + '\n' +208 'Content-Type: application/x-ns-proxy-autoconfig\n' +209 '\n' + this.pac_;210 process_utils.scheduleFunction(this.app_, 'Write local PAC file',211 fs.writeFile, localPac, response);212 this.adb_.adb(['push', localPac, this.pacFile_]);213 process_utils.scheduleFunction(this.app_, 'Remove local PAC file',214 fs.unlink, localPac);215 // Start netcat server216 var args = ['-s', this.deviceSerial_, 'shell', 'su', '-c',217 'while true; do nc -l ' + PAC_PORT + ' < ' + this.pacFile_ + '; done'];218 logger.debug('Starting netcat on device: adb ' + args);219 process_utils.scheduleSpawn(this.app_, 'adb', args).then(function(proc) {220 this.pacServer_ = proc;221 proc.on('exit', function(code) {222 if (this.pacServer_) {223 logger.error('Unexpected pacServer exit: ' + code);224 this.pacServer_ = undefined;225 }226 }.bind(this));227 }.bind(this));228};229/**230 * Stops the PAC server.231 *232 * @private233 */234BrowserAndroidChrome.prototype.stopPacServer_ = function() {235 'use strict';236 if (this.pacServer_) {237 var proc = this.pacServer_;238 this.pacServer_ = undefined;239 process_utils.scheduleKill(this.app_, 'Kill PAC server', proc);240 }241 if (this.pacFile_) {242 var file = this.pacFile_;243 this.pacFile_ = undefined;244 this.adb_.shell(['rm', file]);245 }246};247/**248 * Kills the browser and cleans up.249 */250BrowserAndroidChrome.prototype.kill = function() {251 'use strict';252 this.devToolsUrl_ = undefined;253 this.releaseDevToolsPort_();254 this.stopPacServer_();255 this.adb_.shell(['am', 'force-stop', this.chromePackage_]);256};257/**258 * @return {boolean}259 */260BrowserAndroidChrome.prototype.isRunning = function() {261 'use strict';262 return undefined !== this.devToolsUrl_;263};264/**265 * @return {string} WebDriver URL.266 */267BrowserAndroidChrome.prototype.getServerUrl = function() {268 'use strict';269 return undefined;270};271/**272 * @return {string} DevTools URL.273 */274BrowserAndroidChrome.prototype.getDevToolsUrl = function() {275 'use strict';276 return this.devToolsUrl_;277};278/**279 * @return {Object.<string>} browser capabilities.280 */281BrowserAndroidChrome.prototype.scheduleGetCapabilities = function() {282 'use strict';283 return this.video_.scheduleIsSupported().then(function(isSupported) {284 return {285 webdriver: false,286 'wkrdp.Page.captureScreenshot': false, // TODO(klm): check before-26.287 'wkrdp.Network.clearBrowserCache': true,288 'wkrdp.Network.clearBrowserCookies': true,289 videoRecording: isSupported,290 takeScreenshot: true291 };292 }.bind(this));293};294/**295 * @return {webdriver.promise.Promise} The scheduled promise, where the296 * resolved value is a Buffer of base64-encoded PNG data.297 */298BrowserAndroidChrome.prototype.scheduleTakeScreenshot = function() {299 'use strict';300 return this.adb_.shell(['screencap', '-p'],301 {encoding: 'binary', maxBuffer: 5000 * 1024}).then(function(binout) {302 // Adb shell incorrectly thinks that the binary PNG stdout is text and303 // mangles it by translating all 0x0a '\n's into 0x0d0a '\r\n's. For304 // details, see:305 // http://stackoverflow.com/questions/13578416306 // We use "dos2unix" to un-mangle these 0x0d0a's back into 0x0a's.307 //308 // Another option would be to write the screencap to a remote temp file309 // (e.g. in /mnt/sdcard/) and `adb pull` it to a local temp file.310 return new Buffer(this.adb_.dos2unix(binout), 'base64');311 }.bind(this));312};313/**314 * @param {string} filename The local filename to write to.315 * @param {Function=} onExit Optional exit callback, as noted in video_hdmi.316 */317BrowserAndroidChrome.prototype.scheduleStartVideoRecording = function(318 filename, onExit) {319 'use strict';320 // The video record command needs to know device type for cropping etc.321 this.adb_.shell(['getprop', 'ro.product.device']).then(322 function(stdout) {323 this.video_.scheduleStartVideoRecording(filename, this.deviceSerial_,324 stdout.trim(), this.videoCard_, onExit);325 }.bind(this));326};327/**328 * Stops the video recording.329 */330BrowserAndroidChrome.prototype.scheduleStopVideoRecording = function() {331 'use strict';332 this.video_.scheduleStopVideoRecording();...

Full Screen

Full Screen

file-actions.js

Source:file-actions.js Github

copy

Full Screen

...80 const [packageId, pathInContainer] = parseContainerPath(remotePath);81 this.log.debug(`Parsed package identifier '${packageId}' from '${remotePath}'. Will get the data from '${pathInContainer}'`);82 tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;83 try {84 await this.adb.shell(['run-as', packageId, `chmod 777 '${escapePath(pathInContainer)}'`]);85 await this.adb.shell([86 'run-as', packageId,87 `cp -f '${escapePath(pathInContainer)}' '${escapePath(tmpDestination)}'`88 ]);89 } catch (e) {90 this.log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +91 `Is the application installed and has 'debuggable' build option set to true? ` +92 `Original error: ${e.message}`);93 }94 }95 const localFile = await tempDir.path({prefix: 'appium', suffix: '.tmp'});96 try {97 await this.adb.pull(tmpDestination || remotePath, localFile);98 return (await util.toInMemoryBase64(localFile)).toString();99 } finally {100 if (await fs.exists(localFile)) {101 await fs.unlink(localFile);102 }103 if (tmpDestination) {104 await this.adb.shell(['rm', '-f', tmpDestination]);105 }106 }107};108/**109 * Pushed the given data to a file on the remote device110 * It is required, that a package has debugging flag enabled111 * in order to access its files.112 *113 * @param {string} remotePath The full path to the remote file or114 * a file inside a package bundle115 * @param {string} base64Data Base64 encoded data to be written to the116 * remote file. The remote file will be silently overridden if it already exists.117 * @throws {Error} If there was an error while pushing the data118 */119commands.pushFile = async function pushFile (remotePath, base64Data) {120 if (remotePath.endsWith('/')) {121 throw new errors.InvalidArgumentError(122 `It is expected that remote path points to a file and not to a folder. ` +123 `'${remotePath}' is given instead`124 );125 }126 const localFile = await tempDir.path({prefix: 'appium', suffix: '.tmp'});127 if (_.isArray(base64Data)) {128 // some clients (ahem) java, send a byte array encoding utf8 characters129 // instead of a string, which would be infinitely better!130 base64Data = Buffer.from(base64Data).toString('utf8');131 }132 const content = Buffer.from(base64Data, 'base64');133 let tmpDestination = null;134 try {135 await fs.writeFile(localFile, content.toString('binary'), 'binary');136 if (remotePath.startsWith(CONTAINER_PATH_MARKER)) {137 const [packageId, pathInContainer] = parseContainerPath(remotePath);138 this.log.debug(`Parsed package identifier '${packageId}' from '${remotePath}'. ` +139 `Will put the data into '${pathInContainer}'`);140 tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;141 try {142 await this.adb.shell(143 ['run-as', packageId, `mkdir -p '${escapePath(path.posix.dirname(pathInContainer))}'`]144 );145 await this.adb.shell(['run-as', packageId, `touch '${escapePath(pathInContainer)}'`]);146 await this.adb.shell(['run-as', packageId, `chmod 777 '${escapePath(pathInContainer)}'`]);147 await this.adb.push(localFile, tmpDestination);148 await this.adb.shell([149 'run-as', packageId,150 `cp -f '${escapePath(tmpDestination)}' '${escapePath(pathInContainer)}'`151 ]);152 } catch (e) {153 this.log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +154 `Is the application installed and has 'debuggable' build option set to true? ` +155 `Original error: ${e.message}`);156 }157 } else {158 // adb push creates folders and overwrites existing files.159 await this.adb.push(localFile, remotePath);160 // if we have pushed a file, it might be a media file, so ensure that161 // apps know about it162 await scanMedia(this.adb, remotePath, this.log);163 }164 } finally {165 if (await fs.exists(localFile)) {166 await fs.unlink(localFile);167 }168 if (tmpDestination) {169 await this.adb.shell(['rm', '-f', tmpDestination]);170 }171 }172};173/**174 * Pulls the whole folder from the remote device175 *176 * @param {string} remotePath The full path to a folder on the177 * remote device or a folder inside an application bundle178 * @returns {string} Base64-encoded and zipped content of the folder179 * @throws {Error} If there was a failure while getting the folder content180 */181commands.pullFolder = async function pullFolder (remotePath) {182 let localFolder = await tempDir.path({prefix: 'appium'});183 await this.adb.pull(remotePath, localFolder);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/**2 * AndroidAutomataion3 * Simple nodejs library for Andorid automation4 *5 * Requires uiautomator and Android SDK6 *7 * @author: Andrei Nedobylskii (admin@twister-vl.ru)8 */9const utils = require('util');10const exec = utils.promisify(require('child_process').exec);11const fs = require('fs');12const xpath = require('xpath')13 , dom = require('xmldom').DOMParser14const aaUtils = require('./utils');15class AndroidAutomation {16 /**17 * Keys codes18 * @type {{KEYCODE_ALT_RIGHT: string, KEYCODE_SYM: string, KEYCODE_AT: string, KEYCODE_DPAD_UP: string, KEYCODE_MINUS: string, KEYCODE_ENVELOPE: string, KEYCODE_COMMA: string, KEYCODE_DPAD_DOWN: string, KEYCODE_EQUALS: string, KEYCODE_Y: string, KEYCODE_DPAD_LEFT: string, KEYCODE_Z: string, KEYCODE_W: string, KEYCODE_X: string, KEYCODE_U: string, KEYCODE_UNKNOWN: string, KEYCODE_V: string, KEYCODE_S: string, KEYCODE_T: string, KEYCODE_SHIFT_LEFT: string, TAG_LAST_KEYCODE: string, KEYCODE_VOLUME_UP: string, KEYCODE_LEFT_BRACKET: string, KEYCODE_PLUS: string, KEYCODE_BACKSLASH: string, KEYCODE_CLEAR: string, KEYCODE_ENDCALL: string, KEYCODE_GRAVE: string, KEYCODE_HEADSETHOOK: string, KEYCODE_POWER: string, KEYCODE_POUND: string, KEYCODE_DPAD_CENTER: string, KEYCODE_NUM: string, KEYCODE_EXPLORER: string, KEYCODE_SLASH: string, KEYCODE_BACK: string, KEYCODE_1: string, KEYCODE_2: string, KEYCODE_SHIFT_RIGHT: string, KEYCODE_SEMICOLON: string, KEYCODE_0: string, KEYCODE_DEL: string, KEYCODE_CALL: string, KEYCODE_NOTIFICATION: string, KEYCODE_VOLUME_DOWN: string, KEYCODE_RIGHT_BRACKET: string, KEYCODE_SPACE: string, KEYCODE_I: string, KEYCODE_STAR: string, KEYCODE_J: string, KEYCODE_G: string, KEYCODE_PERIOD: string, KEYCODE_H: string, KEYCODE_E: string, KEYCODE_F: string, KEYCODE_C: string, KEYCODE_D: string, KEYCODE_Q: string, KEYCODE_R: string, KEYCODE_O: string, KEYCODE_P: string, KEYCODE_M: string, KEYCODE_ENTER: string, KEYCODE_N: string, KEYCODE_K: string, KEYCODE_L: string, KEYCODE_SOFT_RIGHT: string, KEYCODE_9: string, KEYCODE_APOSTROPHE: string, KEYCODE_MENU: string, KEYCODE_TAB: string, KEYCODE_7: string, KEYCODE_FOCUS: string, KEYCODE_HOME: string, KEYCODE_8: string, KEYCODE_ALT_LEFT: string, KEYCODE_5: string, KEYCODE_6: string, KEYCODE_CAMERA: string, KEYCODE_3: string, KEYCODE_SEARCH: string, KEYCODE_4: string, KEYCODE_A: string, KEYCODE_B: string, KEYCODE_DPAD_RIGHT: string}}19 */20 KEY_CODE = aaUtils.KEY_CODES;21 /**22 * Simple async wait23 * @type {(function(*=): Promise<unknown>)|*}24 */25 wait = aaUtils.wait;26 constructor(options) {27 options = {...options, sdkPath: process.env.ANDROID_SDK_ROOT, tempPath: '.'}28 this.sdkPath = options.sdkPath;29 this.adb = `${this.sdkPath}/platform-tools/adb`;30 this.tempPath = options.tempPath;31 }32 /**33 * Download screenshot34 * @param {string} path35 * @returns {Promise<string>}36 */37 async donwloadScreenshot(path = this.tempPath + '/screenshot.png') {38 let screenResult = await exec(`${this.adb} shell screencap -p /data/local/tmp/app.png`);39 //console.log(screenResult);40 let downloadScreenResult = await exec(`${this.adb} pull /data/local/tmp/app.png ${path}`);41 //console.log(downloadScreenResult);42 return path;43 }44 /**45 * Download UIX to specefied path46 * @param {string} path47 * @returns {Promise<string>}48 */49 async downloadUIX(path = this.tempPath + '/currentUI.uix') {50 let screenResult = await exec(`${this.adb} shell uiautomator dump /data/local/tmp/app.uix`);51 //console.log(screenResult);52 let downloadScreenResult = await exec(`${this.adb} pull /data/local/tmp/app.uix ${path}`);53 return path;54 }55 /**56 * Get UIX XML57 * @returns {Promise<string>}58 */59 async getUIX() {60 let uixPath = await this.downloadUIX();61 return fs.readFileSync(uixPath).toString();62 }63 /**64 * XPath selector to UI elements65 * @param {string} selector66 * @returns {Promise<*[SelectorResult]>}67 */68 async $(selector) {69 let uixString = await this.getUIX();70 let doc = new dom().parseFromString(uixString);71 // console.log(doc);72 let nodes = xpath.select(selector, doc);73 // console.log(nodes);74 let selectorResults = [];75 for (let selectorResult of nodes) {76 selectorResults.push(new SelectorResult(this, selectorResult))77 }78 /*if(selectorResults.length === 1){79 selectorResults = selectorResults[0];80 //selectorResults[0] = selectorResults[0];81 }*/82 return selectorResults;83 }84 /**85 * Click (tap) on screen86 * @param {number} x87 * @param {number} y88 * @returns {Promise<void>}89 */90 async tapTouch(x, y) {91 let tapResult = await exec(`${this.adb} shell input tap ${x} ${y}`);92 }93 /**94 * Write text to form95 * @param {string} text96 * @returns {Promise<void>}97 */98 async writeText(text) {99 let tapResult = await exec(`${this.adb} shell input text '${JSON.stringify(text)}'`);100 }101 /**102 * Send key event103 * @param {string|number} keyCode Key code from KEY_CODES104 * @returns {Promise<void>}105 */106 async key(keyCode) {107 let tapResult = await exec(`${this.adb} shell input keyevent ${keyCode}`);108 }109 /**110 * Wait for selector available111 * @param {string} selector112 * @returns {Promise<SelectorResult[]>}113 */114 async waitForSelector(selector) {115 let selectorResult;116 while (true) {117 selectorResult = await this.$(selector);118 if(selectorResult.length !== 0) {119 return selectorResult;120 }121 await aaUtils.wait();122 }123 }124 /**125 * Run app by package id126 * @param packageId127 * @param intent128 * @returns {Promise<void>}129 */130 async runApp(packageId, intent = 'android.intent.category.LAUNCHER') {131 let runResult = await exec(`${this.adb} shell monkey -p ${packageId} -c ${intent} 1`);132 }133 /**134 * Force stop app by package id135 * @param packageId136 * @returns {Promise<void>}137 */138 async forceStop(packageId) {139 let stopResult = await exec(`${this.adb} shell am force-stop ${packageId}`);140 }141}142/**143 * Element selector result144 */145class SelectorResult {146 constructor(androidAutomation, selectorResult) {147 this.androidAutomation = androidAutomation;148 this.selectorResult = selectorResult;149 //Element attributes150 this.attributes = {};151 for (let i = 0; i < this.selectorResult.attributes.length; i++) {152 let attribute = this.selectorResult.attributes[i];153 this.attributes[attribute.name] = attribute.value;154 }155 //Short version for attributes156 this.attr = this.attributes;157 //Parsed element boundaries158 this.bounds = aaUtils.parseBounds(this.attr['bounds']);159 }160 /**161 * Click on element162 * @returns {Promise<void>}163 */164 async click(timeout = 0) {165 let x = Math.round((this.bounds[0][0] + this.bounds[1][0]) / 2);166 let y = Math.round((this.bounds[0][1] + this.bounds[1][1]) / 2);167 await this.androidAutomation.tapTouch(x, y);168 if(timeout > 0) {169 await aaUtils.wait(500);170 }171 }172}...

Full Screen

Full Screen

api.js

Source:api.js Github

copy

Full Screen

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 }...

Full Screen

Full Screen

android-performance.js

Source:android-performance.js Github

copy

Full Screen

...48 return _.startsWith(line.trim(), 'TOTAL ');49 }).trim().split(/\s+/g);50 };51 var promise = new Promise((resolve, reject) => {52 this.adb.shell(cmd).then(data => {53 var sec = parser(data);54 resolve(sec[1]);55 }).catch(err => {56 reject(`exec ${cmd} error with: ${err}`);57 });58 });59 if (args.length > 1) {60 var cb = args[1];61 promise.then(data => {62 var sec = parser(data);63 cb.call(this, null, sec[1]);64 }).catch(err => {65 cb.call(this, err);66 });67 } else {68 return promise;69 }70};71AndroidPerformance.prototype.getPid = function() {72 var args = Array.prototype.slice.call(arguments);73 var name = args[0];74 var cmd = `ps`;75 var parser = function(data) {76 return _.find(data.split('\n'), function(line) {77 return line.split(/\s+/g)[8] === name;78 }).trim().split(/\s+/g);79 };80 var promise = new Promise((resolve, reject) => {81 this.adb.shell(cmd).then(data => {82 var sec = parser(data);83 resolve(sec[1]);84 }).catch(err => {85 reject(`exec ${cmd} error with: ${err}`);86 });87 });88 if (args.length > 1) {89 var cb = args[1];90 promise.then(data => {91 var sec = parser(data);92 cb.call(this, null, sec[1]);93 }).catch(err => {94 cb.call(this, err);95 });96 } else {97 return promise;98 }99};100AndroidPerformance.prototype.getThreadCountByPid = function() {101 var args = Array.prototype.slice.call(arguments);102 var pid = args[0];103 var cmd = `cat /proc/${pid}/status`;104 var parser = function(data) {105 return _.find(data.split('\n'), function(line) {106 return line.includes('Threads');107 }).trim().split(/\s+/g);108 };109 var promise = new Promise((resolve, reject) => {110 this.adb.shell(cmd).then(data => {111 var sec = parser(data);112 resolve(sec[1]);113 }).catch(err => {114 reject(`exec ${cmd} error with: ${err}`);115 });116 });117 if (args.length > 1) {118 var cb = args[1];119 promise.then(data => {120 var sec = parser(data);121 cb.call(this, null, sec[1]);122 }).catch(err => {123 cb.call(this, err);124 });125 } else {126 return promise;127 }128};129AndroidPerformance.prototype.getUidByPid = function() {130 var args = Array.prototype.slice.call(arguments);131 var pid = args[0];132 var cmd = `cat /proc/${pid}/status`;133 var parser = function(data) {134 return _.find(data.split('\n'), function(line) {135 return line.includes('Uid');136 }).trim().split(/\s+/g);137 };138 var promise = new Promise((resolve, reject) => {139 this.adb.shell(cmd).then(data => {140 var sec = parser(data);141 resolve(sec[1]);142 }).catch(err => {143 reject(`exec ${cmd} error with: ${err}`);144 });145 });146 if (args.length > 1) {147 var cb = args[1];148 promise.then(data => {149 var sec = parser(data);150 cb.call(this, null, sec[1]);151 }).catch(err => {152 cb.call(this, err);153 });154 } else {155 return promise;156 }157};158AndroidPerformance.prototype.getTrafficByUid = function() {159 var args = Array.prototype.slice.call(arguments);160 var uid = args[0];161 var cmd = `cat /proc/net/xt_qtaguid/stats`;162 var parser = function(data) {163 var res = {164 wifi: {165 rcv: 0,166 snd: 0167 },168 mobile: {169 rcv: 0,170 snd: 0171 }172 };173 var uidx, typex, rcvx, sndx;174 _.forEach(data.split('\n'), function(line) {175 var token = line.trim().split(/\s+/g);176 if (token[0] === 'idx') {177 uidx = _.indexOf(token, 'uid_tag_int');178 typex = _.indexOf(token, 'iface');179 rcvx = _.indexOf(token, 'rx_bytes');180 sndx = _.indexOf(token, 'tx_bytes');181 } else if (token[uidx] === uid) {182 if (token[typex].includes('wlan')) {183 res.wifi.rcv += parseInt(token[rcvx], 10);184 res.wifi.snd += parseInt(token[sndx], 10);185 } else {186 res.mobile.rcv += parseInt(token[rcvx], 10);187 res.mobile.rcv += parseInt(token[sndx], 10);188 }189 }190 });191 return res;192 };193 var promise = new Promise((resolve, reject) => {194 this.adb.shell(cmd).then(data => {195 var res = parser(data);196 resolve(res);197 }).catch(err => {198 reject(`exec ${cmd} error with: ${err}`);199 });200 });201 if (args.length > 1) {202 var cb = args[1];203 promise.then(data => {204 var res = parser(data);205 cb.call(this, null, res);206 }).catch(err => {207 cb.call(this, err);208 });209 } else {210 return promise;211 }212};213AndroidPerformance.prototype.getCPUByPid = function() {214 var args = Array.prototype.slice.call(arguments);215 var pid = args[0];216 var cmd = `top -n 1`;217 var parser = function(data) {218 return _.find(data.split('\n'), function(line) {219 return line.includes(pid);220 }).trim().split(/\s+/g);221 };222 var promise = new Promise((resolve, reject) => {223 this.adb.shell(cmd).then(data => {224 var sec = parser(data);225 resolve(sec[2]);226 }).catch(err => {227 reject(`exec ${cmd} error with: ${err}`);228 });229 });230 if (args.length > 1) {231 var cb = args[1];232 promise.then(data => {233 var sec = parser(data);234 cb.call(this, null, sec[2]);235 }).catch(err => {236 cb.call(this, err);237 });...

Full Screen

Full Screen

uiautomator-client.js

Source:uiautomator-client.js Github

copy

Full Screen

...21 yield this.adb.forward(this.proxyPort, this.proxyPort);22 const ANDROID_TMP_DIR = this.adb.getTmpDir();23 // install dirver pkg olny when pkg not exists24 try {25 let testPkgList = yield this.adb.shell(`pm list packages | grep ${UIAUTOMATORWD.TEST_PACKAGE}$`);26 if (testPkgList && testPkgList.split(':')[1] === UIAUTOMATORWD.TEST_PACKAGE) {27 logger.debug(`Package ${UIAUTOMATORWD.TEST_PACKAGE} already exists. No need reinstall.`);28 yield this.adb.shell(`pm clear "${UIAUTOMATORWD.TEST_PACKAGE}"`);29 } else {30 throw new Error('Package is not exists');31 }32 } catch (e) {33 logger.debug(`Package ${UIAUTOMATORWD.TEST_PACKAGE} is not exists,execute intsall action.`);34 if (_.isExistedFile(UIAUTOMATORWD.TEST_APK_BUILD_PATH)) {35 yield this.adb.push(UIAUTOMATORWD.TEST_APK_BUILD_PATH, `${ANDROID_TMP_DIR}/${UIAUTOMATORWD.TEST_PACKAGE}`);36 } else {37 logger.error(`${UIAUTOMATORWD.TEST_APK_BUILD_PATH} not found, please resolve and reinstall android driver`);38 }39 yield this.adb.shell(`pm install -r "${ANDROID_TMP_DIR}/${UIAUTOMATORWD.TEST_PACKAGE}"`);40 }41 // install dirver pkg olny when pkg not exists42 try {43 let extraTestPkgList = yield this.adb.shell(`pm list packages | grep ${UIAUTOMATORWD.TEST_PACKAGE}.test$`);44 if (extraTestPkgList && extraTestPkgList.split(':')[1] === 'com.macaca.android.testing.test') {45 logger.debug(`Package ${UIAUTOMATORWD.TEST_PACKAGE}.test already exists. No need reinstall.`);46 yield this.adb.shell(`pm clear "${UIAUTOMATORWD.TEST_PACKAGE}.test"`);47 } else {48 throw new Error('Package is not exists');49 }50 } catch (e) {51 logger.debug(`Package ${UIAUTOMATORWD.TEST_PACKAGE}.test is not exists,execute intsall action.`);52 if (_.isExistedFile(UIAUTOMATORWD.APK_BUILD_PATH)) {53 yield this.adb.push(UIAUTOMATORWD.APK_BUILD_PATH, `${ANDROID_TMP_DIR}/${UIAUTOMATORWD.TEST_PACKAGE}.test`);54 } else {55 logger.error(`${UIAUTOMATORWD.APK_BUILD_PATH} not found, please resolve and reinstall android driver`);56 }57 yield this.adb.shell(`pm install -r "${ANDROID_TMP_DIR}/${UIAUTOMATORWD.TEST_PACKAGE}.test"`);58 }59 yield this.adb.shell(`am force-stop ${UIAUTOMATORWD.TEST_PACKAGE}`);60 yield this.adb.shell(`am force-stop ${UIAUTOMATORWD.TEST_PACKAGE}.test`);61 yield this.startServer();62};63UIAutomator.prototype.initProxy = function() {64 this.proxy = new WDProxy({65 proxyHost: this.proxyHost,66 proxyPort: this.proxyPort,67 urlBase: this.urlBase68 });69};70UIAutomator.prototype.startServer = function() {71 return new Promise(resolve => {72 let permissionPatterns = this.permissionPatterns ? `-e permissionPattern ${this.permissionPatterns}` : '';73 let args = `shell am instrument -w -r ${permissionPatterns} -e port ${this.proxyPort} -e class ${UIAUTOMATORWD.PACKAGE_NAME} ${UIAUTOMATORWD.TEST_PACKAGE}.test/${UIAUTOMATORWD.RUNNER_CLASS}`.split(' ');74 var proc = this.adb.spawn(args, {...

Full Screen

Full Screen

FileXfer.js

Source:FileXfer.js Github

copy

Full Screen

1const path = require('path');2class FileXfer {3 constructor(adb, destinationDir) {4 this._adb = adb;5 this._dir = destinationDir;6 }7 async prepareDestinationDir(deviceId) {8 await this._adb.shell(deviceId, `rm -fr ${this._dir}`);9 await this._adb.shell(deviceId, `mkdir -p ${this._dir}`);10 }11 async send(deviceId, sourcePath, destinationFilename) {12 const destinationPath = path.posix.join(this._dir, destinationFilename);13 await this._adb.push(deviceId, sourcePath, destinationPath);14 return destinationPath;15 }16}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('appium-adb');2var driver = new AndroidDriver();3var adb = new ADB();4driver.adb = adb;5driver.adb.shell('ls', function(err, stdout) {6 console.log(stdout);7});8var adb = require('appium-adb');9var driver = new AndroidDriver();10var adb = new ADB();11driver.adb = adb;12driver.adb.shell('ls', function(err, stdout) {13 console.log(stdout);14});15var adb = require('appium-adb');16var driver = new AndroidDriver();17var adb = new ADB();18driver.adb = adb;19driver.adb.shell('ls', function(err, stdout) {20 console.log(stdout);21});22var adb = require('appium-adb');23var driver = new AndroidDriver();24var adb = new ADB();25driver.adb = adb;26driver.adb.shell('ls', function(err, stdout) {27 console.log(stdout);28});29var adb = require('appium-adb');30var driver = new AndroidDriver();31var adb = new ADB();32driver.adb = adb;33driver.adb.shell('ls', function(err, stdout) {34 console.log(stdout);35});36var adb = require('appium-adb');37var driver = new AndroidDriver();38var adb = new ADB();39driver.adb = adb;40driver.adb.shell('ls', function(err, stdout) {41 console.log(stdout);42});43var adb = require('appium-adb');44var driver = new AndroidDriver();45var adb = new ADB();46driver.adb = adb;47driver.adb.shell('ls', function(err, stdout) {48 console.log(stdout);49});50var adb = require('appium-adb');51var driver = new AndroidDriver();52var adb = new ADB();53driver.adb = adb;54driver.adb.shell('ls', function(err, stdout) {55 console.log(stdout);56});

Full Screen

Using AI Code Generation

copy

Full Screen

1var Appium = require("appium"),2 wd = require("wd"),3 path = require("path"),4 _ = require("underscore");5var driver = wd.promiseChainRemote("localhost", 4723);6driver.init({7 app: path.resolve(__dirname, "myapp.apk")8}).then(function () {9 return driver.setImplicitWaitTimeout(5000);10}).then(function () {11 return driver.elementByName("My Button");12}).then(function (el) {13 return el.click();14}).then(function () {15 return driver.shell(["am", "start", "-n", "com.myapp/.MyActivity"]);16}).then(function () {17 return driver.elementByName("My Text");18}).then(function (el) {19 return el.text();20}).then(function (text) {21 console.log(text);22}).then(function () {23 return driver.quit();24}).done();25return driver.shell(["dumpsys", "window", "windows"]);26I am using the following code to get the output of the command "dumpsys window windows". return driver.shell(["dumpsys", "window", "windows"]);

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('appium-adb');2var AndroidDriver = require('appium-android-driver');3var driver = new AndroidDriver();4var adb = driver.adb;5adb.shell('su -c "dumpsys window windows"').then(function(stdout) {6 console.log(stdout);7});8var adb = require('appium-adb');9var AndroidDriver = require('appium-android-driver');10var driver = new AndroidDriver();11var adb = driver.adb;12adb.shell('su -c "dumpsys window windows"').then(function(stdout) {13 console.log(stdout);14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('appium-adb');2var driver = new adb.ADB();3driver.shell('ls', function(err, stdout) {4 if (err) {5 console.log('Error occurred while executing command');6 } else {7 console.log(stdout);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('appium-adb');2var adb = new adb.ADB();3adb.getConnectedDevices(function(err, devices) {4 if (err) {5 console.log("Error in getting connected devices");6 } else {7 console.log("Connected Devices : " + devices);8 }9});10adb.shell(devices[0], "ls", function(err, output) {11 if (err) {12 console.log("Error in executing shell command");13 } else {14 console.log("Output : " + output);15 }16});

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 Android Driver automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful