How to use helpers.pinUnlock method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

unlock-helper-specs.js

Source:unlock-helper-specs.js Github

copy

Full Screen

...168          .returns(e.ELEMENT.toString());169      }170      mocks.asyncbox.expects('sleep').withExactArgs(UNLOCK_WAIT_TIME).once();171      sandbox.stub(driver, 'click');172      await helpers.pinUnlock(adb, driver, caps);173      driver.click.getCall(0).args[0].should.equal(1);174      driver.click.getCall(1).args[0].should.equal(3);175      driver.click.getCall(2).args[0].should.equal(5);176      driver.click.getCall(3).args[0].should.equal(7);177      driver.click.getCall(4).args[0].should.equal(9);178      driver.click.getCall(5).args[0].should.equal(100);179      mocks.helpers.verify();180      mocks.driver.verify();181      mocks.adb.verify();182      mocks.asyncbox.verify();183    });184    it('should be able to unlock device using pin (API level < 21)', async () => {185      mocks.helpers.expects('dismissKeyguard').once();186      mocks.helpers.expects('stringKeyToArr').returns(keys);187      mocks.adb.expects('getApiLevel').returns(20);188      for (let pin of keys) {189        mocks.driver.expects('findElOrEls')190          .withExactArgs("id", `com.android.keyguard:id/key${pin}`, false)191          .returns({ELEMENT: parseInt(pin, 10)});192      }193      mocks.driver.expects('findElOrEls')194        .withExactArgs("id", "com.android.keyguard:id/key_enter", false)195        .returns({ELEMENT: 100});196      mocks.asyncbox.expects('sleep').withExactArgs(UNLOCK_WAIT_TIME).once();197      sandbox.stub(driver, 'click');198      await helpers.pinUnlock(adb, driver, caps);199      driver.click.getCall(0).args[0].should.equal(1);200      driver.click.getCall(1).args[0].should.equal(3);201      driver.click.getCall(2).args[0].should.equal(5);202      driver.click.getCall(3).args[0].should.equal(7);203      driver.click.getCall(4).args[0].should.equal(9);204      driver.click.getCall(5).args[0].should.equal(100);205      mocks.helpers.verify();206      mocks.driver.verify();207      mocks.adb.verify();208      mocks.asyncbox.verify();209    });210    it('should throw error if pin buttons does not exist (API level >= 21)', async () => {211      mocks.helpers.expects('dismissKeyguard').once();212      mocks.helpers.expects('stringKeyToArr').once();213      mocks.adb.expects('getApiLevel').returns(21);214      mocks.driver.expects('findElOrEls').returns(null);215      await helpers.pinUnlock(adb, driver, caps).should.eventually.be216        .rejectedWith('Error finding unlock pin buttons!');217      mocks.helpers.verify();218      mocks.driver.verify();219      mocks.adb.verify();220    });221    it('should throw error if pin buttons does not exist (API level < 21)', async () => {222      mocks.helpers.expects('dismissKeyguard').once();223      mocks.helpers.expects('stringKeyToArr').returns(keys);224      mocks.adb.expects('getApiLevel').returns(20);225      mocks.driver.expects('findElOrEls')226        .withExactArgs('id', 'com.android.keyguard:id/key1', false)227        .returns(null);228      await helpers.pinUnlock(adb, driver, caps).should.eventually.be229        .rejectedWith(`Error finding unlock pin '1' button!`);230      mocks.helpers.verify();231      mocks.driver.verify();232      mocks.adb.verify();233    });234  }));235  describe('passwordUnlock', withMocks({adb, helpers, asyncbox}, (mocks) => {236    it('should be able to unlock device using password', async () => {237      let caps = {unlockKey: 'psswrd'};238      mocks.helpers.expects('dismissKeyguard').withExactArgs(driver, adb).once();239      mocks.helpers.expects('encodePassword').withExactArgs(caps.unlockKey).returns(caps.unlockKey);240      mocks.adb.expects('shell').withExactArgs(['input', 'text', caps.unlockKey]).once();241      mocks.asyncbox.expects('sleep').withExactArgs(INPUT_KEYS_WAIT_TIME).once();242      mocks.adb.expects('shell').withExactArgs(['input', 'keyevent', KEYCODE_NUMPAD_ENTER]);...

Full Screen

Full Screen

unlock-helpers.js

Source:unlock-helpers.js Github

copy

Full Screen

1import logger from './logger';2import { sleep } from 'asyncbox';3import _ from 'lodash';4const PIN_UNLOCK = "pin";5const PASSWORD_UNLOCK = "password";6const PATTERN_UNLOCK = "pattern";7const FINGERPRINT_UNLOCK = "fingerprint";8const UNLOCK_TYPES = [PIN_UNLOCK, PASSWORD_UNLOCK, PATTERN_UNLOCK, FINGERPRINT_UNLOCK];9const KEYCODE_NUMPAD_ENTER = "66";10const UNLOCK_WAIT_TIME = 100;11const HIDE_KEYBOARD_WAIT_TIME = 100;12const INPUT_KEYS_WAIT_TIME = 100;13let helpers = {};14helpers.isValidUnlockType = function (type) {15  return UNLOCK_TYPES.indexOf(type) !== -1;16};17helpers.isValidKey = function (type, key) {18  if (_.isUndefined(key)) {19    return false;20  }21  if (type === PIN_UNLOCK || type === FINGERPRINT_UNLOCK) {22    return /^[0-9]+$/.test(key.trim());23  }24  if (type === PATTERN_UNLOCK) {25    if (!/^[1-9]{2,9}$/.test(key.trim())) {26      return false;27    }28    return !(/([1-9]).*?\1/.test(key.trim()));29  }30  // Dont trim password key, you can use blank spaces in your android password31  // ¯\_(ツ)_/¯32  if (type === PASSWORD_UNLOCK) {33    return /.{4,}/g.test(key);34  }35  throw new Error(`Invalid unlock type ${type}`);36};37helpers.dismissKeyguard = async function (driver, adb) {38  let isKeyboardShown = await driver.isKeyboardShown();39  if (isKeyboardShown) {40    await driver.hideKeyboard();41    // Waits a bit for the keyboard to hide42    await sleep(HIDE_KEYBOARD_WAIT_TIME);43  }44  // dismiss notifications45  logger.info("Dismiss notifications from unlock view");46  await adb.shell(["service", "call", "notification", "1"]);47  await adb.back();48  if (await adb.getApiLevel() > 21) {49    logger.info("Trying to dismiss keyguard");50    await adb.shell(["wm", "dismiss-keyguard"]);51    return;52  }53  logger.info("Swiping up to dismiss keyguard");54  await helpers.swipeUp(driver);55};56helpers.swipeUp = async function (driver) {57  let windowSize = await driver.getWindowSize();58  let x0 = parseInt(windowSize.x / 2, 10);59  let y0 = windowSize.y - 10;60  let yP = 100;61  let actions = [62    {action: 'press', options: {element: null, x: x0, y: y0}},63    {action: 'moveTo', options: {element: null, x: x0, y: yP}},64    {action: 'release'}65  ];66  await driver.performTouch(actions);67};68helpers.encodePassword = function (key) {69  return key.replace(/\s/ig, "%s");70};71helpers.stringKeyToArr = function (key) {72  return key.trim().replace(/\s+/g, '').split(/\s*/);73};74helpers.fingerprintUnlock = async function (adb, driver, capabilities) {75  if (await adb.getApiLevel() < 23) {76    throw new Error("Fingerprint unlock only works for Android 6+ emulators");77  }78  await adb.fingerprint(capabilities.unlockKey);79  await sleep(UNLOCK_WAIT_TIME);80};81helpers.pinUnlock = async function (adb, driver, capabilities) {82  logger.info(`Trying to unlock device using pin ${capabilities.unlockKey}`);83  await helpers.dismissKeyguard(driver, adb);84  let keys = helpers.stringKeyToArr(capabilities.unlockKey);85  if (await adb.getApiLevel() >= 21) {86    let els = await driver.findElOrEls("id", "com.android.systemui:id/digit_text", true);87    if (_.isEmpty(els)) {88      throw new Error("Error finding unlock pin buttons!");89    }90    let pins = {};91    for (let e of els) {92      let text = await driver.getAttribute("text", e.ELEMENT);93      pins[text] = e;94    }95    for (let pin of keys) {96      let el = pins[pin];97      await driver.click(el.ELEMENT);98    }99    let el = await driver.findElOrEls("id", "com.android.systemui:id/key_enter", false);100    await driver.click(el.ELEMENT);101  } else {102    for (let pin of keys) {103      let el = await driver.findElOrEls("id", `com.android.keyguard:id/key${pin}`, false);104      if (el === null) {105        throw new Error(`Error finding unlock pin '${pin}' button!`);106      }107      await driver.click(el.ELEMENT);108    }109    let el = await driver.findElOrEls("id", "com.android.keyguard:id/key_enter", false);110    await driver.click(el.ELEMENT);111  }112  // Waits a bit for the device to be unlocked113  await sleep(UNLOCK_WAIT_TIME);114};115helpers.passwordUnlock = async function (adb, driver, capabilities) {116  logger.info(`Trying to unlock device using password ${capabilities.unlockKey}`);117  await helpers.dismissKeyguard(driver, adb);118  let key = capabilities.unlockKey;119  // Replace blank spaces with %s120  key = helpers.encodePassword(key);121  // Why adb ? It was less flaky122  await adb.shell(["input", "text", key]);123  // Why sleeps ? Avoid some flakyness waiting for the input to receive the keys124  await sleep(INPUT_KEYS_WAIT_TIME);125  await adb.shell(["input", "keyevent", KEYCODE_NUMPAD_ENTER]);126  // Waits a bit for the device to be unlocked127  await sleep(UNLOCK_WAIT_TIME);128};129helpers.getPatternKeyPosition = function (key, initPos, piece) {130  /*131  How the math works:132  We have 9 buttons divided in 3 columns and 3 rows inside the lockPatternView,133  every button has a position on the screen corresponding to the lockPatternView since134  it is the parent view right at the middle of each column or row.135  */136  const cols = 3;137  const pins = 9;138  let xPos = (key, x, piece) => {139    return Math.round(x + ((key % cols) || cols) * piece - piece / 2);140  };141  let yPos = (key, y, piece) => {142    return Math.round(y + (Math.ceil(((key % pins) || pins) / cols) * piece - piece / 2));143  };144  return {x: xPos(key, initPos.x, piece), y: yPos(key, initPos.y, piece)};145};146helpers.getPatternActions = function (keys, initPos, piece) {147  let actions = [];148  let lastPos;149  for (let key of keys) {150    let keyPos = helpers.getPatternKeyPosition(key, initPos, piece);151    if (key === keys[0]) {152      actions.push({action: 'press', options: {element: null, x: keyPos.x, y: keyPos.y}});153      lastPos = keyPos;154      continue;155    }156    let moveTo = {x:0, y:0};157    let diffX = keyPos.x - lastPos.x;158    if (diffX > 0) {159      moveTo.x = piece;160      if (Math.abs(diffX) > piece) {161        moveTo.x += piece;162      }163    } else if (diffX < 0) {164      moveTo.x = -1 * piece;165      if (Math.abs(diffX) > piece) {166        moveTo.x -= piece;167      }168    }169    let diffY = keyPos.y - lastPos.y;170    if (diffY > 0) {171      moveTo.y = piece;172      if (Math.abs(diffY) > piece) {173        moveTo.y += piece;174      }175    } else if (diffY < 0) {176      moveTo.y = -1 * piece;177      if (Math.abs(diffY) > piece) {178        moveTo.y -= piece;179      }180    }181    actions.push({action: 'moveTo', options: {element: null, x: moveTo.x, y: moveTo.y}});182    lastPos = keyPos;183  }184  actions.push({action: 'release'});185  return actions;186};187helpers.patternUnlock = async function (adb, driver, capabilities) {188  logger.info(`Trying to unlock device using pattern ${capabilities.unlockKey}`);189  await helpers.dismissKeyguard(driver, adb);190  let keys = helpers.stringKeyToArr(capabilities.unlockKey);191  /* We set the device pattern buttons as number of a regular phone192   *  | • • • |     | 1 2 3 |193   *  | • • • | --> | 4 5 6 |194   *  | • • • |     | 7 8 9 |195  The pattern view buttons are not seeing by the uiautomator since they are196  included inside a FrameLayout, so we are going to try clicking on the buttons197  using the parent view bounds and math.198  */199  let apiLevel = await adb.getApiLevel();200  let el = await driver.findElOrEls("id",201    `com.android.${apiLevel >= 21 ? 'systemui' : 'keyguard'}:id/lockPatternView`,202    false203  );204  let initPos = await driver.getLocation(el.ELEMENT);205  let size = await driver.getSize(el.ELEMENT);206  // Get actions to perform207  let actions = helpers.getPatternActions(keys, initPos, size.width / 3);208  // Perform gesture209  await driver.performTouch(actions);210  // Waits a bit for the device to be unlocked211  await sleep(UNLOCK_WAIT_TIME);212};213helpers.PIN_UNLOCK = PIN_UNLOCK;214helpers.PASSWORD_UNLOCK = PASSWORD_UNLOCK;215helpers.PATTERN_UNLOCK = PATTERN_UNLOCK;216helpers.FINGERPRINT_UNLOCK = FINGERPRINT_UNLOCK;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .forBrowser('chrome')4    .build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.wait(function() {8  return driver.getTitle().then(function(title) {9    return title === 'webdriver - Google Search';10  });11}, 1000);12driver.quit();13var webdriver = require('selenium-webdriver');14var driver = new webdriver.Builder()15    .forBrowser('chrome')16    .build();17driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');18driver.findElement(webdriver.By.name('btnG')).click();19driver.wait(function() {20  return driver.getTitle().then(function(title) {21    return title === 'webdriver - Google Search';22  });23}, 1000);24driver.quit();25var webdriver = require('selenium-webdriver');26var driver = new webdriver.Builder()27    .forBrowser('chrome')28    .build();29driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');30driver.findElement(webdriver.By.name('btnG')).click();31driver.wait(function() {32  return driver.getTitle().then(function(title) {33    return title === 'webdriver - Google Search';34  });35}, 1000);36driver.quit();37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder()39    .forBrowser('chrome')40    .build();41driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');42driver.findElement(webdriver.By.name('btnG')).click();43driver.wait(function() {44  return driver.getTitle().then(function(title) {45    return title === 'webdriver - Google Search';46  });47}, 1000);48driver.quit();49var webdriver = require('selenium-webdriver');50var driver = new webdriver.Builder()

Full Screen

Using AI Code Generation

copy

Full Screen

1    build();2driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');3driver.findElement(webdriver.By.name('btnG')).click();4driver.wait(function() {5  return driver.getTitle().then(function(title) {6    return title === 'webdriver - Google Search';7  });8}, 1000);9driver.quit();10org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Error executing adbExec. Original error: 'Command '/Users/username/Library/Android/sdk/platform-tools/adb -P 5037 -s emulator-5554 shell "dumpsys window"' exited with code 1'; Stderr: 'Security exception: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/.Launcher } from pid=438, uid=10082 requires android.permission.INTERACT_ACROSS_USERS11at ADB.execFunc$ (../../lib/tools/system-calls.js:323:13)12at tryCatch (/Users/username/.nvm/versions/node/v8.11.3/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:62:40)13at Generator.invoke [as _invoke] (/Users/username/.nvm/versions/node/v8.11.3/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:296:22)14at Generator.prototype.(anonymous function) [as next] (/Users/username/.nvm/versions/node/v8.11.3/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:114:21)15at Generator.tryCatcher (/Users/username/.nvm/versions/node/v8.11.3/lib/node_modules/appium/node_modules/bluebird/js/release/util.js:16:23)16at PromiseSpawn._promiseFulfilled (/Users/username/.nvm/versions/node/v8.11.3/lib/node_modules/appium/node_modules/bluebird/js/release/generators.js:97:49)17at Promise._settlePromise (/Users

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var wd = require('wd');3var desired = require('./desired.json');4  .init(desired)5  .then(function () {6    return driver.unlockScreen();7  })8  .then(function () {9    return driver.sleep(10000);10  })11  .then(function () {12    return driver.quit();13  })14  .done();15var assert = require('assert');16var wd = require('wd');17var desired = require('./desired.json');18  .init(desired)19  .then(function () {20    return driver.unlockScreen();21  })22  .then(function () {23    return driver.sleep(10000);24  })25  .then(function () {26    return driver.quit();27  })28  .done();29var assert = require('assert');30var wd = require('wd');31var desired = require('./desired.json');32  .init(desired)

Full Screen

Using AI Code Generation

copy

Full Screen

1helpers.pinUnlock(1234);2helpers.touchId(1234);3helpers.pinUnlock(1234);4helpers.touchId(1234);5helpers.pinUnlock(1234);6helpers.touchId(1234);7helpers.pinUnlock(1234);8helpers.touchId(1234);9helpers.pinUnlock(1234);10helpers.touchId(1234);11helpers.pinUnlock(1234);12helpers.touchId(1234);13helpers.pinUnlock(1234);14helpers.touchId(1234);15helpers.pinUnlock(1234);16helpers.touchId(1234);17helpers.pinUnlock(1234);18helpers.touchId(1234);19helpers.pinUnlock(1234);20helpers.touchId(1234);21helpers.pinUnlock(1234);

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