How to use shutdownFn method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

filter.jsm

Source:filter.jsm Github

copy

Full Screen

...258        // if (typeof id !== "undefined" && e.data && e.data.id !== id) {259        //     return;260        // }261        if (typeof shutdownFn === "function") {262            shutdownFn();263        }264        global.removeEventListener("unload", shutdown, false);265        global.removeMessageListener(host + "unload", shutdown);266        global.removeEventListener("DOMContentLoaded", loads, false);267    };268    global.addEventListener("unload", shutdown, false);269    global.addMessageListener(host + "unload", shutdown);270    global.addEventListener("DOMContentLoaded", loads, false);271}272function addFrameAddress (global) {273    var scan = function (msg) {274        global.removeMessageListener(host + "scan", scan);275        var newURL = scanURL(msg.data.url);276        if (newURL && global.sendSyncMessage(host + "results", {block: true})[0]) {...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const { spawn } = require('child_process')2const Ganache = require('ganache-core')3const IPFS = require('ipfs')4const HttpIPFS = require('ipfs/src/http')5const fs = require('fs')6const memdown = require('memdown')7const net = require('net')8// Constants9const contractsPackageDir = `${__dirname}/../contracts`10const truffleBuildDir = `${contractsPackageDir}/build/contracts`11const devJsonConfigPath = `${contractsPackageDir}/build/contracts.json`12const portInUse = (port) =>13  new Promise(function (resolve) {14    const srv = net15      .createServer()16      .once('error', () => resolve(true))17      .once('listening', () => srv.once('close', () => resolve(false)).close())18      .listen(port, '0.0.0.0')19  })20const startGanache = (opts = {}) =>21  new Promise((resolve, reject) => {22    console.log('Starting ganache...')23    const ganacheOpts = {24      total_accounts: opts.total_accounts || 5,25      default_balance_ether: 100,26      db_path: `${__dirname}/data/db`,27      network_id: 999,28      mnemonic:29        'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat'30      // blockTime: 331    }32    if (opts.inMemory) {33      ganacheOpts.db = memdown()34    } else {35      try {36        fs.mkdirSync(`${__dirname}/data/db`)37      } catch (e) {38        /* Ignore */39      }40    }41    const server = Ganache.server(ganacheOpts)42    const port = 854543    server.listen(port, (err) => {44      if (err) {45        return reject(err)46      }47      console.log(`Ganache listening on port ${port}.`)48      resolve(server)49    })50  })51const startIpfs = async () => {52  console.log('Start IPFS')53  const ipfs = await IPFS.create({54    repo: `${__dirname}/data/ipfs`,55    preload: {56      enabled: false57    },58    config: {59      Addresses: {60        API: '/ip4/0.0.0.0/tcp/5002',61        Gateway: '/ip4/0.0.0.0/tcp/8080',62        Swarm: []63      },64      Bootstrap: [],65      Discovery: {66        MDNS: { Enabled: false },67        webRTCStar: { Enabled: false }68      }69    }70  })71  const httpAPI = new HttpIPFS(ipfs)72  await httpAPI.start()73  console.log('Started IPFS')74  return httpAPI75}76/**77 * Utility method to update the JSON config file for local network based on78 * addresses of contracts deployed by truffle.79 *  - Look for contracts ABIs in truffle's build directory: packages/contracts/build/contracts/80 *  - Get the contract's address for network 99981 *  - Write the address into the JSON config file packages/contracts/build/contracts.json82 */83function _updateContractsJsonConfig() {84  // Mapping between contract names and their associated key85  // in the JSON file packages/contracts/build/contracts.json86  const contracts = {87    V01_Marketplace: 'Marketplace_V01',88    OriginToken: 'OGN',89    MockOUSD: 'OUSD'90  }91  // 1. Look for contracts ABIs in truffle's build directory92  const addresses = {}93  for (const [contractName, configFieldName] of Object.entries(contracts)) {94    const abiPath = `${truffleBuildDir}/${contractName}.json`95    try {96      const rawAbi = fs.readFileSync(abiPath)97      const abi = JSON.parse(rawAbi)98      const address = abi.networks['999'].address99      addresses[configFieldName] = address100      console.log(`Found ABI for ${contractName}. Address=${address}`)101    } catch (err) {102      console.log(`Failed loading truffle generated ABI at ${abiPath}:`, err)103    }104  }105  // Write the addresses that were collected to packages/contracts/build/contracts.json106  if (!fs.existsSync(devJsonConfigPath)) {107    // If for some reason the config is not present, create an empty one.108    fs.writeFileSync(devJsonConfigPath, '{}')109  }110  try {111    // Read the config file from disk, update the addresses and write it back.112    let config = {}113    if (fs.existsSync(devJsonConfigPath)) {114      const rawConfig = fs.readFileSync(devJsonConfigPath)115      config = JSON.parse(rawConfig)116    }117    config = { ...config, ...addresses }118    fs.writeFileSync(devJsonConfigPath, JSON.stringify(config, null, 2))119    console.log(`Updated ${devJsonConfigPath} with locally deployed addresses`)120  } catch (err) {121    console.log(`Failed updating to ${devJsonConfigPath}:`, err)122  }123}124const deployContracts = () =>125  new Promise((resolve, reject) => {126    console.log('Deploying contracts...')127    const cmd = spawn(`npm`, ['run', 'migrate'], {128      cwd: contractsPackageDir,129      stdio: 'inherit',130      env: process.env131    })132    cmd.on('exit', (code) => {133      if (code === 0) {134        // Now sync the JSON config so that it points to the deployed contracts addresses.135        _updateContractsJsonConfig()136        console.log('Deploying contracts succeeded.')137        resolve()138      } else {139        reject('Deploying contracts failed.')140        reject()141      }142    })143  })144/**145 * Main entry point for the module.146 * @type {{}}147 */148const started = {}149let extrasResult150module.exports = async function start(opts = {}) {151  // Handle starting Ganache (local blockchain).152  if (opts.ganache && !started.ganache) {153    const ganacheOpts = opts.ganache === true ? {} : opts.ganache154    if (await portInUse(8545)) {155      if (!opts.quiet) {156        console.log('Ganache already started')157      }158    } else {159      started.ganache = await startGanache(ganacheOpts)160    }161  }162  // Handle starting a local IPFS daemon.163  if (opts.ipfs && !started.ipfs) {164    if (await portInUse(5002)) {165      if (!opts.quiet) {166        console.log('IPFS already started')167      }168    } else {169      started.ipfs = await startIpfs()170    }171  }172  // Handle compiling and deploying contracts on the local blockchain.173  // Writes the addresses of the deployed contract to the config174  // at packages/contracts/build/contracts.json175  if (opts.deployContracts && !started.contracts) {176    await deployContracts()177    started.contracts = true178  }179  // Shutdown callback. Cleanly terminates any server that was started.180  const shutdownFn = async function shutdown() {181    console.log('Shutting services down...')182    if (started.ganache) {183      await started.ganache.close()184    }185    if (started.ipfs) {186      await started.ipfs.stop()187      await started.ipfs._ipfs.stop()188    }189  }190  shutdownFn.extrasResult = extrasResult191  return shutdownFn...

