Best JavaScript code snippet using root
input.ts
Source:input.ts
1import { FalseLiteral } from "typescript";2import { IMenuable } from "../view/display";3import { 4 bfs,5 IncrementFn,6 ISelectable, 7 OptionFn, 8 Stack,9 TerminationFn,10 Tree,11} from "./core";12import { Awaited, Rejection } from "./utilities";13export type PreviewMap<T> = Map<T, Tree<T>>;14// NOTE: PreviewMap Options should return Stack Selection; Array returns T.15export type InputOptions<T> = PreviewMap<T> | Array<T>;16export type InputSelection<T> = Stack<T> | T;17/**18 * NOTE: Key type; from InputOptions generates asynchronous request for InputSelection.19 * Bridge between InputState and user. 20 */21export type InputRequest<T extends ISelectable> = (22 input_options: InputOptions<T>23) => Promise<InputSelection<T>>;24/**25 * Mechanistic Callback/SelectionFn classes - about the "how" of InputFetching 26 * not abstract interfaces.27 */28export type SelectionFn<T extends ISelectable> = (options: Array<T>) => T29// TODO: Pass preview_map directly instead of just options.30export type CallbackSelectionFn<T extends ISelectable> = (31 options: InputOptions<T>, resolve: Awaited<T>, reject: Rejection // Awaited from utilities. Replace in ts 4.532) => void;33/**34 * synthetic/async_input_getter: InputRequest factories really.35 */36export function synthetic_input_getter<T extends ISelectable>(37 selection_fn: SelectionFn<T>38): InputRequest<T> {39 return async function get_input( 40 input_options: InputOptions<T>41 ): Promise<InputSelection<T>> {42 console.log("synthetic_input_getter options: ", input_options);43 if (input_options instanceof Array) {44 return selection_fn(input_options);45 } else {46 var arr = Array.from(input_options.keys())47 var selection = selection_fn(arr);48 return input_options.get(selection);49 }50 };51}52// Builds an async InputRequest. Explicitly constructs promise around selection_fn53export function async_input_getter<T extends ISelectable>(54 selection_fn: CallbackSelectionFn<T>55): InputRequest<T> {56 return async function get_input( 57 input_options: InputOptions<T>58 ): Promise<Stack<T>> {59 console.log("Building InputRequest: ", input_options);60 // TS analog to type guarding kind of.61 if (input_options instanceof Array) {62 var arr: Array<T> = input_options63 } else {64 var arr = Array.from(input_options.keys())65 }66 // Manually specify type to remove errors67 var selection_promise: Promise<T> = new Promise(68 function(resolve, reject) {69 selection_fn(arr, resolve, reject)70 }71 );72 return selection_promise.then(73 function(selection) { 74 console.log("Resolve Selection: ", selection);75 if (input_options instanceof Array) {76 return selection;77 } else {78 return input_options.get(selection); 79 }80 }81 ).catch(82 function() {83 // TODO: Replace with some kind of explicit signal?84 console.log("Reject Selection");85 return null;86 }87 );88 };89}90/**91 * Key Type; Closely related to InputRequest, but a generator version - takes92 * InputOptions and returns corresponding InputSelection type.93 */94// TODO: Refine and use everywhere95export type SelectionGen<T> = (96 ((base?: Stack<T>) => Generator<PreviewMap<T>, Stack<T>, Stack<T>>) | 97 ((base?: T) => Generator<Array<T>, T, T>)98)99// TODO: Move and maybe generate from selectables instead of creating singleton.100export class Confirmation implements ISelectable, IMenuable {101 index: number;102 text: string;103 constructor() {104 this.index = 1;105 this.text = "Confirm";106 }107}108/**109 * InputAcquirers: Generate repeated InputRequests, yielding intermediate InputSelections,110 * until satisfying conditions are met for a final InputSelection to be returned. 111 * `yield` vs. `return` distinguishes the two.112 */113export interface IInputAcquirer<T> {114 current_input: InputSelection<T>;115 input_option_generator: SelectionGen<T>;116 get_options: (input: InputSelection<T>) => InputOptions<T>;117}118export class AutoInputAcquirer<T> implements IInputAcquirer<T> {119 auto_input: T;120 current_input: T;121 122 constructor(123 auto_input: T124 ) {125 this.auto_input = auto_input;126 // NOTE: Pre-queues auto_input; NEVER CHANGED.127 this.current_input = auto_input;128 }129 get_options(input: InputSelection<T>): Array<T> {130 return [this.auto_input];131 }132 * input_option_generator(133 base?: T134 ): Generator<Array<T>, T, T> {135 var selection = yield this.get_options(base); // For confirmation only.136 return selection;137 }138}139export class SimpleInputAcquirer<T> implements IInputAcquirer<T> {140 // TODO: Cleanup - Simplify coupling with controller loop.141 _option_fn: OptionFn<T>;142 current_input: T;143 require_confirmation: boolean;144 145 constructor(146 option_fn: OptionFn<T>,147 require_confirmation = true,148 ) {149 this._option_fn = option_fn;150 // NOTE: State has to return after any complete pop off the stack.151 this.current_input = null;152 this.require_confirmation = require_confirmation;153 }154 public static from_options<U>(options: Array<U>): SimpleInputAcquirer<U> {155 return new SimpleInputAcquirer<U>(() => options);156 }157 get_options(input: InputSelection<T>): Array<T> {158 return this._option_fn(input);159 }160 * input_option_generator(161 base?: InputSelection<T>162 ): Generator<Array<T>, T, T> {163 // Handles cases where intermediate input is required by yielding it.164 // Coroutine case.165 var options = this.get_options(base);166 var input_resp = yield options;167 if (this.require_confirmation) {168 do {169 var REJECT_CASE = !input_resp;170 var CONFIRM_CASE = (input_resp != null && input_resp == this.current_input)171 // TODO: Currently treats "null" response as special flag to pop.172 if (REJECT_CASE) {173 // var input_resp = yield options;174 return null; // NOTE: Propagates POP Signal to subphase175 } else if (CONFIRM_CASE){176 console.log("Confirm Simple InputSelection");177 break;178 } else {179 console.log("InputSelection: ", input_resp);180 this.current_input = input_resp;181 input_resp = yield options;182 }183 } while(true);184 } else {185 return input_resp;186 }187 return this.current_input;188 }189}190export class SequentialInputAcquirer<T> implements IInputAcquirer<T> {191 // TODO: Cleanup - Simplify coupling with controller loop.192 increment_fn: IncrementFn<T>;193 termination_fn: TerminationFn<T>;194 current_input: Stack<T>;195 constructor(196 increment_fn: IncrementFn<T>, 197 termination_fn: TerminationFn<T>, 198 ) {199 this.increment_fn = increment_fn;200 this.termination_fn = termination_fn;201 this.current_input = null;202 }203 get_options(input: Stack<T>): PreviewMap<T> {204 return bfs(input, this.increment_fn, this.termination_fn).to_map();205 }206 * input_option_generator(207 base?: Stack<T>208 ): Generator<PreviewMap<T>, Stack<T>, Stack<T>> {209 // Handles cases where intermediate input is required by yielding it.210 // Coroutine case.211 this.current_input = base;212 var preview_map = this.get_options(this.current_input);213 var input_resp = yield preview_map;214 do {215 var REJECT_CASE = !input_resp;216 var CONFIRM_CASE = (input_resp != null && input_resp.value == this.current_input.value)217 // TODO: Currently treats "null" response as special flag to pop.218 if (REJECT_CASE) {219 // TODO: Propagate null selection better - current state + "pop signal" tuple?220 if (this.current_input.parent) {221 this.current_input = this.current_input.pop();222 console.log("Pop Sequential InputSelection")223 preview_map = this.get_options(this.current_input); 224 } else {225 console.log("Cannot Pop Sequential InputSelection");226 return null; // NOTE: Propagates POP Signal to subphase227 }228 input_resp = yield preview_map;229 } else if (CONFIRM_CASE){230 console.log("Confirm Sequential InputSelection");231 break;232 } else {233 console.log("InputSelection: ", input_resp);234 this.current_input = input_resp;235 preview_map = this.get_options(this.current_input); 236 input_resp = yield preview_map;237 }238 } while(true);239 return this.current_input;240 }241}242export class ChainedInputAcquirer<T> extends SequentialInputAcquirer<T> {243 // static from_input_acquirer_list<U>(244 // input_acquirer_list: Array<IInputAcquirer<U>>245 // ): ChainedInputAcquirer<U> {246 constructor(option_fn_list: Array<OptionFn<T>>) {247 var increment_fn = (stack: Stack<T>): Array<T> => {248 var option_fn_index = stack.depth - 1;249 var option_fn = option_fn_list[option_fn_index];250 return option_fn(stack);251 };252 var termination_fn = (stack: Stack<T>): boolean => {253 return stack.depth > option_fn_list.length;254 };255 super(256 increment_fn,257 termination_fn,258 )259 }260}261/**262 * Experimental Acquirers263 */264// NOTE: Supports set acquisition with DAGish constraints.265// TODO: Actually harder to make an arbitrarily constrained SetInputAcquirer.266// TODO: Replace Stack.to_array with new InputSelection type? ("set" or "pool").267class TreeInputAcquirer<T> implements IInputAcquirer<T> {268 increment_fn: IncrementFn<T>;269 termination_fn: TerminationFn<T>;270 current_input: Stack<T>;271 constructor(272 increment_fn: IncrementFn<T>, 273 termination_fn: TerminationFn<T>, 274 ) {275 this.increment_fn = increment_fn;276 this.termination_fn = termination_fn;277 this.current_input = null;278 }279 get_options(input: Stack<T>): PreviewMap<T> {280 return bfs(input, this.increment_fn, this.termination_fn).to_map();281 }282 * input_option_generator(283 base?: Stack<T>284 ): Generator<PreviewMap<T>, Stack<T>, Stack<T>> {285 // Handles cases where intermediate input is required by yielding it.286 // Coroutine case.287 this.current_input = base;288 var preview_map = this.get_options(this.current_input);289 var input_resp = yield preview_map;290 do {291 // TODO: Currently treats "null" response as special flag to pop.292 var REJECT_CASE = input_resp == null;293 if (REJECT_CASE) {294 // TODO: Propagate null selection better - current state + "pop signal" tuple?295 if (this.current_input.parent) {296 this.current_input = this.current_input.pop();297 console.log("Pop Sequential InputSelection")298 preview_map = this.get_options(this.current_input); 299 } else {300 console.log("Cannot Pop Sequential InputSelection");301 return null; // NOTE: Propagates POP Signal to subphase302 }303 input_resp = yield preview_map;304 } else {305 var already_selected = input_resp.value in this.current_input.to_array()306 var SELECT_CASE = input_resp != null && !already_selected;307 var DESELECT_CASE = input_resp != null && already_selected;308 var CONFIRM_CASE = false; // TODO: Implement.309 if (CONFIRM_CASE){310 console.log("Confirm Sequential InputSelection");311 break;312 } else {313 console.log("InputSelection: ", input_resp);314 this.current_input = input_resp;315 preview_map = this.get_options(this.current_input); 316 input_resp = yield preview_map;317 }318 }319 } while(true);320 return this.current_input;321 }...
MonitoredInstrumentation.test.js
Source:MonitoredInstrumentation.test.js
1// @ts-nocheck2describe('Monitored instrumentation', () => {3 const deviceId = 'mock-device-id';4 const bundleId = 'mock-bundle-id';5 const INSTRUMENTATION_STACKTRACE_MOCK = 'Stacktrace mock';6 let adb;7 let logger;8 beforeEach(() => {9 jest.mock('../../../../../utils/logger');10 logger = require('../../../../../utils/logger');11 const ADB = jest.genMockFromModule('../exec/ADB');12 adb = new ADB();13 });14 let InstrumentationClass;15 let InstrumentationLogsParserClass;16 beforeEach(() => {17 jest.mock('./Instrumentation');18 InstrumentationClass = require('./Instrumentation');19 jest.mock('./InstrumentationLogsParser');20 InstrumentationLogsParserClass = require('./InstrumentationLogsParser').InstrumentationLogsParser;21 InstrumentationLogsParserClass.mockImplementation(() => {22 const instances = InstrumentationLogsParserClass.mock.instances;23 const _this = instances[instances.length - 1];24 _this.getStackTrace.mockReturnValue(INSTRUMENTATION_STACKTRACE_MOCK);25 });26 });27 const instrumentationObj = () => InstrumentationClass.mock.instances[0];28 const instrumentationLogsParserObj = () => InstrumentationLogsParserClass.mock.instances[0];29 let uut;30 beforeEach(() => {31 const MonitoredInstrumentation = require('./MonitoredInstrumentation');32 uut = new MonitoredInstrumentation(adb);33 });34 it('should properly init the underlying instrumentation', () => {35 expect(InstrumentationClass).toHaveBeenCalledWith(adb, logger, expect.any(Function), expect.any(Function));36 });37 describe('launch', () => {38 it('should launch the underlying instrumentation', async () => {39 const launchArgs = {};40 await uut.launch(deviceId, bundleId, launchArgs);41 expect(instrumentationObj().launch).toHaveBeenCalledWith(deviceId, bundleId, launchArgs);42 });43 it('should break if underlying launch fails', async () => {44 instrumentationObj().launch.mockRejectedValue(new Error());45 try {46 await uut.launch(deviceId, bundleId, {});47 fail();48 } catch (e) {}49 });50 });51 describe('Unexpected termination', () => {52 it('should invoke user termination callback', async () => {53 const terminationFn = jest.fn();54 uut.setTerminationFn(terminationFn);55 await uut.launch(deviceId, bundleId, {});56 await invokeUnderlyingTerminationCallback();57 expect(terminationFn).toHaveBeenCalled();58 });59 });60 describe('Initiation termination', () => {61 it('should terminate the underlying instrumentation', async () => {62 await uut.launch(deviceId, bundleId, {});63 await uut.terminate();64 expect(instrumentationObj().terminate).toHaveBeenCalled();65 });66 it('should break if underlying termination fails', async () => {67 instrumentationObj().terminate.mockRejectedValue(new Error());68 await uut.launch(deviceId, bundleId, {});69 try {70 await uut.terminate();71 fail();72 } catch (e) {}73 });74 it('should allow for termination without launch', async () => {75 await uut.terminate();76 expect(instrumentationObj().terminate).toHaveBeenCalled();77 });78 });79 it('should allow for user-initiated clearing of termination callback function', async () => {80 const terminationFn = jest.fn();81 uut.setTerminationFn(terminationFn);82 await uut.launch(deviceId, bundleId, {});83 uut.setTerminationFn(null);84 await invokeUnderlyingTerminationCallback();85 expect(terminationFn).not.toHaveBeenCalled();86 });87 it('should query underlying instrumentation for status', async () => {88 mockUnderlyingInstrumentationRunning();89 expect(uut.isRunning()).toEqual(true);90 mockUnderlyingInstrumentationDead();91 expect(uut.isRunning()).toEqual(false);92 });93 describe('Crash monitoring', () => {94 let onReject;95 beforeEach(async () => {96 onReject = jest.fn();97 await uut.launch(deviceId, bundleId, {});98 mockUnderlyingInstrumentationRunning();99 });100 it('should signal termination due to unexpected underlying termination, if waited-for', async () => {101 uut.waitForCrash().catch(onReject);102 await invokeUnderlyingTerminationCallback();103 expect(onReject).toHaveBeenCalled();104 });105 it('should signal termination due to initiated termination, if waited-for', async () => {106 uut.waitForCrash().catch(onReject);107 await uut.terminate();108 expect(onReject).toHaveBeenCalled();109 });110 it('should signal termination with a parsed stack-trace', async () => {111 mockLogsParserHasStacktrace();112 uut.waitForCrash().catch(onReject);113 await invokeUnderlyingLogListenerCallbackWith('mock data');114 await invokeUnderlyingTerminationCallback();115 assertRejectedWithNativeStacktrace();116 });117 it('should signal termination with no stack-trace, if none available', async () => {118 mockLogsParserHasNoStacktrace();119 uut.waitForCrash().catch(onReject);120 await invokeUnderlyingLogListenerCallbackWith('mock data');121 await invokeUnderlyingTerminationCallback();122 expect(instrumentationLogsParserObj().parse).toHaveBeenCalledWith('mock data');123 assertRejectedWithoutStacktrace();124 });125 it('should allow for user-initiated clearing of app-wait', async () => {126 const onResolve = jest.fn();127 const promise = uut.waitForCrash().then(onResolve);128 uut.abortWaitForCrash();129 await promise;130 expect(onResolve).toHaveBeenCalled();131 });132 it('should immediately signal termination if already terminated', async () => {133 mockUnderlyingInstrumentationDead();134 await uut.waitForCrash().catch(onReject);135 expect(onReject).toHaveBeenCalled();136 });137 it('should account for all waiting crash-wait clients', async () => {138 uut.waitForCrash().catch(onReject);139 uut.waitForCrash().catch(onReject);140 await uut.terminate();141 expect(onReject).toHaveBeenCalledTimes(2);142 });143 const assertRejectedWithNativeStacktrace = () => {144 const e = onReject.mock.calls[0][0];145 expect(e.toString()).toContain('DetoxRuntimeError: Failed to run application on the device');146 expect(e.toString()).toContain(`Native stacktrace dump: ${INSTRUMENTATION_STACKTRACE_MOCK}`);147 };148 const assertRejectedWithoutStacktrace = () => {149 const e = onReject.mock.calls[0][0];150 expect(e.toString()).toContain('DetoxRuntimeError: Failed to run application on the device');151 expect(e.toString()).not.toContain('Native stacktrace dump');152 };153 });154 const extractUnderlyingTerminationCallback = () => InstrumentationClass.mock.calls[0][2];155 const invokeUnderlyingTerminationCallback = async () => {156 const fn = extractUnderlyingTerminationCallback();157 await fn();158 };159 const extractUnderlyingLogListenerCallback = () => InstrumentationClass.mock.calls[0][3];160 const invokeUnderlyingLogListenerCallbackWith = async (data) => {161 const fn = extractUnderlyingLogListenerCallback();162 await fn(data);163 };164 const mockUnderlyingInstrumentationRunning = () => instrumentationObj().isRunning.mockReturnValue(true);165 const mockUnderlyingInstrumentationDead = () => instrumentationObj().isRunning.mockReturnValue(false);166 const mockLogsParserHasStacktrace = () => instrumentationLogsParserObj().containsStackTraceLog.mockReturnValue(true);167 const mockLogsParserHasNoStacktrace = () => instrumentationLogsParserObj().containsStackTraceLog.mockReturnValue(false);...
graceful-stop.test.ts
Source:graceful-stop.test.ts
...94 cases.forEach(({ name, expectedExitCode, timeout, cleanup, gracefulWrappers }) =>95 test(name, async () => {96 const onShutdown = jest.fn();97 const terminationFn = terminationHandlerFactory({ timeout, gracefulWrappers, onShutdown, cleanup });98 await terminationFn();99 expect(onShutdown).toHaveBeenCalledWith(expectedExitCode);100 }),101 );102});103describe('gracefulWrapperConsumerFactory', () => {104 beforeEach(() => {105 jest.resetAllMocks();106 });107 test('should initiate consumer shutdown', async () => {108 const consumer = consumerFactory({ isProcessing: async () => Promise.resolve(false) });109 const spy = jest.spyOn(consumer, 'stopReception');110 await gracefulWrapperConsumerFactory(consumer).shutdown();111 expect(spy).toHaveBeenCalledTimes(1);112 });...
Using AI Code Generation
1var myApp = angular.module('myApp', []);2myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {3 $scope.name = 'Everyone';4 $timeout(function() {5 $scope.name = 'Everyone!';6 }, 3000);7}]);8var myApp = angular.module('myApp', []);9myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {10 $scope.name = 'Everyone';11 $timeout(function() {12 $scope.$apply(function() {13 $scope.name = 'Everyone!';14 });15 }, 3000);16}]);17var myApp = angular.module('myApp', []);18myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {19 $scope.name = 'Everyone';20 $timeout(function() {21 $scope.$evalAsync(function() {22 $scope.name = 'Everyone!';23 });24 }, 3000);25}]);26var myApp = angular.module('myApp', []);27myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {28 $scope.name = 'Everyone';29 $timeout(function() {30 $scope.$applyAsync(function() {31 $scope.name = 'Everyone!';32 });33 }, 3000);34}]);35var myApp = angular.module('myApp', []);36myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {37 $scope.name = 'Everyone';38 $scope.$watch('name', function(newValue, oldValue) {39 console.log('Changed!');40 console.log('Old: ' + oldValue);41 console.log('New: ' + newValue);42 });43 $timeout(function() {44 $scope.name = 'Everyone!';45 }, 3000);46}]);47var myApp = angular.module('myApp', []);48myApp.controller('mainController', ['$scope', '$timeout', function($scope, $timeout) {
Using AI Code Generation
1app.run(function($rootScope) {2 $rootScope.terminationFn = function() {3 console.log('Terminating app');4 }5});6app.run(function($rootScope) {7 $rootScope.terminationFn = function() {8 console.log('Terminating app');9 }10});11app.run(function($rootScope) {12 $rootScope.terminationFn = function() {13 console.log('Terminating app');14 }15});16app.run(function($rootScope) {17 $rootScope.terminationFn = function() {18 console.log('Terminating app');19 }20});21app.run(function($rootScope) {22 $rootScope.terminationFn = function() {23 console.log('Terminating app');24 }25});26app.run(function($rootScope) {27 $rootScope.terminationFn = function() {28 console.log('Terminating app');29 }30});31app.run(function($rootScope) {32 $rootScope.terminationFn = function() {33 console.log('Terminating app');34 }35});36app.run(function($rootScope) {37 $rootScope.terminationFn = function() {38 console.log('Terminating app');39 }40});41app.run(function($rootScope) {42 $rootScope.terminationFn = function() {43 console.log('Terminating app');44 }45});46app.run(function($rootScope) {47 $rootScope.terminationFn = function() {48 console.log('Terminating app');49 }50});51app.run(function($rootScope) {52 $rootScope.terminationFn = function() {53 console.log('Terminating app');54 }55});
Using AI Code Generation
1angular.module('myApp', [])2 .controller('myCtrl', ['$scope', function($scope) {3 $scope.$on('$destroy', function(){4 console.log('destroyed');5 });6 }]);
Using AI Code Generation
1const root = require('./root');2const terminationFn = root.terminationFn;3terminationFn();4module.exports = {5 terminationFn: function(){6 }7}8const root = require('./root');9const terminationFn = root.terminationFn;10terminationFn();11module.exports = {12 terminationFn: function(){13 }14}15const root = require('./root');16const terminationFn = root.terminationFn;17terminationFn();18module.exports = {19 terminationFn: function(){20 }21}22const root = require('./root');23const terminationFn = root.terminationFn;24terminationFn();25module.exports = {26 terminationFn: function(){27 }28}29const root = require('./root');30const terminationFn = root.terminationFn;31terminationFn();32module.exports = {33 terminationFn: function(){34 }35}36const root = require('./root');37const terminationFn = root.terminationFn;38terminationFn();39module.exports = {40 terminationFn: function(){41 }42}43const root = require('./root');44const terminationFn = root.terminationFn;45terminationFn();46module.exports = {47 terminationFn: function(){48 }49}50const root = require('./root');
Using AI Code Generation
1$rootScope.$on('$locationChangeStart', function(event, next, current) {2 if ($rootScope.terminationFn) {3 $rootScope.terminationFn();4 }5});6$scope.$on('$destroy', function() {7 if ($rootScope.terminationFn) {8 $rootScope.terminationFn();9 }10});
Using AI Code Generation
1var root = require('root');2root.terminationFn();3**Note:** If you are using the `root` module in a web application, you should use `root.terminationFn()` in the `uncaughtException` event handler of the `process` object. For example:4var root = require('root');5process.on('uncaughtException', function(err) {6 root.terminationFn();7});8#### `root.terminationFn()`
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!!