How to use this.runReset method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

driver.js

Source:driver.js Github

copy

Full Screen

...248 }249 if (!this.opts.bundleId) {250 this.opts.bundleId = await this.extractBundleId(this.opts.app);251 }252 await this.runReset();253 const startLogCapture = async () => {254 const result = await this.startLogCapture();255 if (result) {256 this.logEvent('logCaptureStarted');257 }258 return result;259 };260 const isLogCaptureStarted = await startLogCapture();261 log.info(`Setting up ${this.isRealDevice() ? 'real device' : 'simulator'}`);262 if (this.isSimulator()) {263 this.localeConfig = await iosSettings.setLocale(this.opts.device, this.opts, {}, this.isSafari());264 await iosSettings.setPreferences(this.opts.device, this.opts, this.isSafari());265 // Cleanup of installd cache helps to save disk space while running multiple tests266 // without restarting the Simulator: https://github.com/appium/appium/issues/9410267 await this.opts.device.clearCaches('com.apple.mobile.installd.staging');268 await this.startSim();269 this.logEvent('simStarted');270 if (!isLogCaptureStarted) {271 // Retry log capture if Simulator was not running before272 await startLogCapture();273 }274 }275 if (this.opts.app) {276 await this.installApp();277 this.logEvent('appInstalled');278 }279 // if we only have bundle identifier and no app, fail if it is not already installed280 if (!this.opts.app && this.opts.bundleId && !this.safari) {281 if (!await this.opts.device.isAppInstalled(this.opts.bundleId)) {282 log.errorAndThrow(`App with bundle identifier '${this.opts.bundleId}' unknown`);283 }284 }285 await SHARED_RESOURCES_GUARD.acquire(XCUITestDriver.name,286 async () => await this.startWda(this.opts.sessionId, realDevice));287 await this.setInitialOrientation(this.opts.orientation);288 this.logEvent('orientationSet');289 if (this.isRealDevice() && this.opts.startIWDP) {290 try {291 await this.startIWDP();292 log.debug(`Started ios_webkit_debug proxy server at: ${this.iwdpServer.endpoint}`);293 } catch (err) {294 log.errorAndThrow(`Could not start ios_webkit_debug_proxy server: ${err.message}`);295 }296 }297 if (this.isSafari() || this.opts.autoWebview) {298 log.debug('Waiting for initial webview');299 await this.navToInitialWebview();300 this.logEvent('initialWebviewNavigated');301 }302 if (!this.isRealDevice()) {303 if (this.opts.calendarAccessAuthorized) {304 await this.opts.device.enableCalendarAccess(this.opts.bundleId);305 } else if (this.opts.calendarAccessAuthorized === false) {306 await this.opts.device.disableCalendarAccess(this.opts.bundleId);307 }308 }309 }310 async startWda (sessionId, realDevice) {311 this.wda = new WebDriverAgent(this.xcodeVersion, this.opts);312 await this.wda.cleanupObsoleteProcesses();313 if (this.opts.useNewWDA) {314 log.debug(`Capability 'useNewWDA' set to true, so uninstalling WDA before proceeding`);315 await this.wda.quit();316 await this.wda.uninstall();317 this.logEvent('wdaUninstalled');318 } else if (!util.hasValue(this.wda.webDriverAgentUrl) && (await this.wda.isRunning())) {319 log.info(`Will reuse previously cached WDA instance at '${this.wda.url.href}'. ` +320 `Set the wdaLocalPort capability to a value different from ${this.wda.url.port} ` +321 `if this is an undesired behavior.`);322 this.wda.webDriverAgentUrl = this.wda.url.href;323 }324 // local helper for the two places we need to uninstall wda and re-start it325 const quitAndUninstall = async (msg) => {326 log.debug(msg);327 log.debug('Quitting and uninstalling WebDriverAgent, then retrying');328 await this.wda.quit();329 await this.wda.uninstall();330 throw new Error(msg);331 };332 const startupRetries = this.opts.wdaStartupRetries || (this.isRealDevice() ? WDA_REAL_DEV_STARTUP_RETRIES : WDA_SIM_STARTUP_RETRIES);333 const startupRetryInterval = this.opts.wdaStartupRetryInterval || WDA_STARTUP_RETRY_INTERVAL;334 await retryInterval(startupRetries, startupRetryInterval, async () => {335 this.logEvent('wdaStartAttempted');336 try {337 this.cachedWdaStatus = await this.wda.launch(sessionId, realDevice);338 } catch (err) {339 this.logEvent('wdaStartFailed');340 let errorMsg = `Unable to launch WebDriverAgent because of xcodebuild failure: "${err.message}".`;341 if (this.isRealDevice()) {342 errorMsg += ` Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +343 `Try to remove the WebDriverAgentRunner application from the device if it is installed ` +344 `and reboot the device.`;345 }346 await quitAndUninstall(errorMsg);347 }348 this.proxyReqRes = this.wda.proxyReqRes.bind(this.wda);349 this.jwpProxyActive = true;350 try {351 await retryInterval(15, 1000, async () => {352 this.logEvent('wdaSessionAttempted');353 log.debug('Sending createSession command to WDA');354 try {355 this.cachedWdaStatus = this.cachedWdaStatus || await this.proxyCommand('/status', 'GET');356 await this.startWdaSession(this.opts.bundleId, this.opts.processArguments);357 } catch (err) {358 log.debug('Failed to create WDA session. Retrying...');359 throw err;360 }361 });362 this.logEvent('wdaSessionStarted');363 } catch (err) {364 let errorMsg = `Unable to start WebDriverAgent session because of xcodebuild failure: "${err.message}".`;365 if (this.isRealDevice()) {366 errorMsg += ` Make sure you follow the tutorial at ${WDA_REAL_DEV_TUTORIAL_URL}. ` +367 `Try to remove the WebDriverAgentRunner application from the device if it is installed ` +368 `and reboot the device.`;369 }370 await quitAndUninstall(errorMsg);371 }372 if (!util.hasValue(this.opts.preventWDAAttachments)) {373 // XCTest prior to Xcode 9 SDK has no native way to disable attachments374 this.opts.preventWDAAttachments = this.xcodeVersion.major < 9;375 if (this.opts.preventWDAAttachments) {376 log.info('Enabled WDA attachments prevention by default to save the disk space. ' +377 'Set preventWDAAttachments capability to false if this is an undesired behavior.');378 }379 }380 if (this.opts.preventWDAAttachments) {381 await adjustWDAAttachmentsPermissions(this.wda, this.opts.preventWDAAttachments ? '555' : '755');382 this.logEvent('wdaPermsAdjusted');383 }384 if (this.opts.clearSystemFiles) {385 await markSystemFilesForCleanup(this.wda);386 }387 // we expect certain socket errors until this point, but now388 // mark things as fully working389 this.wda.fullyStarted = true;390 this.logEvent('wdaStarted');391 });392 }393 // create an alias so we can actually unit test createSession by stubbing394 // this395 async extractBundleId (app) {396 return await appUtils.extractBundleId(app);397 }398 async runReset (opts = null) {399 this.logEvent('resetStarted');400 if (this.isRealDevice()) {401 await runRealDeviceReset(this.opts.device, opts || this.opts);402 } else {403 await runSimulatorReset(this.opts.device, opts || this.opts);404 }405 this.logEvent('resetComplete');406 }407 async deleteSession () {408 await SHARED_RESOURCES_GUARD.acquire(XCUITestDriver.name, async () => {409 await this.stop();410 // reset the permissions on the derived data folder, if necessary411 if (this.opts.preventWDAAttachments) {412 await adjustWDAAttachmentsPermissions(this.wda, '755');413 }414 if (this.opts.clearSystemFiles) {415 await clearSystemFiles(this.wda, !!this.opts.showXcodeLog);416 } else {417 log.debug('Not clearing log files. Use `clearSystemFiles` capability to turn on.');418 }419 });420 if (this.isWebContext()) {421 log.debug('In a web session. Removing remote debugger');422 await this.stopRemote();423 }424 if (this.opts.resetOnSessionStartOnly === false) {425 await this.runReset();426 }427 if (this.isSimulator() && this.opts.udid && this.opts.customSSLCert) {428 await uninstallSSLCert(this.opts.customSSLCert, this.opts.udid);429 }430 if (this.isSimulator() && !this.opts.noReset && !!this.opts.device) {431 if (this.lifecycleData.createSim) {432 await resetXCTestProcesses(this.opts.udid, true);433 log.debug(`Deleting simulator created for this run (udid: '${this.opts.udid}')`);434 await this.opts.device.shutdown();435 await this.opts.device.delete();436 }437 }438 if (!_.isEmpty(this.logs)) {439 this.logs.syslog.stopCapture();440 this.logs = {};441 }442 if (this.iwdpServer) {443 this.stopIWDP();444 }445 if (this.opts.enableAsyncExecuteFromHttps && !this.isRealDevice()) {446 await this.stopHttpsAsyncServer();447 }448 this.resetIos();449 await super.deleteSession();450 }451 async stop () {452 this.jwpProxyActive = false;453 this.proxyReqRes = null;454 if (this.wda && this.wda.fullyStarted) {455 if (this.wda.jwproxy) {456 try {457 await this.proxyCommand(`/session/${this.sessionId}`, 'DELETE');458 } catch (err) {459 // an error here should not short-circuit the rest of clean up460 log.debug(`Unable to DELETE session on WDA: '${err.message}'. Continuing shutdown.`);461 }462 }463 if (this.wda && !this.wda.webDriverAgentUrl && this.opts.useNewWDA) {464 await this.wda.quit();465 }466 }467 }468 async executeCommand (cmd, ...args) {469 log.debug(`Executing command '${cmd}'`);470 if (cmd === 'receiveAsyncResponse') {471 return await this.receiveAsyncResponse(...args);472 }473 // TODO: once this fix gets into base driver remove from here474 if (cmd === 'getStatus') {475 return await this.getStatus();476 }477 return await super.executeCommand(cmd, ...args);478 }479 async configureApp () {480 function appIsPackageOrBundle (app) {481 return (/^([a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+)+$/).test(app);482 }483 // the app name is a bundleId assign it to the bundleId property484 if (!this.opts.bundleId && appIsPackageOrBundle(this.opts.app)) {485 this.opts.bundleId = this.opts.app;486 this.opts.app = '';487 }488 // we have a bundle ID, but no app, or app is also a bundle489 if ((this.opts.bundleId && appIsPackageOrBundle(this.opts.bundleId)) &&490 (this.opts.app === '' || appIsPackageOrBundle(this.opts.app))) {491 log.debug('App is an iOS bundle, will attempt to run as pre-existing');492 return;493 }494 // check for supported build-in apps495 if (this.opts.app && this.opts.app.toLowerCase() === 'settings') {496 this.opts.bundleId = 'com.apple.Preferences';497 this.opts.app = null;498 return;499 } else if (this.opts.app && this.opts.app.toLowerCase() === 'calendar') {500 this.opts.bundleId = 'com.apple.mobilecal';501 this.opts.app = null;502 return;503 }504 try {505 // download if necessary506 this.opts.app = await this.helpers.configureApp(this.opts.app, '.app', this.opts.mountRoot, this.opts.windowsShareUserName, this.opts.windowsSharePassword);507 } catch (err) {508 log.error(err);509 throw new Error(510 `Bad app: ${this.opts.app}. App paths need to be absolute, or relative to the appium ` +511 'server install dir, or a URL to compressed file, or a special app name.');512 }513 }514 async determineDevice () {515 // in the one case where we create a sim, we will set this state516 this.lifecycleData.createSim = false;517 // if we get generic names, translate them518 this.opts.deviceName = await translateDeviceName(this.xcodeVersion, this.opts.platformVersion, this.opts.deviceName);519 // check for a particular simulator520 if (this.opts.udid && (await simExists(this.opts.udid))) {521 const device = await getSimulator(this.opts.udid);522 return {device, realDevice: false, udid: this.opts.udid};523 }524 if (this.opts.udid) {525 if (this.opts.udid.toLowerCase() === 'auto') {526 try {527 this.opts.udid = await detectUdid();528 } catch (err) {529 // Trying to find matching UDID for Simulator530 log.warn(`Cannot detect any connected real devices. Falling back to Simulator. Original error: ${err.message}`);531 const device = await getExistingSim(this.opts);532 if (!device) {533 // No matching Simulator is found. Throw an error534 log.errorAndThrow(`Cannot detect udid for ${this.opts.deviceName} Simulator running iOS ${this.opts.platformVersion}`);535 }536 // Matching Simulator exists and is found. Use it537 this.opts.udid = device.udid;538 return {device, realDevice: false, udid: device.udid};539 }540 } else {541 // make sure it is a connected device. If not, the udid passed in is invalid542 const devices = await getConnectedDevices();543 log.debug(`Available devices: ${devices.join(', ')}`);544 if (devices.indexOf(this.opts.udid) === -1) {545 throw new Error(`Unknown device or simulator UDID: '${this.opts.udid}'`);546 }547 }548 const device = await getRealDeviceObj(this.opts.udid);549 return {device, realDevice: true, udid: this.opts.udid};550 }551 // figure out the correct simulator to use, given the desired capabilities552 let device = await getExistingSim(this.opts);553 // check for an existing simulator554 if (device) {555 return {device, realDevice: false, udid: device.udid};556 }557 // no device of this type exists, so create one558 log.info('Simulator udid not provided, using desired caps to create a new simulator');559 if (!this.opts.platformVersion) {560 log.info(`No platformVersion specified. Using latest version Xcode supports: '${this.iosSdkVersion}' ` +561 `This may cause problems if a simulator does not exist for this platform version.`);562 this.opts.platformVersion = this.iosSdkVersion;563 }564 if (this.opts.noReset) {565 // Check for existing simulator just with correct capabilities566 let device = await getExistingSim(this.opts);567 if (device) {568 return {device, realDevice: false, udid: device.udid};569 }570 }571 device = await this.createSim();572 return {device, realDevice: false, udid: device.udid};573 }574 async startSim () {575 const runOpts = {576 scaleFactor: this.opts.scaleFactor,577 connectHardwareKeyboard: !!this.opts.connectHardwareKeyboard,578 isHeadless: !!this.opts.isHeadless,579 devicePreferences: {},580 };581 // add the window center, if it is specified582 if (this.opts.SimulatorWindowCenter) {583 runOpts.devicePreferences.SimulatorWindowCenter = this.opts.SimulatorWindowCenter;584 }585 // This is to workaround XCTest bug about changing Simulator586 // orientation is not synchronized to the actual window orientation587 const orientation = _.isString(this.opts.orientation) && this.opts.orientation.toUpperCase();588 switch (orientation) {589 case 'LANDSCAPE':590 runOpts.devicePreferences.SimulatorWindowOrientation = 'LandscapeLeft';591 runOpts.devicePreferences.SimulatorWindowRotationAngle = 90;592 break;593 case 'PORTRAIT':594 runOpts.devicePreferences.SimulatorWindowOrientation = 'Portrait';595 runOpts.devicePreferences.SimulatorWindowRotationAngle = 0;596 break;597 }598 await this.opts.device.run(runOpts);599 }600 async createSim () {601 this.lifecycleData.createSim = true;602 // create sim for caps603 let sim = await createSim(this.opts, this.sessionId);604 log.info(`Created simulator with udid '${sim.udid}'.`);605 return sim;606 }607 async launchApp () {608 const APP_LAUNCH_TIMEOUT = 20 * 1000;609 this.logEvent('appLaunchAttempted');610 await launch(this.opts.device.udid, this.opts.bundleId);611 let checkStatus = async () => {612 let response = await this.proxyCommand('/status', 'GET');613 let currentApp = response.currentApp.bundleID;614 if (currentApp !== this.opts.bundleId) {615 throw new Error(`${this.opts.bundleId} not in foreground. ${currentApp} is in foreground`);616 }617 };618 log.info(`Waiting for '${this.opts.bundleId}' to be in foreground`);619 let retries = parseInt(APP_LAUNCH_TIMEOUT / 200, 10);620 await retryInterval(retries, 200, checkStatus);621 log.info(`${this.opts.bundleId} is in foreground`);622 this.logEvent('appLaunched');623 }624 async startWdaSession (bundleId, processArguments) {625 let args = processArguments ? processArguments.args : [];626 let env = processArguments ? processArguments.env : {};627 let shouldWaitForQuiescence = util.hasValue(this.opts.waitForQuiescence) ? this.opts.waitForQuiescence : true;628 let maxTypingFrequency = util.hasValue(this.opts.maxTypingFrequency) ? this.opts.maxTypingFrequency : 60;629 let shouldUseSingletonTestManager = util.hasValue(this.opts.shouldUseSingletonTestManager) ? this.opts.shouldUseSingletonTestManager : true;630 let shouldUseTestManagerForVisibilityDetection = false;631 if (util.hasValue(this.opts.simpleIsVisibleCheck)) {632 shouldUseTestManagerForVisibilityDetection = this.opts.simpleIsVisibleCheck;633 }634 if (!isNaN(parseFloat(this.opts.platformVersion)) && parseFloat(this.opts.platformVersion).toFixed(1) === '9.3') {635 log.info(`Forcing shouldUseSingletonTestManager capability value to true, because of known XCTest issues under 9.3 platform version`);636 shouldUseTestManagerForVisibilityDetection = true;637 }638 if (util.hasValue(this.opts.language)) {639 args.push('-AppleLanguages', `(${this.opts.language})`);640 args.push('-NSLanguages', `(${this.opts.language})`);641 }642 if (util.hasValue(this.opts.locale)) {643 args.push('-AppleLocale', this.opts.locale);644 }645 let desired = {646 desiredCapabilities: {647 bundleId,648 arguments: args,649 environment: env,650 shouldWaitForQuiescence,651 shouldUseTestManagerForVisibilityDetection,652 maxTypingFrequency,653 shouldUseSingletonTestManager,654 }655 };656 await this.proxyCommand('/session', 'POST', desired);657 }658 // Override Proxy methods from BaseDriver659 proxyActive () {660 return this.jwpProxyActive;661 }662 getProxyAvoidList () {663 if (this.isWebview()) {664 return NO_PROXY_WEB_LIST;665 }666 return NO_PROXY_NATIVE_LIST;667 }668 canProxy () {669 return true;670 }671 isSafari () {672 return !!this.safari;673 }674 isRealDevice () {675 return this.opts.realDevice;676 }677 isSimulator () {678 return !this.opts.realDevice;679 }680 isWebview () {681 return this.isSafari() || this.isWebContext();682 }683 validateLocatorStrategy (strategy) {684 super.validateLocatorStrategy(strategy, this.isWebContext());685 }686 validateDesiredCaps (caps) {687 // check with the base class, and return if it fails688 let res = super.validateDesiredCaps(caps);689 if (!res) {690 return res;691 }692 // make sure that the capabilities have one of `app` or `bundleId`693 if ((caps.browserName || '').toLowerCase() !== 'safari' &&694 !caps.app && !caps.bundleId) {695 let msg = 'The desired capabilities must include either an app or a bundleId for iOS';696 log.errorAndThrow(msg);697 }698 let verifyProcessArgument = (processArguments) => {699 if (!_.isNil(processArguments.args) && !_.isArray(processArguments.args)) {700 log.errorAndThrow('processArguments.args must be an array of string');701 }702 if (!_.isNil(processArguments.env) && !_.isObject(caps.processArguments.env)) {703 log.errorAndThrow('processArguments.env must be an object <key,value> pair {a:b, c:d}');704 }705 };706 // `processArguments` should be JSON string or an object with arguments and/ environment details707 if (caps.processArguments) {708 if (_.isString(caps.processArguments)) {709 try {710 // try to parse the string as JSON711 caps.processArguments = JSON.parse(caps.processArguments);712 verifyProcessArgument(caps.processArguments);713 } catch (err) {714 log.errorAndThrow(`processArguments must be a json format or an object with format {args : [], env : {a:b, c:d}}. Both environment and argument can be null. Error: ${err}`);715 }716 } else if (_.isObject(caps.processArguments)) {717 verifyProcessArgument(caps.processArguments);718 } else {719 log.errorAndThrow('processArguments must be an object, or a string JSON object with format {args : [], env : {a:b, c:d}}. Both environment and argument can be null.');720 }721 }722 // there is no point in having `keychainPath` without `keychainPassword`723 if ((caps.keychainPath && !caps.keychainPassword) || (!caps.keychainPath && caps.keychainPassword)) {724 log.errorAndThrow(`If 'keychainPath' is set, 'keychainPassword' must also be set (and vice versa).`);725 }726 if (caps.autoAcceptAlerts || caps.autoDismissAlerts) {727 log.warn(`The capabilities 'autoAcceptAlerts' and 'autoDismissAlerts' ` +728 `do not work for XCUITest-based tests. Please adjust your ` +729 `alert handling accordingly.`);730 }731 // `resetOnSessionStartOnly` should be set to true by default732 this.opts.resetOnSessionStartOnly = !util.hasValue(this.opts.resetOnSessionStartOnly) || this.opts.resetOnSessionStartOnly;733 this.opts.useNewWDA = util.hasValue(this.opts.useNewWDA) ? this.opts.useNewWDA : false;734 // finally, return true since the superclass check passed, as did this735 return true;736 }737 async installApp () {738 if (this.isSafari()) {739 return;740 }741 // if user has passed in desiredCaps.autoLaunch = false742 // meaning they will manage app install / launching743 if (this.opts.autoLaunch === false) {744 return;745 }746 if (this.isRealDevice()) {747 await installToRealDevice (this.opts.device, this.opts.app, this.opts.bundleId, this.opts.noReset);748 } else {749 await installToSimulator(this.opts.device, this.opts.app, this.opts.bundleId, this.opts.noReset);750 }751 if (util.hasValue(this.opts.iosInstallPause)) {752 // https://github.com/appium/appium/issues/6889753 let pause = parseInt(this.opts.iosInstallPause, 10);754 log.debug(`iosInstallPause set. Pausing ${pause} ms before continuing`);755 await B.delay(pause);756 }757 }758 async setInitialOrientation (orientation) {759 if (!_.isString(orientation)) {760 log.info('Skipping setting of the initial display orientation. ' +761 'Set the "orientation" capability to either "LANDSCAPE" or "PORTRAIT", if this is an undesired behavior.');762 return;763 }764 orientation = orientation.toUpperCase();765 if (!_.includes(['LANDSCAPE', 'PORTRAIT'], orientation)) {766 log.debug(`Unable to set initial orientation to '${orientation}'`);767 return;768 }769 log.debug(`Setting initial orientation to '${orientation}'`);770 try {771 await this.proxyCommand('/orientation', 'POST', {orientation});772 this.opts.curOrientation = orientation;773 } catch (err) {774 log.warn(`Setting initial orientation failed with: ${err.message}`);775 }776 }777 _getCommandTimeout (cmdName) {778 this.opts.commandTimeouts = normalizeCommandTimeouts(this.opts.commandTimeouts);779 if (this.opts.commandTimeouts) {780 if (cmdName && _.has(this.opts.commandTimeouts, cmdName)) {781 return this.opts.commandTimeouts[cmdName];782 }783 return this.opts.commandTimeouts[DEFAULT_TIMEOUT_KEY];784 }785 }786 /**787 * Get session capabilities merged with what WDA reports788 * This is a library command but needs to call 'super' so can't be on789 * a helper object790 */791 async getSession () {792 // call super to get event timings, etc...793 let driverSession = await super.getSession();794 let wdaCaps = await this.proxyCommand('/', 'GET');795 log.info("Merging WDA caps over Appium caps for session detail response");796 return Object.assign({udid: this.opts.udid}, driverSession, wdaCaps.capabilities);797 }798 async startIWDP () {799 this.logEvent('iwdpStarting');800 this.iwdpServer = new IWDP(this.opts.webkitDebugProxyPort, this.opts.udid);801 await this.iwdpServer.start();802 this.logEvent('iwdpStarted');803 }804 async stopIWDP () {805 if (this.iwdpServer) {806 await this.iwdpServer.stop();807 delete this.iwdpServer;808 }809 }810 async reset () {811 if (this.opts.noReset) {812 // This is to make sure reset happens even if noReset is set to true813 let opts = _.cloneDeep(this.opts);814 opts.noReset = false;815 opts.fullReset = false;816 const shutdownHandler = this.resetOnUnexpectedShutdown;817 this.resetOnUnexpectedShutdown = () => {};818 try {819 await this.runReset(opts);820 } finally {821 this.resetOnUnexpectedShutdown = shutdownHandler;822 }823 }824 await super.reset();825 }826}827for (let [cmd, fn] of _.toPairs(commands)) {828 XCUITestDriver.prototype[cmd] = fn;829}830export default XCUITestDriver;...

Full Screen

Full Screen

build.js

Source:build.js Github

copy

Full Screen

1'use strict';2const { debug, print, strong, warn } = require('./utils/cnsl');3const { filepathName, findUniqueFilepath, isUniqueFilepath } = require('./utils/filepath');4const { maxInputStringLength, recommendedFileSizeLimit } = require('./settings');5const { truncate } = require('./utils/string');6const callable = require('./utils/callable');7const chalk = require('chalk');8const env = require('./utils/env');9const flatten = require('lodash/flatten');10const fs = require('fs');11const match = require('minimatch');12const parallel = require('async/parallel');13const path = require('path');14const prettyBytes = require('pretty-bytes');15const series = require('async/series');16const stopwatch = require('./utils/stopwatch');17const unique = require('lodash/uniq');18const waterfall = require('async/waterfall');19const zlib = require('zlib');20const RE_GENERATED_SHARED = /common|shared/;21/**22 * Build instance factory23 * @param {Object} props24 * - {Boolean} batch25 * - {Boolean} boilerplate26 * - {Boolean} bootstrap27 * - {Boolean} [browser]28 * - {Boolean} bundle29 * - {FileCache} [fileCache]30 * - {Function} [fileFactory]31 * - {String} generatedInputPattern32 * - {Number} index33 * - {String} input34 * - {Array} inputpaths35 * - {Boolean} [isAppServer]36 * - {Boolean} [isDynamicBuild]37 * - {Boolean} [isGeneratedBuild]38 * - {String} label39 * - {Number} level40 * - {String} output41 * - {Array} outputpaths42 * - {Build} parent43 * - {Object} runtimeOptions44 * - {String} type45 * - {Boolean} watchOnly46 * @returns {Build}47 */48module.exports = function buildFactory(props) {49 return new Build(props);50};51class Build {52 /**53 * Constructor54 * @param {Object} props55 * - {Boolean} batch56 * - {Boolean} boilerplate57 * - {Boolean} bootstrap58 * - {Boolean} [browser]59 * - {Boolean} bundle60 * - {FileCache} [fileCache]61 * - {Function} [fileFactory]62 * - {String} generatedInputPattern63 * - {Number} index64 * - {String} input65 * - {Array} inputpaths66 * - {Boolean} [isAppServer]67 * - {Boolean} [isDynamicBuild]68 * - {Boolean} [isGeneratedBuild]69 * - {String} label70 * - {Number} level71 * - {String} output72 * - {Array} outputpaths73 * - {Build} parent74 * - {Object} runtimeOptions75 * - {String} type76 * - {Boolean} watchOnly77 */78 constructor(props) {79 Object.assign(this, props);80 this.builds = [];81 this.childInputpaths = [];82 this.id = this.label || (this.index != null && this.index.toString());83 this.inputFiles = [];84 this.processFilesOptions = {};85 this.referencedFiles = [];86 this.results = [];87 this.timerID = this.inputpaths[0];88 this.outputFiles = [];89 this.printPrefix = new Array(this.level + 1).join('\u2219');90 // Handle printing long input/output arrays91 this.inputString = generatePathString(this.inputpaths);92 this.outputString = generatePathString(this.outputpaths);93 debug(`created Build instance with input: ${strong(this.inputString)} and output: ${strong(this.output)}`, 2);94 }95 /**96 * Determine if 'filepath' is a referenced file (child targets included)97 * @param {String} filepath98 * @returns {Boolean}99 */100 hasFile(filepath) {101 if (this.referencedFiles.some(refFile => refFile.filepath == filepath)) return true;102 if (this.builds.length) return this.builds.some(build => build.hasFile(filepath));103 return false;104 }105 /**106 * Run build107 * @param {Function} fn(err, results)108 */109 run(fn) {110 waterfall([callable(this, 'runProcess'), callable(this, 'runWrite'), callable(this, 'runReset')], fn);111 }112 /**113 * Run processing tasks114 * @param {Function} fn(err)115 */116 runProcess(fn) {117 waterfall(118 [119 // Initialize120 callable(this, 'init'),121 // Process input files122 callable(this, 'processFiles' /* , files */),123 // Print process progress124 callable(this, 'printProcessProgress' /* , referencedFiles */),125 // Print process progress126 callable(this, 'runProcessForChildren' /* , referencedFiles */),127 // Process generated build128 callable(this, 'processGeneratedBuild'),129 // Pre-process output files130 callable(this, 'preProcessWriteFiles')131 ],132 fn133 );134 }135 /**136 * Run write tasks137 * @param {Function} fn(err)138 */139 runWrite(fn) {140 waterfall(141 [142 // Write files143 callable(this, 'writeFiles', this.outputFiles),144 // Build child targets145 callable(this, 'runWriteForChildren' /* , referencedFiles, results */)146 ],147 fn148 );149 }150 /**151 * Run reset tasks152 * @param {Function} fn(err, results)153 */154 runReset(fn) {155 waterfall(156 [157 // Reset158 callable(this, 'reset', this.results),159 // Build child targets160 callable(this, 'runResetForChildren' /* , results */),161 // Write file progress162 callable(this, 'printWriteProgress' /* , results */)163 ],164 fn165 );166 }167 /**168 * Initialize state before run169 * @param {Function} fn(err, files)170 * @returns {null}171 */172 init(fn) {173 let type = this.watchOnly && this.runtimeOptions.watch ? 'watching' : 'building';174 if (this.isDynamicBuild) type += ' dynamic';175 this.inputFiles = [];176 this.referencedFiles = [];177 this.results = [];178 this.outputFiles = [];179 this.processFilesOptions = {180 batch: !this.bundle && this.batch,181 boilerplate: this.boilerplate,182 bootstrap: this.bootstrap,183 browser: this.browser,184 bundle: this.bundle,185 compress: this.runtimeOptions.compress,186 // TODO: only include helpers in root? Difficult on watch187 helpers: true,188 ignoredFiles: this.childInputpaths,189 importBoilerplate: false,190 watchOnly: this.watchOnly191 };192 stopwatch.start(this.timerID);193 // Skip if watch only and not running a watch build194 if (this.watchOnly && !this.runtimeOptions.watch) return fn(null, []);195 if (this.isGeneratedBuild) {196 print(`${this.printPrefix} ${type} ${strong(this.outputString)}`, 1);197 } else {198 print(199 `${this.printPrefix} ${type} ${strong(this.inputString)} ${this.outputString ? 'to ' + strong(this.outputString) : ''}`,200 1201 );202 }203 fn(204 null,205 this.inputpaths.reduce(206 (files, filepath) => {207 const file = this.fileFactory(filepath);208 if (!file) {209 warn(`${strong(filepath)} not found in project source`, 1);210 } else {211 // Force for dynamic builds212 file.options = this.fileFactoryOptions;213 files.push(file);214 this.inputFiles.push(file);215 }216 return files;217 },218 []219 )220 );221 }222 /**223 * Process 'files'224 * @param {Array} files225 * @param {Function} fn(err, files)226 */227 processFiles(files, fn) {228 env('INPUT', files, this.id);229 env('INPUT_HASH', files, this.id);230 env('INPUT_DATE', files, this.id);231 parallel(files.map(file => callable(file, 'run', 'standard', this.processFilesOptions)), err => {232 if (err) return fn(err);233 this.referencedFiles = files.reduce(234 (referencedFiles, file) => {235 referencedFiles.push(file);236 file.getAllDependencies().forEach(dependency => {237 if (!referencedFiles.includes(dependency)) referencedFiles.push(dependency);238 });239 return referencedFiles;240 },241 []242 );243 fn(null, this.referencedFiles);244 });245 }246 /**247 * Print progress248 * @param {Array} files249 * @param {Function} fn(err, files)250 */251 printProcessProgress(files, fn) {252 if (files.length) {253 print(254 '[processed ' +255 strong(files.length) +256 (files.length > 1 ? ' files' : ' file') +257 ' in ' +258 chalk.cyan(stopwatch.stop(this.timerID, true)) +259 ']',260 2 + this.printPrefix.length261 );262 }263 fn(null, files);264 }265 /**266 * Run processing for child builds267 * @param {Array} files268 * @param {Function} fn(err)269 * @returns {null}270 */271 runProcessForChildren(files, fn) {272 if (!this.builds.length) return fn();273 // Lock files to prevent inclusion in downstream targets274 this.lock(this.referencedFiles);275 series(this.builds.map(build => callable(build, 'runProcess')), (err, childFiles) => {276 if (err) return fn(err);277 this.unlock(this.referencedFiles);278 fn();279 });280 }281 /**282 * Process generated build based on children283 * @param {Function} fn(err)284 * @returns {null}285 */286 processGeneratedBuild(fn) {287 if (!this.isGeneratedBuild) return fn();288 const dummyFile = this.inputFiles[0];289 let matchingFiles = [];290 function getFiles(builds) {291 return builds.reduce(292 (files, build) => {293 files.push(294 ...build.inputFiles.reduce(295 (files, file) => {296 // Use dependencyReferences to include those missing from dependencies due to locking etc.297 return files.concat(298 ...file.dependencyReferences299 .filter(reference => reference.file != null)300 .map(reference => reference.file)301 );302 },303 []304 )305 );306 // Traverse children307 if (build.builds.length) files.push(...getFiles(build.builds));308 return files;309 },310 []311 );312 }313 if (RE_GENERATED_SHARED.test(this.generatedInputPattern)) {314 const seen = {};315 // Recursively generate 1D array of all inputFiles dependencies316 matchingFiles = getFiles(this.builds)317 // Include all files with at least 1 other match318 .reduce(319 (matchingFiles, file) => {320 if (!(file.id in seen)) {321 seen[file.id] = 1;322 } else if (!matchingFiles.includes(file)) {323 matchingFiles.push(file);324 }325 return matchingFiles;326 },327 []328 );329 } else {330 matchingFiles = unique(getFiles(this.builds)).filter(file =>331 match(file.filepath, this.generatedInputPattern, { matchBase: true, nocase: true }));332 }333 // Generate dummy dependency references334 const matchingDependencies = matchingFiles.map(file => {335 file.isDependency = false;336 return { filepath: file.filepath };337 });338 dummyFile.allDependencies = (dummyFile.allDependencyReferences = null);339 dummyFile.addDependencies(matchingDependencies, this.processFilesOptions);340 dummyFile.getAllDependencies().forEach(dependency => {341 if (!this.referencedFiles.includes(dependency)) this.referencedFiles.push(dependency);342 });343 fn();344 }345 /**346 * Pre-process write files347 * @param {Function} fn(err)348 */349 preProcessWriteFiles(fn) {350 this.outputFiles = this.inputFiles.filter(file => file.isWriteable(this.processFilesOptions.batch)).reduce((351 outputFiles,352 file,353 idx354 ) => {355 let filepath = '';356 this.inputpaths.some((inputpath, idx) => {357 if (inputpath == file.filepath) {358 filepath = this.outputpaths[idx];359 return true;360 }361 });362 // Don't write if no output path363 if (filepath) {364 // Handle generating unique paths365 if (isUniqueFilepath(filepath)) {366 // Remove existing367 const existing = findUniqueFilepath(filepath);368 if (existing) {369 try {370 fs.unlinkSync(existing);371 } catch (err) {372 /* ignore */373 }374 }375 }376 file.prepareForWrite(filepath, this.processFilesOptions);377 outputFiles.push(file);378 env('OUTPUT', file, this.id);379 env('OUTPUT_HASH', file, this.id);380 env('OUTPUT_DATE', file, this.id);381 env('OUTPUT_URL', file, this.id);382 }383 return outputFiles;384 }, []);385 fn(null);386 }387 /**388 * Write content for 'files'389 * @param {Array} files390 * @param {Function} fn(err, files, results)391 */392 writeFiles(files, fn) {393 const writeable = files.map(file => callable(file, 'write', this.processFilesOptions));394 // Results are [{ filepath, content, type }]395 parallel(writeable, (err, results) => {396 if (err) return fn(err);397 this.results = results;398 this.results.forEach(result => {399 result.printPrefix = this.printPrefix;400 });401 fn(null, files, results);402 });403 }404 /**405 * Run write for child builds406 * @param {Array} files407 * @param {Array} results408 * @param {Function} fn(err)409 * @returns {null}410 */411 runWriteForChildren(files, results, fn) {412 if (!this.builds.length) return fn();413 // Lock files to prevent inclusion in downstream targets414 this.lock(this.referencedFiles);415 series(this.builds.map(build => callable(build, 'runWrite')), (err, childResults) => {416 if (err) return fn(err);417 this.unlock(this.referencedFiles);418 fn();419 });420 }421 /**422 * Reset input files423 * @param {Array} results424 * @param {Array} fn(err, results)425 */426 reset(results, fn) {427 this.referencedFiles.forEach(file => file.reset());428 fn(null, results);429 }430 /**431 * Run reset for child builds432 * @param {Array} results433 * @param {Array} fn(err, results)434 * @returns {null}435 */436 runResetForChildren(results, fn) {437 if (!this.builds.length) return fn(null, results);438 series(this.builds.map(build => callable(build, 'runReset')), (err, childResults) => {439 if (err) return fn(err);440 fn(null, results.concat(flatten(childResults || [])));441 });442 }443 /**444 * Print progress445 * @param {Array} results446 * @param {Function} fn(err, results)447 * @returns {null}448 */449 printWriteProgress(results, fn) {450 if (this.parent) return fn(null, results);451 const prints = results.slice().reverse().map(result => {452 return callable(453 printResult,454 null,455 result,456 this.runtimeOptions.deploy,457 this.runtimeOptions.compress,458 result.printPrefix459 );460 });461 parallel(prints, err => {462 fn(err, results);463 });464 }465 /**466 * Set lock flag for 'files'467 * @param {Array} files468 */469 lock(files) {470 files.forEach(file => {471 file.isLocked = true;472 });473 }474 /**475 * Unset lock flag for 'files'476 * @param {Array} files477 */478 unlock(files) {479 files.forEach(file => {480 file.isLocked = false;481 });482 }483}484/**485 * Generate path string for 'paths'486 * @param {Array} paths487 * @returns {String}488 */489function generatePathString(paths) {490 let pathString = '';491 if (!paths || !paths.length) return pathString;492 if (paths.length > 1) {493 pathString = paths.map(pathItem => filepathName(pathItem));494 // Trim long lists495 if (pathString.length > maxInputStringLength) {496 const remainder = pathString.length - maxInputStringLength;497 pathString = `${pathString498 .slice(0, maxInputStringLength)499 .join(', ')} ...and ${remainder} other${remainder > 1 ? 's' : ''}`;500 } else {501 pathString = pathString.join(', ');502 }503 } else {504 pathString = filepathName(paths[0]);505 }506 return pathString;507}508/**509 * Print 'result'510 * @param {Object} result511 * @param {Boolean} isDeploy512 * @param {Boolean} isCompressed513 * @param {String} prefix514 * @param {Function} fn515 */516function printResult(result, isDeploy, isCompressed, prefix, fn) {517 const relpath = truncate(path.relative(process.cwd(), result.filepath));518 if ((result.type == 'js' || result.type == 'css') && isDeploy) {519 zlib.gzip(result.content, (err, buffer) => {520 if (err) return fn(err);521 const stat = fs.statSync(result.filepath);522 const bytes = stat.size;523 const over = bytes > recommendedFileSizeLimit;524 const overZipped = buffer.length > recommendedFileSizeLimit;525 print(chalk.green(`${chalk.green(prefix)} built and compressed ${strong(relpath)}`), 1);526 print(`[compressed size: ${chalk[over ? 'red' : 'green'](prettyBytes(bytes))}]`, 2 + prefix.length);527 print(`[gzipped size: ${chalk[overZipped ? 'red' : 'green'](prettyBytes(buffer.length))}]`, 2 + prefix.length);528 if (over || overZipped) {529 warn(530 `the output file exceeds the recommended ${strong(prettyBytes(recommendedFileSizeLimit))} size`,531 2 + prefix.length532 );533 print(534 'Consider splitting into smaller bundles to help improve browser startup execution time',535 2 + prefix.length536 );537 }538 fn();539 });540 } else {541 print(chalk.green(`${chalk.green(prefix)} built${isCompressed ? ' and compressed' : ''} ${strong(relpath)}`), 1);542 fn();543 }...

Full Screen

Full Screen

labs.js

Source:labs.js Github

copy

Full Screen

...52 else53 {54 if(Memory.rooms[roomName].lab.reset)55 {56 this.runReset(roomName)57 return58 }59 sourceLab1 = Game.getObjectById(Memory.rooms[roomName].lab.source1)60 sourceLab2 = Game.getObjectById(Memory.rooms[roomName].lab.source2)61 for(labIdx in Memory.rooms[roomName].lab.producers)62 {63 labId = Memory.rooms[roomName].lab.producers[labIdx]64 lab = Game.getObjectById(labId)65 lab.runReaction(sourceLab1, sourceLab2)66 }67 }68 },69 decideReaction(roomName)70 {...

Full Screen

Full Screen

roleLabSupplier.js

Source:roleLabSupplier.js Github

copy

Full Screen

...45 }46 var labInfo = labs.getLabInfo(creep.memory.home)47 if(labInfo.reset)48 {49 this.runReset(creep)50 return51 }52 var container = labs.getContainer(creep.memory.home)53 var reaction = labs.getReaction(creep.memory.home)54 var boost1 = labs.getBoost1(creep.memory.home)55 var boost2 = labs.getBoost2(creep.memory.home)56 if(!container || !reaction)57 {58 labPos = labs.getLabPosition(creep.memory.home)59 if(creep.pos.x != labPos.x || creep.pos.y!=labPos.y)60 {61 creep.moveTo(labPos)62 }63 return...

Full Screen

Full Screen

square-grid.js

Source:square-grid.js Github

copy

Full Screen

1import React, { Component } from 'react'2import '../styles/square-grid.css'3import '../styles/square.css'4import '../styles/button-grid.css'5import '../styles/button.css'6class SquareGrid extends Component {7 constructor() {8 super()9 this.state = {10 sqrA: 'white',11 sqrB: 'white',12 sqrC: 'white',13 sqrD: 'white',14 color: '',15 colors: []16 }17 this.makeBlack = this.makeBlack.bind(this)18 }19 makeBlack = () => {20 if(this.state.sqrA !== '#222f3e'){21 this.setState({22 sqrA: '#222f3e',23 sqrB: '#222f3e',24 sqrC: '#222f3e',25 sqrD: '#222f3e'26 })27 } else {28 this.setState({29 sqrA: 'white',30 sqrB: 'white',31 sqrC: 'white',32 sqrD: 'white'33 })34 }35 }36 makePurple = () => {37 this.setState({38 sqrA: '#5f27cd',39 sqrB: '#5f27cd'40 })41 }42 makeBottomLeftBlue = () => {43 this.setState({sqrC: '#54a0ff'})44 }45 makeBottomRightBlue = () => {46 this.setState({sqrD: '#54a0ff'})47 }48 topLeft = () => {49 this.setState({sqrA: '#ee5253'})50 }51 topRight = () => {52 this.setState({sqrB: '#00d2d3'})53 }54 bottomLeft = () => {55 this.setState({sqrC: '#10ac84'})56 }57 bottomRight = () => {58 this.setState({sqrD: '#feca57'})59 }60 handleChange = e => {61 this.setState({color: e.target.value})62 }63 handleSubmit = e => {64 e.preventDefault();65 this.setState(prevState => {66 console.log(prevState.color)67 return {68 colors: [prevState.color,...prevState.colors]69 }70 }, () => {71 console.log(this.state.colors)72 73 })74 75 }76 runColors = () => {77 this.intervalId = setInterval(this.startColors, 1000)78 }79 startColors = () => {80 let a = Math.floor(Math.random() * this.state.colors.length)81 let b = Math.floor(Math.random() * this.state.colors.length)82 let c = Math.floor(Math.random() * this.state.colors.length)83 let d = Math.floor(Math.random() * this.state.colors.length)84 this.setState({85 sqrA: this.state.colors[a],86 sqrB: this.state.colors[b],87 sqrC: this.state.colors[c],88 sqrD: this.state.colors[d]89 })90 }91 stopColors = () => {92 clearInterval(this.intervalId)93 }94 runReset = () => {95 this.setState({colors: []})96 }97 render() {98 const styles = {99 sqrA: {100 backgroundColor: this.state.sqrA101 },102 sqrB: {103 backgroundColor: this.state.sqrB104 },105 sqrC: {106 backgroundColor: this.state.sqrC107 },108 sqrD: {109 backgroundColor: this.state.sqrD110 }111 }112 return (113 <div>114 <div className='square-grid'>115 <div className='square-single sqrA' style={styles.sqrA}></div>116 <div className='square-single sqrA' style={styles.sqrB}></div>117 <div className='square-single sqrA' style={styles.sqrC}></div>118 <div className='square-single sqrA' style={styles.sqrD}></div>119 </div>120 <div className='button-grid'>121 <button className="btn" onClick={this.makeBlack}>black</button>122 <button className="btn" onClick={this.makePurple}>purple</button>123 <button className="btn" onClick={this.makeBottomLeftBlue}>blue</button>124 <button className="btn" onClick={this.makeBottomRightBlue}>blue</button>125 <button className="btn" onClick={this.topLeft}>red</button>126 <button className="btn" onClick={this.topRight}>aqua</button>127 <button className="btn" onClick={this.bottomLeft}>green</button>128 <button className="btn" onClick={this.bottomRight}>yellow</button>129 </div>130 <div className='custom-grid'>131 <form onSubmit={this.handleSubmit}>132 <input type="text" name='color' placeholder='enter color' value={this.state.color} onChange={this.handleChange}/>133 <button>submit</button>134 </form>135 <button onClick={this.runColors}>Start Colors</button>136 <button onClick={this.stopColors}>Stop Colors</button>137 <button onClick={this.runReset}>Reset</button>138 </div>139 </div>140 )141 }142}...

Full Screen

Full Screen

roleLabAssistant.js

Source:roleLabAssistant.js Github

copy

Full Screen

...59 }60 var labInfo = labs.getLabInfo(creep.memory.home)61 if(labInfo.reset)62 {63 this.runReset(creep)64 return65 }66 var source1 = Game.getObjectById(labInfo.source1)67 var source2 = Game.getObjectById(labInfo.source2)68 //Todo, add code to empty incorrect resources out of sourceLabs69 if(source1.store[reaction.chem1]<2500&& (container.store[reaction.chem1]>0 || creep.store[reaction.chem1]>0))70 {71 if(!creep.pos.isNearTo(container))72 {73 creep.moveTo(container)74 return75 }76 creep.moveTo(source1)77 creep.withdraw(container, reaction.chem1)...

Full Screen

Full Screen

ResetPassword.js

Source:ResetPassword.js Github

copy

Full Screen

...57 <Text style={{marginLeft:30,marginRight:30}}>{getLabel("Yêu cầu khôi phục mật khẩu")}</Text>58 </Button>59 </View>60 </Form>61 <GoogleReCaptchaModal onSuccess={(_token)=>this.runReset(_token)} ref={_ref=>this.verifyCaptcha = _ref}/>62 {this.state.running?63 <View style={loading}>64 <ActivityIndicator />65 </View>66 :null67 }68 </KeyboardAvoidingContent>69 </Content>70 <Footer path="User" navigation={this.props.navigation}/>71 </Container>72 );73 }...