Full Screen

Full Screen

settings.js

Source:settings.js Github

copy

Full Screen

...25  const localConfig = await setLocale(sim, opts, {}, safari);26  const prefsUpdated = await setPreferences(sim, opts, safari);27  if (localConfig._updated || prefsUpdated) {28    logger.debug('Updated settings. Rebooting the simulator if it is already open');29    await shutdownFn(sim);30  } else {31    logger.debug('Setting did not need to be updated');32  }33  delete localConfig._updated;34  return localConfig;35}36// pass in the simulator so that other systems that use the function can supply37// whatever they have38async function setLocale (sim, opts, localeConfig = {}, safari = false) {39  if (!opts.language && !opts.locale && !opts.calendarFormat) {40    logger.debug('No reason to set locale');41    return {42      _updated: false,43    };...

Full Screen

Full Screen

controller.js

Source:controller.js Github

copy

Full Screen

...15		const host = lookup(module)16		// if the app needs to do some cleanup before shutting down17		// it can supply a .shutdown method called here18		const shutdownFn = host.app.shutdown || function (done) { done() }19		shutdownFn(() => {20			try {21				host.status = 'offline'22				for (const h in host.app.hosts) {23					if (host.app.hosts[h] === host.app) {24						// remove the app25						host.app.hosts[h] = undefined26					}27				}28				host.app = undefined29				// this is *pretty* hacky, but we don't want to lose diet or the modules object when30				// decaching the module so we hold onto them here and restore them below31				const diet = require.cache[require.resolve('diet')]32				const modules = require.cache[require.resolve('../../../modules')]33				// unrequire the module...

