How to use helpers.getScreenshotDataWithAdbExecOut method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

actions-specs.js

Source:actions-specs.js Github

copy

Full Screen

...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;388      jimp.read.calledWithExactly('stdout').should.be.true;389    });390    it('should throw error if size of the screenshot is zero', async function () {391      sandbox.stub(teen_process, 'exec');392      teen_process.exec.returns({stdout: '', stderr: ''});393      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)394        .should.be.rejectedWith('Screenshot returned no data');395    });396    it('should throw error if code is not 0', async function () {397      sandbox.stub(teen_process, 'exec');398      teen_process.exec.returns({code: 1, stdout: '', stderr: ''});399      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)400        .should.be.rejectedWith(`Screenshot returned error, code: '1', stderr: ''`);401    });402    it('should throw error if stderr is not empty', async function () {403      sandbox.stub(teen_process, 'exec');404      teen_process.exec.returns({code: 0, stdout: '', stderr: 'Oops'});405      await helpers.getScreenshotDataWithAdbExecOut(driver.adb)406        .should.be.rejectedWith(`Screenshot returned error, code: '0', stderr: 'Oops'`);407    });408  });409  describe('getScreenshot', function () {410    let image;411    beforeEach(function () {412      image = new jimp(1, 1);413      sandbox.stub(driver.adb, 'getApiLevel');414      sandbox.stub(driver.adb, 'getScreenOrientation');415      sandbox.stub(driver, 'getScreenshotDataWithAdbExecOut');416      sandbox.stub(driver, 'getScreenshotDataWithAdbShell');417      sandbox.stub(image, 'getBuffer').callsFake(function (mime, cb) { // eslint-disable-line promise/prefer-await-to-callbacks418        return cb.call(this, null, Buffer.from('appium'));419      });...

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

1const helpers = require('appium-android-driver').androidHelpers;2async function getScreenShotDataWithAdbExecOut() {3  const adb = await helpers.createADB();4  const screenShotData = await helpers.getScreenshotDataWithAdbExecOut(adb);5  console.log(screenShotData);6}7getScreenShotDataWithAdbExecOut();8const helpers = require('appium-android-driver').androidHelpers;9async function getScreenShotDataWithAapt() {10  const adb = await helpers.createADB();11  const screenShotData = await helpers.getScreenshotDataWithAapt(adb);12  console.log(screenShotData);13}14getScreenShotDataWithAapt();15const helpers = require('appium-android-driver').androidHelpers;16async function getScreenShotDataWithAdbShell() {17  const adb = await helpers.createADB();18  const screenShotData = await helpers.getScreenshotDataWithAdbShell(adb);19  console.log(screenShotData);20}21getScreenShotDataWithAdbShell();22const helpers = require('appium-android-driver').androidHelpers;23async function getDisplayDensity() {24  const adb = await helpers.createADB();25  const displayDensity = await helpers.getDisplayDensity(adb);26  console.log(displayDensity);27}28getDisplayDensity();29const helpers = require('appium-android-driver').androidHelpers;30async function getDisplayRotation() {31  const adb = await helpers.createADB();32  const displayRotation = await helpers.getDisplayRotation(adb);33  console.log(displayRotation);34}35getDisplayRotation();36const helpers = require('appium-android-driver').androidHelpers;37async function getDisplaySize() {38  const adb = await helpers.createADB();39  const displaySize = await helpers.getDisplaySize(adb);40  console.log(displaySize);41}42getDisplaySize();43const helpers = require('appium-android-driver').androidHelpers;44async function getDevicePixelRatio() {45  const adb = await helpers.createADB();

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumAndroidDriver = require('appium-android-driver');2var helpers = AppiumAndroidDriver.helpers;3var adb = helpers.require('adb');4var path = require('path');5adb.getScreenshotDataWithAdbExecOut('/Users/saikrishna/Downloads/adb', path.resolve(__dirname, 'screenshot.png')).then(function (data) {6  console.log(data);7});

Full Screen

Using AI Code Generation

copy

Full Screen

1const helpers = require('appium-android-driver').androidHelpers;2const adb = helpers.createAdb({3});4const screenshotData = helpers.getScreenshotDataWithAdbExecOut(adb, 'emulator-5554');5console.log(`screenshot data: ${screenshotData}`);6const helpers = require('appium-android-driver').androidHelpers;7const screenshotData = helpers.getScreenshotDataWithAdbExecOut('emulator-5554');8console.log(`screenshot data: ${screenshotData}`);9const helpers = require('appium-android-driver').androidHelpers;10const screenshotData = helpers.getScreenshotData('emulator-5554');11console.log(`screenshot data: ${screenshotData}`);12const helpers = require('appium-android-driver').androidHelpers;13const adb = helpers.createAdb({14});15const screenshotData = helpers.getScreenshotData(adb, 'emulator-5554');16console.log(`screenshot data: ${screenshotData}`);

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var path = require('path');3var helpers = require('appium-android-driver').androidHelpers;4var adbExecOut = helpers.getScreenshotDataWithAdbExecOut;5var adb = require('appium-adb').ADB.createADB();6var screenshotPath = path.resolve(__dirname, 'screenshot.png');7adbExecOut(adb, function (err, screenshotData) {8    if (err) {9        console.error(err);10    } else {11        fs.writeFile(screenshotPath, screenshotData, {encoding: 'base64'}, function (err) {12            if (err) {13                console.error(err);14            } else {15                console.log('Screenshot saved to ' + screenshotPath);16            }17        });18    }19});20{21    "scripts": {22    },23    "dependencies": {24    }25}

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