Best JavaScript code snippet using appium-base-driver
proxy.js
Source: proxy.js
...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) {...
protocol-converter.js
Source: protocol-converter.js
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}...
Using AI Code Generation
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}
Using AI Code Generation
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,
Using AI Code Generation
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});
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
Software testing is fueling the IT sector forward by scaling up the test process and continuous product delivery. Currently, this profession is in huge demand, as it needs certified testers with expertise in automation testing. When it comes to outsourcing software testing jobs, whether it’s an IT company or an individual customer, they all look for accredited professionals. That’s why having an software testing certification has become the need of the hour for the folks interested in the test automation field. A well-known certificate issued by an authorized institute kind vouches that the certificate holder is skilled in a specific technology.
Ruby is a programming language which is well suitable for web automation. Ruby makes an excellent choice because of its clean syntax, focus on built-in library integrations, and an active community. Another benefit of Ruby is that it also allows other programming languages like Java, Python, etc. to be used in order to automate applications written in any other frameworks. Therefore you can use Selenium Ruby to automate any sort of application in your system and test the results in any type of testing environment
I still remember the day when our delivery manager announced that from the next phase, the project is going to be Agile. After attending some training and doing some online research, I realized that as a traditional tester, moving from Waterfall to agile testing team is one of the best learning experience to boost my career. Testing in Agile, there were certain challenges, my roles and responsibilities increased a lot, workplace demanded for a pace which was never seen before. Apart from helping me to learn automation tools as well as improving my domain and business knowledge, it helped me get close to the team and participate actively in product creation. Here I will be sharing everything I learned as a traditional tester moving from Waterfall to Agile.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Mobile App Testing Tutorial.
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!