How to use sigintListener method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

parallel-buffered-runner.js

Source:parallel-buffered-runner.js Github

copy

Full Screen

1/**2 * A test Runner that uses a {@link module:buffered-worker-pool}.3 * @module parallel-buffered-runner4 * @private5 */6'use strict';7const allSettled = require('promise.allsettled');8const Runner = require('../runner');9const {EVENT_RUN_BEGIN, EVENT_RUN_END} = Runner.constants;10const debug = require('debug')('mocha:parallel:parallel-buffered-runner');11const {BufferedWorkerPool} = require('./buffered-worker-pool');12const {setInterval, clearInterval} = global;13const {createMap} = require('../utils');14/**15 * Outputs a debug statement with worker stats16 * @param {BufferedWorkerPool} pool - Worker pool17 */18/* istanbul ignore next */19const debugStats = pool => {20 const {totalWorkers, busyWorkers, idleWorkers, pendingTasks} = pool.stats();21 debug(22 '%d/%d busy workers; %d idle; %d tasks queued',23 busyWorkers,24 totalWorkers,25 idleWorkers,26 pendingTasks27 );28};29/**30 * The interval at which we will display stats for worker processes in debug mode31 */32const DEBUG_STATS_INTERVAL = 5000;33const ABORTED = 'ABORTED';34const IDLE = 'IDLE';35const ABORTING = 'ABORTING';36const RUNNING = 'RUNNING';37const BAILING = 'BAILING';38const BAILED = 'BAILED';39const COMPLETE = 'COMPLETE';40const states = createMap({41 [IDLE]: new Set([RUNNING, ABORTING]),42 [RUNNING]: new Set([COMPLETE, BAILING, ABORTING]),43 [COMPLETE]: new Set(),44 [ABORTED]: new Set(),45 [ABORTING]: new Set([ABORTED]),46 [BAILING]: new Set([BAILED, ABORTING]),47 [BAILED]: new Set([COMPLETE, ABORTING])48});49/**50 * This `Runner` delegates tests runs to worker threads. Does not execute any51 * {@link Runnable}s by itself!52 * @private53 */54class ParallelBufferedRunner extends Runner {55 constructor(...args) {56 super(...args);57 let state = IDLE;58 Object.defineProperty(this, '_state', {59 get() {60 return state;61 },62 set(newState) {63 if (states[state].has(newState)) {64 state = newState;65 } else {66 throw new Error(`invalid state transition: ${state} => ${newState}`);67 }68 }69 });70 this.once(Runner.constants.EVENT_RUN_END, () => {71 this._state = COMPLETE;72 });73 }74 /**75 * Returns a mapping function to enqueue a file in the worker pool and return results of its execution.76 * @param {BufferedWorkerPool} pool - Worker pool77 * @param {Options} options - Mocha options78 * @returns {FileRunner} Mapping function79 */80 _createFileRunner(pool, options) {81 return async file => {82 debug('run(): enqueueing test file %s', file);83 try {84 const {failureCount, events} = await pool.run(file, options);85 if (this._state === BAILED) {86 // short-circuit after a graceful bail. if this happens,87 // some other worker has bailed.88 // TODO: determine if this is the desired behavior, or if we89 // should report the events of this run anyway.90 return;91 }92 debug(93 'run(): completed run of file %s; %d failures / %d events',94 file,95 failureCount,96 events.length97 );98 this.failures += failureCount; // can this ever be non-numeric?99 let event = events.shift();100 while (event) {101 this.emit(event.eventName, event.data, event.error);102 if (103 this._state !== BAILING &&104 event.data &&105 event.data._bail &&106 (failureCount || event.error)107 ) {108 debug('run(): nonzero failure count & found bail flag');109 // we need to let the events complete for this file, as the worker110 // should run any cleanup hooks111 this._state = BAILING;112 }113 event = events.shift();114 }115 if (this._state === BAILING) {116 debug('run(): terminating pool due to "bail" flag');117 this._state = BAILED;118 await pool.terminate();119 }120 } catch (err) {121 if (this._state === BAILED || this._state === ABORTING) {122 debug(123 'run(): worker pool terminated with intent; skipping file %s',124 file125 );126 } else {127 // this is an uncaught exception128 debug('run(): encountered uncaught exception: %O', err);129 if (this.allowUncaught) {130 // still have to clean up131 this._state = ABORTING;132 await pool.terminate(true);133 }134 throw err;135 }136 } finally {137 debug('run(): done running file %s', file);138 }139 };140 }141 /**142 * Listen on `Process.SIGINT`; terminate pool if caught.143 * Returns the listener for later call to `process.removeListener()`.144 * @param {BufferedWorkerPool} pool - Worker pool145 * @returns {SigIntListener} Listener146 */147 _bindSigIntListener(pool) {148 const sigIntListener = async () => {149 debug('run(): caught a SIGINT');150 this._state = ABORTING;151 try {152 debug('run(): force-terminating worker pool');153 await pool.terminate(true);154 } catch (err) {155 console.error(156 `Error while attempting to force-terminate worker pool: ${err}`157 );158 process.exitCode = 1;159 } finally {160 process.nextTick(() => {161 debug('run(): imminent death');162 this._state = ABORTED;163 process.kill(process.pid, 'SIGINT');164 });165 }166 };167 process.once('SIGINT', sigIntListener);168 return sigIntListener;169 }170 /**171 * Runs Mocha tests by creating a thread pool, then delegating work to the172 * worker threads.173 *174 * Each worker receives one file, and as workers become available, they take a175 * file from the queue and run it. The worker thread execution is treated like176 * an RPC--it returns a `Promise` containing serialized information about the177 * run. The information is processed as it's received, and emitted to a178 * {@link Reporter}, which is likely listening for these events.179 *180 * @param {Function} callback - Called with an exit code corresponding to181 * number of test failures.182 * @param {{files: string[], options: Options}} opts - Files to run and183 * command-line options, respectively.184 */185 run(callback, {files, options} = {}) {186 /**187 * Listener on `Process.SIGINT` which tries to cleanly terminate the worker pool.188 */189 let sigIntListener;190 // This function should _not_ return a `Promise`; its parent (`Runner#run`)191 // returns this instance, so this should do the same. However, we want to make192 // use of `async`/`await`, so we use this IIFE.193 (async () => {194 /**195 * This is an interval that outputs stats about the worker pool every so often196 */197 let debugInterval;198 /**199 * @type {BufferedWorkerPool}200 */201 let pool;202 try {203 pool = BufferedWorkerPool.create({maxWorkers: options.jobs});204 sigIntListener = this._bindSigIntListener(pool);205 /* istanbul ignore next */206 debugInterval = setInterval(207 () => debugStats(pool),208 DEBUG_STATS_INTERVAL209 ).unref();210 // this is set for uncaught exception handling in `Runner#uncaught`211 // TODO: `Runner` should be using a state machine instead.212 this.started = true;213 this._state = RUNNING;214 this.emit(EVENT_RUN_BEGIN);215 const results = await allSettled(216 files.map(this._createFileRunner(pool, options))217 );218 // note that pool may already be terminated due to --bail219 await pool.terminate();220 results221 .filter(({status}) => status === 'rejected')222 .forEach(({reason}) => {223 if (this.allowUncaught) {224 // yep, just the first one.225 throw reason;226 }227 // "rejected" will correspond to uncaught exceptions.228 // unlike the serial runner, the parallel runner can always recover.229 this.uncaught(reason);230 });231 if (this._state === ABORTING) {232 return;233 }234 this.emit(EVENT_RUN_END);235 debug('run(): completing with failure count %d', this.failures);236 callback(this.failures);237 } catch (err) {238 // this `nextTick` takes us out of the `Promise` scope, so the239 // exception will not be caught and returned as a rejected `Promise`,240 // which would lead to an `unhandledRejection` event.241 process.nextTick(() => {242 debug('run(): re-throwing uncaught exception');243 throw err;244 });245 } finally {246 clearInterval(debugInterval);247 process.removeListener('SIGINT', sigIntListener);248 }249 })();250 return this;251 }252}253module.exports = ParallelBufferedRunner;254/**255 * Listener function intended to be bound to `Process.SIGINT` event256 * @private257 * @callback SigIntListener258 * @returns {Promise<void>}259 */260/**261 * A function accepting a test file path and returning the results of a test run262 * @private263 * @callback FileRunner264 * @param {string} filename - File to run265 * @returns {Promise<SerializedWorkerResult>}...

Full Screen

Full Screen

service-runner.ts

Source:service-runner.ts Github

copy

Full Screen

1import * as http from 'http';2import * as https from 'https';3import * as express from 'express';4import { readFileSync } from 'fs';5import { errWithCause } from '../lib-common/exceptions/error';6import * as getopts from 'getopts';7export interface HttpConf {8 hostname?: string;9 port: number;10 sslOpts?: https.ServerOptions;11}12type HttpServer = http.Server | https.Server;13export const CONF_ARG = 'service-conf';14export abstract class ServiceRunner {15 private server: HttpServer|undefined = undefined;16 private closingProc: Promise<void>|undefined = undefined;17 private cleanups: (() => Promise<void>)[] = [];18 protected constructor(19 private httpConf: HttpConf) {20 }21 static readConfFromFile(): any {22 const cliOpts = getopts(process.argv.slice(2));23 const file = cliOpts[CONF_ARG];24 if (typeof file !== 'string') { throw new Error(25 `Missing ${CONF_ARG} argument, or it has no path to config file.`); }26 try {27 return JSON.parse(readFileSync(file, 'utf8'));28 } catch (err) {29 throw errWithCause(err, `Have problem parsing config file ${file}`);30 }31 }32 33 protected abstract makeApp(): Promise<express.Express>;34 protected addCleanup(cleanup: () => Promise<void>): void {35 this.cleanups.push(cleanup);36 }37 async start(): Promise<void> {38 if (this.server) { throw new Error(`Server is already set`); }39 // setup server40 const app = await this.makeApp();41 this.server = (this.httpConf.sslOpts ?42 https.createServer(this.httpConf.sslOpts, app) :43 http.createServer(app));44 // start listening45 this.closingProc = undefined;46 await (new Promise<void>((resolve, reject) => {47 const cb = (err) => {48 if (err) { reject(err); }49 else { resolve(); }50 };51 if (this.httpConf.hostname) {52 this.server!.listen(this.httpConf.port, this.httpConf.hostname, cb);53 } else {54 this.server!.listen(this.httpConf.port, cb);55 }56 }));57 58 this.attachStopSignalListeners();59 }60 startOrExitProcess(): void {61 this.start().catch(err => {62 console.error(`Cannot start app due to the following error:`);63 console.error(err);64 process.exit(-1);65 });66 }67 private attachStopSignalListeners(): void {68 const sigintListener = () => this.stop();69 process.on('SIGINT', sigintListener);70 process.on('SIGTERM', sigintListener);71 this.addCleanup(async () => {72 process.removeListener('SIGINT', sigintListener);73 process.removeListener('SIGTERM', sigintListener);74 });75 }76 async stop(): Promise<void> {77 if (!this.server) { return; }78 if (!this.closingProc) {79 this.closingProc = new Promise<void>((resolve, reject) => {80 const cb = (err) => {81 if (err) { reject(err); }82 else { resolve(); }83 };84 this.server!.close(cb);85 this.server = undefined;86 }).then(async () => { 87 await this.performCleanups();88 }, async err => {89 await this.performCleanups();90 console.error(err);91 });92 }93 await this.closingProc;94 }95 private async performCleanups(): Promise<void> {96 const promises: Promise<void>[] = [];97 for (const cleanup of this.cleanups) {98 promises.push(cleanup());99 }100 this.cleanups = [];101 await Promise.all(promises);102 }103}104Object.freeze(ServiceRunner.prototype);105Object.freeze(ServiceRunner);...

Full Screen

Full Screen

utils.ts

Source:utils.ts Github

copy

Full Screen

1/*******************/2/* Round */3/*******************/4import { logger } from './logger';5export const toDecimalPlaces = (decimals: number) => (value: number) => {6 return parseFloat(value.toFixed(decimals));7};8export const to2DecimalPlaces = toDecimalPlaces(2);9export const to8DecimalPlaces = toDecimalPlaces(8);10export const toInteger = toDecimalPlaces(0);11export class SigIntListener {12 private locked: boolean;13 private quitRequested: boolean;14 private static instance: SigIntListener;15 private constructor() {16 this.locked = false;17 this.quitRequested = false;18 process.on('SIGINT', async () => await this.tryInterrupt());19 process.on('SIGTERM', async () => await this.tryInterrupt());20 }21 public static init() {22 if (!SigIntListener.instance) {23 SigIntListener.instance = new SigIntListener();24 }25 }26 public static getInstance(): SigIntListener {27 SigIntListener.init();28 return SigIntListener.instance;29 }30 private async tryInterrupt() {31 this.quitRequested = true;32 logger.info('Shutting down...');33 if (this.locked) {34 logger.warn('Waiting for process to unlock');35 await new Promise((resolve) => setTimeout(resolve, 10000));36 logger.error('Process failed to unlock: force qutting');37 this.exit(1);38 }39 this.exit(0);40 }41 private exit(code: number) {42 logger.info('Bye!');43 process.exit(code);44 }45 lock() {46 this.locked = true;47 }48 unlock() {49 this.locked = false;50 if (this.quitRequested) {51 this.exit(0);52 }53 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var sigintListener = require('devicefarmer-stf').sigintListener;2sigintListener(function () {3 console.log('SIGINT received');4 process.exit(0);5});6console.log('test.js is running');

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('devicefarmer-stf');2stf.sigintListener();3var stf = require('devicefarmer-stf');4stf.sigintListener();5var stf = require('devicefarmer-stf');6var device = stf.getDevice('8d3e5c4b');7device.captureScreenshot('c:\\temp\\screenshot.png', function(err, result){8 if(err){9 console.log(err);10 }11 else{12 console.log(result);13 }14});15var stf = require('devicefarmer-stf');16stf.sigintListener();

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 devicefarmer-stf automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful