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 };...
main.js
Source:main.js
1"use strict";2var parser = require('./parser.js')()3 , logFactory = require('./logger.js')4 , logger = null5 , args = null6 , fs = require('fs')7 , path = require('path')8 , noPermsCheck = false;9require('colors');10process.chdir(path.resolve(__dirname, '../..'));11if (require.main === module) {12 args = parser.parseArgs();13 noPermsCheck = args.noPermsCheck;14 logFactory.init(args);15}16logger = logFactory.get('appium');17if (!noPermsCheck) {18 var appiumPermStat = fs.statSync(path.resolve(__dirname,19 '../../package.json'));20 var launchCmd = (process.env.SUDO_COMMAND || "").toLowerCase();21 var isWindows = require('appium-support').system.isWindows();22 if (23 !isWindows &&24 // Appium should be run by user who owns files in Appium installation directory25 appiumPermStat.uid !== process.getuid() &&26 // authorize* commands could be run using sudo27 !launchCmd.match(/authorize/)28 ) {29 logger.error("Appium will not work if used or installed with sudo. " +30 "Please rerun/install as a non-root user. If you had to " +31 "install Appium using `sudo npm install -g appium`, the " +32 "solution is to reinstall Node using a method (Homebrew, " +33 "for example) that doesn't require sudo to install global " +34 "npm packages.");35 process.exit(1);36 }37}38var http = require('http')39 , express = require('express')40 , favicon = require('serve-favicon')41 , bodyParser = require('body-parser')42 , methodOverride = require('method-override')43 , morgan = require('morgan') // logger44 , routing = require('./routing.js')45 , path = require('path')46 , appium = require('../appium.js')47 , parserWrap = require('./middleware').parserWrap48 , appiumVer = require('../../package.json').version49 , appiumRev = null50 , async = require('async')51 , helpers = require('./helpers.js')52 , logFinalWarning = require('../helpers.js').logFinalDeprecationWarning53 , getConfig = require('../helpers.js').getAppiumConfig54 , allowCrossDomain = helpers.allowCrossDomain55 , catchAllHandler = helpers.catchAllHandler56 , checkArgs = helpers.checkArgs57 , configureServer = helpers.configureServer58 , startListening = helpers.startListening59 , conditionallyPreLaunch = helpers.conditionallyPreLaunch60 , prepareTmpDir = helpers.prepareTmpDir61 , requestStartLoggingFormat = require('./helpers.js').requestStartLoggingFormat62 , requestEndLoggingFormat = require('./helpers.js').requestEndLoggingFormat63 , domainMiddleware = require('./helpers.js').domainMiddleware;64var main = function (args, readyCb, doneCb) {65 if (args.showConfig) {66 try {67 console.log(JSON.stringify(getConfig()));68 } catch (e) {69 process.exit(1);70 }71 process.exit(0);72 }73 checkArgs(parser, args);74 if (typeof doneCb === "undefined") {75 doneCb = function () {};76 }77 var rest = express()78 , server = http.createServer(rest);79 rest.use(domainMiddleware());80 rest.use(morgan(function (tokens, req, res) {81 // morgan output is redirected straight to winston82 logger.info(requestEndLoggingFormat(tokens, req, res),83 (res.jsonResp || '').grey);84 }));85 rest.use(favicon(path.join(__dirname, 'static/favicon.ico')));86 rest.use(express.static(path.join(__dirname, 'static')));87 rest.use(allowCrossDomain);88 rest.use(parserWrap);89 rest.use(bodyParser.urlencoded({extended: true}));90 // 8/18/14: body-parser requires that we supply the limit field to ensure the server can91 // handle requests large enough for Appium's use cases. Neither Node nor HTTP spec defines a max92 // request size, so any hard-coded request-size limit is arbitrary. Units are in bytes (ie "gb" == "GB",93 // not "Gb"). Using 1GB because..., well because it's arbitrary and 1GB is sufficiently large for 99.99%94 // of testing scenarios while still providing an upperbounds to reduce the odds of squirrelliness.95 rest.use(bodyParser.json({limit: '1gb'}));96 rest.use(morgan(function (tokens, req, res) {97 // morgan output is redirected straight to winston98 var data = '';99 try {100 if (req.body) data = JSON.stringify(req.body).substring(0, 1000);101 } catch (ign) {}102 logger.info(requestStartLoggingFormat(tokens, req, res), data.grey);103 }, {immediate: true}));104 rest.use(methodOverride());105 // Instantiate the appium instance106 var appiumServer = appium(args);107 // Hook up REST http interface108 appiumServer.attachTo(rest);109 routing(appiumServer);110 rest.use(catchAllHandler);111 async.series([112 function (cb) {113 configureServer(getConfig(), appiumVer, appiumServer, function (err, rev) {114 if (err) return cb(err);115 appiumRev = rev;116 cb();117 });118 },119 function (cb) {120 prepareTmpDir(args, cb);121 },122 function (cb) {123 conditionallyPreLaunch(args, appiumServer, cb);124 },125 function (cb) {126 startListening(server, args, parser, appiumVer, appiumRev, appiumServer, cb);127 }128 ], function (err) {129 if (err) {130 process.exit(1);131 } else if (typeof readyCb === "function") {132 readyCb(appiumServer);133 }134 });135 server.on('close', function () {136 logFinalWarning();137 doneCb();138 });139};140if (require.main === module) {141 main(args);142}...
appium-server.js
Source:appium-server.js
1const debug = require('debug')('tiappium:AppiumServer');2const fetch = require('node-fetch');3const { existsSync } = require('fs');4const { join } = require('path');5const { spawn } = require('child_process'); // eslint-disable-line security/detect-child-process6let appiumStarted;7/**8 * Represents an Appium Server9 *10 * @class AppiumServer11 */12class AppiumServer {13 /**14 * Creates an instance of AppiumServer.15 *16 * @param {Object} config - Various config settings.17 * @param {Boolean} config.overrideAppium - Override the appium instance with a local one.18 */19 constructor({ config }) {20 if (config.overrideAppium) {21 this.binary = this.resolveBinary(config.projectDir);22 } else {23 this.binary = this.resolveBinary(join(__dirname, '..'));24 }25 this.started = false;26 }27 /**28 * Start the appium server.29 *30 * @param {Number} [port] - Port to start the Appium server on.31 */32 async start(port) {33 this.port = port || '4723';34 debug('Starting server on %s', this.port);35 this.spawnServer();36 await monitorOutput(this.appiumServer, 60000);37 this.started = true;38 appiumStarted = true;39 }40 /**41 * Spawn the Appium process.42 *43 * @private44 */45 spawnServer() {46 const args = [ '-p', this.port ];47 debug('Starting appium with args %o', args);48 debug('Using appium binary at %s', this.binary);49 this.appiumServer = spawn(this.binary, args, { shell: true, detached: true });50 }51 /**52 * Stop the Appium server.53 */54 stop() {55 debug('Stopping server');56 if (process.platform === 'win32') {57 // TODO58 } else {59 this.appiumServer.kill();60 }61 this.started = false;62 }63 /**64 * Look up the Appium binary located in node_modules relative to a directory65 *66 * @param {String} dir - Directory to look up the Appium binary relative to.67 * @returns {String} - Path to the appium binary68 * @private69 */70 resolveBinary(dir) {71 const binaryPath = join(dir, 'node_modules', '.bin', 'appium');72 if (!existsSync(binaryPath)) {73 throw new Error(`Could not find the "appium" binary in ${dir}`);74 }75 return binaryPath;76 }77}78/**79 * Watch a spawned process for a specific string(s), resolving or rejecting a promise once seen. Or80 * erroring after a timeout if not seen.81 *82 * @param {any} proc Result of calling `child_process.spawn`.83 * @param {Number} timeout Length of time to wait for.84 * @returns {Promise}85 */86function monitorOutput (proc, timeout) {87 const successRegex = /listener started on/i;88 const errorRegex = /Error: listen/i;89 const alreadyRunningRegex = /Could not start REST http interface listener/i;90 let testingIfRunning = false;91 return new Promise((resolve, reject) => {92 const abortIt = setTimeout(() => {93 proc.kill();94 debug('Timed out waiting for %s'.successRegex);95 const err = new Error('Did not see debug before timeout elapsed');96 err.code = 'ETIMEDOUT';97 reject(err);98 }, timeout || 3000);99 proc.stdout.on('data', async (data) => {100 data = data.toString();101 !appiumStarted && debug(data);102 if (successRegex.test(data)) {103 clearTimeout(abortIt);104 debug('Saw success, resolving');105 resolve(true);106 }107 // Just incase wires get crossed108 if (errorRegex.test(data)) {109 clearTimeout(abortIt);110 const err = new Error('Saw error debug in output');111 err.code = 'ESPAWNFAILED';112 reject(err);113 } else if (alreadyRunningRegex.test(data)) {114 clearTimeout(abortIt);115 debug('Saw that server is already running attempting to determine if Appium server');116 try {117 const res = await fetch('http://0.0.0.0:4723/wd/hub/status');118 const json = await res.json();119 if (json.value && json.value.build && json.value.build.version) {120 debug('Server running on port looks like an appium server, here we go');121 resolve(true);122 } else {123 const err = new Error('Port is taken and it does not look like an appium server');124 err.code = 'EPORTINUSE';125 reject(err);126 }127 } catch (e) {128 const err = new Error('Port is taken and it does not look like an appium server');129 err.code = 'EPORTINUSE';130 reject(err);131 }132 }133 });134 proc.stderr.on('data', async (data) => {135 data = data.toString();136 !appiumStarted && debug(data);137 if (errorRegex.test(data) && !testingIfRunning) {138 clearTimeout(abortIt);139 const err = new Error('Saw error debug in output');140 err.code = 'ESPAWNFAILED';141 reject(err);142 } else if (alreadyRunningRegex.test(data)) {143 clearTimeout(abortIt);144 debug('Saw that server is already running attempting to determine if Appium server');145 testingIfRunning = true;146 try {147 const res = await fetch('http://0.0.0.0:4723/wd/hub/status');148 const json = await res.json();149 console.log(json);150 if (json.value && json.value.build && json.value.build.version) {151 debug('Server running on port looks like an appium server, here we go');152 resolve(true);153 } else {154 const err = new Error('Port is taken and it does not look like an appium server');155 err.code = 'EPORTINUSE';156 reject(err);157 }158 } catch (e) {159 const err = new Error('Port is taken and it does not look like an appium server');160 err.code = 'EPORTINUSE';161 reject(err);162 }163 }164 });165 });166}...
appium-hook.js
Source:appium-hook.js
1const AppiumServer = require('../lib/appium-server');2const Driver = require('../lib/driver');3const {4 checkNodeVersion,5 getCommands,6 getConfig,7 getTestFiles,8 requireWithOverride9} = require('../lib/utils');10exports.id = 'com.awam.appiumplugin';11exports.cliVersion = '>=3.2';12let appiumServer;13exports.init = function (logger, config, cli) {14 let testConfig;15 let platform;16 let projectDir;17 cli.addHook('build.config', function (data, finished) {18 const r = data.result[1] || {};19 r.flags || (r.flags = {});20 r.flags['appium'] = {21 default: false,22 desc: 'enable appium e2e testing'23 };24 finished(null, data);25 });26 cli.addHook('build.pre.construct', function (data, finished) {27 if (cli.argv['appium']) {28 cli.argv['build-only'] = true;29 platform = cli.argv.platform || cli.argv.p;30 projectDir = cli.argv['project-dir'] || cli.argv.d;31 testConfig = getConfig(projectDir, platform);32 testConfig.projectDir = projectDir;33 appiumServer = new AppiumServer({ config: testConfig });34 }35 finished();36 });37 cli.addHook('build.finalize', async function (builder, finished) {38 if (cli.argv['appium']) {39 logger.info('TiAppium starting');40 try {41 checkNodeVersion();42 // Can we start this without blocking? Or, maybe do a43 // Promise.all for the server start and driver setup44 await appiumServer.start();45 const testFiles = getTestFiles(projectDir, platform);46 if (platform === 'ios') {47 testConfig.appium.app = builder.xcodeAppDir;48 testConfig.appium.platformName = 'iOS';49 } else if (platform === 'android') {50 testConfig.appium.app = builder.apkFile;51 testConfig.appium.platformName = 'Android';52 } else if (platform === 'windows') {53 // TODO:54 // 1. Need to either have the app accessible off builder55 // or make pull in the code from ti.windows-remote-deployment56 // 2. Investigate the options needed57 // 3. Validate what's supported by appium, iirc only ws-local is58 }59 logger.debug('testConfig is %O', testConfig);60 // Setup the driver instance61 // TODO: testConfig.driver === 'custom' ?62 logger.debug(`Using driver type ${testConfig.driver}`);63 const driver = new Driver(testConfig);64 await driver.init({ port: 4723, host: 'localhost', desiredCapabilities: testConfig.appium });65 const commands = getCommands(projectDir);66 for (const command of commands) {67 const com = require(command); // eslint-disable-line security/detect-non-literal-require68 logger.debug(`Loading command ${com.name} for ${platform}`);69 driver.addCommand(com, platform);70 }71 // Setup mocha instance72 // TODO: Allow overriding the mocha opts mocha object in main testConfig.json?73 // TODO: Could we speed up test writing by watching the e2e dir74 // and then restarting on change, rather than requiring a rebuild?75 const Mocha = requireWithOverride('mocha', projectDir);76 const mocha = new Mocha();77 for (const file of testFiles) {78 logger.debug(`Adding ${file} to mocha instance`);79 mocha.addFile(file);80 }81 mocha.run()82 .on('end', async () => {83 logger.info('Test finished, stopping appium server');84 await driver.quit();85 appiumServer.stop();86 });87 } catch (e) {88 logger.error(e);89 // TODO: Handle these to make nicer error logs90 switch (e.code) {91 case 'ETIMEDOUT':92 break;93 case 'ESPAWNFAILED':94 break;95 case 'ENOTSUPPORTED':96 break;97 default:98 break;99 }100 appiumServer.started && appiumServer.stop();101 }102 }103 finished();104 });...
appium.js
Source:appium.js
1/**2 * Created by aluedeke on 31.05.15.3 */4var Remote = require('remote');5var Appium = Remote.require('appium');6var defaultAppiumArgs = Remote.require('appium/lib/server/parser')().parseArgs();7var logger = Remote.require('appium/lib/server/logger').get('appium');8var async = require('async');9var xml2js = require('xml2js');10module.exports = ['$rootScope', '$q', '$interval', function($rootScope, $q, $interval) {11 function keepAlive(appiumServer){12 var intervalPromise = $interval(function(){ appiumServer.resetTimeout()}, appiumServer.commandTimeoutMs / 2);13 return function() {$interval.cancel(intervalPromise)};14 }15 function startAppiumServer(appiumShutdownDeferred){16 return function(cb){17 Appium.run(defaultAppiumArgs, function(appiumServer) {cb(null, appiumServer)}, function(){appiumShutdownDeferred.resolve()});18 }19 }20 function startAppiumSession(capabilities){21 return function(appiumServer, cb){22 appiumServer.start(capabilities, function(err, appiumSession) {23 cb(err, appiumServer, appiumSession)24 });25 }26 }27 return {28 start: function(capabilities){29 var appiumDeferred = $q.defer();30 var appiumShutdownDeferred = $q.defer();31 async.waterfall([startAppiumServer(appiumShutdownDeferred), startAppiumSession(capabilities)], function(err, server, session){32 if(err){33 appiumDeferred.reject(err);34 } else {35 appiumDeferred.resolve({server: server, session: session, donePromise: appiumShutdownDeferred.promise, stopKeepAlive: keepAlive(server)});36 }37 });38 return appiumDeferred.promise;39 },40 stop: function(appium){41 appium.stopKeepAlive();42 appium.session.stop(function(err, result){43 appium.server.shutdown();44 });45 return appium.donePromise;46 },47 takeScreenshot: function(appium){48 var imageDeferred = $q.defer();49 appium.server.device.getScreenshot(function(err, response){50 if(err){51 imageDeferred.reject(err);52 } else {53 imageDeferred.resolve(response.value);54 }55 });56 return imageDeferred.promise;57 },58 takePageSource: function(appium){59 var sourceDeferred = $q.defer();60 function toJSONObject(json, cb){61 return xml2js.parseString(json.value, {explicitRoot: false, explicitChildren: true, childkey: 'children', preserveChildrenOrder: true}, cb);62 }63 async.waterfall([appium.server.device.getPageSource, toJSONObject], function(err, json){64 if(err){65 sourceDeferred.reject(err);66 } else {67 sourceDeferred.resolve(json);68 }69 });70 return sourceDeferred.promise;71 },72 log: function(cb){73 logger.on('logging', cb);74 return { close: function(){ logger.remove('logging', cb)}};75 }76 };...
world.js
Source:world.js
1import { defineSupportCode } from 'cucumber';2import 'colors';3import { install } from 'source-map-support';4import chai, { should, expect } from 'chai';5import Bluebird from 'bluebird';6import chaiAsPromised from 'chai-as-promised';7import wd from 'wd';8import homeScreen from '../pages/pages_common/homeScreen';9import loginScreen from '../pages/pages_login_and_registration/loginScreen';10import myAccountScreen from '../pages/pages_login_and_registration/myAccountScreen';11import myProfileScreen from '../pages/pages_login_and_registration/myProfileScreen';12import menuScreen from '../pages/pages_common/menuScreen';13// Enable source maps14install();15chai.use(chaiAsPromised);16global.should = should();17global.expect = expect;18global.Promise = Bluebird;19const appiumServerConfig = {20 host: "localhost",21 port: 472322};23// enables chai assertion chaining24chaiAsPromised.transferPromiseness = wd.transferPromiseness;25wd.addPromiseChainMethod();26class World {27 constructor({ attach, parameters }) {28 if (typeof parameters.appiumServer === 'string') {29 this.driver = wd.promiseChainRemote(parameters.appiumServer);30 } else {31 this.driver = wd.promiseChainRemote(32 parameters.appiumServer || appiumServerConfig33 );34 }35 this.parameters = parameters;36 this.currentPlatform = parameters.device.platformName;37 this.deviceName = parameters.device.deviceName;38 this.pages = {39 homeScreen: new homeScreen(this.driver, this.currentPlatform, this.deviceName),40 loginScreen: new loginScreen(this.driver, this.currentPlatform, this.deviceName),41 myAccountScreen: new myAccountScreen(this.driver, this.currentPlatform, this.deviceName),42 myProfileScreen: new myProfileScreen(this.driver, this.currentPlatform, this.deviceName),43 menuScreen: new menuScreen(this.driver, this.currentPlatform, this.deviceName)44 };45 this.attach = attach;46 }47}48defineSupportCode(({ setWorldConstructor, setDefaultTimeout }) => {49 setWorldConstructor(World);50 setDefaultTimeout(1200 * 1000);...
appium.test.js
Source:appium.test.js
1import wd from 'wd';2import execa from 'execa';3jest.setTimeout(80000);4const PORT = 4723;5const config = {6 platformName: 'Windows',7 deviceName: 'WindowsPC',8};9const driver = wd.promiseChainRemote('localhost', PORT);10let appiumServer = { cancel() {} };11beforeAll(async () => {12 appiumServer = execa.command('yarn run appium');13 await new Promise(resolve => setTimeout(resolve, 20000));14 await driver.init({ ...config, app: 'Root' });15 await driver.sleep(2000);16 console.log('Getting RNWTestApp native window handle');17 const testAppWindow = await driver.elementByName('RNWTestApp');18 const testAppWindowHandle = await testAppWindow.getAttribute('NativeWindowHandle');19 const testAppHandle = parseInt(testAppWindowHandle, 10).toString(16);20 console.log('Initializing new session with top level window', testAppHandle);21 await driver.init({22 ...config,23 appTopLevelWindow: testAppHandle.toLowerCase(),24 });25 await driver.sleep(2000);26});27afterAll(async () => {28 await driver.quit();29 appiumServer.cancel();30});31async function getByTestId(testId) {32 const element = await driver.waitForElementByAccessibilityId(testId);33 console.log('Found element', testId);34 return element;35}36test('RNWTestApp renders correctly', async () => {37 (await getByTestId('navigateToInitial')).click();38 await driver.sleep(1000);39 expect(await getByTestId('emptyHost')).toBeDefined();40 (await getByTestId('navigateToapp0')).click();41 await driver.sleep(1000);42 expect(await getByTestId('app0')).toBeDefined();43 expect(await (await getByTestId('app0LoadTime')).text()).toMatch(/Load time: ([1-9]|[0-9]{2}) ms/);44 (await getByTestId('navigateToapp1')).click();45 await driver.sleep(1000);46 expect(await getByTestId('app1')).toBeDefined();47 expect(await (await getByTestId('app1LoadTime')).text()).toMatch(/Load time: ([1-9]|[0-9]{2}) ms/);48 expect(await getByTestId('films')).toBeDefined();...
appiumserver.js
Source:appiumserver.js
1import { main as appiumServer } from 'appium';2class AppiumServer {3 async startServer() {4 let args = {};5 return await appiumServer(args);6 }7}...
Using AI Code Generation
1const AppiumServer = require('appium-server');2const appiumServer = new AppiumServer();3appiumServer.appiumServer();4const AppiumServer = require('appium-server');5const appiumServer = new AppiumServer();6appiumServer.appiumServer();7const AppiumServer = require('appium-server');8const appiumServer = new AppiumServer();9appiumServer.appiumServer();10const AppiumServer = require('appium-server');11const appiumServer = new AppiumServer();12appiumServer.appiumServer();13const AppiumServer = require('appium-server');14const appiumServer = new AppiumServer();15appiumServer.appiumServer();16const AppiumServer = require('appium-server');17const appiumServer = new AppiumServer();18appiumServer.appiumServer();19const AppiumServer = require('appium-server');20const appiumServer = new AppiumServer();21appiumServer.appiumServer();22const AppiumServer = require('appium-server');23const appiumServer = new AppiumServer();24appiumServer.appiumServer();25const AppiumServer = require('appium-server');26const appiumServer = new AppiumServer();27appiumServer.appiumServer();28const AppiumServer = require('appium-server');29const appiumServer = new AppiumServer();30appiumServer.appiumServer();31const AppiumServer = require('appium-server');
Using AI Code Generation
1appiumServer.startAppiumServer()2appiumServer.stopAppiumServer()3appiumServer.restartAppiumServer()4appiumServer.startAppiumServer()5appiumServer.restartAppiumServer()6appiumServer.startAppiumServer()7appiumServer.stopAppiumServer()8appiumServer.restartAppiumServer()9appiumServer.startAppiumServer()10appiumServer.restartAppiumServer()11appiumServer.stopAppiumServer()12appiumServer.stopAppiumServer()13appiumServer.startAppiumServer()14appiumServer.restartAppiumServer()
Using AI Code Generation
1var AppiumServer = require('./appiumServer.js');2var appiumServer = new AppiumServer();3appiumServer.appiumServer();4var appium = require('appium');5var wd = require('wd');6var child_process = require('child_process');7var fs = require('fs');8var path = require('path');9var exec = require('child_process').exec;10var AppiumServer = function() {11 this.appiumServer = function() {12 var appiumServer = appium();13 var appiumServerProcess = child_process.spawn('appium');14 appiumServerProcess.stdout.on('data', function(data) {15 console.log('stdout: ' + data);16 });17 appiumServerProcess.stderr.on('data', function(data) {18 console.log('stderr: ' + data);19 });20 appiumServerProcess.on('close', function(code) {21 console.log('closing code: ' + code);22 });23 }24}25module.exports = AppiumServer;26var AppiumServer = require('./appiumServer.js');27var appiumServer = new AppiumServer();28appiumServer.appiumServer();29var appium = require('appium');30var wd = require('wd');31var child_process = require('child_process');32var fs = require('fs');33var path = require('path');34var exec = require('child_process').exec;35var AppiumServer = function() {36 this.appiumServer = function() {37 var appiumServer = appium();38 var appiumServerProcess = child_process.spawn('appium');39 appiumServerProcess.stdout.on('data', function(data) {40 console.log('stdout: ' + data);41 });42 appiumServerProcess.stderr.on('data', function(data) {43 console.log('stderr: ' + data);44 });45 appiumServerProcess.on('close', function(code) {46 console.log('closing code: ' + code);47 });48 }49}50module.exports = AppiumServer;51var AppiumServer = require('./appiumServer.js');
Using AI Code Generation
1var appiumServer = require('./appiumServer');2appiumServer.startAppiumServer();3var appium = require('appium');4var child_process = require('child_process');5var server = null;6var startAppiumServer = function() {7 var args = {
Using AI Code Generation
1var appiumServer = require('./appiumServer.js');2appiumServer.startAppiumServer();3var AppiumServer = function () {4 this.appiumServer = require('appium');5};6AppiumServer.prototype.startAppiumServer = function () {7 this.appiumServer.main({logNoColors: true});8};9module.exports = new AppiumServer();
Using AI Code Generation
1var AppiumDriver = require('appium-java-client').AppiumDriver;2var AndroidDriver = require('appium-java-client').AndroidDriver;3var appiumDriver = new AppiumDriver();4appiumDriver.getAppiumServer();5var AndroidDriver = require('appium-java-client').AndroidDriver;6var androidDriver = new AndroidDriver();7androidDriver.getAppiumServer();8var AndroidDriver = require('appium-java-client').AndroidDriver;9var androidDriver = new AndroidDriver();10androidDriver.getAppiumServer();11var AndroidDriver = require('appium-java-client').AndroidDriver;12var androidDriver = new AndroidDriver();13androidDriver.getAppiumServer();14var AndroidDriver = require('appium-java-client').AndroidDriver;15var androidDriver = new AndroidDriver();16androidDriver.getAppiumServer();17var AndroidDriver = require('appium-java-client').AndroidDriver;18var androidDriver = new AndroidDriver();19androidDriver.getAppiumServer();20var AndroidDriver = require('appium-java-client').AndroidDriver;21var androidDriver = new AndroidDriver();22androidDriver.getAppiumServer();23var AndroidDriver = require('appium-java-client').AndroidDriver;24var androidDriver = new AndroidDriver();25androidDriver.getAppiumServer();26var AndroidDriver = require('appium-java-client').AndroidDriver;27var androidDriver = new AndroidDriver();28androidDriver.getAppiumServer();29var AndroidDriver = require('appium-java-client').AndroidDriver;30var androidDriver = new AndroidDriver();31androidDriver.getAppiumServer();32var AndroidDriver = require('appium-java-client').AndroidDriver;33var androidDriver = new AndroidDriver();34androidDriver.getAppiumServer();35var AndroidDriver = require('appium-java-client').AndroidDriver;36var androidDriver = new AndroidDriver();
Using AI Code Generation
1var AppiumDriver = require('appiumdriver');2var appiumDriver = new AppiumDriver();3appiumDriver.appiumServer(function(err, res) {4 if (err) {5 console.log(err);6 } else {7 console.log(res);8 }9});10var AppiumDriver = require('appiumdriver');11var appiumDriver = new AppiumDriver();12appiumDriver.stopAppiumServer(function(err, res) {13 if (err) {14 console.log(err);15 } else {16 console.log(res);17 }18});19var AppiumDriver = require('appiumdriver');20var appiumDriver = new AppiumDriver();21appiumDriver.appiumServer(function(err, res) {22 if (err) {23 console.log(err);24 } else {25 console.log(res);26 }27});28var AppiumDriver = require('appiumdriver');29var appiumDriver = new AppiumDriver();30appiumDriver.stopAppiumServer(function(err, res) {31 if (err) {32 console.log(err);33 } else {34 console.log(res);35 }36});37var AppiumDriver = require('appiumdriver');38var appiumDriver = new AppiumDriver();39appiumDriver.appiumServer(function(err, res) {40 if (err) {41 console.log(err);42 } else {43 console.log(res);44 }45});46var AppiumDriver = require('appiumdriver');47var appiumDriver = new AppiumDriver();48appiumDriver.stopAppiumServer(function(err, res) {49 if (err) {50 console.log(err);51 } else {52 console.log(res);53 }54});55var AppiumDriver = require('appiumdriver');56var appiumDriver = new AppiumDriver();57appiumDriver.appiumServer(function(err, res) {58 if (err) {
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!!