Full Screen

Full Screen

refreshCommand.js

Source:refreshCommand.js Github

copy

Full Screen

...20 let $step = this.input.getOption('step') || 1;21 if ($step > 1) {22 await this.runRollback($database, $path, $step);23 } else {24 await this.runReset($database, $path);25 }26 await this.callCommand('migrate', Object.filter({27 '--database': $database,28 '--path': $path,29 '--realpath': this.input.getOption('realpath'),30 '--force': true,31 }));32 if (this.needsSeeding()) {33 this.runSeeder($database);34 }35 return 0;36 }37 runRollback($database, $path, $step) {38 return this.callCommand('migrate:rollback', Object.filter({...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const wd = require('wd');3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5const { XCUITestDriver } = require('appium-xcuitest-driver');6chai.should();7chai.use(chaiAsPromised);8const PORT = 4723;9const HOST = 'localhost';10const BUNDLE_ID = 'com.my.app';11const DEVICE_UDID = 'my-udid';12const DEVICE_NAME = 'my-device-name';13const PLATFORM_VERSION = '12.1';14const PLATFORM_NAME = 'iOS';15const DEVICE_ORIENTATION = 'PORTRAIT';16const APP = path.resolve(__dirname, 'my-app.app');17const driver = wd.promiseChainRemote(HOST, PORT);18const xcuitestDriver = new XCUITestDriver({port: PORT, host: HOST});19const desiredCaps = {20};21describe('Appium XCUITest Driver', () => {22 before(async () => {23 await xcuitestDriver.createSession(desiredCaps);24 });25 it('should reset the app', async () => {26 await xcuitestDriver.runReset();27 });28 after(async () => {29 await xcuitestDriver.deleteSession();30 });31});32const wd = require('wd');33const chai = require('chai');34const chaiAsPromised = require('chai-as-promised');35const { XCUITestDriver } = require('appium-xcuitest-driver');36chai.should();37chai.use(chaiAsPromised);38const PORT = 4723;39const HOST = 'localhost';40const BUNDLE_ID = 'com.my.app';41const DEVICE_UDID = 'my-udid';42const DEVICE_NAME = 'my-device-name';43const PLATFORM_VERSION = '12.1';44const PLATFORM_NAME = 'iOS';45const DEVICE_ORIENTATION = 'PORTRAIT';46const driver = wd.promiseChainRemote(HOST, PORT);47const xcuitestDriver = new XCUITestDriver({port: PORT, host: HOST});48const desiredCaps = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var driver = wd.promiseChainRemote("localhost", 4723);3driver.init({4}).then(function () {5 return driver.runReset();6});7var wd = require('wd');8var driver = wd.promiseChainRemote("localhost", 4723);9driver.init({10}).then(function () {11 return driver.reset();12});13var wd = require('wd');14var driver = wd.promiseChainRemote("localhost", 4723);15driver.init({16}).then(function () {17 return driver.resetApp();18});19var wd = require('wd');20var driver = wd.promiseChainRemote("localhost", 4723);21driver.init({22}).then(function () {23 return driver.runReset();24});25var wd = require('wd');26var driver = wd.promiseChainRemote("localhost", 4723);27driver.init({28}).then(function () {29 return driver.reset();30});31var wd = require('wd');32var driver = wd.promiseChainRemote("localhost", 4723);33driver.init({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { XCUITestDriver } = require('appium-xcuitest-driver');2let driver = new XCUITestDriver();3driver.runReset();4class XCUITestDriver extends BaseDriver {5 async runReset() {6 }7}

Full Screen

Using AI Code Generation

copy

Full Screen

1this.runReset();2this.runReset();3this.runReset();4this.runReset();5this.runReset();6this.runReset();7this.runReset();8this.runReset();9this.runReset();10this.runReset();11this.runReset();12this.runReset();

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