Full Screen

Full Screen

Lifecycle.js

Source:Lifecycle.js Github

copy

Full Screen

...67    }68    try {69      this._state = SHUTTING_DOWN;70      const shutdownFn = this._shutdownFn;71      shutdownFn(this._onShutdownFn, this._onFailureFn); // TODO handle async errors as well72    } catch (e) {73      this._state = SHUTDOWN;74      this._shutdownSignal.fail(e);75    }76  }77  _onShutdown() {78    // TODO throwing may be not the best option79    const state = this._state;80    if (state !== ACTIVE && state !== SHUTTING_DOWN && state !== SHUTDOWN) {81      throw new Error('Can not complete lifecycle this is not started up');82    }83    this._state = SHUTDOWN;84    this._shutdownSignal.emit();85  }...

Full Screen

Full Screen

worker.js

Source:worker.js Github

copy

Full Screen

...31    }32    // if the state of the worker is 'waiting',33    // then we can shutdown safely34    if (workerState === 0) {35      shutdownFn();36    }37  }38  function execJob(job) {39    workerState = 2;40    if (!workerProcesses[job.name]) {41      winston.error('worker: unknown job pushed on the stack', job);42      waitForJob();43      return;44    }45    winston.info('worker: executing job', job);46    winston.profile('worker: execution time', job); // does not print47    var done = function(err) {48      winston.profile('worker: execution time');49      if (err) {50        winston.error('worker: job errored out', job);51        console.log(err);52        waitForJob();53        return;54      }55      winston.info('worker: job completed', job);56      waitForJob();57    }58    done = timeout(done, config.get('timeout'));59    try {60      workerProcesses[job.name](job, done);61    } catch ($e) {62      done($e);63    }64  }65  function waitForJob() {66    workerState = 0;67    winston.info('worker: waiting for job');68    // if the shutdown function is set69    // stop right here cause we shouldn't70    // execute any more jobs71    if (shutdownFn) {72      return shutdownFn();73    }74    queue.pop(function(err, data) {75      workerState = 1;76      if (err) {77        winston.error('worker: error when receiving job data');78        console.log(err);79        return waitForJob();80      }81      var job;82      try {83        job = new Job(_.last(data));84      } catch (err) {85        winston.error('worker: error when interpreting job data');86        console.log(err);...

Full Screen

Full Screen

dontLetMeDown.js

Source:dontLetMeDown.js Github

copy

Full Screen

