Best JavaScript code snippet using root
ADB.js
Source:ADB.js
...89 const apiLvl = await this.apiLevel(deviceId);90 const command = (apiLvl >= 23)91 ? `install -r -g -t ${apkPath}`92 : `install -rg ${apkPath}`;93 const result = await this.adbCmdSpawned(deviceId, command, { timeout: INSTALL_TIMEOUT, retries: 3 });94 const [failure] = (result.stdout || '').match(/^Failure \[.*\]$/m) || [];95 if (failure) {96 throw new DetoxRuntimeError({97 message: `Failed to install app on ${deviceId}: ${apkPath}`,98 debugInfo: failure,99 });100 }101 }102 async remoteInstall(deviceId, path) {103 const apiLvl = await this.apiLevel(deviceId);104 const command = (apiLvl >= 23)105 ? `pm install -r -g -t ${path}`106 : `pm install -rg ${path}`;107 return this.shellSpawned(deviceId, command, { timeout: INSTALL_TIMEOUT, retries: 3 });108 }109 async uninstall(deviceId, appId) {110 await this.adbCmd(deviceId, `uninstall ${appId}`);111 }112 async terminate(deviceId, appId) {113 await this.shell(deviceId, `am force-stop ${appId}`);114 }115 async setLocation(deviceId, lat, lon) {116 // NOTE: QEMU for Android for the telnet part relies on C stdlib117 // function `strtod` which is locale-sensitive, meaning that depending118 // on user environment you'll have to send either comma-separated119 // numbers or dot-separated ones.120 //121 // See: https://android.googlesource.com/platform/external/qemu/+/ae0eaf51751391abea2639a65200e724131dc3d6/android/console.c#2273122 //123 // As by default Node.js is distributed without ICU, the locale issue124 // becomes tricky to solve across different platforms, that's why125 // it's easier for us just to send 2 commands in a row, ignoring one126 // which will obviously fail.127 //128 // Since `adb emu` commands fail silently, .catch() is not necessary.129 const dot = `${lon} ${lat}`;130 const comma = dot.replace(/\./g, ',');131 await this.emu(deviceId, `geo fix ${dot}`);132 await this.emu(deviceId, `geo fix ${comma}`);133 }134 async pidof(deviceId, bundleId) {135 const bundleIdRegex = escape.inQuotedRegexp(bundleId) + '$';136 const command = `ps | grep "${bundleIdRegex}"`;137 const options = { silent: true };138 const processes = await this.shell(deviceId, command, options).catch(() => '');139 if (!processes) {140 return NaN;141 }142 return parseInt(processes.split(' ').filter(Boolean)[1], 10);143 }144 async getFileSize(deviceId, filename) {145 const { stdout, stderr } = await this.adbCmd(deviceId, 'shell du ' + filename).catch(e => e);146 if (stderr.includes('No such file or directory')) {147 return -1;148 }149 return Number(stdout.slice(0, stdout.indexOf(' ')));150 }151 async isBootComplete(deviceId) {152 try {153 const bootComplete = await this.shell(deviceId, `getprop dev.bootcomplete`, { retries: 0, silent: true });154 return (bootComplete === '1');155 } catch (ex) {156 return false;157 }158 }159 async apiLevel(deviceId) {160 if (this._cachedApiLevels.has(deviceId)) {161 return this._cachedApiLevels.get(deviceId);162 }163 const lvl = Number(await this.shell(deviceId, `getprop ro.build.version.sdk`, { retries: 5 }));164 this._cachedApiLevels.set(deviceId, lvl);165 return lvl;166 }167 async disableAndroidAnimations(deviceId) {168 await this.shell(deviceId, `settings put global animator_duration_scale 0`);169 await this.shell(deviceId, `settings put global window_animation_scale 0`);170 await this.shell(deviceId, `settings put global transition_animation_scale 0`);171 }172 async screencap(deviceId, path) {173 await this.shell(deviceId, `screencap ${path}`);174 }175 /***176 * @returns ChildProcessPromise177 */178 screenrecord(deviceId, { path, size, bitRate, timeLimit, verbose }) {179 const [width = 0, height = 0] = size || [];180 const _size = (width > 0) && (height > 0)181 ? ['--size', `${width}x${height}`]182 : [];183 const _bitRate = (bitRate > 0)184 ? ['--bit-rate', String(bitRate)]185 : [];186 const _timeLimit = (timeLimit > 0)187 ? [`--time-limit`, timeLimit]188 : [];189 const _verbose = verbose ? ['--verbose'] : [];190 const screenRecordArgs = [..._size, ..._bitRate, ..._timeLimit, ..._verbose, path];191 return this.spawn(deviceId, ['shell', 'screenrecord', ...screenRecordArgs]);192 }193 /***194 * @returns ChildProcessPromise195 */196 logcat(deviceId, { file, pid, time }) {197 let shellCommand = 'logcat';198 // HACK: cannot make this function async, otherwise ChildProcessPromise.childProcess field will get lost,199 // and this will break interruptProcess() call for any logcat promise.200 const apiLevel = this._cachedApiLevels.get(deviceId);201 if (time && apiLevel >= 21) {202 shellCommand += ` -T "${time}"`;203 }204 if (apiLevel < 24) {205 if (pid > 0) {206 const __pid = String(pid).padStart(5);207 shellCommand += ` -v brief | grep "(${__pid}):"`;208 }209 if (file) {210 shellCommand += ` >> ${file}`;211 }212 } else {213 if (pid > 0) {214 shellCommand += ` --pid=${pid}`;215 }216 if (file) {217 shellCommand += ` -f ${file}`;218 }219 }220 return this.spawn(deviceId, ['shell', shellCommand]);221 }222 async push(deviceId, src, dst) {223 await this.adbCmd(deviceId, `push "${src}" "${dst}"`);224 }225 async pull(deviceId, src, dst = '') {226 await this.adbCmd(deviceId, `pull "${src}" "${dst}"`);227 }228 async rm(deviceId, path, force = false) {229 await this.shell(deviceId, `rm ${force ? '-f' : ''} "${path}"`);230 }231 /***232 * @returns {ChildProcessPromise}233 */234 spawnInstrumentation(deviceId, userArgs, testRunner) {235 const spawnArgs = ['shell', 'am', 'instrument', '-w', '-r', ...userArgs, testRunner];236 return this.spawn(deviceId, spawnArgs, { detached: false });237 }238 async listInstrumentation(deviceId) {239 return this.shell(deviceId, 'pm list instrumentation');240 }241 async getInstrumentationRunner(deviceId, bundleId) {242 const instrumentationRunners = await this.listInstrumentation(deviceId);243 const instrumentationRunner = this._instrumentationRunnerForBundleId(instrumentationRunners, bundleId);244 if (instrumentationRunner === 'undefined') {245 throw new DetoxRuntimeError(`No instrumentation runner found on device ${deviceId} for package ${bundleId}`);246 }247 return instrumentationRunner;248 }249 _instrumentationRunnerForBundleId(instrumentationRunners, bundleId) {250 const runnerForBundleRegEx = new RegExp(`^instrumentation:(.*) \\(target=${bundleId.replace(new RegExp('\\.', 'g'), '\\.')}\\)$`, 'gm');251 return _.get(runnerForBundleRegEx.exec(instrumentationRunners), [1], 'undefined');252 }253 async shell(deviceId, command, options) {254 const result = await this.adbCmd(deviceId, `shell "${escape.inQuotedString(command)}"`, options);255 return result.stdout.trim();256 }257 async shellSpawned(deviceId, command, options) {258 const _command = `shell ${command}`;259 const result = await this.adbCmdSpawned(deviceId, _command, options);260 return result.stdout.trim();261 }262 async emu(deviceId, cmd, options) {263 return (await this.adbCmd(deviceId, `emu "${escape.inQuotedString(cmd)}"`, options)).stdout.trim();264 }265 async reverse(deviceId, port) {266 return this.adbCmd(deviceId, `reverse tcp:${port} tcp:${port}`);267 }268 async reverseRemove(deviceId, port) {269 return this.adbCmd(deviceId, `reverse --remove tcp:${port}`);270 }271 async emuKill(deviceId) {272 return this.adbCmd(deviceId, `emu kill`);273 }274 // TODO refactor the whole thing so as to make usage of BinaryExec -- similar to EmulatorExec275 async adbCmd(deviceId, params, options = {}) {276 const serial = `${deviceId ? `-s ${deviceId}` : ''}`;277 const cmd = `"${this.adbBin}" ${serial} ${params}`;278 const _options = {279 retries: 1,280 ...options,281 };282 return execWithRetriesAndLogs(cmd, _options);283 }284 async adbCmdSpawned(deviceId, command, spawnOptions = {}) {285 const flags = command.split(/\s+/);286 const serial = deviceId ? ['-s', deviceId] : [];287 const _flags = [...serial, ...flags];288 const _spawnOptions = {289 ...spawnOptions,290 capture: ['stdout'],291 };292 return spawnWithRetriesAndLogs(this.adbBin, _flags, _spawnOptions);293 }294 /***295 * @returns {ChildProcessPromise}296 */297 spawn(deviceId, params, spawnOptions) {298 const serial = deviceId ? ['-s', deviceId] : [];...
Using AI Code Generation
1var adb = require('adbkit');2var client = adb.createClient();3client.listDevices()4 .then(function(devices) {5 return Promise.all(devices.map(function(device) {6 return client.shell(device.id, 'ls -l');7 }));8 })9 .then(adb.util.readAll)10 .then(function(output) {11 console.log('[%s] %s', device.id, output.toString().trim());12 })13 .catch(function(err) {14 console.error('Something went wrong:', err.stack);15 });16var adb = require('adbkit');17var client = adb.createClient();18client.listDevices()19 .then(function(devices) {20 return Promise.all(devices.map(function(device) {21 return client.shell(device.id, 'ls -l');22 }));23 })24 .then(adb.util.readAll)25 .then(function(output) {26 console.log('[%s] %s', device.id, output.toString().trim());27 })28 .catch(function(err) {29 console.error('Something went wrong:', err.stack);30 });31[MIT](LICENSE)
Using AI Code Generation
1const root = require('./root');2const adb = require('adbkit');3const client = adb.createClient();4const fs = require('fs');5client.listDevices()6 .then(function(devices) {7 return Promise.all(devices.map(function(device) {8 return client.shell(device.id, 'pm list packages -f')9 .then(adb.util.readAll)10 .then(function(output) {11 console.log('[%s] %s', device.id, output.toString().trim());12 });13 }));14 })15 .catch(function(err) {16 console.error('Something went wrong:', err.stack);17 });18const adb = require('adbkit');19const client = adb.createClient();20const fs = require('fs');21function adbCmdSpawned(cmd, callback) {22 var spawn = require('child_process').spawn;23 var adb = spawn('adb', cmd);24 var output = '';25 adb.stdout.on('data', function(data) {26 output += data.toString();27 });28 adb.on('close', function(code) {29 callback(output);30 });31}32module.exports = {33}34const root = require('./root');35const adb = require('adbkit');36const client = adb.createClient();37const fs = require('fs');38client.listDevices()39 .then(function(devices) {40 return Promise.all(devices.map(function(device) {41 return client.shell(device.id, 'pm list packages -f')42 .then(adb.util.readAll)43 .then(function(output) {44 root.adbCmdSpawned('pm list packages -f', function(output) {45 console.log(output);46 });47 });48 }));49 })50 .catch(function(err) {51 console.error('Something went wrong:', err.stack);
Using AI Code Generation
1var root = require('./root.js');2var adb = require('adbkit');3var client = adb.createClient();4client.listDevices()5 .then(function(devices) {6 devices.forEach(function(device) {7 root.adbCmdSpawned(client,device.id,"shell","su","-c","getprop ro.build.version.release").then(function(res){8 console.log(res);9 });10 });11 });
Using AI Code Generation
1var root = require('./root.js');2var adbCmdSpawned = root.adbCmdSpawned;3var cmd = 'ls';4var args = ['-l', '/data/app'];5adbCmdSpawned(cmd, args, function (error, stdout, stderr) {6 if (error) {7 console.log(error);8 }9 console.log(stdout);10 console.log(stderr);11});12var spawn = require('child_process').spawn;13var adbCmdSpawned = function (cmd, args, callback) {14 var child = spawn(cmd, args);15 var stdout = '';16 var stderr = '';17 child.stdout.on('data', function (data) {18 stdout += data;19 });20 child.stderr.on('data', function (data) {21 stderr += data;22 });23 child.on('close', function (code) {24 callback(code, stdout, stderr);25 });26};27exports.adbCmdSpawned = adbCmdSpawned;
Using AI Code Generation
1var adb = require('./root');2adb.adbCmdSpawned('shell', ['id'], function(err, data) {3 console.log('err: ' + err);4 console.log('data: ' + data);5});6var adb = require('./root');7adb.adbCmd('shell', ['id'], function(err, data) {8 console.log('err: ' + err);9 console.log('data: ' + data);10});11var adb = require('./root');12var data = adb.adbCmdSync('shell', ['id']);13console.log('data: ' + data);14var adb = require('./root');15var data = adb.adbCmdSync('shell', ['id']);16console.log('data: ' + data);17exports.adbCmdSpawned = function(cmd, args, callback) {18 var adb = spawn('adb', [cmd].concat(args));19 var data = '';20 adb.stdout.on('data', function(chunk) {21 data += chunk;22 });23 adb.on('error', function(err) {24 callback(err, data);25 });26 adb.on('exit', function(code) {27 callback(null, data);28 });29};30exports.adbCmd = function(cmd, args, callback) {31 var adb = spawn('adb', [cmd].concat(args));32 var data = '';33 adb.stdout.on('data', function(chunk) {34 data += chunk;35 });36 adb.on('error', function(err) {37 callback(err, data);38 });39 adb.on('exit', function(code) {40 callback(null, data);41 });42};43exports.adbCmdSync = function(cmd, args) {44 var data = '';45 var adb = spawnSync('adb', [cmd].concat(args));46 if (adb.stdout) {47 data = adb.stdout.toString();48 }49 if (adb.stderr) {50 data = adb.stderr.toString();51 }52 return data;53};
Using AI Code Generation
1var root = require('./root.js');2root.adbCmdSpawned('devices', '', function(err, result){3 if(err){4 console.log(err);5 }else{6 console.log(result);7 }8});9var root = require('./root.js');10var result = root.adbCmdSpawnedSync('devices', '');11console.log(result);12var root = require('./root.js');13root.adbCmdExec('devices', '', function(err, result){14 if(err){15 console.log(err);16 }else{17 console.log(result);18 }19});20var root = require('./root.js');21var result = root.adbCmdExecSync('devices', '');22console.log(result);
Using AI Code Generation
1var root = require('./root.js');2var adb = require('./adb.js');3var cmd = 'adb shell getprop ro.build.version.release';4var options = {5};6root.adbCmdSpawned(cmd, options, function(error, stdout, stderr) {7 if (error) {8 console.log('error: ' + error);9 }10 console.log('stdout: ' + stdout);11 console.log('stderr: ' + stderr);12});13var root = require('./root.js');14var cmd = 'adb shell getprop ro.build.version.release';15var options = {16};17root.adbCmd(cmd, options, function(error, stdout, stderr) {18 if (error) {19 console.log('error: ' + error);20 }21 console.log('stdout: ' + stdout);22 console.log('stderr: ' + stderr);23});24exports.adbCmdSpawned = function(cmd, options, callback) {25 var adb = spawn('adb', ['shell', 'su']);26 adb.stdout.on('data', function(data) {27 adb.stdin.write('exit\n');28 adb.stdin.end();29 callback(null, data.toString(), null);30 });31 adb.stderr.on('data', function(data) {32 adb.stdin.write('exit\n');33 adb.stdin.end();34 callback(null, null, data.toString());35 });36 adb.on('error', function(err) {37 callback(err, null, null);38 });39 adb.on('close', function(code) {40 if (code !== 0) {41 callback(new Error('child process exited with code ' + code), null, null);42 }43 });44};45exports.adbCmd = function(cmd, options, callback) {46 var adb = exec('adb shell su', options, function(error, stdout, stderr) {47 if (error) {48 callback(error, null, null);49 }50 callback(null, stdout, stderr);51 });52 adb.stdin.write(cmd);53 adb.stdin.write('\n');54 adb.stdin.write('exit\n
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!!