How to use driver.lock method in Appium

Best JavaScript code snippet using appium

ApiDriver.js

Source:ApiDriver.js Github

copy

Full Screen

1/**2 * Created by AlexanderC on 2/3/16.3 */4'use strict';5import {AbstractDriver} from './AbstractDriver';6import request from 'fetchy-request';7import util from '../../../Helpers/util';8import {RegistryAutoDiscovery} from './Helpers/Api/RegistryAutoDiscovery';9import path from 'path';10export class ApiDriver extends AbstractDriver {11  /**12   * @param {RegistryConfig|*} registryConfig13   */14  constructor(registryConfig) {15    super();16    this._authorizer = null;17    this._registryConfig = registryConfig;18    this._endpoints = registryConfig.extract();19  }20  /**21   * @param {String} baseHost22   * @param {Function} cb23   * @param {Boolean} cached24   */25  static autoDiscover(baseHost, cb, cached = false) {26    (new RegistryAutoDiscovery(baseHost))[cached ? 'discoverCached' : 'discover']((error, registryConfig) => {27      if (error) {28        cb(error, null);29        return;30      }31      try {32        cb(null, new ApiDriver(registryConfig));33      } catch (exception) {34        cb(exception, null);35      }36    });37  }38  /**39   * @returns {Authorizer|null}40   */41  get authorizer() {42    return this._authorizer;43  }44  /**45   * @param {Authorizer|null} authorizer46   */47  set authorizer(authorizer) {48    this._authorizer = authorizer;49  }50  /**51   * @returns {Object}52   */53  get endpoints() {54    return this._endpoints;55  }56  /**57   * @returns {RegistryConfig|*}58   */59  get registryConfig() {60    return this._registryConfig;61  }62  /**63   * @param {String} objPath64   * @param {Function} cb65   */66  hasObj(objPath, cb) {67    this._request('hasObj', objPath, (error, data) => {68      let resultError = error || data.error;69      cb(resultError, resultError ? null : data.data);70    });71  }72  /**73   * @param {String} objPath74   * @param {Function} cb75   */76  readObj(objPath, cb) {77    this._request('readObj', objPath, (error, data) => {78      let resultError = error || data.error;79      cb(resultError, resultError ? null : data.data);80    });81  }82  /**83   * @param {String} objPath84   * @param {String|*} data85   * @param {Function} cb86   */87  putObj(objPath, data, cb) {88    this._request('putObj', objPath, (error, data) => {89      cb(error || data.error);90    }, data);91  }92  /**93   * @param {String} objPath94   * @param {Function} cb95   */96  deleteObj(objPath, cb) {97    this._request('deleteObj', objPath, (error, data) => {98      cb(error || data.error);99    });100  }101  /**102   * @param {String} objPath103   * @param {Function} cb104   */105  lockObj(objPath, cb) {106    this.putObj(ApiDriver._lockObjPath(objPath), '', cb);107  }108  /**109   * @param {String} objPath110   * @param {Function} cb111   */112  isObjLocked(objPath, cb) {113    this.hasObj(ApiDriver._lockObjPath(objPath), cb);114  }115  /**116   * @param {String} objPath117   * @param {Function} cb118   */119  releaseObjLock(objPath, cb) {120    this.deleteObj(ApiDriver._lockObjPath(objPath), cb);121  }122  /**123   * @param {String} objPath124   * @returns {String}125   * @private126   */127  static _lockObjPath(objPath) {128    return `${path.dirname(objPath)}/.${path.basename(objPath)}.lock`;129  }130  /**131   * @param {String} endpointName132   * @param {String} objPath133   * @param {Function} cb134   * @param {Object|null} data135   * @private136   */137  _request(endpointName, objPath, cb, data = null) {138    let payload = {objPath,};139    if (data !== null) {140      payload.data = ApiDriver._encodeResponseData(endpointName, data);141    }142    let requestData = {143      uri: this._endpoints[endpointName],144      method: 'POST',145      retry: ApiDriver.RETRY_COUNT,146      displayName: `POST:${endpointName}`,147      headers: {'Content-Type': 'application/json',},148      body: JSON.stringify(payload),149    };150    if (this._authorizer) {151      this._authorizer.injectIntoRequest(requestData);152    }153    request(requestData)154      .then((response) => {155        if (!response.ok) {156          cb(response._error || new Error(response.statusText), null);157          return;158        }159        response160          .text()161          .then((plainData) => {162            let data = null;163            let parsedData = null;164            try {165              data = JSON.parse(plainData);166            } catch (error) {167              data = ApiDriver._decodeData(plainData);168            }169            if (data.errorMessage) {170              cb(ApiDriver._extractError(data.errorMessage), null);171              return;172            }173            parsedData = util.isObject(data) ? data : {};174            // mimic callback args175            parsedData.data = ApiDriver._decodeResponseData(endpointName, parsedData.data || null);176            parsedData.error = parsedData.error || null;177            if (parsedData.error) {178              parsedData.error = ApiDriver._extractError(parsedData.error);179            }180            cb(null, parsedData);181          })182          .catch((error) => {183            cb(error, null);184          });185      }).catch((error) => {186        cb(error, null);187      });188  }189  /**190   * @param {String|Object} data191   * @returns {Object}192   * @private193   */194  static _decodeData(data) {195    if (util.isObject(data)) {196      return data;197    }198    try {199      return JSON.parse(data);200    } catch (e) {201      console.debug('Unable to parse: ', e);202    }203    return {};204  }205  /**206   * @param {String} rawErrorData207   * @returns {Error}208   * @private209   */210  static _extractError(rawErrorData) {211    if (util.isObject(rawErrorData)) {212      return new Error(213        rawErrorData.errorMessage.toString() ||214        `An unknown error occurred (${JSON.stringify(rawErrorData)})`215      );216    }217    let errorMsg = rawErrorData;218    try {219      let errorObj = JSON.parse(rawErrorData);220      errorMsg = errorObj.errorMessage || `An unknown error occurred (${rawErrorData})`;221    } catch (error) {222      console.debug('Unable to parse: ', error);223    }224    return new Error(errorMsg);225  }226  /**227   * @param {String} endpointName228   * @param {String|*} data229   * @returns {String|*}230   */231  static _encodeResponseData(endpointName, data) {232    if (['putObj', 'readObj'].indexOf(endpointName) === -1) {233      return data;234    }235    return data ? (new Buffer(data.toString())).toString('base64') : data;236  }237  /**238   * @param {String} endpointName239   * @param {String|*} rawData240   * @returns {String|*}241   */242  static _decodeResponseData(endpointName, rawData) {243    if (['putObj', 'readObj'].indexOf(endpointName) === -1) {244      return rawData;245    }246    return rawData ? (new Buffer(rawData.toString(), 'base64')).toString('ascii') : rawData;247  }248  /**249   * @returns {Number}250   */251  static get RETRY_COUNT() {252    return 3;253  }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...31        const key = lockerFactory.hash(resourceId);32        const retry = dget(options, 'retry', false);33        const retryInterval = dget(options, 'retryInterval', DEFAULT_RETRY_INTERVAL);34        let maxRetryAttempts = dget(options, 'maxRetryAttempts', DEFAULT_RETRY_ATTEMPTS);35        return driver.lock(key, options)36            .then(numberOfLocks => handleLockingResult(numberOfLocks));37        function handleLockingResult(numberOfLocks) {38            if (numberOfLocks === 1) {39                return buildLock(resourceId, key);40            }41            if (retry && --maxRetryAttempts >= 0) {42                return retryLockingAfterTimeout();43            }44            throw new ResourceLockedError(resourceId, numberOfLocks);45        }46        function retryLockingAfterTimeout() {47            return promiseTimeout(retryInterval)48                .then(() => driver.lock(key, options))49                .then(numberOfLocks => handleLockingResult(numberOfLocks));50        }51        function promiseTimeout(duration) {52            return new Promise(resolve => setTimeout(resolve, duration));53        }54        function dget(obj, key, def) {55            if (!obj || 'undefined' === typeof obj[key]) {56                return def;57            }58            const val = obj[key];59            delete obj[key];60            return val;61        }62    }...

Full Screen

Full Screen

lock-specs.js

Source:lock-specs.js Github

copy

Full Screen

1"use strict";2var setup = require("../../common/setup-base")3    , desired = require("./desired")4    , Asserter = require('wd').Asserter5    , chai = require('chai');6describe("apidemos - lock", function () {7  var driver;8  setup(this, desired).then(function (d) { driver = d; });9  var isLockedAsserter = function (opts) {10    return new Asserter(11      function (driver) {12        return driver13          .isLocked()14          .then(function (isLocked) {15            isLocked.should.equal(opts.expected);16            return isLocked;17          })18          .catch(function (err) {19            err.retriable = err instanceof chai.AssertionError;20            throw err;21          });22      }23    );24  };25  it('should lock the screen', function (done) {26    driver27      .isLocked()28      .should.not.eventually.be.ok29      .lockDevice(3)30      .waitFor(isLockedAsserter({expected: true}), 5000, 500)31      .should.eventually.be.ok32      .nodeify(done);33      });34  // TODO: flaky test35  it('should unlock the screen @skip-ci', function (done) {36    driver37      .lockDevice(3)38      .waitFor(isLockedAsserter({expected: true}), 5000, 500)39      .should.eventually.be.ok40      .unlockDevice()41      .sleep(1000)42      .waitFor(isLockedAsserter({expected: false}), 10000, 1000)43      .should.not.eventually.be.ok44      .nodeify(done);45    });...

Full Screen

Full Screen

device-specs.js

Source:device-specs.js Github

copy

Full Screen

1"use strict";2var env = require('../../../helpers/env'),3    setup = require("../../common/setup-base"),4    desired = require('./desired');5describe('uicatalog - device @skip-ios7up', function () {6  describe('lock device', function () {7    var driver;8    setup(this, desired).then(function (d) { driver = d; });9    var allowance = env.IOS7 ? 5 : 2;10    it("should lock the device for 4 of seconds (+/- " + allowance + "  secs)", function (done) {11      var before = new Date().getTime() / 1000;12      driver13        .lockDevice(4)14        .then(function () {15          var now = (new Date().getTime() / 1000);16          (now - before).should.be.above(4);17          (now - before).should.be.below(4 + allowance + 1);18        }).nodeify(done);19    });20  });21  describe('background app', function () {22    var driver;23    setup(this, desired).then(function (d) { driver = d; });24    it("should background the app for 4 of seconds (+/- 6 secs)", function (done) {25      var before = new Date().getTime() / 1000;26      driver27        .backgroundApp(4)28        .then(function () {29          ((new Date().getTime() / 1000) - before).should.be.below(11);30        }).nodeify(done);31    });32  });...

Full Screen

Full Screen

lock-device-specs.js

Source:lock-device-specs.js Github

copy

Full Screen

...5  let driver = session.driver;6  let allowance = 10;7  it(`should lock the device for 4 seconds (+/- ${allowance} secs)`, async function () {8    let before = new Date().getTime() / 1000;9    await driver.lock(4);10    let now = (new Date().getTime() / 1000);11    (now - before).should.be.above(4);12    (now - before).should.be.below(4 + allowance + 1);13  });14  it(`should default to 0 lock the device for +/- ${allowance} secs`, async function () {15    let before = new Date().getTime() / 1000;16    await driver.lock(0);17    let now = (new Date().getTime() / 1000);18    (now - before).should.be.above(0);19    (now - before).should.be.below(allowance + 1);20  });...

Full Screen

Full Screen

steps.js

Source:steps.js Github

copy

Full Screen

...4Given(/^I open the demo app$/, async () => {5    await console.log('Mobile app is open');6});7When(/^I lock device$/, async () => {8    await driver.lock();9});10When(/^I unlock device$/, async () => {11    await driver.unlock();12});13When(/^I navigate to login tab$/, async () => {14    await LandingPage.btnLogin_tap();15});16When(17    /^I initiate login with ([^"]*)? and ([^"]*)?$/,18    async (email, password) => {19        await LoginPage.txtEmail_setText(email);20        await LoginPage.txtPassword_setText(password);21        await LoginPage.btnLogin_tap();22    },...

Full Screen

Full Screen

variables_6c.js

Source:variables_6c.js Github

copy

Full Screen

1var searchData=2[3  ['location',['location',['../structprinter__driver.html#a6a0d5603410d5eda93c0ff341966cce1',1,'printer_driver']]],4  ['lock',['lock',['../structprint__job__list.html#a0abaf4b5d42c4e5d19190035fade3599',1,'print_job_list']]],5  ['logfile',['logfile',['../main_8c.html#ab25a3625a8efbaa3d81ef27bbb51c9c5',1,'main.c']]],6  ['logname',['logname',['../main_8c.html#a9fedf8eb982ca1b1aa71c127d299620d',1,'main.c']]]...

Full Screen

Full Screen

all_6c.js

Source:all_6c.js Github

copy

Full Screen

1var searchData=2[3  ['location',['location',['../structprinter__driver.html#a6a0d5603410d5eda93c0ff341966cce1',1,'printer_driver']]],4  ['lock',['lock',['../structprint__job__list.html#a0abaf4b5d42c4e5d19190035fade3599',1,'print_job_list']]],5  ['logfile',['logfile',['../main_8c.html#ab25a3625a8efbaa3d81ef27bbb51c9c5',1,'main.c']]],6  ['logname',['logname',['../main_8c.html#a9fedf8eb982ca1b1aa71c127d299620d',1,'main.c']]]...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.lock(10);2driver.unlock();3driver.isLocked();4driver.backgroundApp(10);5driver.isAppInstalled("com.android.calculator2");6driver.installApp("C:\\apk\\calculator.apk");7driver.removeApp("com.android.calculator2");8driver.launchApp();9driver.closeApp();10driver.resetApp();11driver.startActivity("com.android.calculator2", "com.android.calculator2.Calculator");12driver.getCurrentPackage();13driver.getCurrentActivity();14driver.getDeviceTime();15driver.pullFile("data/local/tmp/strings.json");16driver.pullFolder("data/local/tmp");17driver.pushFile("data/local/tmp/strings.json", "C:\\apk\\strings.json");18driver.getSettings();19driver.updateSettings({"ignoreUnimportantViews": true});20driver.getSupportedPerformanceDataTypes();21driver.getPerformanceData("com.android.calculator2", "memoryinfo", 10);22driver.getPerformanceDataTypes("com.android.calculator2");23driver.toggleLocationServices();24driver.getNetworkConnection();25driver.setNetworkConnection(0);

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require("webdriverio");2const opts = {3  capabilities: {4  },5};6async function main() {7  try {8    const driver = await wdio.remote(op

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