How to use convertAndProxy method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

proxy.js

Source:proxy.js Github

copy

Full Screen

...234 if (!commandName) {235 return await this.proxy(url, method, body);236 }237 log.debug(`Matched '${url}' to command name '${commandName}'`);238 return await this.protocolConverter.convertAndProxy(commandName, url, method, body);239 }240 async command (url, method, body = null) {241 let response;242 let resBodyObj;243 try {244 [response, resBodyObj] = await this.proxyCommand(url, method, body);245 } catch (err) {246 if (isErrorType(err, errors.ProxyRequestError)) {247 throw err.getActualError();248 }249 throw new errors.UnknownError(err.message);250 }251 const protocol = this.getProtocolFromResBody(resBodyObj);252 if (protocol === MJSONWP) {...

Full Screen

Full Screen

protocol-converter.js

Source:protocol-converter.js Github

copy

Full Screen

1import _ from 'lodash';2import { logger, util } from 'appium-support';3import { duplicateKeys } from '../basedriver/helpers';4import {5 MJSONWP_ELEMENT_KEY, W3C_ELEMENT_KEY, PROTOCOLS6} from '../constants';7import { formatStatus } from '../protocol/helpers';8const log = logger.getLogger('Protocol Converter');9export const COMMAND_URLS_CONFLICTS = [10 {11 commandNames: ['execute', 'executeAsync'],12 jsonwpConverter: (url) => url.replace(/\/execute.*/,13 url.includes('async') ? '/execute_async' : '/execute'),14 w3cConverter: (url) => url.replace(/\/execute.*/,15 url.includes('async') ? '/execute/async' : '/execute/sync'),16 },17 {18 commandNames: ['getElementScreenshot'],19 jsonwpConverter: (url) => url.replace(/\/element\/([^/]+)\/screenshot$/,20 '/screenshot/$1'),21 w3cConverter: (url) => url.replace(/\/screenshot\/([^/]+)/,22 '/element/$1/screenshot'),23 },24 {25 commandNames: ['getWindowHandles', 'getWindowHandle'],26 jsonwpConverter (url) {27 return /\/window$/.test(url)28 ? url.replace(/\/window$/, '/window_handle')29 : url.replace(/\/window\/handle(s?)$/, '/window_handle$1');30 },31 w3cConverter (url) {32 return /\/window_handle$/.test(url)33 ? url.replace(/\/window_handle$/, '/window')34 : url.replace(/\/window_handles$/, '/window/handles');35 },36 },37 {38 commandNames: ['getProperty'],39 jsonwpConverter: (w3cUrl) => {40 const w3cPropertyRegex = /\/element\/([^/]+)\/property\/([^/]+)/;41 const jsonwpUrl = w3cUrl.replace(w3cPropertyRegex, '/element/$1/attribute/$2');42 log.info(`Converting W3C '${w3cUrl}' to '${jsonwpUrl}'`);43 return jsonwpUrl;44 },45 w3cConverter: (jsonwpUrl) => jsonwpUrl // Don't convert JSONWP URL to W3C. W3C accepts /attribute and /property46 }47];48const {MJSONWP, W3C} = PROTOCOLS;49class ProtocolConverter {50 constructor (proxyFunc) {51 this.proxyFunc = proxyFunc;52 this._downstreamProtocol = null;53 }54 set downstreamProtocol (value) {55 this._downstreamProtocol = value;56 }57 get downstreamProtocol () {58 return this._downstreamProtocol;59 }60 /**61 * W3C /timeouts can take as many as 3 timeout types at once, MJSONWP /timeouts only takes one62 * at a time. So if we're using W3C and proxying to MJSONWP and there's more than one timeout type63 * provided in the request, we need to do 3 proxies and combine the result64 *65 * @param {Object} body Request body66 * @return {Array} Array of W3C + MJSONWP compatible timeout objects67 */68 getTimeoutRequestObjects (body) {69 if (this.downstreamProtocol === W3C && _.has(body, 'ms') && _.has(body, 'type')) {70 const typeToW3C = (x) => x === 'page load' ? 'pageLoad' : x;71 return [{72 [typeToW3C(body.type)]: body.ms,73 }];74 }75 if (this.downstreamProtocol === MJSONWP && (!_.has(body, 'ms') || !_.has(body, 'type'))) {76 const typeToJSONWP = (x) => x === 'pageLoad' ? 'page load' : x;77 return _.toPairs(body)78 // Only transform the entry if ms value is a valid positive float number79 .filter((pair) => /^\d+(?:[.,]\d*?)?$/.test(`${pair[1]}`))80 .map(function (pair) {81 return {82 type: typeToJSONWP(pair[0]),83 ms: pair[1],84 };85 });86 }87 return [body];88 }89 /**90 * Proxy an array of timeout objects and merge the result91 * @param {String} url Endpoint url92 * @param {String} method Endpoint method93 * @param {Object} body Request body94 */95 async proxySetTimeouts (url, method, body) {96 let response, resBody;97 const timeoutRequestObjects = this.getTimeoutRequestObjects(body);98 log.debug(`Will send the following request bodies to /timeouts: ${JSON.stringify(timeoutRequestObjects)}`);99 for (const timeoutObj of timeoutRequestObjects) {100 [response, resBody] = await this.proxyFunc(url, method, timeoutObj);101 // If we got a non-MJSONWP response, return the result, nothing left to do102 if (this.downstreamProtocol !== MJSONWP) {103 return [response, resBody];104 }105 // If we got an error, return the error right away106 if (response.statusCode >= 400) {107 return [response, resBody];108 }109 // ...Otherwise, continue to the next timeouts call110 }111 return [response, resBody];112 }113 async proxySetWindow (url, method, body) {114 const bodyObj = util.safeJsonParse(body);115 if (_.isPlainObject(bodyObj)) {116 if (this.downstreamProtocol === W3C && _.has(bodyObj, 'name') && !_.has(bodyObj, 'handle')) {117 log.debug(`Copied 'name' value '${bodyObj.name}' to 'handle' as per W3C spec`);118 return await this.proxyFunc(url, method, {119 ...bodyObj,120 handle: bodyObj.name,121 });122 }123 if (this.downstreamProtocol === MJSONWP && _.has(bodyObj, 'handle') && !_.has(bodyObj, 'name')) {124 log.debug(`Copied 'handle' value '${bodyObj.handle}' to 'name' as per JSONWP spec`);125 return await this.proxyFunc(url, method, {126 ...bodyObj,127 name: bodyObj.handle,128 });129 }130 }131 return await this.proxyFunc(url, method, body);132 }133 async proxySetValue (url, method, body) {134 const bodyObj = util.safeJsonParse(body);135 if (_.isPlainObject(bodyObj) && (util.hasValue(bodyObj.text) || util.hasValue(bodyObj.value))) {136 let {text, value} = bodyObj;137 if (util.hasValue(text) && !util.hasValue(value)) {138 value = _.isString(text)139 ? [...text]140 : (_.isArray(text) ? text : []);141 log.debug(`Added 'value' property ${JSON.stringify(value)} to 'setValue' request body`);142 } else if (!util.hasValue(text) && util.hasValue(value)) {143 text = _.isArray(value)144 ? value.join('')145 : (_.isString(value) ? value : '');146 log.debug(`Added 'text' property ${JSON.stringify(text)} to 'setValue' request body`);147 }148 return await this.proxyFunc(url, method, Object.assign({}, bodyObj, {149 text,150 value,151 }));152 }153 return await this.proxyFunc(url, method, body);154 }155 async proxySetFrame (url, method, body) {156 const bodyObj = util.safeJsonParse(body);157 return _.has(bodyObj, 'id') && _.isPlainObject(bodyObj.id)158 ? await this.proxyFunc(url, method, {159 ...bodyObj,160 id: duplicateKeys(bodyObj.id, MJSONWP_ELEMENT_KEY, W3C_ELEMENT_KEY),161 })162 : await this.proxyFunc(url, method, body);163 }164 async proxyPerformActions (url, method, body) {165 const bodyObj = util.safeJsonParse(body);166 return _.isPlainObject(bodyObj)167 ? await this.proxyFunc(url, method, duplicateKeys(bodyObj, MJSONWP_ELEMENT_KEY, W3C_ELEMENT_KEY))168 : await this.proxyFunc(url, method, body);169 }170 /**171 * Handle "crossing" endpoints for the case172 * when upstream and downstream drivers operate different protocols173 *174 * @param {string} commandName175 * @param {string} url176 * @param {string} method177 * @param {?string|object} body178 * @returns The proxyfying result as [response, responseBody] tuple179 */180 async convertAndProxy (commandName, url, method, body) {181 if (!this.downstreamProtocol) {182 // Patch calls with GENERIC protocol183 // to preserve the backward compatibility184 const [res, resBodyObj] = await this.proxyFunc(url, method, body);185 return [res, formatStatus(resBodyObj, res.statusCode)];186 }187 // Same url, but different arguments188 switch (commandName) {189 case 'timeouts':190 return await this.proxySetTimeouts(url, method, body);191 case 'setWindow':192 return await this.proxySetWindow(url, method, body);193 case 'setValue':194 return await this.proxySetValue(url, method, body);195 case 'performActions':196 return await this.proxyPerformActions(url, method, body);197 case 'setFrame':198 return await this.proxySetFrame(url, method, body);199 default:200 break;201 }202 // Same arguments, but different URLs203 for (const {commandNames, jsonwpConverter, w3cConverter} of COMMAND_URLS_CONFLICTS) {204 if (!commandNames.includes(commandName)) {205 continue;206 }207 const rewrittenUrl = this.downstreamProtocol === MJSONWP208 ? jsonwpConverter(url)209 : w3cConverter(url);210 if (rewrittenUrl === url) {211 log.debug(`Did not know how to rewrite the original URL '${url}' ` +212 `for ${this.downstreamProtocol} protocol`);213 break;214 }215 log.info(`Rewrote the original URL '${url}' to '${rewrittenUrl}' ` +216 `for ${this.downstreamProtocol} protocol`);217 return await this.proxyFunc(rewrittenUrl, method, body);218 }219 // No matches found. Proceed normally220 return await this.proxyFunc(url, method, body);221 }222}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { convertAndProxy } from 'appium-base-driver/build/lib/protocol/protocol';2import { BaseDriver } from 'appium-base-driver';3import { MyDriver } from './my-driver';4const driver = new MyDriver();5const proxyReqRes = convertAndProxy(driver);6const appiumRouter = new AppiumRouter();7appiumRouter.post('/my-driver/execute', proxyReqRes);8import { BaseDriver } from 'appium-base-driver';9import { util } from 'appium-support';10export class MyDriver extends BaseDriver {11 async executeCommand (cmd, ...args) {12 }13}14async executeCommand (cmd, ...args) {15}

Full Screen

Using AI Code Generation

copy

Full Screen

1async function convertAndProxy (driver, url) {2 return await driver.convertAndProxy(url);3}4async function convertAndProxy (driver, url) {5 return await driver.convertAndProxy(url);6}7async function convertAndProxy (driver, url) {8 return await driver.convertAndProxy(url);9}10async function convertAndProxy (driver, url) {11 return await driver.convertAndProxy(url);12}13async function convertAndProxy (driver, url) {14 return await driver.convertAndProxy(url);15}16async function convertAndProxy (driver, url) {17 return await driver.convertAndProxy(url);18}19async function convertAndProxy (driver, url) {20 return await driver.convertAndProxy(url);21}22async function convertAndProxy (driver, url) {23 return await driver.convertAndProxy(url);24}25async function convertAndProxy (driver, url) {26 return await driver.convertAndProxy(url);27}28async function convertAndProxy (driver, url) {29 return await driver.convertAndProxy(url);30}31async function convertAndProxy (driver, url) {32 return await driver.convertAndProxy(url);33}34async function convertAndProxy (driver, url) {35 return await driver.convertAndProxy(url);36}37async function convertAndProxy (driver, url) {38 return await driver.convertAndProxy(url);39}40async function convertAndProxy (driver, url) {41 return await driver.convertAndProxy(url);42}43async function convertAndProxy (driver,

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumBaseDriver = require('appium-base-driver');2const {convertAndProxy} = AppiumBaseDriver.prototype;3const args = {4 headers: {},5 json: {},6};7convertAndProxy(args).then((res) => {8 console.log(res);9}).catch((err) => {10 console.log(err);11});12const BaseDriver = require('appium-base-driver');13const {convertAndProxy} = BaseDriver.prototype;14const args = {15 headers: {},16 json: {},17};18convertAndProxy(args).then((res) => {19 console.log(res);20}).catch((err) => {21 console.log(err);22});

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