How to use getCoordDefault method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

controller.js

Source:controller.js Github

copy

Full Screen

...429    // thing with destElement below.430    return hasValue(val) ? val : 0.5;431  };432  var touchCount = req.body.touchCount || 1433    , startX =  getCoordDefault(gestures[0].options.x)434    , startY = getCoordDefault(gestures[0].options.y)435    , endX = getCoordDefault(gestures[2].options.x)436    , endY = getCoordDefault(gestures[2].options.y)437    , duration = _getSwipeTouchDuration(gestures[1])438    , element = gestures[0].options.element439    , destElement = gestures[2].options.element || gestures[0].options.element;440  // there's no destination element handling in bootstrap and since it applies to all platforms, we handle it here441  if (hasValue(destElement)) {442    req.device.getLocation(destElement, function (err, locResult) {443      if (err) {444        respondError(req, res, err);445      } else {446        req.device.getSize(destElement, function (er, sizeResult) {447          if (er) {448            respondError(req, res, er);449          } else {450            var offsetX = (Math.abs(endX) < 1 && Math.abs(endX) > 0) ?...

Full Screen

Full Screen

driver.js

Source:driver.js Github

copy

Full Screen

...326    }327    this.clearNewCommandTimeout();328  }329  async getSwipeOptions (gestures, touchCount = 1) {330    let startX = this.helpers.getCoordDefault(gestures[0].options.x),331        startY = this.helpers.getCoordDefault(gestures[0].options.y),332        endX = this.helpers.getCoordDefault(gestures[2].options.x),333        endY = this.helpers.getCoordDefault(gestures[2].options.y),334        duration = this.helpers.getSwipeTouchDuration(gestures[1]),335        element = gestures[0].options.element,336        destElement = gestures[2].options.element || gestures[0].options.element;337    // there's no destination element handling in bootstrap and since it applies to all platforms, we handle it here338    if (util.hasValue(destElement)) {339      let locResult = await this.getLocationInView(destElement);340      let sizeResult = await this.getSize(destElement);341      let offsetX = (Math.abs(endX) < 1 && Math.abs(endX) > 0) ? sizeResult.width * endX : endX;342      let offsetY = (Math.abs(endY) < 1 && Math.abs(endY) > 0) ? sizeResult.height * endY : endY;343      endX = locResult.x + offsetX;344      endY = locResult.y + offsetY;345      // if the target element was provided, the coordinates for the destination need to be relative to it.346      if (util.hasValue(element)) {347        let firstElLocation = await this.getLocationInView(element);...

Full Screen

Full Screen

helpers.js

Source:helpers.js Github

copy

Full Screen

1import _ from 'lodash';2import path from 'path';3import url from 'url';4import logger from './logger';5import _fs from 'fs';6import B from 'bluebird';7import { tempDir, fs, util, zip } from 'appium-support';8import request from 'request';9import asyncRequest from 'request-promise';10import LRU from 'lru-cache';11import AsyncLock from 'async-lock';12import sanitize from 'sanitize-filename';13const ZIP_EXTS = ['.zip', '.ipa'];14const ZIP_MIME_TYPES = [15  'application/zip',16  'application/x-zip-compressed',17  'multipart/x-zip',18];19const APPLICATIONS_CACHE = new LRU({20  max: 100,21});22const APPLICATIONS_CACHE_GUARD = new AsyncLock();23const SANITIZE_REPLACEMENT = '-';24const DEFAULT_BASENAME = 'appium-app';25async function retrieveHeaders (link) {26  try {27    const response = await asyncRequest({28      url: link,29      method: 'HEAD',30      resolveWithFullResponse: true,31      timeout: 5000,32    });33    return response.headers;34  } catch (e) {35    logger.debug(`Cannot send HEAD request to '${link}'. Original error: ${e.message}`);36  }37  return {};38}39function getCachedApplicationPath (link, currentModified) {40  if (!APPLICATIONS_CACHE.has(link) || !currentModified) {41    return null;42  }43  const {lastModified, fullPath} = APPLICATIONS_CACHE.get(link);44  if (lastModified && currentModified.getTime() <= lastModified.getTime()) {45    logger.debug(`Reusing already downloaded application at '${fullPath}'`);46    return fullPath;47  }48  logger.debug(`'Last-Modified' timestamp of '${link}' has been updated. ` +49    `An updated copy of the application is going to be downloaded.`);50  return null;51}52function verifyAppExtension (app, supportedAppExtensions) {53  if (supportedAppExtensions.includes(path.extname(app))) {54    return app;55  }56  throw new Error(`New app path '${app}' did not have extension(s) '${supportedAppExtensions}'`);57}58async function configureApp (app, supportedAppExtensions) {59  if (!_.isString(app)) {60    // immediately shortcircuit if not given an app61    return;62  }63  if (!_.isArray(supportedAppExtensions)) {64    supportedAppExtensions = [supportedAppExtensions];65  }66  let newApp = app;67  let shouldUnzipApp = false;68  let archiveHash = null;69  let currentModified = null;70  const {protocol, pathname} = url.parse(newApp);71  const isUrl = ['http:', 'https:'].includes(protocol);72  return await APPLICATIONS_CACHE_GUARD.acquire(app, async () => {73    if (isUrl) {74      // Use the app from remote URL75      logger.info(`Using downloadable app '${newApp}'`);76      const headers = await retrieveHeaders(newApp);77      if (headers['last-modified']) {78        logger.debug(`Last-Modified: ${headers['last-modified']}`);79        currentModified = new Date(headers['last-modified']);80      }81      const cachedPath = getCachedApplicationPath(app, currentModified);82      if (cachedPath) {83        if (await fs.exists(cachedPath)) {84          logger.info(`Reusing the previously downloaded application at '${cachedPath}'`);85          return verifyAppExtension(cachedPath, supportedAppExtensions);86        }87        logger.info(`The application at '${cachedPath}' does not exist anymore. Deleting it from the cache`);88        APPLICATIONS_CACHE.del(app);89      }90      let fileName = null;91      const basename = sanitize(path.basename(decodeURIComponent(pathname)), {92        replacement: SANITIZE_REPLACEMENT93      });94      const extname = path.extname(basename);95      // to determine if we need to unzip the app, we have a number of places96      // to look: content type, content disposition, or the file extension97      if (ZIP_EXTS.includes(extname)) {98        fileName = basename;99        shouldUnzipApp = true;100      }101      if (headers['content-type']) {102        logger.debug(`Content-Type: ${headers['content-type']}`);103        // the filetype may not be obvious for certain urls, so check the mime type too104        if (ZIP_MIME_TYPES.some(mimeType => new RegExp(`\\b${_.escapeRegExp(mimeType)}\\b`).test(headers['content-type']))) {105          if (!fileName) {106            fileName = `${DEFAULT_BASENAME}.zip`;107          }108          shouldUnzipApp = true;109        }110      }111      if (headers['content-disposition'] && /^attachment/i.test(headers['content-disposition'])) {112        logger.debug(`Content-Disposition: ${headers['content-disposition']}`);113        const match = /filename="([^"]+)/i.exec(headers['content-disposition']);114        if (match) {115          fileName = sanitize(match[1], {116            replacement: SANITIZE_REPLACEMENT117          });118          shouldUnzipApp = shouldUnzipApp || ZIP_EXTS.includes(path.extname(fileName));119        }120      }121      if (!fileName) {122        // assign the default file name and the extension if none has been detected123        const resultingName = basename124          ? basename.substring(0, basename.length - extname.length)125          : DEFAULT_BASENAME;126        let resultingExt = extname;127        if (!supportedAppExtensions.includes(resultingExt)) {128          logger.info(`The current file extension '${resultingExt}' is not supported. ` +129            `Defaulting to '${_.first(supportedAppExtensions)}'`);130          resultingExt = _.first(supportedAppExtensions);131        }132        fileName = `${resultingName}${resultingExt}`;133      }134      const targetPath = await tempDir.path({135        prefix: fileName,136        suffix: '',137      });138      newApp = await downloadApp(newApp, targetPath);139    } else if (await fs.exists(newApp)) {140      // Use the local app141      logger.info(`Using local app '${newApp}'`);142      shouldUnzipApp = ZIP_EXTS.includes(path.extname(newApp));143    } else {144      let errorMessage = `The application at '${newApp}' does not exist or is not accessible`;145      // protocol value for 'C:\\temp' is 'c:', so we check the length as well146      if (_.isString(protocol) && protocol.length > 2) {147        errorMessage = `The protocol '${protocol}' used in '${newApp}' is not supported. ` +148          `Only http: and https: protocols are supported`;149      }150      throw new Error(errorMessage);151    }152    if (shouldUnzipApp) {153      const archivePath = newApp;154      archiveHash = await fs.hash(archivePath);155      if (APPLICATIONS_CACHE.has(app) && archiveHash === APPLICATIONS_CACHE.get(app).hash) {156        const {fullPath} = APPLICATIONS_CACHE.get(app);157        if (await fs.exists(fullPath)) {158          if (archivePath !== app) {159            await fs.rimraf(archivePath);160          }161          logger.info(`Will reuse previously cached application at '${fullPath}'`);162          return verifyAppExtension(fullPath, supportedAppExtensions);163        }164        logger.info(`The application at '${fullPath}' does not exist anymore. Deleting it from the cache`);165        APPLICATIONS_CACHE.del(app);166      }167      const tmpRoot = await tempDir.openDir();168      try {169        newApp = await unzipApp(archivePath, tmpRoot, supportedAppExtensions);170      } finally {171        if (newApp !== archivePath && archivePath !== app) {172          await fs.rimraf(archivePath);173        }174      }175      logger.info(`Unzipped local app to '${newApp}'`);176    } else if (!path.isAbsolute(newApp)) {177      newApp = path.resolve(process.cwd(), newApp);178      logger.warn(`The current application path '${app}' is not absolute ` +179        `and has been rewritten to '${newApp}'. Consider using absolute paths rather than relative`);180      app = newApp;181    }182    verifyAppExtension(newApp, supportedAppExtensions);183    if (app !== newApp && (archiveHash || currentModified)) {184      APPLICATIONS_CACHE.set(app, {185        hash: archiveHash,186        lastModified: currentModified,187        fullPath: newApp,188      });189    }190    return newApp;191  });192}193async function downloadApp (app, targetPath) {194  const {href} = url.parse(app);195  const started = process.hrtime();196  try {197    // don't use request-promise here, we need streams198    await new B((resolve, reject) => {199      request(href)200        .on('error', reject) // handle real errors, like connection errors201        .on('response', (res) => {202          // handle responses that fail, like 404s203          if (res.statusCode >= 400) {204            return reject(new Error(`${res.statusCode} - ${res.statusMessage}`));205          }206        })207        .pipe(_fs.createWriteStream(targetPath))208        .on('close', resolve);209    });210  } catch (err) {211    throw new Error(`Problem downloading app from url ${href}: ${err.message}`);212  }213  const [seconds, ns] = process.hrtime(started);214  const secondsElapsed = seconds + ns / 1e09;215  const {size} = await fs.stat(targetPath);216  logger.debug(`'${href}' (${util.toReadableSizeString(size)}) ` +217    `has been downloaded to '${targetPath}' in ${secondsElapsed.toFixed(3)}s`);218  if (secondsElapsed >= 2) {219    const bytesPerSec = Math.floor(size / secondsElapsed);220    logger.debug(`Approximate download speed: ${util.toReadableSizeString(bytesPerSec)}/s`);221  }222  return targetPath;223}224async function walkDir (dir) {225  const result = [];226  for (const name of await fs.readdir(dir)) {227    const currentPath = path.join(dir, name);228    result.push(currentPath);229    if ((await fs.stat(currentPath)).isDirectory()) {230      result.push(...(await walkDir(currentPath)));231    }232  }233  return result;234}235async function unzipApp (zipPath, dstRoot, supportedAppExtensions) {236  await zip.assertValidZip(zipPath);237  if (!_.isArray(supportedAppExtensions)) {238    supportedAppExtensions = [supportedAppExtensions];239  }240  const tmpRoot = await tempDir.openDir();241  try {242    logger.debug(`Unzipping '${zipPath}'`);243    await zip.extractAllTo(zipPath, tmpRoot);244    const allExtractedItems = await walkDir(tmpRoot);245    logger.debug(`Extracted ${allExtractedItems.length} item(s) from '${zipPath}'`);246    const isSupportedAppItem = (relativePath) => supportedAppExtensions.includes(path.extname(relativePath))247      || _.some(supportedAppExtensions, (x) => relativePath.includes(`${x}${path.sep}`));248    const itemsToKeep = allExtractedItems249      .map((itemPath) => path.relative(tmpRoot, itemPath))250      .filter((relativePath) => isSupportedAppItem(relativePath))251      .map((relativePath) => path.resolve(tmpRoot, relativePath));252    const itemsToRemove = _.difference(allExtractedItems, itemsToKeep)253      // Avoid parent folders to be recursively removed254      .filter((itemToRemovePath) => !_.some(itemsToKeep, (itemToKeepPath) => itemToKeepPath.startsWith(itemToRemovePath)));255    await B.all(itemsToRemove, async (itemPath) => {256      if (await fs.exists(itemPath)) {257        await fs.rimraf(itemPath);258      }259    });260    const allBundleItems = (await walkDir(tmpRoot))261      .map((itemPath) => path.relative(tmpRoot, itemPath))262      .filter((relativePath) => isSupportedAppItem(relativePath))263      // Get the top level match264      .sort((a, b) => a.split(path.sep).length - b.split(path.sep).length);265    if (_.isEmpty(allBundleItems)) {266      throw new Error(`App zip unzipped OK, but we could not find ${supportedAppExtensions} bundle(s) ` +267        `in it. Make sure your archive contains ${supportedAppExtensions} package(s) ` +268        `and nothing else`);269    }270    const matchedBundle = _.first(allBundleItems);271    logger.debug(`Matched ${allBundleItems.length} item(s) in the extracted archive. ` +272      `Assuming '${matchedBundle}' is the correct bundle`);273    await fs.mv(path.resolve(tmpRoot, matchedBundle), path.resolve(dstRoot, matchedBundle), {274      mkdirp: true275    });276    return path.resolve(dstRoot, matchedBundle);277  } finally {278    await fs.rimraf(tmpRoot);279  }280}281function isPackageOrBundle (app) {282  return (/^([a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+)+$/).test(app);283}284function getCoordDefault (val) {285  // going the long way and checking for undefined and null since286  // we can't be assured `elId` is a string and not an int. Same287  // thing with destElement below.288  return util.hasValue(val) ? val : 0.5;289}290function getSwipeTouchDuration (waitGesture) {291  // the touch action api uses ms, we want seconds292  // 0.8 is the default time for the operation293  let duration = 0.8;294  if (typeof waitGesture.options.ms !== 'undefined' && waitGesture.options.ms) {295    duration = waitGesture.options.ms / 1000;296    if (duration === 0) {297      // set to a very low number, since they wanted it fast298      // but below 0.1 becomes 0 steps, which causes errors299      duration = 0.1;300    }301  }302  return duration;303}304/**305 * Finds all instances 'firstKey' and create a duplicate with the key 'secondKey',306 * Do the same thing in reverse. If we find 'secondKey', create a duplicate with the key 'firstKey'.307 *308 * This will cause keys to be overwritten if the object contains 'firstKey' and 'secondKey'.309 * @param {*} input Any type of input310 * @param {String} firstKey The first key to duplicate311 * @param {String} secondKey The second key to duplicate312 */313function duplicateKeys (input, firstKey, secondKey) {314  // If array provided, recursively call on all elements315  if (_.isArray(input)) {316    return input.map((item) => duplicateKeys(item, firstKey, secondKey));317  }318  // If object, create duplicates for keys and then recursively call on values319  if (_.isPlainObject(input)) {320    const resultObj = {};321    for (let [key, value] of _.toPairs(input)) {322      const recursivelyCalledValue = duplicateKeys(value, firstKey, secondKey);323      if (key === firstKey) {324        resultObj[secondKey] = recursivelyCalledValue;325      } else if (key === secondKey) {326        resultObj[firstKey] = recursivelyCalledValue;327      }328      resultObj[key] = recursivelyCalledValue;329    }330    return resultObj;331  }332  // Base case. Return primitives without doing anything.333  return input;334}335/**336 * Takes a desired capability and tries to JSON.parse it as an array,337 * and either returns the parsed array or a singleton array.338 *339 * @param {string|Array<String>} cap A desired capability340 */341function parseCapsArray (cap) {342  let parsedCaps;343  try {344    parsedCaps = JSON.parse(cap);345    if (_.isArray(parsedCaps)) {346      return parsedCaps;347    }348  } catch (ign) {349    logger.warn(`Failed to parse capability as JSON array`);350  }351  if (_.isString(cap)) {352    return [cap];353  }354  throw new Error(`must provide a string or JSON Array; received ${cap}`);355}356export {357  configureApp, isPackageOrBundle, getCoordDefault, getSwipeTouchDuration, duplicateKeys, parseCapsArray...

Full Screen

Full Screen

touch.js

Source:touch.js Github

copy

Full Screen

...142    throw e;143  }144};145commands.getSwipeOptions = async function getSwipeOptions (gestures, touchCount = 1) {146  let startX = getCoordDefault(gestures[0].options.x),147      startY = getCoordDefault(gestures[0].options.y),148      endX = getCoordDefault(gestures[2].options.x),149      endY = getCoordDefault(gestures[2].options.y),150      duration = getSwipeTouchDuration(gestures[1]),151      element = gestures[0].options.element,152      destElement = gestures[2].options.element || gestures[0].options.element;153  // there's no destination element handling in bootstrap and since it applies to all platforms, we handle it here154  if (util.hasValue(destElement)) {155    let locResult = await this.getLocationInView(destElement);156    let sizeResult = await this.getSize(destElement);157    let offsetX = (Math.abs(endX) < 1 && Math.abs(endX) > 0) ? sizeResult.width * endX : endX;158    let offsetY = (Math.abs(endY) < 1 && Math.abs(endY) > 0) ? sizeResult.height * endY : endY;159    endX = locResult.x + offsetX;160    endY = locResult.y + offsetY;161    // if the target element was provided, the coordinates for the destination need to be relative to it.162    if (util.hasValue(element)) {163      let firstElLocation = await this.getLocationInView(element);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const wdio = require('webdriverio');3const opts = {4  capabilities: {5  }6};7(async () => {8  const client = await wdio.remote(opts);9  const location = await el.getLocation();10  const size = await el.getSize();11  const x = location.x + size.width / 2;12  const y = location.y + size.height / 2;13  const res = await client.touchPerform([{14    options: { x, y }15  }]);16  await client.pause(2000);17  const location1 = await el1.getLocation();18  const size1 = await el1.getSize();19  const x1 = location1.x + size1.width / 2;20  const y1 = location1.y + size1.height / 2;21  const res1 = await client.touchPerform([{22    options: { x: x1, y: y1 }23  }]);24  await client.pause(2000);25  const location2 = await el2.getLocation();26  const size2 = await el2.getSize();27  const x2 = location2.x + size2.width / 2;28  const y2 = location2.y + size2.height / 2;29  const res2 = await client.touchPerform([{30    options: { x: x2, y: y2 }31  }]);32  await client.pause(2000);33  const location3 = await el3.getLocation();34  const size3 = await el3.getSize();35  const x3 = location3.x + size3.width / 2;36  const y3 = location3.y + size3.height / 2;37  const res3 = await client.touchPerform([{

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new AndroidDriver();2driver.getCoordDefault();3var driver = new IOSDriver();4driver.getCoordDefault();5var driver = new WindowsDriver();6driver.getCoordDefault();7var driver = new MacDriver();8driver.getCoordDefault();9var driver = new LinuxDriver();10driver.getCoordDefault();11var driver = new ChromeDriver();12driver.getCoordDefault();13var driver = new FirefoxDriver();14driver.getCoordDefault();15var driver = new OperaDriver();16driver.getCoordDefault();17var driver = new SafariDriver();18driver.getCoordDefault();19var driver = new EdgeDriver();20driver.getCoordDefault();21var driver = new IEDriver();22driver.getCoordDefault();23var driver = new PhantomJSDriver();24driver.getCoordDefault();25var driver = new HTMLUnitDriver();26driver.getCoordDefault();27var driver = new HtmlUnitWithJSDriver();28driver.getCoordDefault();29var driver = new InternetExplorerDriver();30driver.getCoordDefault();31var driver = new AndroidDriver();32driver.getCoordDefault();33var driver = new IosDriver();34driver.getCoordDefault();35var driver = new WindowsDriver();36driver.getCoordDefault();37var driver = new MacDriver();38driver.getCoordDefault();

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.getCoordDefault();2driver.getCoord();3driver.getCoordDefault();4driver.getCoord();5driver.getCoordDefault();6driver.getCoord();7driver.getCoordDefault();8driver.getCoord();9driver.getCoordDefault();10driver.getCoord();11driver.getCoordDefault();12driver.getCoord();13driver.getCoordDefault();14driver.getCoord();15driver.getCoordDefault();16driver.getCoord();17driver.getCoordDefault();18driver.getCoord();19driver.getCoordDefault();20driver.getCoord();21driver.getCoordDefault();22driver.getCoord();23driver.getCoordDefault();24driver.getCoord();25driver.getCoordDefault();26driver.getCoord();27driver.getCoordDefault();28driver.getCoord();

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.init(caps).then(function() {2    return driver.getCoordDefault();3}).then(function(coord) {4    console.log('coord: ' + JSON.stringify(coord));5}).fin(function() {6    return driver.quit();7}).done();8commands.getCoordDefault = async function () {9    return await this.adb.getCoordDefault();10};11helpers.getCoordDefault = async function () {12    let apiLevel = await this.getApiLevel();13    if (apiLevel < 17) {14        return {x: 0.5, y: 0.5};15    } else {16        return {x: 0.5, y: 0.85};17    }18};19methods.getCoordDefault = async function () {20    let apiLevel = await this.getApiLevel();21    if (apiLevel < 17) {22        return {x: 0.5, y: 0.5};23    } else {24        return {x: 0.5, y: 0.85};25    }26};27commands.getApiLevel = async function () {28    let out = await this.shell(['getprop', 'ro.build.version.sdk']);29    return parseInt(out, 10);30};31commands.shell = async function (cmd, opts = {}) {32    if (typeof cmd === 'string') {33        cmd = cmd.split(' ');34    }35    return await this.exec(['shell', ...cmd], opts);36};37commands.exec = async function (cmd, opts = {}) {38    let {timeout} = opts;39    if (timeout === undefined) {40        timeout = this.execTimeout;41    }42    return await this.adbExec(cmd, {timeout});43};44adbExec (cmd, opts = {}) {45    log.debug(`Sending command to android: ${cmd}`);46    return new B(async (resolve, reject) => {47      try {48        let stdout = await exec(this.executable

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var _ = require('underscore');4var androidDriver = wd.remote("localhost", 4723);5androidDriver.init({6}, function() {7    androidDriver.elementByName("my_text_field", function(err, el) {8        assert.ok(!err, err);9        el.text(function(err, txt) {10            assert.ok(!err, err);11            assert.ok(txt === "Enter text here");12        });13    });14});15androidDriver.getCoordDefault(function(err,coord) {16    assert.ok(!err, err);17    console.log(coord);18});19androidDriver.quit();20{ x: 0, y: 0, width: 480, height: 800 }

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