Best JavaScript code snippet using appium
helpers.js
Source:helpers.js
1"use strict";2var _ = require("underscore")3 , gridRegister = require('./grid-register.js')4 , logger = require('./logger.js').get('appium')5 , status = require('./status.js')6 , io = require('socket.io')7 , mkdirp = require('mkdirp')8 , bytes = require('bytes')9 , domain = require('domain')10 , format = require('util').format11 , Args = require("vargs").Constructor;12module.exports.allowCrossDomain = function (req, res, next) {13 safely(req, function () {14 res.header('Access-Control-Allow-Origin', '*');15 res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,DELETE');16 res.header('Access-Control-Allow-Headers', 'origin, content-type, accept');17 });18 // need to respond 200 to OPTIONS19 if ('OPTIONS' === req.method) {20 safely(req, function () {21 res.sendStatus(200);22 });23 } else {24 next();25 }26};27module.exports.winstonStream = {28 write: function (msg) {29 msg = msg.replace(/$\s*$/m, "");30 msg = msg.replace(/\[[^\]]+\] /, "");31 logger.log('debug', msg);32 }33};34module.exports.catchAllHandler = function (e, req, res, next) {35 safely(req, function () {36 res.status(500).send({37 status: status.codes.UnknownError.code38 , value: "ERROR running Appium command: " + e.message39 });40 });41 next(e);42};43module.exports.checkArgs = function (parser, args) {44 var exclusives = [45 ['noReset', 'fullReset']46 , ['ipa', 'safari']47 , ['app', 'safari']48 , ['forceIphone', 'forceIpad']49 , ['deviceName', 'defaultDevice']50 ];51 _.each(exclusives, function (exSet) {52 var numFoundInArgs = 0;53 _.each(exSet, function (opt) {54 if (_.has(args, opt) && args[opt]) {55 numFoundInArgs++;56 }57 });58 if (numFoundInArgs > 1) {59 console.error(("You can't pass in more than one argument from the set " +60 JSON.stringify(exSet) + ", since they are mutually exclusive").red);61 process.exit(1);62 }63 });64 var checkValidPort = function (port) {65 if (port > 0 && port < 65536) return true;66 console.error("Port must be greater than 0 and less than 65536");67 return false;68 };69 var validations = {70 port: checkValidPort71 , callbackPort: checkValidPort72 , bootstrapPort: checkValidPort73 , selendroidPort: checkValidPort74 , chromedriverPort: checkValidPort75 , robotPort: checkValidPort76 , backendRetries: function (r) { return r >= 0; }77 };78 var nonDefaultArgs = getNonDefaultArgs(parser, args);79 _.each(validations, function (validator, arg) {80 if (_.has(nonDefaultArgs, arg)) {81 if (!validator(args[arg])) {82 console.error("Invalid argument for param " + arg + ": " + args[arg]);83 process.exit(1);84 }85 }86 });87};88module.exports.noColorLogger = function (tokens, req, res) {89 var len = parseInt(res.getHeader('Content-Length'), 10);90 len = isNaN(len) ? '' : ' - ' + bytes(len);91 return req.method + ' ' + req.originalUrl + ' ' +92 res.statusCode + ' ' + (new Date() - req._startTime) + 'ms' + len;93};94module.exports.configureServer = function (rawConfig, appiumVer, appiumServer,95 cb) {96 var appiumRev;97 if (!rawConfig) {98 return cb(new Error('config data required'));99 }100 var versionMismatches = {};101 var excludedKeys = ["git-sha", "node_bin", "built"];102 _.each(rawConfig, function (deviceConfig, key) {103 if (deviceConfig.version !== appiumVer && !_.contains(excludedKeys, key)) {104 versionMismatches[key] = deviceConfig.version;105 } else if (key === "git-sha") {106 appiumRev = rawConfig['git-sha'];107 }108 });109 if (_.keys(versionMismatches).length) {110 logger.error("Got some configuration version mismatches. Appium is " +111 "at " + appiumVer + ".");112 _.each(versionMismatches, function (mismatchedVer, key) {113 logger.error(key + " configured at " + mismatchedVer);114 });115 logger.error("Please re-run reset.sh or config");116 return cb(new Error("Appium / config version mismatch"));117 } else {118 appiumServer.registerConfig(rawConfig);119 cb(null, appiumRev);120 }121};122module.exports.conditionallyPreLaunch = function (args, appiumServer, cb) {123 if (args.launch) {124 logger.debug("Starting Appium in pre-launch mode");125 appiumServer.preLaunch(function (err) {126 if (err) {127 logger.error("Could not pre-launch appium: " + err);128 cb(err);129 } else {130 cb(null);131 }132 });133 } else {134 cb(null);135 }136};137module.exports.prepareTmpDir = function (args, cb) {138 if (args.tmpDir === null) return cb();139 mkdirp(args.tmpDir, function (err) {140 if (err) {141 logger.error("Could not ensure tmp dir '" + args.tmpDir + "' exists");142 logger.error(err);143 }144 cb(err);145 });146};147var startAlertSocket = function (restServer, appiumServer) {148 var alerts = io(restServer, {149 'flash policy port': -1,150 'logger': logger,151 'log level': 1,152 'polling duration': 10,153 'transports': ['websocket', 'flashsocket']154 });155 alerts.sockets.on("connection", function (socket) {156 logger.debug("Client connected: " + (socket.id).toString());157 socket.on('disconnect', function (data) {158 logger.debug("Client disconnected: " + data);159 });160 });161 // add web socket so we can emit events162 appiumServer.attachSocket(alerts);163};164var getNonDefaultArgs = function (parser, args) {165 var nonDefaults = {};166 _.each(parser.rawArgs, function (rawArg) {167 var arg = rawArg[1].dest;168 if (args[arg] !== rawArg[1].defaultValue) {169 nonDefaults[arg] = args[arg];170 }171 });172 return nonDefaults;173};174var getDeprecatedArgs = function (parser, args) {175 var deprecated = {};176 _.each(parser.rawArgs, function (rawArg) {177 var arg = rawArg[1].dest;178 if (args[arg] && rawArg[1].deprecatedFor) {179 deprecated[rawArg[0]] = "use instead: " + rawArg[1].deprecatedFor;180 }181 });182 return deprecated;183};184module.exports.startListening = function (server, args, parser, appiumVer, appiumRev, appiumServer, cb) {185 var alreadyReturned = false;186 server.listen(args.port, args.address, function () {187 var welcome = "Welcome to Appium v" + appiumVer;188 if (appiumRev) {189 welcome += " (REV " + appiumRev + ")";190 }191 logger.info(welcome);192 var logMessage = "Appium REST http interface listener started on " +193 args.address + ":" + args.port;194 logger.info(logMessage);195 startAlertSocket(server, appiumServer);196 if (args.nodeconfig !== null) {197 gridRegister.registerNode(args.nodeconfig, args.address, args.port);198 }199 var showArgs = getNonDefaultArgs(parser, args);200 if (_.size(showArgs)) {201 logger.debug("Non-default server args: " + JSON.stringify(showArgs));202 }203 var deprecatedArgs = getDeprecatedArgs(parser, args);204 if (_.size(deprecatedArgs)) {205 logger.warn("Deprecated server args: " + JSON.stringify(deprecatedArgs));206 }207 logger.info('Console LogLevel: ' + logger.transports.console.level);208 if (logger.transports.file) {209 logger.info('File LogLevel: ' + logger.transports.file.level);210 }211 });212 server.on('error', function (err) {213 if (err.code === 'EADDRNOTAVAIL') {214 logger.error("Couldn't start Appium REST http interface listener. Requested address is not available.");215 } else {216 logger.error("Couldn't start Appium REST http interface listener. Requested port is already in use. Please make sure there's no other instance of Appium running already.");217 }218 if (!alreadyReturned) {219 alreadyReturned = true;220 cb(err);221 }222 });223 server.on('connection', function (socket) {224 socket.setTimeout(600 * 1000); // 10 minute timeout225 });226 setTimeout(function () {227 if (!alreadyReturned) {228 alreadyReturned = true;229 cb(null);230 }231 }, 1000);232};233// Copied the morgan compile function over so that cooler formats234// may be configured235function compile(fmt) {236 fmt = fmt.replace(/"/g, '\\"');237 var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g,238 function (_, name, arg) {239 return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "';240 }) + '";';241 // jshint evil:true242 return new Function('tokens, req, res', js);243}244module.exports.requestStartLoggingFormat = compile('-->'.white + ' ' + ':method'.white + ' ' +245 ':url'.white);246// Copied the morgan format.dev function, modified to use colors package247// and custom logging line248module.exports.requestEndLoggingFormat = function (tokens, req, res) {249 var status = res.statusCode;250 var statusStr = ':status';251 if (status >= 500) statusStr = statusStr.red;252 else if (status >= 400) statusStr = statusStr.yellow;253 else if (status >= 300) statusStr = statusStr.cyan;254 else statusStr = statusStr.green;255 var fn = compile('<-- :method :url '.white + statusStr +256 ' :response-time ms - :res[content-length]'.grey);257 return fn(tokens, req, res);258};259function getRequestContext(req) {260 if (!req) return '';261 var data = '';262 try {263 if (req.body) data = JSON.stringify(req.body).substring(0, 200);264 } catch (ign) {}265 return format('context: [%s %s %s]', req.method, req.url, data).replace(/ ]$/, '');266}267// Mainly used to wrap http response methods, or for cases where errors268// perdure the domain269var safely = function () {270 var args = new (Args)(arguments);271 var req = args.all[0];272 var fn = args.callback;273 try {274 fn();275 } catch (err) {276 logger.error('Unexpected error:', err.stack, getRequestContext(req));277 }278};279module.exports.safely = safely;280module.exports.domainMiddleware = function () {281 return function (req, res, next) {282 var reqDomain = domain.create();283 reqDomain.add(req);284 reqDomain.add(res);285 res.on('close', function () {286 setTimeout(function () {287 reqDomain.dispose();288 }, 5000);289 });290 reqDomain.on('error', function (err) {291 logger.error('Unhandled error:', err.stack, getRequestContext(req));292 });293 reqDomain.run(next);294 };...
config.js
Source:config.js
1import _ from 'lodash';2import path from 'path';3import { mkdirp, fs } from 'appium-support';4import { exec } from 'teen_process';5import logger from './logger';6import pkgObj from '../../package.json'; // eslint-disable-line import/no-unresolved7const APPIUM_VER = pkgObj.version;8function getNodeVersion () {9 // expect v<major>.<minor>.<patch>10 // we will pull out `major` and `minor`11 let version = process.version.match(/^v(\d+)\.(\d+)/);12 return [Number(version[1]), Number(version[2])];13}14async function getGitRev () {15 let cwd = path.resolve(__dirname, "..", "..");16 let rev = null;17 try {18 let {stdout} = await exec("git", ["rev-parse", "HEAD"], {cwd});19 rev = stdout.trim();20 } catch (ign) {}21 return rev;22}23async function getAppiumConfig () {24 let stat = await fs.stat(path.resolve(__dirname, '..'));25 let built = stat.mtime.getTime();26 let config = {27 'git-sha': await getGitRev(),28 built,29 version: APPIUM_VER,30 };31 return config;32}33function checkNodeOk () {34 let [major, minor] = getNodeVersion();35 if (major < 5) {36 let msg = `Node version must be >= 5. Currently ${major}.${minor}`;37 logger.errorAndThrow(msg);38 }39}40function warnNodeDeprecations () {41 let [major] = getNodeVersion();42 if (major < 4) {43 logger.warn("Appium support for versions of node < 4 has been " +44 "deprecated and will be removed in a future version. Please " +45 "upgrade!");46 }47}48async function showConfig () {49 let config = await getAppiumConfig();50 console.log(JSON.stringify(config)); // eslint-disable-line no-console51}52function getNonDefaultArgs (parser, args) {53 let nonDefaults = {};54 for (let rawArg of parser.rawArgs) {55 let arg = rawArg[1].dest;56 if (args[arg] && args[arg] !== rawArg[1].defaultValue) {57 nonDefaults[arg] = args[arg];58 }59 }60 return nonDefaults;61}62function getDeprecatedArgs (parser, args) {63 // go through the server command line arguments and figure64 // out which of the ones used are deprecated65 let deprecated = {};66 for (let rawArg of parser.rawArgs) {67 let arg = rawArg[1].dest;68 let defaultValue = rawArg[1].defaultValue;69 let isDeprecated = !!rawArg[1].deprecatedFor;70 if (args[arg] && args[arg] !== defaultValue && isDeprecated) {71 deprecated[rawArg[0]] = rawArg[1].deprecatedFor;72 }73 }74 return deprecated;75}76function checkValidPort (port, portName) {77 if (port > 0 && port < 65536) return true; // eslint-disable-line curly78 logger.error(`Port '${portName}' must be greater than 0 and less than 65536. Currently ${port}`);79 return false;80}81function validateServerArgs (parser, args) {82 // arguments that cannot both be set83 let exclusives = [84 ['noReset', 'fullReset'],85 ['ipa', 'safari'],86 ['app', 'safari'],87 ['forceIphone', 'forceIpad'],88 ['deviceName', 'defaultDevice']89 ];90 for (let exSet of exclusives) {91 let numFoundInArgs = 0;92 for (let opt of exSet) {93 if (_.has(args, opt) && args[opt]) {94 numFoundInArgs++;95 }96 }97 if (numFoundInArgs > 1) {98 throw new Error(`You can't pass in more than one argument from the ` +99 `set ${JSON.stringify(exSet)}, since they are ` +100 `mutually exclusive`);101 }102 }103 const validations = {104 port: checkValidPort,105 callbackPort: checkValidPort,106 bootstrapPort: checkValidPort,107 selendroidPort: checkValidPort,108 chromedriverPort: checkValidPort,109 robotPort: checkValidPort,110 backendRetries: (r) => { return r >= 0; }111 };112 const nonDefaultArgs = getNonDefaultArgs(parser, args);113 for (let [arg, validator] of _.toPairs(validations)) {114 if (_.has(nonDefaultArgs, arg)) {115 if (!validator(args[arg], arg)) {116 throw new Error(`Invalid argument for param ${arg}: ${args[arg]}`);117 }118 }119 }120}121async function validateTmpDir (tmpDir) {122 try {123 await mkdirp(tmpDir);124 } catch (e) {125 throw new Error(`We could not ensure that the temp dir you specified ` +126 `(${tmpDir}) exists. Please make sure it's writeable.`);127 }128}129export { getAppiumConfig, validateServerArgs, checkNodeOk, showConfig,130 warnNodeDeprecations, validateTmpDir, getNonDefaultArgs,...
Using AI Code Generation
1const { AppiumServiceBuilder } = require('appium');2const { AppiumServiceBuilder } = require('appium');3const { AppiumServiceBuilder } = require('appium');4const { AppiumServiceBuilder } = require('appium');5const { AppiumServiceBuilder } = require('appium');6const { AppiumServiceBuilder } = require('appium');7const { AppiumServiceBuilder } = require('appium');8const { AppiumServiceBuilder } = require('appium');9const { AppiumServiceBuilder } = require('appium');10console.log(App
Using AI Code Generation
1var appium = require('appium');2var appium = require('appium');3var appium = appium.getAppium();4appium.startServer();5var appium = require('appium');6var appium = appium.getAppium();7appium.stopServer();8var appium = require('appium');9var driver = appium.getAppiumDriver();10driver.quit();11var appium = require('appium');12var driver = appium.getAppiumDriver();13driver.quit();14var appium = require('appium');15var driver = appium.getAppiumDriver();16driver.quit();17var appium = require('appium');18var driver = appium.getAppiumDriver();19driver.quit();20var appium = require('appium');21var driver = appium.getAppiumDriver();22driver.quit();23var appium = require('appium');24var driver = appium.getAppiumDriver();25driver.quit();26var appium = require('appium');27var driver = appium.getAppiumDriver();28driver.quit();29var appium = require('appium');
Using AI Code Generation
1const AppiumServer = require("appium-server").AppiumServer;2const appiumServer = new AppiumServer();3appiumServer.checkValidPort(4723).then((validPort) => {4 console.log("Valid Port: ", validPort);5}).catch((error) => {6 console.log("Error: ", error);7});8const AppiumServer = require("appium-server").AppiumServer;9const appiumServer = new AppiumServer();10appiumServer.startServer().then((server) => {11 console.log("Server: ", server);12}).catch((error) => {13 console.log("Error: ", error);14});15const AppiumServer = require("appium-server").AppiumServer;16const appiumServer = new AppiumServer();17appiumServer.stopServer().then((server) => {18 console.log("Server: ", server);19}).catch((error) => {20 console.log("Error: ", error);21});22const AppiumServer = require("appium-server").AppiumServer;23const appiumServer = new AppiumServer();24appiumServer.startServer().then((server) => {25 console.log("Server: ", server);26 appiumServer.stopServer().then((server) => {27 console.log("Server: ", server);28 }).catch((error) => {29 console.log("Error: ", error);30 });31}).catch((error) => {32 console.log("Error: ", error);33});34const AppiumServer = require("appium-server").AppiumServer;35const appiumServer = new AppiumServer();36appiumServer.startServer().then((server) => {37 console.log("Server: ", server);38 appiumServer.stopServer().then((server) => {39 console.log("Server: ", server);40 }).catch((error) => {41 console.log("Error: ", error);42 });43}).catch((error) => {44 console.log("Error: ", error);45});
Using AI Code Generation
1var appium = require('appium');2var port = 4723;3var valid = appium.checkValidPort(port);4if(valid){5 console.log("Port is valid");6}else{7 console.log("Port is not valid");8}
Using AI Code Generation
1var appium = require('appium');2if (appium.checkValidPort(1234)) {3 console.log('Port is valid');4} else {5 console.log('Port is invalid');6}7var appium = require('appium');8if (appium.checkPortInUse(1234)) {9 console.log('Port is in use');10} else {11 console.log('Port is not in use');12}13var appium = require('appium');14if (appium.checkPortAvailable(1234)) {15 console.log('Port is available');16} else {17 console.log('Port is not available');18}19var appium = require('appium');20var port = appium.getPort(1234);21console.log(port);22var appium = require('appium');23var ports = appium.getPorts(1234, 2);24console.log(ports);25var appium = require('appium');26var ports = appium.getPorts(1234, 2, 2);27console.log(ports);28var appium = require('appium');29var ports = appium.getPorts(1234, 2, 2, 2);30console.log(ports);31var appium = require('appium');32var ports = appium.getPorts(1234, 2, 2, 2, 2);33console.log(ports);34var appium = require('appium');35var ports = appium.getPorts(1234, 2, 2, 2, 2, 2);36console.log(ports);37var appium = require('appium');38var ports = appium.getPorts(1234, 2, 2, 2, 2, 2, 2);39console.log(ports);40var appium = require('appium');41var ports = appium.getPorts(1234, 2
Using AI Code Generation
1driver.checkValidPort(4723);2driver.checkValidPort(4724);3driver.checkValidPort(4725);4driver.checkValidPort(4723);5driver.checkValidPort(4724);6driver.checkValidPort(4725);7driver.checkValidPort(4723);8driver.checkValidPort(4724);9driver.checkValidPort(4725);10driver.checkValidPort(4723);11driver.checkValidPort(4724);12driver.checkValidPort(4725);13driver.checkValidPort(4723);14driver.checkValidPort(4724);15driver.checkValidPort(4725);16driver.checkValidPort(4723);17driver.checkValidPort(4724);18driver.checkValidPort(4725);19driver.checkValidPort(4723);20driver.checkValidPort(4724);21driver.checkValidPort(4725);22driver.checkValidPort(4723);23driver.checkValidPort(4724);24driver.checkValidPort(4725);25driver.checkValidPort(4723);26driver.checkValidPort(4724);27driver.checkValidPort(4725);28driver.checkValidPort(4723);29driver.checkValidPort(4724);30driver.checkValidPort(4725);31driver.checkValidPort(4723);32driver.checkValidPort(4724);33driver.checkValidPort(4725);
Using AI Code Generation
1var Appium = require('appium-js').Appium;2var appium = new Appium();3appium.checkValidPort(4000, function(err, isValid) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log('Port is valid: ' + isValid);8 }9});10checkPortStatus(port, callback)11var Appium = require('appium-js').Appium;12var appium = new Appium();13appium.checkPortStatus(4000, function(err, status) {14 if (err) {15 console.log('Error: ' + err);16 } else {17 console.log('Port status: ' + status);18 }19});
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!!