Best JavaScript code snippet using appium-xcuitest-driver
driver.js
Source:driver.js
...183 }184 if (this.isRealDevice()) {185 await runRealDeviceReset(this.realDevice, this.opts);186 } else {187 await runSimulatorReset(this.sim, this.opts, this.keepAppToRetainPrefs);188 }189 await super.deleteSession();190 }191 async getSession () {192 let caps = await super.getSession();193 const viewportRect = await this.getViewportRect();194 const pixelRatio = await this.getDevicePixelRatio();195 const statBarHeight = await this.getStatusBarHeight();196 caps.viewportRect = viewportRect;197 caps.pixelRatio = pixelRatio;198 caps.statBarHeight = statBarHeight;199 return caps;200 }201 async executeCommand (cmd, ...args) {202 logger.debug(`Executing iOS command '${cmd}'`);203 if (cmd === 'receiveAsyncResponse') {204 return await this.receiveAsyncResponse(...args);205 } else if (this.ready || _.includes(['launchApp'], cmd)) {206 return await super.executeCommand(cmd, ...args);207 }208 throw new errors.NoSuchDriverError(`Driver is not ready, cannot execute ${cmd}.`);209 }210 // TODO: reformat this.helpers + configureApp211 async configureApp () {212 try {213 // if the app name is a bundleId assign it to the bundleId property214 if (!this.opts.bundleId && utils.appIsPackageOrBundle(this.opts.app)) {215 this.opts.bundleId = this.opts.app;216 }217 if (this.opts.app && this.opts.app.toLowerCase() === 'settings') {218 if (parseFloat(this.opts.platformVersion) >= 8) {219 logger.debug('We are on iOS8+ so not copying preferences app');220 this.opts.bundleId = 'com.apple.Preferences';221 this.opts.app = null;222 }223 } else if (this.opts.app && this.opts.app.toLowerCase() === 'calendar') {224 if (parseFloat(this.opts.platformVersion) >= 8) {225 logger.debug('We are on iOS8+ so not copying calendar app');226 this.opts.bundleId = 'com.apple.mobilecal';227 this.opts.app = null;228 }229 } else if (this.isSafari()) {230 if (!this.isRealDevice()) {231 if (parseFloat(this.opts.platformVersion) >= 8) {232 logger.debug('We are on iOS8+ so not copying Safari app');233 this.opts.bundleId = SAFARI_BUNDLE;234 this.opts.app = null;235 }236 } else {237 // on real device, need to check if safari launcher exists238 // first check if it is already on the device239 if (!await this.realDevice.isInstalled(this.opts.bundleId)) {240 // it's not on the device, so check if we need to build241 if (await needsInstall()) {242 logger.debug('SafariLauncher not found, building...');243 await install();244 }245 this.opts.bundleId = SAFARI_LAUNCHER_BUNDLE;246 }247 }248 } else if (this.opts.bundleId &&249 utils.appIsPackageOrBundle(this.opts.bundleId) &&250 (this.opts.app === '' || utils.appIsPackageOrBundle(this.opts.app))) {251 // we have a bundle ID, but no app, or app is also a bundle252 logger.debug('App is an iOS bundle, will attempt to run as pre-existing');253 } else {254 this.opts.app = await this.helpers.configureApp(this.opts.app, '.app');255 }256 } catch (err) {257 logger.error(err);258 throw new Error(259 `Bad app: ${this.opts.app}. App paths need to be absolute, or relative to the appium ` +260 'server install dir, or a URL to compressed file, or a special app name.');261 }262 }263 async startSimulator () {264 await utils.removeInstrumentsSocket(this.sock);265 if (!this.xcodeVersion) {266 logger.debug('Setting Xcode version');267 this.xcodeVersion = await utils.getAndCheckXcodeVersion(this.opts);268 logger.debug(`Xcode version set to ${this.xcodeVersion.versionString}`);269 }270 logger.debug('Setting iOS SDK Version');271 this.iosSdkVersion = await utils.getAndCheckIosSdkVersion();272 logger.debug(`iOS SDK Version set to ${this.iosSdkVersion}`);273 let timeout = _.isObject(this.opts.launchTimeout) ? this.opts.launchTimeout.global : this.opts.launchTimeout;274 let availableDevices = await retry(3, instrumentsUtils.getAvailableDevices, timeout);275 let iosSimUdid = await checkSimulatorAvailable(this.opts, this.iosSdkVersion, availableDevices);276 this.sim = await getSimulator(iosSimUdid, this.xcodeVersion.versionString);277 await moveBuiltInApp(this.sim);278 this.opts.localizableStrings = await utils.parseLocalizableStrings(this.opts);279 await utils.setBundleIdFromApp(this.opts);280 await this.createInstruments();281 {282 // previously setDeviceInfo()283 this.shouldPrelaunchSimulator = utils.shouldPrelaunchSimulator(this.opts, this.iosSdkVersion);284 let dString = await getAdjustedDeviceName(this.opts);285 if (this.caps.app) {286 await utils.setDeviceTypeInInfoPlist(this.opts.app, dString);287 }288 }289 await runSimulatorReset(this.sim, this.opts, this.keepAppToRetainPrefs);290 if (this.caps.customSSLCert && !this.isRealDevice()) {291 await installSSLCert(this.caps.customSSLCert, this.sim.udid);292 }293 if (this.opts.enableAsyncExecuteFromHttps && !this.isRealDevice()) {294 // await this.sim.shutdown();295 await this.startHttpsAsyncServer();296 }297 await isolateSimulatorDevice(this.sim, this.opts);298 this.localConfig = await setLocaleAndPreferences(this.sim, this.opts, this.isSafari(), endSimulator);299 await this.setUpLogCapture();300 await this.prelaunchSimulator();301 await this.startInstruments();302 await this.onInstrumentsLaunch();303 await this.configureBootstrap();...
simulator-management-specs.js
Source:simulator-management-specs.js
...88 udid: '301CD634-00A9-4042-B463-BD4E755167EA',89 bundleId: 'io.appium.example',90 noReset: false, fullReset: false91 };92 await runSimulatorReset(stoppedDeviceDummy, opts);93 result.path.should.eql('');94 result.bundleId.should.eql('io.appium.example');95 });96 it('should return immediately with noReset', async function () {97 const opts = {98 udid: '301CD634-00A9-4042-B463-BD4E755167EA',99 bundleId: 'io.appium.example',100 noReset: true, fullReset: false101 };102 await runSimulatorReset(stoppedDeviceDummy, opts);103 should.equal(result, undefined);104 });105 it('should call clean with fullRest', async function () {106 const opts = {107 udid: '301CD634-00A9-4042-B463-BD4E755167EA',108 bundleId: 'io.appium.example',109 noReset: false, fullReset: true110 };111 await runSimulatorReset(stoppedDeviceDummy, opts);112 result.should.eql('cleaned');113 });114 it('should call scrubCustomApp with fastReset and app', async function () {115 const opts = {116 udid: '301CD634-00A9-4042-B463-BD4E755167EA',117 bundleId: 'io.appium.example',118 app: 'path/to/app.app',119 noReset: false, fullReset: false120 };121 await runSimulatorReset(stoppedDeviceDummy, opts);122 should.equal(result, undefined);123 });124 it('should return immediately with noReset and app', async function () {125 const opts = {126 udid: '301CD634-00A9-4042-B463-BD4E755167EA',127 bundleId: 'io.appium.example',128 app: 'path/to/app.app',129 noReset: true, fullReset: false130 };131 await runSimulatorReset(stoppedDeviceDummy, opts);132 should.equal(result, undefined);133 });134 it('should call clean with fullRest and app', async function () {135 const opts = {136 udid: '301CD634-00A9-4042-B463-BD4E755167EA',137 bundleId: 'io.appium.example',138 app: 'path/to/app.app',139 noReset: false, fullReset: true140 };141 await runSimulatorReset(stoppedDeviceDummy, opts);142 result.should.eql('cleaned');143 });144 it('should not call scrubCustomApp with fastReset, but no bundleid and app', async function () {145 const opts = {146 udid: '301CD634-00A9-4042-B463-BD4E755167EA',147 noReset: false, fullReset: false148 };149 await runSimulatorReset(stoppedDeviceDummy, opts);150 should.equal(result, undefined);151 });152 });...
device.js
Source:device.js
1import _ from 'lodash';2import { getDeviceString } from 'appium-ios-simulator';3import path from 'path';4import * as utils from './utils';5import logger from './logger';6async function checkSimulatorAvailable (opts, sdkVersion, availableDevices) {7 if (sdkVersion < 7.1) {8 logger.debug('Instruments v < 7.1, not checking device string support');9 return;10 }11 logger.debug('Checking whether our device string is supported');12 let dString = await getAdjustedDeviceName(opts);13 let noDevicesError = function () {14 let msg = `Could not find a device to launch. You requested ` +15 `'${dString}', but the available devices were: ` +16 JSON.stringify(availableDevices);17 logger.errorAndThrow(msg);18 };19 if (sdkVersion >= 8) {20 let sim = utils.getSimForDeviceString(dString, availableDevices);21 if (sim[0] === null || sim[1] === null) {22 noDevicesError();23 }24 logger.debug(`iOS sim UDID is ${sim[1]}`);25 return sim[1];26 } else if (!_.includes(availableDevices, dString)) {27 noDevicesError();28 }29}30async function getAdjustedDeviceName (opts) {31 opts._adjustedDeviceName = opts._adjustedDeviceName || await getDeviceString(opts);32 return opts._adjustedDeviceName;33}34// TODO: what to do with this?35async function moveBuiltInApp (/*sim*/) {36 // call sim function once it is in place37}38async function runSimulatorReset (sim, opts, keepApp) {39 if (!opts.reset && !opts.fullReset) {40 logger.debug('Reset not set, not ending sim');41 return;42 }43 logger.debug('Running ios sim reset flow');44 // The simulator process must be ended before we delete applications.45 await endSimulator(sim);46 if (opts.fullReset) {47 logger.debug('Full reset is on, so erasing simulator');48 await fullResetSimulator(sim);49 } else if (opts.reset) {50 await resetSimulator(sim, opts, keepApp);51 }52}53async function fullResetSimulator (sim) {54 logger.debug('Cleaning the simulator');55 if (sim) {56 await sim.clean();57 }58}59async function resetSimulator (sim, opts, keepApp) {60 if (!sim) return; // eslint-disable-line curly61 logger.debug('Cleaning sim state.');62 try {63 await clearAppData(sim, opts, keepApp);64 } catch (err) {65 logger.warn(err);66 logger.warn('Could not reset simulator. Leaving as is.');67 }68}69async function endSimulator (sim) {70 if (!sim) return; // eslint-disable-line curly71 logger.debug('Killing the simulator');72 await sim.shutdown();73}74async function isolateSimulatorDevice (sim, opts, sdkVersion) {75 if (opts.isolateSimDevice && sdkVersion >= 8) {76 await sim.isolateSim();77 }78}79async function clearAppData (sim, opts, keepApp) {80 if (!keepApp && opts.app && opts.bundleId) {81 await sim.cleanCustomApp(path.basename(opts.app), opts.bundleId);82 }83}84async function resetRealDevice (device, opts) {85 if (opts.bundleId && opts.fullReset) {86 let bundleId = opts.bundleId;87 logger.debug(`Full reset requested. Will try to uninstall the app '${bundleId}'.`);88 if (!await device.isInstalled(bundleId)) {89 logger.debug('App not installed. No need to uninstall');90 return;91 }92 try {93 await device.remove(bundleId);94 } catch (err) {95 logger.error(`Could not remove '${bundleId}' from device`);96 throw err;97 }98 logger.debug(`Removed ${bundleId}`);99 }100}101async function runRealDeviceReset (device, opts) {102 if (opts.reset || opts.fullReset) {103 logger.debug('Running ios real device reset flow');104 if (opts.reset) {105 await resetRealDevice(device, opts);106 }107 } else {108 logger.debug('Reset not set, continuing');109 }110}111export {112 runSimulatorReset, isolateSimulatorDevice, checkSimulatorAvailable,113 moveBuiltInApp, getAdjustedDeviceName, endSimulator, runRealDeviceReset,...
simulator-management.js
Source:simulator-management.js
1import path from 'path';2import { getSimulator } from 'appium-ios-simulator';3import { createDevice, getDevices, terminate } from 'node-simctl';4import { resetXCTestProcesses } from './utils';5import _ from 'lodash';6import log from './logger';7// returns sim for desired caps8async function createSim (caps, sessionId) {9 let name = `appiumTest-${sessionId}`;10 let udid = await createDevice(name, caps.deviceName, caps.platformVersion);11 return await getSimulator(udid);12}13async function getExistingSim (opts) {14 let devices = await getDevices(opts.platformVersion);15 for (let device of _.values(devices)) {16 if (device.name === opts.deviceName) {17 return await getSimulator(device.udid);18 }19 }20 return null;21}22async function runSimulatorReset (device, opts) {23 if (opts.noReset && !opts.fullReset) {24 // noReset === true && fullReset === false25 log.debug('Reset: noReset is on. Leaving simulator as is');26 return;27 }28 if (!device) {29 log.debug('Reset: no device available. Skipping');30 return;31 }32 if (opts.fullReset) {33 log.debug('Reset: fullReset is on. Cleaning simulator');34 // stop XCTest processes if running to avoid unexpected side effects35 await resetXCTestProcesses(device.udid, true);36 // The simulator process must be ended before we delete applications.37 await device.shutdown();38 await device.clean();39 } else if (opts.bundleId) {40 // Terminate the app under test if it is still running on Simulator41 // Termination is not needed if Simulator is not running42 if (await device.isRunning()) {43 if (device.xcodeVersion.major >= 8) {44 try {45 await terminate(device.udid, opts.bundleId);46 } catch (err) {47 log.warn(`Reset: failed to terminate Simulator application with id "${opts.bundleId}"`);48 }49 } else {50 await device.shutdown();51 }52 }53 if (opts.app) {54 log.info('Not scrubbing third party app in anticipation of uninstall');55 return;56 }57 const isSafari = (opts.browserName || '').toLowerCase() === 'safari';58 try {59 if (isSafari) {60 await device.cleanSafari();61 } else {62 await device.scrubCustomApp(path.basename(opts.app), opts.bundleId);63 }64 } catch (err) {65 log.warn(err.message);66 log.warn(`Reset: could not scrub ${isSafari ? 'Safari browser' : 'application with id "' + opts.bundleId + '"'}. Leaving as is.`);67 }68 }69}70async function installToSimulator (device, app, bundleId, noReset = true) {71 if (!app) {72 log.debug('No app path is given. Nothing to install.');73 return;74 }75 if (bundleId) {76 if (await device.isAppInstalled(bundleId)) {77 if (noReset) {78 log.debug(`App '${bundleId}' is already installed. No need to reinstall.`);79 return;80 }81 log.debug(`Reset requested. Removing app with id '${bundleId}' from the device`);82 await device.removeApp(bundleId);83 }84 }85 log.debug(`Installing '${app}' on Simulator with UUID '${device.udid}'...`);86 await device.installApp(app);87 log.debug('The app has been installed successfully.');88}...
Using AI Code Generation
1const wd = require('wd');2driver.init({3}).then(() => {4 return driver.runSimulatorReset('iPhone 7', '11.2');5}).then(() => {6 return driver.quit();7}).catch((err) => {8 console.log(err);9});10commands.runSimulatorReset = async function (udid, version) {11 if (!udid) {12 throw new Error('udid is required to reset simulator');13 }14 if (!version) {15 throw new Error('version is required to reset simulator');16 }17 const sim = await getSimulator(udid, version);18 await sim.runReset();19};20async runReset () {21 await this.shutdown();22 await this.delete();23 await this.create();24 await this.start();25}26async shutdown () {27 await this.simctl.shutdownDevice(this.udid);28}29async shutdownDevice (udid) {30 await this.runCommand(['simctl', 'shutdown', udid]);31}32async runCommand (args, opts = {}) {33 const {timeout} = opts;34 log.info(`Executing simctl with args '${JSON.stringify(args)}' and timeout '${timeout}'`);35 try {36 return await exec('xcrun', args, {timeout});37 } catch (err) {38 log.errorAndThrow(`simctl error running '${args}': ${err.message}`);39 }40}41const wd = require('wd');
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var caps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6 .init(caps)7 .runSimulatorReset()8 .quit();9from appium import webdriver10from selenium.webdriver.support.ui import WebDriverWait11from selenium.webdriver.support import expected_conditions as EC12from selenium.webdriver.common.by import By13caps = {14}15driver.run_simulator_reset()16driver.quit()17import io.appium.java_client.ios.IOSDriver;18import io.appium.java_client.remote.MobileCapabilityType;19import org.openqa.selenium.remote.DesiredCapabilities;20import java.net.URL;21import java.net.MalformedURLException;22public class Test {23 public static void main(String[] args) throws MalformedURLException {24 DesiredCapabilities caps = new DesiredCapabilities();25 caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");26 caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10.2");27 caps.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 6");28 caps.setCapability(MobileCapabilityType.APP, "path/to/app");
Using AI Code Generation
1var wd = require('wd');2var path = require('path');3var asserters = wd.asserters;4var _ = require('lodash');5var fs = require('fs');6var os = require('os');7var rimraf = require('rimraf');8var desired = {9};10var driver = wd.promiseChainRemote('localhost', 4723);11driver.on('status', function(info) {12 console.log('\x1b[36m%s\x1b[0m', info);13});14driver.on('command', function(meth, path, data) {15 console.log(' > \x1b[33m%s\x1b[0m: %s', meth, path, data || '');16});17driver.on('http', function(meth, path, data) {18 console.log(' > \x1b[90m%s\x1b[0m %s', meth, path, data || '');19});20 .init(desired)21 .then(function() {22 return driver.resetApp();23 })24 .then(function() {25 return driver.quit();26 })27 .catch(function(err) {28 console.error('Error: ' + err);29 })30 .finally(function() {31 console.log('Done');32 });
Using AI Code Generation
1package com.appium;2import io.appium.java_client.ios.IOSDriver;3import io.appium.java_client.ios.IOSElement;4import org.openqa.selenium.By;5import org.openqa.selenium.remote.DesiredCapabilities;6import java.net.MalformedURLException;7import java.net.URL;8public class ResetShutdownSimulator {9 public static void main(String[] args) throws MalformedURLException {10 DesiredCapabilities capabilities = new DesiredCapabilities();11 capabilities.setCapability("platformName", "iOS");12 capabilities.setCapability("platformVersion", "13.6");13 capabilities.setCapability("deviceName", "iPhone 11 Pro Max");14 capabilities.setCapability("automationName", "XCUITest");15 capabilities.setCapability("app", "path/to/your/app");
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!!