How to use helpers.getScreenshotDataWithAdbShell method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

actions-specs.js

Source:actions-specs.js Github

copy

Full Screen

...352 driver.adb.fileSize.withArgs(png).returns(1);353 jimp.read.withArgs(localFile).returns('screenshoot_context');354 });355 it('should be able to get screenshot via adb shell', async function () {356 await helpers.getScreenshotDataWithAdbShell(driver.adb, {})357 .should.become('screenshoot_context');358 driver.adb.shell.calledWithExactly(['/system/bin/rm', `${png};`359 , '/system/bin/screencap', '-p', png]).should.be.true;360 driver.adb.pull.calledWithExactly(png, localFile).should.be.true;361 jimp.read.calledWithExactly(localFile).should.be.true;362 support.fs.exists.calledTwice.should.be.true;363 support.fs.unlink.calledTwice.should.be.true;364 });365 it('should be possible to change default png dir', async function () {366 path.posix.resolve.withArgs('/custom/path/tmp/', 'screenshot.png').returns(png);367 await helpers.getScreenshotDataWithAdbShell(driver.adb368 , {androidScreenshotPath: '/custom/path/tmp/'})369 .should.become('screenshoot_context');370 });371 it('should throw error if size of the screenshot is zero', async function () {372 driver.adb.fileSize.withArgs(png).returns(0);373 await helpers.getScreenshotDataWithAdbShell(driver.adb, {})374 .should.be.rejectedWith('equals to zero');375 });376 });377 describe('getScreenshotDataWithAdbExecOut', function () {378 it('should be able to take screenshot via exec-out', async function () {379 sandbox.stub(teen_process, 'exec');380 sandbox.stub(jimp, 'read');381 teen_process.exec.returns({stdout: 'stdout', stderr: ''});382 driver.adb.executable.path = 'path/to/adb';383 await helpers.getScreenshotDataWithAdbExecOut(driver.adb);384 teen_process.exec.calledWithExactly(driver.adb.executable.path,385 driver.adb.executable.defaultArgs386 .concat(['exec-out', '/system/bin/screencap', '-p']),387 {encoding: 'binary', isBuffer: true}).should.be.true;...

Full Screen

Full Screen

actions.js

Source:actions.js Github

copy

Full Screen

1import androidHelpers from '../android-helpers';2import { fs, util, tempDir} from 'appium-support';3import path from 'path';4import log from '../logger';5import B from 'bluebird';6import jimp from 'jimp';7import { exec } from 'teen_process';8const swipeStepsPerSec = 28;9const dragStepsPerSec = 40;10let commands = {}, helpers = {}, extensions = {};11commands.keyevent = async function keyevent (keycode, metastate = null) {12 // TODO deprecate keyevent; currently wd only implements keyevent13 log.warn('keyevent will be deprecated use pressKeyCode');14 return await this.pressKeyCode(keycode, metastate);15};16commands.pressKeyCode = async function pressKeyCode (keycode, metastate = null) {17 return await this.bootstrap.sendAction('pressKeyCode', {keycode, metastate});18};19commands.longPressKeyCode = async function longPressKeyCode (keycode, metastate = null) {20 return await this.bootstrap.sendAction('longPressKeyCode', {keycode, metastate});21};22commands.getOrientation = async function getOrientation () {23 let params = {24 naturalOrientation: !!this.opts.androidNaturalOrientation,25 };26 let orientation = await this.bootstrap.sendAction('orientation', params);27 return orientation.toUpperCase();28};29commands.setOrientation = async function setOrientation (orientation) {30 orientation = orientation.toUpperCase();31 let params = {32 orientation,33 naturalOrientation: !!this.opts.androidNaturalOrientation,34 };35 return await this.bootstrap.sendAction('orientation', params);36};37commands.fakeFlick = async function fakeFlick (xSpeed, ySpeed) {38 return await this.bootstrap.sendAction('flick', {xSpeed, ySpeed});39};40commands.fakeFlickElement = async function fakeFlickElement (elementId, xoffset, yoffset, speed) {41 let params = {xoffset, yoffset, speed, elementId};42 return await this.bootstrap.sendAction('element:flick', params);43};44commands.swipe = async function swipe (startX, startY, endX, endY, duration, touchCount, elId) {45 if (startX === 'null') {46 startX = 0.5;47 }48 if (startY === 'null') {49 startY = 0.5;50 }51 let swipeOpts = {startX, startY, endX, endY,52 steps: Math.round(duration * swipeStepsPerSec)};53 // going the long way and checking for undefined and null since54 // we can't be assured `elId` is a string and not an int55 if (util.hasValue(elId)) {56 swipeOpts.elementId = elId;57 }58 return await this.doSwipe(swipeOpts);59};60commands.doSwipe = async function doSwipe (swipeOpts) {61 if (util.hasValue(swipeOpts.elementId)) {62 return await this.bootstrap.sendAction('element:swipe', swipeOpts);63 } else {64 return await this.bootstrap.sendAction('swipe', swipeOpts);65 }66};67commands.pinchClose = async function pinchClose (startX, startY, endX, endY, duration, percent, steps, elId) {68 let pinchOpts = {69 direction: 'in',70 elementId: elId,71 percent,72 steps73 };74 return await this.bootstrap.sendAction('element:pinch', pinchOpts);75};76commands.pinchOpen = async function pinchOpen (startX, startY, endX, endY, duration, percent, steps, elId) {77 let pinchOpts = {direction: 'out', elementId: elId, percent, steps};78 return await this.bootstrap.sendAction('element:pinch', pinchOpts);79};80commands.flick = async function flick (element, xSpeed, ySpeed, xOffset, yOffset, speed) {81 if (element) {82 await this.fakeFlickElement(element, xOffset, yOffset, speed);83 } else {84 await this.fakeFlick(xSpeed, ySpeed);85 }86};87commands.drag = async function drag (startX, startY, endX, endY, duration, touchCount, elementId, destElId) {88 let dragOpts = {89 elementId, destElId, startX, startY, endX, endY,90 steps: Math.round(duration * dragStepsPerSec)91 };92 return await this.doDrag(dragOpts);93};94commands.doDrag = async function doDrag (dragOpts) {95 if (util.hasValue(dragOpts.elementId)) {96 return await this.bootstrap.sendAction('element:drag', dragOpts);97 } else {98 return await this.bootstrap.sendAction('drag', dragOpts);99 }100};101commands.lock = async function lock (seconds) {102 await this.adb.lock();103 if (isNaN(seconds)) {104 return;105 }106 const floatSeconds = parseFloat(seconds);107 if (floatSeconds <= 0) {108 return;109 }110 await B.delay(1000 * floatSeconds);111 await this.unlock();112};113commands.isLocked = async function isLocked () {114 return await this.adb.isScreenLocked();115};116commands.unlock = async function unlock () {117 return await androidHelpers.unlock(this, this.adb, this.caps);118};119commands.openNotifications = async function openNotifications () {120 return await this.bootstrap.sendAction('openNotification');121};122commands.setLocation = async function setLocation (latitude, longitude) {123 return await this.adb.sendTelnetCommand(`geo fix ${longitude} ${latitude}`);124};125commands.fingerprint = async function fingerprint (fingerprintId) {126 if (!this.isEmulator()) {127 log.errorAndThrow('fingerprint method is only available for emulators');128 }129 await this.adb.fingerprint(fingerprintId);130};131commands.sendSMS = async function sendSMS (phoneNumber, message) {132 if (!this.isEmulator()) {133 log.errorAndThrow('sendSMS method is only available for emulators');134 }135 await this.adb.sendSMS(phoneNumber, message);136};137commands.gsmCall = async function gsmCall (phoneNumber, action) {138 if (!this.isEmulator()) {139 log.errorAndThrow('gsmCall method is only available for emulators');140 }141 await this.adb.gsmCall(phoneNumber, action);142};143commands.gsmSignal = async function gsmSignal (signalStrengh) {144 if (!this.isEmulator()) {145 log.errorAndThrow('gsmSignal method is only available for emulators');146 }147 await this.adb.gsmSignal(signalStrengh);148};149commands.gsmVoice = async function gsmVoice (state) {150 if (!this.isEmulator()) {151 log.errorAndThrow('gsmVoice method is only available for emulators');152 }153 await this.adb.gsmVoice(state);154};155commands.powerAC = async function powerAC (state) {156 if (!this.isEmulator()) {157 log.errorAndThrow('powerAC method is only available for emulators');158 }159 await this.adb.powerAC(state);160};161commands.powerCapacity = async function powerCapacity (batteryPercent) {162 if (!this.isEmulator()) {163 log.errorAndThrow('powerCapacity method is only available for emulators');164 }165 await this.adb.powerCapacity(batteryPercent);166};167commands.networkSpeed = async function networkSpeed (networkSpeed) {168 if (!this.isEmulator()) {169 log.errorAndThrow('networkSpeed method is only available for emulators');170 }171 await this.adb.networkSpeed(networkSpeed);172};173/**174 * Emulate sensors values on the connected emulator.175 *176 * @typedef {Object} Sensor177 * @property {string} sensorType - sensor type declared in adb.SENSORS178 * @property {string} value - value to set to the sensor179 *180 * @param {Object} Sensor181 * @throws {Error} - If sensorType is not defined182 * @throws {Error} - If value for the se sor is not defined183 * @throws {Error} - If deviceType is not an emulator184 */185commands.sensorSet = async function sensorSet (sensor = {}) {186 const {sensorType, value} = sensor;187 if (!util.hasValue(sensorType)) {188 log.errorAndThrow(`'sensorType' argument is required`);189 }190 if (!util.hasValue(value)) {191 log.errorAndThrow(`'value' argument is required`);192 }193 if (!this.isEmulator()) {194 log.errorAndThrow('sensorSet method is only available for emulators');195 }196 await this.adb.sensorSet(sensorType, value);197};198helpers.getScreenshotDataWithAdbShell = async function getScreenshotDataWithAdbShell (adb, opts) {199 const localFile = await tempDir.path({prefix: 'appium', suffix: '.png'});200 if (await fs.exists(localFile)) {201 await fs.unlink(localFile);202 }203 try {204 const pngDir = opts.androidScreenshotPath || '/data/local/tmp/';205 const png = path.posix.resolve(pngDir, 'screenshot.png');206 const cmd = ['/system/bin/rm', `${png};`, '/system/bin/screencap', '-p', png];207 await adb.shell(cmd);208 if (!await adb.fileSize(png)) {209 throw new Error('The size of the taken screenshot equals to zero.');210 }211 await adb.pull(png, localFile);212 return await jimp.read(localFile);213 } finally {214 if (await fs.exists(localFile)) {215 await fs.unlink(localFile);216 }217 }218};219helpers.getScreenshotDataWithAdbExecOut = async function getScreenshotDataWithAdbExecOut (adb) {220 let {stdout, stderr, code} = await exec(adb.executable.path,221 adb.executable.defaultArgs222 .concat(['exec-out', '/system/bin/screencap', '-p']),223 {encoding: 'binary', isBuffer: true});224 // if there is an error, throw225 if (code || stderr.length) {226 throw new Error(`Screenshot returned error, code: '${code}', stderr: '${stderr.toString()}'`);227 }228 // if we don't get anything at all, throw229 if (!stdout.length) {230 throw new Error('Screenshot returned no data');231 }232 return await jimp.read(stdout);233};234commands.getScreenshot = async function getScreenshot () {235 const apiLevel = await this.adb.getApiLevel();236 let image = null;237 if (apiLevel > 20) {238 try {239 // This screenshoting approach is way faster, since it requires less external commands240 // to be executed. Unfortunately, exec-out option is only supported by newer Android/SDK versions (5.0 and later)241 image = await this.getScreenshotDataWithAdbExecOut(this.adb);242 } catch (e) {243 log.info(`Cannot get screenshot data with 'adb exec-out' because of '${e.message}'. ` +244 `Defaulting to 'adb shell' call`);245 }246 }247 if (!image) {248 try {249 image = await this.getScreenshotDataWithAdbShell(this.adb, this.opts);250 } catch (e) {251 const err = `Cannot get screenshot data because of '${e.message}'. ` +252 `Make sure the 'LayoutParams.FLAG_SECURE' is not set for ` +253 `the current view`;254 log.errorAndThrow(err);255 }256 }257 if (apiLevel < 23) {258 // Android bug 8433742 - rotate screenshot if screen is rotated259 let screenOrientation = await this.adb.getScreenOrientation();260 try {261 image = await image.rotate(-90 * screenOrientation);262 } catch (err) {263 log.warn(`Could not rotate screenshot due to error: ${err}`);264 }265 }266 const getBuffer = B.promisify(image.getBuffer, {context: image});267 const imgBuffer = await getBuffer(jimp.MIME_PNG);268 return imgBuffer.toString('base64');269};270Object.assign(extensions, commands, helpers);271export { commands, helpers };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var helpers = require('appium-android-driver').androidHelpers;2helpers.getScreenshotDataWithAdbShell('emulator-5554', function(err, screenshotData) {3 if (err) {4 console.log(err);5 } else {6 console.log(screenshotData);7 }8});9var fs = require('fs');10var screenshotData = 'base64 encoded string';11var decodedScreenshot = new Buffer(screenshotData, 'base64');12fs.writeFileSync('screenshot.png', decodedScreenshot);

Full Screen

Using AI Code Generation

copy

Full Screen

1var helpers = require('appium-android-driver').androidHelpers;2var screenshotData = helpers.getScreenshotDataWithAdbShell();3var helpers = require('appium-android-driver').androidHelpers;4var screenshotData = helpers.getScreenshotDataWithAdbExec();5var helpers = require('appium-android-driver').androidHelpers;6var screenshotData = helpers.getScreenshotDataWithAapt();7var helpers = require('appium-android-driver').androidHelpers;8var screenshotData = helpers.getScreenshotDataWithLibChimp();9var helpers = require('appium-android-driver').androidHelpers;10var screenshotData = helpers.getScreenshotDataWithUiAutomator();11var helpers = require('appium-android-driver').androidHelpers;12var screenshotData = helpers.getScreenshotDataWithMinicap();13var helpers = require('appium-android-driver').androidHelpers;14var screenshotData = helpers.getScreenshotDataWithMinicap();15var helpers = require('appium-android-driver').androidHelpers;16var screenshotData = helpers.getScreenshotDataWithMinicap();17var helpers = require('appium-android-driver').androidHelpers;18var screenshotData = helpers.getScreenshotDataWithMinicap();19var helpers = require('appium-android-driver').androidHelpers;20var screenshotData = helpers.getScreenshotDataWithMinicap();

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumAndroidDriver = require('appium-android-driver');2var helpers = AppiumAndroidDriver.helpers;3var adb = helpers.getAdb();4var adbPath = adb.adb.path;5var screenshotData = helpers.getScreenshotDataWithAdbShell(adbPath, 'emulator-5554');6console.log(screenshotData);

Full Screen

Using AI Code Generation

copy

Full Screen

1const helpers = require('appium-android-driver').androidHelpers;2const adb = helpers.createADB();3const opts = {4};5adb.getScreenshotDataWithAdbShell(opts).then((res) => {6 console.log(res);7}).catch((err) => {8 console.log(err);9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var path = require('path');3var fs = require('fs');4var helpers = require('./node_modules/appium-android-driver/lib/android-helpers.js');5var desired = {6 app: path.resolve(__dirname, 'app-debug.apk'),7};8var driver = wd.promiseChainRemote('localhost', 4723);9 .init(desired)10 .then(function() {11 return helpers.getScreenshotDataWithAdbShell('com.example.test', 'com.example.test.MainActivity');12 })13 .then(function(imageData) {14 fs.writeFile('screenshot.png', imageData, 'base64', function(err) {15 if (err) {16 console.log(err);17 }18 });19 })20 .fin(function() { return driver.quit(); })21 .done();22"use strict";23var _ = require('lodash');24var ADB = require('appium-adb');25var logger = require('./logger.js').get('AndroidHelpers');26var async = require('async');27var AndroidHelpers = {};28AndroidHelpers.getScreenshotDataWithAdbShell = function(appPackage, appActivity) {29 var adb = new ADB();30 return adb.getScreenshotDataWithAdbShell(appPackage, appActivity);31};32module.exports = AndroidHelpers;33"use strict";34var _ = require('lodash');35var spawn = require('child_process').spawn;36var logger = require('./logger.js').get('ADB');37var async = require('async');38var ADB = function(opts) {39 this.opts = _.defaults(opts || {}, {40 });41};42ADB.prototype.getScreenshotDataWithAdbShell = function(appPackage, appActivity) {43 var cmd, args, screenshotCmd, data = "";44 cmd = 'shell';45 args = ['screencap', '-p'];46 screenshotCmd = spawn(this.adb, args);47 return new Promise(function(resolve, reject) {48 screenshotCmd.stdout.on('data', function(output) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var helpers = require('appium-android-driver').androidHelpers;2helpers.getScreenshotDataWithAdbShell().then(function(screenshotData) {3 console.log(screenshotData);4});5var helpers = require('appium-android-driver').androidHelpers;6var fs = require('fs');7helpers.getScreenshotDataWithAdbShell().then(function(screenshotData) {8 fs.writeFile('screenshot.png', screenshotData, 'base64', function(err) {9 if (err) {10 console.log(err);11 }12 });13});14var helpers = require('appium-android-driver').androidHelpers;15var fs = require('fs');16helpers.getScreenshotDataWithAdbShell().then(function(screenshotData) {17 fs.readFile('baseline_screenshot.png', 'base64', function(err, baselineScreenshotData) {18 if (err) {19 console.log(err);20 } else {21 if (baselineScreenshotData == screenshotData) {22 console.log('Screenshot matches with baseline screenshot');23 } else {24 console.log('Screenshot does not match with baseline screenshot');25 }26 }27 });28});29var helpers = require('appium-android-driver').androidHelpers;30var fs = require('fs');31var resemble = require('resemblejs');32helpers.getScreenshotDataWithAdbShell().then(function(screenshotData) {33 fs.readFile('baseline_screenshot.png', 'base64', function(err, baselineScreenshotData) {34 if (err) {35 console.log(err);36 } else {37 resemble(baselineScreenshotData).compareTo(screenshotData).onComplete(function(data) {38 if (data.misMatchPercentage == 0) {39 console.log('Screenshot matches with baseline screenshot');40 } else {41 console.log('Screenshot does not match with baseline screenshot');42 }43 });44 }45 });46});

Full Screen

Using AI Code Generation

copy

Full Screen

1var helpers = require('appium-android-driver').androidHelpers;2helpers.getScreenshotDataWithAdbShell("path-to-screenshot-destination").then(function (screenshotData) {3 console.log("Screenshot data is: " + screenshotData);4});5var fs = require('fs');6var helpers = require('appium-android-driver').androidHelpers;7helpers.getScreenshotDataWithAdbShell("path-to-screenshot-destination").then(function (screenshotData) {8 fs.writeFile('screenshot.png', screenshotData, 'base64', function (err) {9 if (err) {10 console.log(err);11 } else {12 console.log("Screenshot saved");13 }14 });15});16var fs = require('fs');17var helpers = require('appium-android-driver').androidHelpers;18helpers.getScreenshotDataWithAdbShell("path-to-screenshot-destination").then(function (screenshotData) {19 var baselineScreenshotData = fs.readFileSync('path-to-baseline-screenshot', 'base64');20 if (screenshotData === baselineScreenshotData) {21 console.log("Screenshots match");22 } else {23 console.log("Screenshots do not match");24 }25});26var fs = require('fs');27var helpers = require('appium-android-driver').androidHelpers;28helpers.getScreenshotDataWithAdbShell("path-to-screenshot-destination").then(function (screenshotData) {29 var baselineScreenshotData = fs.readFileSync('path-to-baseline-screenshot', 'base64');30 if (screenshotData === baselineScreenshotData) {31 console.log("Screenshots match");32 } else {33 console.log("Screenshots do not match");34 }35});36var fs = require('fs');37var helpers = require('appium-android-driver').androidHelpers;38helpers.getScreenshotDataWithAdbShell("path-to-screenshot-

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