...27            this.taskIsRunning = false28            clearInterval(_this.watcher)29            setTimeout( () => {30                if (_this.shouldFinish) {31                    _this.shutdownFn()32                } else {33                    _this.taskIsRunning = true;34                    return _this.start()35                }36            }, _this.period)37        })38        this.currentTask.on('error', (error) => {39            _this.log(error);40        })41        return this.currentTask.on('message', data => {42            _this.log("received message " + data)43            if (data === 'alive') {44                _this.lastVerification = _this.moment()45            }46            if (data === 'finish') {47                _this._stop()48            }49        })50    }51    startObserver() {52        this.log('Starting observer')53        this.lastVerification = this.moment();54        const _this = this55        this.watcher = setInterval( () => {56            if (_this.moment().diff(_this.lastVerification, 'milliseconds') > _this.timeout) {57                console.error('Timeout!')58                return _this._stop()59            } else {60                // return log('its ok');61            }62        }, this.observerTimeout)63    }64    _stop() {65        this.log('Forcing exit')66        this.currentTask.kill()67        clearInterval(this.watcher)68    }69    shutdown() {70        console.log('Shutting down', this.name)71        this.shouldFinish = true72        if (!this.taskIsRunning) this.shutdownFn()73    }74    log(msg) {75        if (this.debug) console.log(msg)76    }77}...

Full Screen

Full Screen

shutdown.hook.js

Source:shutdown.hook.js Github

copy

Full Screen

...36    var sortedFunctions = _.sortBy(self.shutdownFunctions, "order");37    return Promise.each(sortedFunctions, function(shutdownFunctionDescriptor, index) {38      self.emit('ComponentShutdown', {name: shutdownFunctionDescriptor.name, order: shutdownFunctionDescriptor.order, index: index})39      var shutdownFn = shutdownFunctionDescriptor.fn;40      return shutdownFn();41    }).timeout(self.timeout, "Shutdown operation timed out after " + self.timeout + 'ms')42      .then(function() {43        self.emit('ShutdownEnded', {code: 0});44        self.exit(0);45      })46      .catch(function(err) {47        self.emit('ShutdownEnded', {code: 1, error: err});48        self.exit(1);49      })50  }).catch(function(error) {51    console.error('Unexpected error during shutdown sequence:\n' + error.stack);52    self.exit(1);53  })54}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5var caps = {6};7chai.use(chaiAsPromised);8chai.should();9var driver = wd.promiseChainRemote('localhost', 4723);10driver.init(caps).then(function() {11}).then(function() {12  return driver.sleep(5000);13}).then(function() {14  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});15}).then(function() {16  return driver.sleep(5000);17}).then(function() {18  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});19}).then(function() {20  return driver.sleep(5000);21}).then(function() {22  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});23}).then(function() {24  return driver.sleep(5000);25}).then(function() {26  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});27}).then(function() {28  return driver.sleep(5000);29}).then(function() {30  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});31}).then(function() {32  return driver.sleep(5000);33}).then(function() {34  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});35}).then(function() {36  return driver.sleep(5000);37}).then(function() {38  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});39}).then(function() {40  return driver.sleep(5000);41}).then(function() {42  return driver.execute('mobile: shutdownFn', {fn: 'function() { return 1; }'});43}).then(function() {44  return driver.sleep(5000);45}).then(function() {46  return driver.execute('mobile: shutdownFn',

Full Screen

Using AI Code Generation

copy

Full Screen

1const { XCUITestDriver } = require('appium-xcuitest-driver');2const { XCUITestDriverShutdownFn } = require('appium-xcuitest-driver/lib/driver');3const driver = new XCUITestDriver();4driver.startSession();5driver.shutdownFn();6const { XCUITestDriver } = require('appium-xcuitest-driver');7const driver = new XCUITestDriver();8driver.startSession();9driver.shutdown();10const { BaseDriver } = require('appium-base-driver');11const driver = new BaseDriver();12driver.startSession();13driver.shutdown();14const { IOSDriver } = require('appium-ios-driver');15const driver = new IOSDriver();16driver.startSession();17driver.shutdown();18{19}

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.shutdownFn();2driver.shutdown();3driver.deleteSession();4driver.deleteSession();5driver.deleteSession();6driver.deleteSession();7driver.deleteSession();8driver.deleteSession();9driver.deleteSession();10driver.deleteSession();11driver.deleteSession();12driver.deleteSession();13driver.deleteSession();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { shutdownFn } = require('appium-xcuitest-driver/lib/driver');2const { shutdown } = require('appium-xcuitest-driver/lib/utils');3async function main() {4  await shutdownFn();5  await shutdown();6}7main();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { exec } = require('child_process');2exec('lsof -t -i tcp:4723', (err, stdout, stderr) => {3    if (err) {4        console.log("Error in getting process id");5        return;6    }7    console.log(`stdout: ${stdout}`);8    console.log(`stderr: ${stderr}`);9});10const { exec } = require('child_process');11exec('lsof -t -i tcp:4723', (err, stdout, stderr) => {12    if (err) {13        console.log("Error in getting process id");14        return;15    }16    console.log(`stdout: ${stdout}`);17    console.log(`stderr: ${stderr}`);18});19const { exec } = require('child_process');20exec('lsof -t -i tcp:4723', (err, stdout, stderr) => {21    if (err) {22        console.log("Error in getting process id");23        return;24    }25    console.log(`stdout: ${stdout}`);26    console.log(`stderr: ${stderr}`);27});28const { exec } = require('child_process');29exec('lsof -t -i tcp:4723', (err, stdout, stderr) => {30    if (err) {31        console.log("Error in getting process id");32        return;33    }34    console.log(`stdout: ${stdout}`);35    console.log(`stderr: ${stderr}`);36});37const { exec } = require('child_process');38exec('lsof -t -i tcp:4723', (err, stdout, stderr) => {39    if (err) {40        console.log("Error in getting process id");41        return;42    }43    console.log(`stdout: ${stdout}`);44    console.log(`stderr: ${stderr}`);

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 Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful