How to use getSwipeTouchDuration method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

driver.js

Source:driver.js Github

copy

Full Screen

...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);348 endX -= firstElLocation.x;...

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

...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);164 endX -= firstElLocation.x;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3driver.init({4}).then(function() {5 return driver.getSwipeTouchDuration();6}).then(function(duration) {7 console.log("Swipe Touch Duration is: " + duration);8}).fin(function() { return driver.quit(); }).done();

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.init({2}).then(function() {3 return driver.getSwipeTouchDuration();4}).then(function(duration) {5 console.log(duration);6});7commands.getSwipeTouchDuration = function() {8 return this.adb.getSwipeTouchDuration();9};10ADB.prototype.getSwipeTouchDuration = function() {11 return this.shell("settings get system touch_slop").then(function(stdout) {12 return parseInt(stdout, 10);13 });14};15ADB.prototype.shell = function(cmd, cb) {16 return this.exec("shell", cmd.replace(/"/g, "\\\""), cb);17};18ADB.prototype.exec = function() {19 var args = _.toArray(arguments);20 var cmd = this.adbCmd;21 cmd.push.apply(cmd, args);22 return new B(cmd, { maxBuffer: 524288 }).run();23};24function B(cmd, opts) {25 this.cmd = cmd;26 this.opts = opts;27 this.timeoutMs = opts.timeout || 0;28 this.proc = null;29 this.out = null;30 this.err = null;31 this.didTimeout = false;32 this.killed = false;33 this.onTimeout = null;34 this.onKill = null;35 this.onOutput = null;36 this.onStdout = null;37 this.onStderr = null;38 this.onExit = null;39 this.onDone = null;40 this.exitCode = null;41 this.exitSignal = null;42 this.spawnedProcesses = [];43 this.spawnedProcessesKilled = false;44 this.proc = spawn(cmd[0], cmd.slice(1), opts);45 this.proc.on('error', this._handleError.bind(this));46 this.proc.on('exit', this._handleExit.bind(this));47 this.proc.stdout.on('data', this._handleStdout.bind(this));48 this.proc.stderr.on('data', this._handleStderr.bind(this));49 if (this.timeoutMs)

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.findElement(webdriver.By.name('q')).sendKeys('Appium');4driver.findElement(webdriver.By.name('btnK')).click();5driver.wait(function() {6 return driver.getTitle().then(function(title) {7 return title === 'Appium - Google Search';8 });9}, 1000);10driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6 .init(desired)7 .sleep(5000)8 .getSwipeTouchDuration()9 .then(function (duration) {10 assert.equal(duration, 800);11 })12 .fin(function () { return driver.quit(); })13 .done();14var wd = require('wd');15var assert = require('assert');16var desired = {17};18var driver = wd.promiseChainRemote('localhost', 4723);19 .init(desired)20 .sleep(5000)21 .getWaitForIdleTimeout()22 .then(function (timeout) {23 assert.equal(timeout, 10000);24 })25 .fin(function () { return driver.quit(); })26 .done();27var wd = require('wd');28var assert = require('assert');29var desired = {30};31var driver = wd.promiseChainRemote('localhost', 4723);32 .init(desired)33 .sleep(5000)34 .getWaitForSelectorTimeout()35 .then(function (timeout) {36 assert.equal(timeout, 10000);37 })38 .fin(function () { return driver.quit(); })39 .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var caps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6 .init(caps)7 .elementById('Views')8 .click()9 .elementById('Drag and Drop')10 .click()11 .elementById('io.appium.android.apis:id/drag_dot_1')12 .then(function(el) {13 .getSwipeTouchDuration(el, 100, 100)14 .then(function(duration) {15 return driver.swipe(el, 100, 100, duration);16 });17 })18 .sleep(1000)19 .quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var driver = wd.promiseChainRemote();3driver.init({4}).then(function() {5 return driver.getSwipeTouchDuration();6}).then(function(duration) {7 console.log('duration = ' + duration);8});9var wd = require('wd');10var driver = wd.promiseChainRemote();11driver.init({12}).then(function() {13 return driver.setSwipeTouchDuration(1000);14}).then(function() {15 console.log('duration set to 1000');16});17var wd = require('wd');18var driver = wd.promiseChainRemote();19driver.init({20}).then(function() {21 return driver.getSettings();22}).then(function(settings) {23 console.log('settings = ' + JSON.stringify(settings));24});25var wd = require('wd');26var driver = wd.promiseChainRemote();27driver.init({28}).then(function() {29 return driver.updateSettings({'ignoreUnimportantViews': true});30}).then(function() {31 console.log('settings updated');32});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should work', function() {3 browser.wait(function() {4 return browser.driver.getSwipeTouchDuration().then(function(duration) {5 return duration > 0;6 });7 });8 });9});

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