Best JavaScript code snippet using appium-base-driver
server.js
Source:server.js
1import path from 'path';2import express from 'express';3import http from 'http';4import favicon from 'serve-favicon';5import bodyParser from 'body-parser';6import methodOverride from 'method-override';7import log from './logger';8import { startLogFormatter, endLogFormatter } from './express-logging';9import { allowCrossDomain, fixPythonContentType, defaultToJSONContentType,10 catchAllHandler, catch404Handler, catch4XXHandler,11 allowCrossDomainAsyncExecute} from './middleware';12import { guineaPig, guineaPigScrollable, guineaPigAppBanner, welcome, STATIC_DIR } from './static';13import { produceError, produceCrash } from './crash';14import { addWebSocketHandler, removeWebSocketHandler, removeAllWebSocketHandlers,15 getWebSocketHandlers } from './websocket';16import B from 'bluebird';17async function server (configureRoutes, port, hostname = null, allowCors = true) {18 // create the actual http server19 const app = express();20 let httpServer = http.createServer(app);21 httpServer.addWebSocketHandler = addWebSocketHandler;22 httpServer.removeWebSocketHandler = removeWebSocketHandler;23 httpServer.removeAllWebSocketHandlers = removeAllWebSocketHandlers;24 httpServer.getWebSocketHandlers = getWebSocketHandlers;25 // http.Server.close() only stops new connections, but we need to wait until26 // all connections are closed and the `close` event is emitted27 const close = httpServer.close.bind(httpServer);28 httpServer.close = async () => {29 return await new B((resolve, reject) => {30 httpServer.on('close', resolve);31 close((err) => {32 if (err) reject(err); // eslint-disable-line curly33 });34 });35 };36 return await new B((resolve, reject) => {37 httpServer.on('error', (err) => {38 if (err.code === 'EADDRNOTAVAIL') {39 log.error('Could not start REST http interface listener. ' +40 'Requested address is not available.');41 } else {42 log.error('Could not start REST http interface listener. The requested ' +43 'port may already be in use. Please make sure there is no ' +44 'other instance of this server running already.');45 }46 reject(err);47 });48 httpServer.on('connection', (socket) => {49 socket.setTimeout(600 * 1000); // 10 minute timeout50 socket.on('error', reject);51 });52 configureServer(app, configureRoutes, allowCors);53 let serverArgs = [port];54 if (hostname) {55 // If the hostname is omitted, the server will accept56 // connections on any IP address57 serverArgs.push(hostname);58 }59 httpServer.listen(...serverArgs, (err) => {60 if (err) {61 reject(err);62 }63 resolve(httpServer);64 });65 });66}67function configureServer (app, configureRoutes, allowCors = true) {68 app.use(endLogFormatter);69 // set up static assets70 app.use(favicon(path.resolve(STATIC_DIR, 'favicon.ico')));71 app.use(express.static(STATIC_DIR));72 // crash routes, for testing73 app.use('/wd/hub/produce_error', produceError);74 app.use('/wd/hub/crash', produceCrash);75 // add middlewares76 if (allowCors) {77 app.use(allowCrossDomain);78 } else {79 app.use(allowCrossDomainAsyncExecute);80 }81 app.use(fixPythonContentType);82 app.use(defaultToJSONContentType);83 app.use(bodyParser.urlencoded({extended: true}));84 app.use(methodOverride());85 app.use(catch4XXHandler);86 app.use(catchAllHandler);87 // make sure appium never fails because of a file size upload limit88 app.use(bodyParser.json({limit: '1gb'}));89 // set up start logging (which depends on bodyParser doing its thing)90 app.use(startLogFormatter);91 configureRoutes(app);92 // dynamic routes for testing, etc.93 app.all('/welcome', welcome);94 app.all('/test/guinea-pig', guineaPig);95 app.all('/test/guinea-pig-scrollable', guineaPigScrollable);96 app.all('/test/guinea-pig-app-banner', guineaPigAppBanner);97 // catch this last, so anything that falls through is 404ed98 app.use(catch404Handler);99}...
middleware.js
Source:middleware.js
1import _ from 'lodash';2import log from './logger';3import { errors } from '../protocol';4import { handleIdempotency } from './idempotency';5function allowCrossDomain (req, res, next) {6 try {7 res.header('Access-Control-Allow-Origin', '*');8 res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');9 res.header('Access-Control-Allow-Headers', 'Cache-Control, Pragma, Origin, X-Requested-With, Content-Type, Accept, User-Agent');10 // need to respond 200 to OPTIONS11 if ('OPTIONS' === req.method) {12 return res.sendStatus(200);13 }14 } catch (err) {15 log.error(`Unexpected error: ${err.stack}`);16 }17 next();18}19function allowCrossDomainAsyncExecute (basePath) {20 return (req, res, next) => {21 // there are two paths for async responses, so cover both22 // https://regex101.com/r/txYiEz/123 const receiveAsyncResponseRegExp = new RegExp(`${_.escapeRegExp(basePath)}/session/[a-f0-9-]+/(appium/)?receive_async_response`);24 if (!receiveAsyncResponseRegExp.test(req.url)) {25 return next();26 }27 allowCrossDomain(req, res, next);28 };29}30function fixPythonContentType (basePath) {31 return (req, res, next) => {32 // hack because python client library gives us wrong content-type33 if (new RegExp(`^${_.escapeRegExp(basePath)}`).test(req.path) && /^Python/.test(req.headers['user-agent'])) {34 if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {35 req.headers['content-type'] = 'application/json; charset=utf-8';36 }37 }38 next();39 };40}41function defaultToJSONContentType (req, res, next) {42 if (!req.headers['content-type']) {43 req.headers['content-type'] = 'application/json; charset=utf-8';44 }45 next();46}47function catchAllHandler (err, req, res, next) {48 if (res.headersSent) {49 return next(err);50 }51 log.error(`Uncaught error: ${err.message}`);52 log.error('Sending generic error response');53 const error = errors.UnknownError;54 res.status(error.w3cStatus()).json(patchWithSessionId(req, {55 status: error.code(),56 value: {57 error: error.error(),58 message: `An unknown server-side error occurred while processing the command: ${err.message}`,59 stacktrace: err.stack,60 }61 }));62 log.error(err);63}64function catch404Handler (req, res) {65 log.debug(`No route found for ${req.url}`);66 const error = errors.UnknownCommandError;67 res.status(error.w3cStatus()).json(patchWithSessionId(req, {68 status: error.code(),69 value: {70 error: error.error(),71 message: 'The requested resource could not be found, or a request was ' +72 'received using an HTTP method that is not supported by the mapped ' +73 'resource',74 stacktrace: '',75 }76 }));77}78const SESSION_ID_PATTERN = /\/session\/([^/]+)/;79function patchWithSessionId (req, body) {80 const match = SESSION_ID_PATTERN.exec(req.url);81 if (match) {82 body.sessionId = match[1];83 }84 return body;85}86export {87 allowCrossDomain, fixPythonContentType, defaultToJSONContentType,88 catchAllHandler, allowCrossDomainAsyncExecute, handleIdempotency,89 catch404Handler,...
Using AI Code Generation
1const path = require('path');2const wd = require('wd');3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5const { exec } = require('teen_process');6const { fs, util } = require('appium-support');7const B = require('bluebird');8const { system, net } = require('appium-support');9const _ = require('lodash');10const should = chai.should();11chai.use(chaiAsPromised);12const TEST_APP = path.resolve(__dirname, '..', '..', '..', 'test', 'fixtures', 'appium-uiauto', 'TestApp.app.zip');13const TEST_APP_BUNDLE_ID = 'io.appium.TestApp';14const TEST_APP_ACTIVITY = '.MainActivity';15const TEST_APP_PACKAGE = 'io.appium.android.apis';16const TEST_APP_ACTIVITY = '.ApiDemos';17const TEST_APP_PACKAGE = 'io.appium.android.apis';18const TEST_APP_ACTIVITY = '.view.WebView1';19const TEST_APP_PACKAGE = 'io.appium.android.apis';20const DEFAULT_CAPS = {21};22const DEFAULT_SETTINGS = {23};24const DEFAULT_OPTIONS = {25};26const DEFAULT_EXECUTOR = wd.RemoteExecutor.DEFAULT_EXECUTOR;27const DEFAULT_CONNECTION = {28};29const DEFAULT_CONTEXT = 'NATIVE_APP';30const DEFAULT_DEVICE = {31 screen: {
Using AI Code Generation
1var appiumBaseDriver = require('appium-base-driver');2var appiumBaseDriverAllowCrossDomainAsyncExecute = appiumBaseDriver.allowCrossDomainAsyncExecute;3var appiumBaseDriverAllowCrossDomainAsyncExecute = appiumBaseDriverAllowCrossDomainAsyncExecute(appiumBaseDriver);4appiumBaseDriverAllowCrossDomainAsyncExecute();5var appiumDriver = require('appium');6var appiumDriverAllowCrossDomainAsyncExecute = appiumDriver.allowCrossDomainAsyncExecute;7var appiumDriverAllowCrossDomainAsyncExecute = appiumDriverAllowCrossDomainAsyncExecute(appiumDriver);8appiumDriverAllowCrossDomainAsyncExecute();
Using AI Code Generation
1const AppiumBaseDriver = require('appium-base-driver');2const appiumBaseDriver = new AppiumBaseDriver();3const args = {4 headers: {5 }6};7appiumBaseDriver.allowCrossDomainAsyncExecute(args);8const AppiumBaseDriver = require('appium-base-driver');9const appiumBaseDriver = new AppiumBaseDriver();10const args = {11 headers: {12 }13};14appiumBaseDriver.allowCrossDomain(args);15const AppiumBaseDriver = require('appium-base-driver');16const appiumBaseDriver = new AppiumBaseDriver();17const args = {18 headers: {19 }20};21appiumBaseDriver.allowCrossDomainAsyncExecute(args);22const AppiumBaseDriver = require('appium-base-driver');23const appiumBaseDriver = new AppiumBaseDriver();24const args = {25 headers: {26 }27};28appiumBaseDriver.allowCrossDomain(args);29const AppiumBaseDriver = require('appium-base-driver');30const appiumBaseDriver = new AppiumBaseDriver();31const args = {32 headers: {33 }34};35appiumBaseDriver.allowCrossDomainAsyncExecute(args);36const AppiumBaseDriver = require('appium-base-driver');37const appiumBaseDriver = new AppiumBaseDriver();
Using AI Code Generation
1const { AppiumBaseDriver } = require('appium-base-driver');2const { asyncify } = require('asyncbox');3const { util } = require('appium-support');4const { logger } = require('appium-support');5async function main() {6 const driver = new AppiumBaseDriver();7 const asyncExecute = asyncify(driver.execute.bind(driver));8 const asyncExecuteAsync = asyncify(driver.executeAsync.bind(driver));9 const asyncExecuteAsyncScript = asyncify(driver.executeAsyncScript.bind(driver));10 const asyncExecuteScript = asyncify(driver.executeScript.bind(driver));11 const asyncAllowCrossDomainAsyncExecute = asyncify(driver.allowCrossDomainAsyncExecute.bind(driver));12 const script = 'return 1 + 1;';13 const args = [1, 2, 3];14 const res = await asyncExecute(script, args);15 console.log('execute', res);16 const res2 = await asyncExecuteAsync(script, args);17 console.log('executeAsync', res2);18 const res3 = await asyncExecuteAsyncScript(script, args);19 console.log('executeAsyncScript', res3);20 const res4 = await asyncExecuteScript(script, args);21 console.log('executeScript', res4);22 const res5 = await asyncAllowCrossDomainAsyncExecute(script, args);23 console.log('allowCrossDomainAsyncExecute', res5);24}25main();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var wd = require('wd');4var _ = require('underscore');5var path = require('path');6var app = path.resolve(__dirname, 'android-debug.apk');7var desiredCaps = {8};9var driver = wd.promiseChainRemote('localhost', 4723);10driver.init(desiredCaps).then(function() {11 return driver.allowCrossDomainAsyncExecute();12}).then(function() {13 return driver.executeAsync("var callback = arguments[arguments.length - 1]; setTimeout(function(){ callback('success'); }, 10000);");14}).then(function() {15 console.log('Successfully executed the async script');16}).catch(function(err) {17 console.log('Error executing script: ' + err);18});
Using AI Code Generation
1var appium = require('appium');2var driver = new appium.AppiumDriver();3driver.allowCrossDomainAsyncExecute();4var appium = require('appium');5var driver = new appium.AppiumDriver();6driver.allowCrossDomainAsyncExecute();7var appium = require('appium');8var driver = new appium.AppiumDriver();9driver.allowCrossDomainAsyncExecute();10var appium = require('appium');11var driver = new appium.AppiumDriver();12driver.allowCrossDomainAsyncExecute();13var appium = require('appium');14var driver = new appium.AppiumDriver();15driver.allowCrossDomainAsyncExecute();16var appium = require('appium');17var driver = new appium.AppiumDriver();18driver.allowCrossDomainAsyncExecute();19var appium = require('appium');20var driver = new appium.AppiumDriver();21driver.allowCrossDomainAsyncExecute();22var appium = require('appium');23var driver = new appium.AppiumDriver();24driver.allowCrossDomainAsyncExecute();25var appium = require('appium');26var driver = new appium.AppiumDriver();27driver.allowCrossDomainAsyncExecute();28var appium = require('appium');29var driver = new appium.AppiumDriver();30driver.allowCrossDomainAsyncExecute();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var assert = require('assert');3 build();4driver.executeAsyncScript(function() {5 var callback = arguments[arguments.length - 1];6 callback();7}).then(function() {8 driver.getTitle().then(function(title) {9 assert.equal(title, 'Google');10 console.log("Test passed");11 });12});13driver.quit();14driver.executeAsyncScript(script[, var_args])15var webdriver = require('selenium-webdriver');16var assert = require('assert');17 build();18driver.executeAsyncScript(function() {19 var callback = arguments[arguments.length - 1];20 callback();21}).then(function() {22 driver.getTitle().then(function(title) {23 assert.equal(title, 'Google');24 console.log("Test passed");25 });26});27driver.quit();
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!!