How to use scheduledPromise method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

ChangeHandler.js

Source:ChangeHandler.js Github

copy

Full Screen

1/**2 * Tupaia3 * Copyright (c) 2017 - 2021 Beyond Essential Systems Pty Ltd4 */5import winston from 'winston';6const MAX_RETRY_ATTEMPTS = 3;7export class ChangeHandler {8 /**9 * A map of change translators by record type. Each translator can alter the change details that10 * are queued and scheduled for handling at a later stage, when changes stop coming through.11 *12 * @protected13 * @type {Record<string, Function>}14 */15 changeTranslators = {};16 /**17 * Wait 1 sec after changes before handling the change queue, to avoid double-up.18 * Can override in child classes to fine-tune the timing of queue handling19 *20 * @protected21 */22 debounceTime = 1000; // ms23 changeQueue = [];24 scheduledTimeout = null;25 scheduledPromise = null;26 scheduledPromiseResolve = null;27 activePromise = null;28 changeHandlerCancellers = [];29 lockKey = null;30 /**31 * @param {ModelRegistry} models32 * @param {string} lockKey33 */34 constructor(models, lockKey) {35 this.models = models;36 this.lockKey = lockKey;37 }38 setDebounceTime(debounceTime) {39 this.debounceTime = debounceTime;40 }41 /**42 * @abstract43 * @protected44 */45 // eslint-disable-next-line no-unused-vars46 async handleChanges(transactingModels, changes) {47 throw new Error('Any subclass of ChangeHandler must implement the "handleChanges" method');48 }49 /**50 * @protected51 */52 getChangeDebuggingInfo = changes => {53 return `Change count: ${changes.length}`;54 };55 listenForChanges() {56 if (Object.values(this.changeTranslators).length === 0) {57 throw new Error('No change translators found');58 }59 this.changeHandlerCancellers = Object.entries(this.changeTranslators).map(60 ([recordType, translator]) =>61 this.models[recordType].addChangeHandler(async changeDetails => {62 // Translate changes and schedule their handling as a batch at a later stage63 const translatedChanges = await translator(changeDetails);64 this.changeQueue.push(...translatedChanges);65 return this.scheduleChangeQueueHandler();66 }),67 );68 }69 stopListeningForChanges() {70 this.changeHandlerCancellers.forEach(c => c());71 this.changeHandlerCancellers = [];72 }73 async scheduleChangeQueueHandler() {74 // wait for any active handler to finish before scheduling a new one75 await this.activePromise;76 // clear any previous scheduled handler, so that we debounce all changes in the same time period77 if (this.scheduledTimeout) {78 clearTimeout(this.scheduledTimeout);79 }80 if (!this.scheduledPromise) {81 this.scheduledPromise = new Promise(resolve => {82 this.scheduledPromiseResolve = resolve;83 });84 }85 // schedule the handler to execute after an adequate period of debouncing86 this.scheduledTimeout = setTimeout(() => {87 this.activePromise = this.executeScheduledHandler();88 }, this.debounceTime);89 return this.scheduledPromise;90 }91 executeScheduledHandler = async () => {92 // remove timeout so any changes added now get scheduled anew93 this.scheduledTimeout = null;94 this.scheduledPromise = null;95 const currentQueue = this.changeQueue;96 this.changeQueue = [];97 let success;98 for (let i = 0; i < MAX_RETRY_ATTEMPTS; i++) {99 success = true;100 try {101 await this.models.wrapInTransaction(async transactingModels => {102 // Acquire a database advisory lock for the transaction103 // Ensures no other server instance can execute its change handler at the same time104 await transactingModels.database.acquireAdvisoryLockForTransaction(this.lockKey);105 await this.handleChanges(transactingModels, currentQueue);106 });107 } catch (error) {108 winston.warn(109 [110 `Attempt #${i + 1} to handle change batch failed with error message:`,111 error.message,112 ].join('\n'),113 );114 success = false;115 }116 if (success) {117 break;118 }119 }120 if (!success) {121 this.logFailedChanges(currentQueue);122 }123 this.scheduledPromiseResolve();124 };125 logFailedChanges = failedChanges => {126 winston.error(127 [128 `Failed to handle change batch after trying ${MAX_RETRY_ATTEMPTS} times`,129 'Debugging info:',130 this.getChangeDebuggingInfo(failedChanges),131 ].join('\n'),132 );133 };...

Full Screen

Full Screen

scheduler.js

Source:scheduler.js Github

copy

Full Screen

1"use strict";2exports.__esModule = true;3exports.scheduleJob = void 0;4const _ = require(`lodash`);5const uuidv4 = require(`uuid/v4`);6const pDefer = require(`p-defer`);7const worker = require(`./worker`);8const {9 createProgress10} = require(`./utils`);11const toProcess = new Map();12let pendingImagesCounter = 0;13let completedImagesCounter = 0;14let bar; // node 8 doesn't support promise.finally, we extract this function to re-use it inside then & catch15const cleanupJob = (job, actions) => {16 if (bar) {17 bar.tick(job.task.args.operations.length);18 }19 completedImagesCounter += job.task.args.operations.length;20 if (completedImagesCounter === pendingImagesCounter) {21 if (bar) {22 bar.done();23 bar = null;24 }25 pendingImagesCounter = 0;26 completedImagesCounter = 0;27 }28 actions.endJob({29 id: job.id30 }, {31 name: `gatsby-plugin-sharp`32 });33};34const executeJobs = _.throttle(actions => {35 toProcess.forEach(job => {36 const {37 task38 } = job;39 toProcess.delete(task.inputPaths[0]);40 try {41 worker.IMAGE_PROCESSING(task.inputPaths, task.outputDir, task.args).then(() => {42 job.deferred.resolve();43 cleanupJob(job, actions);44 }).catch(err => {45 job.deferred.reject(err);46 cleanupJob(job, actions);47 });48 } catch (err) {49 job.deferred.reject(err);50 cleanupJob(job, actions);51 }52 });53}, 1000, {54 leading: false55});56const scheduleJob = async (job, actions, pluginOptions, reporter, reportStatus = true) => {57 const isQueued = toProcess.has(job.inputPath);58 let scheduledPromise;59 if (reportStatus && !bar) {60 bar = createProgress(`Generating image thumbnails`, reporter);61 bar.start();62 } // if an input image is already queued we add it to a transforms queue63 // doing different manipulations in parallel makes sharp faster.64 if (isQueued) {65 const registeredJob = toProcess.get(job.inputPath); // add the transform to the transforms list66 const operations = registeredJob.task.args.operations.concat({67 outputPath: job.outputPath,68 transforms: job.args69 });70 scheduledPromise = registeredJob.deferred.promise;71 toProcess.set(job.inputPath, Object.assign({}, registeredJob, {72 task: Object.assign({}, registeredJob.task, {73 args: Object.assign({}, registeredJob.task.args, {74 operations75 })76 })77 })); // update the job78 actions.setJob({79 id: registeredJob.id,80 imagesCount: operations.length81 }, {82 name: `gatsby-plugin-sharp`83 });84 } else {85 const jobId = uuidv4();86 const deferred = pDefer();87 scheduledPromise = deferred.promise; // make our job compliant with new job spec88 toProcess.set(job.inputPath, {89 id: jobId,90 task: {91 inputPaths: [job.inputPath],92 outputDir: job.outputDir,93 args: {94 contentDigest: job.contentDigest,95 pluginOptions,96 operations: [{97 outputPath: job.outputPath,98 transforms: job.args99 }]100 }101 },102 deferred103 }); // create the job so gatsby waits for completion104 actions.createJob({105 id: jobId,106 description: `processing image ${job.inputPath}`,107 imagesCount: 1108 }, {109 name: `gatsby-plugin-sharp`110 });111 }112 pendingImagesCounter++;113 if (bar) {114 bar.total = pendingImagesCounter;115 }116 executeJobs(actions);117 return scheduledPromise;118};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {fc} = require('fast-check');2const {scheduledPromise} = require('fast-check-monorepo');3const {delay} = require('fast-check-monorepo');4const test3 = () => {5 fc.assert(6 fc.property(fc.integer(), async (i) => {7 const p = scheduledPromise(delay(1000), i);8 const result = await p;9 return result === i;10 })11 );12};13module.exports = test3;14const {fc} = require('fast-check');15const {scheduledPromise} = require('fast-check-monorepo');16const {delay} = require('fast-check-monorepo');17const test4 = () => {18 fc.assert(19 fc.property(fc.integer(), async (i) => {20 const p = scheduledPromise(delay(1000), i);21 const result = await p;22 return result === i;23 })24 );25};26module.exports = test4;27const {fc} = require('fast-check');28const {scheduledPromise} = require('fast-check-monorepo');29const {delay} = require('fast-check-monorepo');30const test5 = () => {31 fc.assert(32 fc.property(fc.integer(), async (i) => {33 const p = scheduledPromise(delay(1000), i);34 const result = await p;35 return result === i;36 })37 );38};39module.exports = test5;40const {fc} = require('fast-check');41const {scheduledPromise} = require('fast-check-monorepo');42const {delay} = require('fast-check-monorepo');43const test6 = () => {44 fc.assert(45 fc.property(fc.integer(), async (i) => {46 const p = scheduledPromise(delay(1000), i);47 const result = await p;48 return result === i;49 })50 );51};52module.exports = test6;53const {fc} = require('fast-check');54const {scheduledPromise} = require('fast-check-monorepo');55const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const {scheduledPromise} = require('fast-check');2const myPromise = () => new Promise((resolve, reject) => {3 setTimeout(() => resolve('done!'), 500);4});5scheduledPromise(myPromise, {interval: 1000}).then(console.log);6const {scheduledPromise} = require('fast-check');7const myPromise = () => new Promise((resolve, reject) => {8 setTimeout(() => resolve('done!'), 500);9});10scheduledPromise(myPromise, {interval: 1000}).then(console.log);11const {scheduledPromise} = require('fast-check');12const myPromise = () => new Promise((resolve, reject) => {13 setTimeout(() => resolve('done!'), 500);14});15scheduledPromise(myPromise, {interval: 1000}).then(console.log);16const {scheduledPromise} = require('fast-check');17const myPromise = () => new Promise((resolve, reject) => {18 setTimeout(() => resolve('done!'), 500);19});20scheduledPromise(myPromise, {interval: 1000}).then(console.log);21const {scheduledPromise} = require('fast-check');22const myPromise = () => new Promise((resolve, reject) => {23 setTimeout(() => resolve('done!'), 500);24});25scheduledPromise(myPromise, {interval: 1000}).then(console.log);26const {scheduledPromise} = require('fast-check');27const myPromise = () => new Promise((resolve, reject) => {28 setTimeout(() => resolve('done!'), 500);29});30scheduledPromise(myPromise, {interval: 1000}).then(console.log);31const {scheduledPromise} = require('fast-check');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { scheduledPromise } from 'fast-check';2const promise = scheduledPromise(() => {3 console.log('Hello');4 return 42;5}, 1000);6promise.then((result) => {7 console.log(result);8});9import { scheduledPromise } from 'fast-check';10const promise = scheduledPromise(() => {11 console.log('Hello');12 return 42;13}, 1000);14promise.then((result) => {15 console.log(result);16});17navigation.navigate('MyScreen');18this.props.navigation.navigate('MyScreen');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { check, property } from "fast-check";2import { scheduledPromise } from "fast-check-monorepo";3const arb = property(4 scheduledPromise(5 property(6 check(7 property(8 property((n: number) => n > 0),9 property((m: number) => m > 0),10 (n, m) => n * m11 { numRuns: 10 }12 (p) => {13 return p.then((n) => {14 expect(n).toBeGreaterThan(0);15 });16 }17);18test("scheduledPromise", () => {19 check(arb, { numRuns: 10 });20});21import { check, property } from "fast-check";22import { scheduledPromise } from "fast-check-monorepo";23const arb = property(24 scheduledPromise(25 property(26 check(27 property(28 property((n: number) => n > 0),29 property((m: number) => m > 0),30 (n, m) => n * m31 { numRuns: 10 }32 (p) => {33 return p.then((n) => {34 expect(n).toBeGreaterThan(0);35 });36 }37);38test("scheduledPromise", () => {39 check(arb, { numRuns: 10 });40});41import { check, property } from "fast-check";42import { scheduledPromise } from "fast-check-monorepo";43const arb = property(44 scheduledPromise(45 property(46 check(47 property(48 property((n: number) => n > 0),49 property((m: number) => m > 0),50 (n, m) => n * m51 { numRuns: 10 }52 (p) => {53 return p.then((n) => {54 expect(n).toBeGreaterThan(0);55 });56 }57);58test("scheduledPromise", () => {59 check(arb, { numRuns: 10 });60});

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check-monorepo");2function testFunction() {3 return 1;4}5fc.assert(6 fc.property(7 fc.scheduledPromise(8 fc.integer({ min: 0, max: 1000 }),9 fc.integer({ min: 0, max: 1000 })10 (p) => p.then((r) => r >= 0 && r <= 1000)11);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { scheduler, scheduledPromise } from 'fast-check';2const p1 = scheduledPromise(() => {3 console.log('p1');4 return 1;5});6const p2 = scheduledPromise(() => {7 console.log('p2');8 return 2;9});10const p3 = scheduledPromise(() => {11 console.log('p3');12 return 3;13});14const p4 = scheduledPromise(() => {15 console.log('p4');16 return 4;17});18const p5 = scheduledPromise(() => {19 console.log('p5');20 return 5;21});22const p6 = scheduledPromise(() => {23 console.log('p6');24 return 6;25});26const p7 = scheduledPromise(() => {27 console.log('p7');28 return 7;29});30const p8 = scheduledPromise(() => {31 console.log('p8');32 return 8;33});34const p9 = scheduledPromise(() => {35 console.log('p9');36 return 9;37});38const p10 = scheduledPromise(() => {39 console.log('p10');40 return 10;41});42const p11 = scheduledPromise(() => {43 console.log('p11');44 return 11;45});46const p12 = scheduledPromise(() => {47 console.log('p12');48 return 12;49});50const p13 = scheduledPromise(() => {51 console.log('p13');52 return 13;53});54const p14 = scheduledPromise(() => {55 console.log('p14');56 return 14;57});

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const {scheduledPromise} = require('fast-check-monorepo');3fc.assert(4 fc.property(fc.integer(), (i) => {5 const p = scheduledPromise(i);6 return fc.pre(i > 0) || p.then(() => false, () => true);7 }),8 { time: 500 }9);

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 fast-check-monorepo 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