Best JavaScript code snippet using fast-check-monorepo
CommandsArbitrary.ts
Source:CommandsArbitrary.ts
1import { Arbitrary } from '../../check/arbitrary/definition/Arbitrary';2import { Value } from '../../check/arbitrary/definition/Value';3import { ICommand } from '../../check/model/command/ICommand';4import { CommandsIterable } from '../../check/model/commands/CommandsIterable';5import { CommandWrapper } from '../../check/model/commands/CommandWrapper';6import { ReplayPath } from '../../check/model/ReplayPath';7import { Random } from '../../random/generator/Random';8import { makeLazy } from '../../stream/LazyIterableIterator';9import { Stream } from '../../stream/Stream';10import { oneof } from '../oneof';11import { restrictedIntegerArbitraryBuilder } from './builders/RestrictedIntegerArbitraryBuilder';12// eslint-disable-next-line @typescript-eslint/ban-types13type CommandsArbitraryContext<Model extends object, Real, RunResult, CheckAsync extends boolean> = {14 shrunkOnce: boolean;15 items: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[];16};17/** @internal */18// eslint-disable-next-line @typescript-eslint/ban-types19export class CommandsArbitrary<Model extends object, Real, RunResult, CheckAsync extends boolean> extends Arbitrary<20 CommandsIterable<Model, Real, RunResult, CheckAsync>21> {22 readonly oneCommandArb: Arbitrary<CommandWrapper<Model, Real, RunResult, CheckAsync>>;23 readonly lengthArb: Arbitrary<number>;24 private replayPath: boolean[];25 private replayPathPosition: number;26 constructor(27 commandArbs: Arbitrary<ICommand<Model, Real, RunResult, CheckAsync>>[],28 maxGeneratedCommands: number,29 maxCommands: number,30 readonly sourceReplayPath: string | null,31 readonly disableReplayLog: boolean32 ) {33 super();34 this.oneCommandArb = oneof(...commandArbs).map((c) => new CommandWrapper(c));35 this.lengthArb = restrictedIntegerArbitraryBuilder(0, maxGeneratedCommands, maxCommands);36 this.replayPath = []; // updated at first shrink37 this.replayPathPosition = 0;38 }39 private metadataForReplay() {40 return this.disableReplayLog ? '' : `replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`;41 }42 private buildValueFor(items: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[], shrunkOnce: boolean) {43 const commands = items.map((item) => item.value_);44 const context: CommandsArbitraryContext<Model, Real, RunResult, CheckAsync> = { shrunkOnce, items };45 return new Value(new CommandsIterable(commands, () => this.metadataForReplay()), context);46 }47 generate(mrng: Random): Value<CommandsIterable<Model, Real, RunResult, CheckAsync>> {48 // For the moment, we fully ignore the bias on commands...49 const size = this.lengthArb.generate(mrng, undefined);50 const sizeValue = size.value;51 const items: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[] = Array(sizeValue);52 for (let idx = 0; idx !== sizeValue; ++idx) {53 // ...even when generating the commands themselves54 const item = this.oneCommandArb.generate(mrng, undefined);55 items[idx] = item;56 }57 this.replayPathPosition = 0; // reset replay58 return this.buildValueFor(items, false);59 }60 canShrinkWithoutContext(value: unknown): value is CommandsIterable<Model, Real, RunResult, CheckAsync> {61 // Not supported yet on commands62 return false;63 }64 /** Filter commands based on the real status of the execution */65 private filterOnExecution(itemsRaw: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[]) {66 const items: typeof itemsRaw = [];67 for (const c of itemsRaw) {68 if (c.value_.hasRan) {69 this.replayPath.push(true);70 items.push(c);71 } else this.replayPath.push(false);72 }73 return items;74 }75 /** Filter commands based on the internal replay state */76 private filterOnReplay(itemsRaw: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[]) {77 return itemsRaw.filter((c, idx) => {78 const state = this.replayPath[this.replayPathPosition + idx];79 if (state === undefined) throw new Error(`Too short replayPath`);80 if (!state && c.value_.hasRan) throw new Error(`Mismatch between replayPath and real execution`);81 return state;82 });83 }84 /** Filter commands for shrinking purposes */85 private filterForShrinkImpl(itemsRaw: Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[]) {86 if (this.replayPathPosition === 0) {87 this.replayPath = this.sourceReplayPath !== null ? ReplayPath.parse(this.sourceReplayPath) : [];88 }89 const items =90 this.replayPathPosition < this.replayPath.length91 ? this.filterOnReplay(itemsRaw)92 : this.filterOnExecution(itemsRaw);93 this.replayPathPosition += itemsRaw.length;94 return items;95 }96 shrink(97 _value: CommandsIterable<Model, Real, RunResult, CheckAsync>,98 context: unknown99 ): Stream<Value<CommandsIterable<Model, Real, RunResult, CheckAsync>>> {100 if (context === undefined) {101 return Stream.nil<Value<CommandsIterable<Model, Real, RunResult, CheckAsync>>>();102 }103 const safeContext = context as CommandsArbitraryContext<Model, Real, RunResult, CheckAsync>;104 const shrunkOnce = safeContext.shrunkOnce;105 const itemsRaw = safeContext.items;106 const items = this.filterForShrinkImpl(itemsRaw); // filter out commands that have not been executed107 if (items.length === 0) {108 return Stream.nil<Value<CommandsIterable<Model, Real, RunResult, CheckAsync>>>();109 }110 // The shrinker of commands have to keep the last item111 // because it is the one causing the failure112 const rootShrink: Stream<Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[]> = shrunkOnce113 ? Stream.nil()114 : new Stream([[]][Symbol.iterator]());115 // If the resulting shrinkable was simply built by joining the streams one by one,116 // > stream[n] = stream[n-1].join(nextFor[n]) -- with nextFor[-1] = rootShrink117 // we would run into stack overflows when calling next to get back the 1st element (for huge n).118 // Indeed calling stream[n].next() would require to call stream[n-1].next() and so on...119 // Instead of that we define stream[n] = rootShrink.join(nextFor[0], ..., nextFor[n])120 // So that calling next on stream[n] will not have to run too many recursions121 const nextShrinks: IterableIterator<Value<CommandWrapper<Model, Real, RunResult, CheckAsync>>[]>[] = [];122 // keep fixed number commands at the beginning123 // remove items in remaining part except the last one124 for (let numToKeep = 0; numToKeep !== items.length; ++numToKeep) {125 nextShrinks.push(126 makeLazy(() => {127 const fixedStart = items.slice(0, numToKeep);128 return this.lengthArb129 .shrink(items.length - 1 - numToKeep, undefined)130 .map((l) => fixedStart.concat(items.slice(items.length - (l.value + 1))));131 })132 );133 }134 // shrink one by one135 for (let itemAt = 0; itemAt !== items.length; ++itemAt) {136 nextShrinks.push(137 makeLazy(() =>138 this.oneCommandArb139 .shrink(items[itemAt].value_, items[itemAt].context)140 .map((v) => items.slice(0, itemAt).concat([v], items.slice(itemAt + 1)))141 )142 );143 }144 return rootShrink.join(...nextShrinks).map((shrinkables) => {145 return this.buildValueFor(146 shrinkables.map((c) => new Value(c.value_.clone(), c.context)),147 true148 );149 });150 }...
CommandsIterable.spec.ts
Source:CommandsIterable.spec.ts
1import * as fc from 'fast-check';2import { CommandWrapper } from '../../../../../src/check/model/commands/CommandWrapper';3import { CommandsIterable } from '../../../../../src/check/model/commands/CommandsIterable';4import { Command } from '../../../../../src/check/model/command/Command';5import { cloneMethod } from '../../../../../src/check/symbols';6type Model = Record<string, unknown>;7type Real = unknown;8const buildAlreadyRanCommands = (runFlags: boolean[]) => {9 return runFlags.map((hasRun, idx) => {10 const cmd = new (class implements Command<Model, Real> {11 check = (_m: Readonly<Model>) => true;12 run = (_m: Model, _r: Real) => {};13 toString = () => String(idx);14 })();15 const wrapper = new CommandWrapper(cmd);16 if (hasRun) {17 wrapper.run({}, {});18 }19 return wrapper;20 });21};22describe('CommandsIterable', () => {23 it('Should not reset hasRun flag on iteration', () =>24 fc.assert(25 fc.property(fc.array(fc.boolean()), (runFlags) => {26 const commands = [...new CommandsIterable(buildAlreadyRanCommands(runFlags), () => '')];27 for (let idx = 0; idx !== runFlags.length; ++idx) {28 expect(commands[idx].hasRan).toEqual(runFlags[idx]);29 }30 })31 ));32 it('Should not reset hasRun flag on the original iterable on clone', () =>33 fc.assert(34 fc.property(fc.array(fc.boolean()), (runFlags) => {35 const originalIterable = new CommandsIterable(buildAlreadyRanCommands(runFlags), () => '');36 originalIterable[cloneMethod]();37 const commands = [...originalIterable];38 for (let idx = 0; idx !== runFlags.length; ++idx) {39 expect(commands[idx].hasRan).toEqual(runFlags[idx]);40 }41 })42 ));43 it('Should reset hasRun flag for the clone on clone', () =>44 fc.assert(45 fc.property(fc.array(fc.boolean()), (runFlags) => {46 const commands = [...new CommandsIterable(buildAlreadyRanCommands(runFlags), () => '')[cloneMethod]()];47 for (let idx = 0; idx !== runFlags.length; ++idx) {48 expect(commands[idx].hasRan).toBe(false);49 }50 })51 ));52 it('Should only print ran commands and metadata if any', () =>53 fc.assert(54 fc.property(fc.array(fc.boolean()), fc.fullUnicodeString(), (runFlags, metadata) => {55 const commandsIterable = new CommandsIterable(buildAlreadyRanCommands(runFlags), () => metadata);56 const expectedCommands = runFlags57 .map((hasRan, idx) => (hasRan ? String(idx) : ''))58 .filter((s) => s !== '')59 .join(',');60 const expectedToString = metadata.length !== 0 ? `${expectedCommands} /*${metadata}*/` : expectedCommands;61 expect(commandsIterable.toString()).toEqual(expectedToString);62 })63 ));...
CommandsIterable.ts
Source:CommandsIterable.ts
1import { cloneMethod } from '../../symbols';2import { CommandWrapper } from './CommandWrapper';3/**4 * Iterable datastructure accepted as input for asyncModelRun and modelRun5 */6// eslint-disable-next-line @typescript-eslint/ban-types7export class CommandsIterable<Model extends object, Real, RunResult, CheckAsync extends boolean = false>8 implements Iterable<CommandWrapper<Model, Real, RunResult, CheckAsync>>9{10 constructor(11 readonly commands: CommandWrapper<Model, Real, RunResult, CheckAsync>[],12 readonly metadataForReplay: () => string13 ) {}14 [Symbol.iterator](): Iterator<CommandWrapper<Model, Real, RunResult, CheckAsync>> {15 return this.commands[Symbol.iterator]();16 }17 [cloneMethod](): CommandsIterable<Model, Real, RunResult, CheckAsync> {18 return new CommandsIterable(19 this.commands.map((c) => c.clone()),20 this.metadataForReplay21 );22 }23 toString(): string {24 const serializedCommands = this.commands25 .filter((c) => c.hasRan)26 .map((c) => c.toString())27 .join(',');28 const metadata = this.metadataForReplay();29 return metadata.length !== 0 ? `${serializedCommands} /*${metadata}*/` : serializedCommands;30 }...
Using AI Code Generation
1const fc = require('fast-check');2const { commandsIterable } = require('fast-check-monorepo');3const fc = require('fast-check');4const { commandsIterable } = require('fast-check-monorepo');5const fc = require('fast-check');6const { commandsIterable } = require('fast-check-monorepo');7const fc = require('fast-check');8const { commandsIterable } = require('fast-check-monorepo');9const fc = require('fast-check');10const { commandsIterable } = require('fast-check-monorepo');11const fc = require('fast-check');12const { commandsIterable } = require('fast-check-monorepo');13const fc = require('fast-check');14const { commandsIterable } = require('fast-check-monorepo');15const fc = require('fast-check');16const { commandsIterable } = require('fast-check-monorepo');17const fc = require('fast-check');18const { commandsIterable } = require('fast-check-monorepo');19const fc = require('fast-check');20const { commandsIterable } = require('fast-check-monorepo');21const fc = require('fast-check');22const { commandsIterable } = require('fast-check-monorepo');23const fc = require('fast-check');24const { commandsIterable } = require('fast-check-monorepo');25const fc = require('fast-check');26const { commandsIterable } = require('fast-check-monorepo');27const fc = require('fast-check');28const { commandsIterable } = require('fast-check-monorepo');
Using AI Code Generation
1import * as fc from 'fast-check';2const commandsIterable = fc.commandsIterable();3const commandsIterator = commandsIterable[Symbol.iterator]();4const commandsIteratorResult = commandsIterator.next();5console.log(commandsIteratorResult);6console.log(commandsIteratorResult.value);7console.log(commandsIteratorResult.done);8import * as fc from 'fast-check';9const commandsIterable = fc.commandsIterable();10const commandsIterator = commandsIterable[Symbol.iterator]();11const commandsIteratorResult = commandsIterator.next();12console.log(commandsIteratorResult);13console.log(commandsIteratorResult.value);14console.log(commandsIteratorResult.done);15import * as fc from 'fast-check';16const commandsIterable = fc.commandsIterable();17const commandsIterator = commandsIterable[Symbol.iterator]();18const commandsIteratorResult = commandsIterator.next();19console.log(commandsIteratorResult);20console.log(commandsIteratorResult.value);21console.log(commandsIteratorResult.done);22import * as fc from 'fast-check';23const commandsIterable = fc.commandsIterable();24const commandsIterator = commandsIterable[Symbol.iterator]();25const commandsIteratorResult = commandsIterator.next();26console.log(commandsIteratorResult);27console.log(commandsIteratorResult.value);28console.log(commandsIteratorResult.done);29import * as fc from 'fast-check';30const commandsIterable = fc.commandsIterable();31const commandsIterator = commandsIterable[Symbol.iterator]();32const commandsIteratorResult = commandsIterator.next();33console.log(commandsIteratorResult);34console.log(commandsIteratorResult.value);35console.log(commandsIteratorResult.done);36import * as fc from 'fast-check';37const commandsIterable = fc.commandsIterable();38const commandsIterator = commandsIterable[Symbol.iterator]();39const commandsIteratorResult = commandsIterator.next();40console.log(commandsIteratorResult);41console.log(commandsIteratorResult.value);42console.log(commandsIteratorResult.done);43import * as fc from 'fast-check';44const commandsIterable = fc.commandsIterable();45const commandsIterator = commandsIterable[Symbol.iterator]();46const commandsIteratorResult = commandsIterator.next();47console.log(commandsIteratorResult);48console.log(commandsIteratorResult.value);49console.log(commandsIteratorResult.done);50import * as fc from 'fast-check';
Using AI Code Generation
1const fc = require('fast-check');2const { commandsIterable } = require('fast-check-monorepo');3const commands = commandsIterable({4});5for (const command of commands) {6}7const fc = require('fast-check');8const { commandsIterator } = require('fast-check-monorepo');9const commands = commandsIterator({10});11for (const command of commands) {12}13const fc = require('fast-check');14const { runCommands } = require('fast-check-monorepo');15runCommands({16});17function commandsIterable<Ts>(params: {18 model: (initialState: Ts, commands: Iterable<Command<Ts>>) => Ts;19 pre: (initialState: Ts) => boolean;20 post: (finalState: Ts, commands: Iterable<Command<Ts>>) => boolean;21 init: () => Ts;22 arbitraries: ArbitraryMap<Ts>;23 maxCommands?: number;24 seed?: number;25}): Iterable<Command<Ts>>;26function commandsIterator<Ts>(params: {27 model: (initialState: Ts, commands: Iterable<Command<Ts>>) => Ts;28 pre: (initialState: Ts) => boolean;29 post: (finalState: Ts, commands: Iterable<Command<Ts>>) => boolean;30 init: () => Ts;31 arbitraries: ArbitraryMap<Ts>;32 maxCommands?: number;33 seed?: number;34}): Iterator<Command<Ts>>;35function runCommands<Ts>(params: {36 model: (initialState: Ts, commands: Iterable<Command<Ts>>) => Ts;37 pre: (initialState: Ts) => boolean;38 post: (finalState: Ts, commands: Iterable<Command<Ts>>) => boolean;39 init: () => Ts;40 arbitraries: ArbitraryMap<Ts>;41 maxCommands?: number;42 seed?: number;43}): void;
Using AI Code Generation
1const fc = require('fast-check');2const commandsIterable = require('fast-check-monorepo').commandsIterable;3const commands = commandsIterable(fc);4const fc = require('fast-check');5const commandsIterable = require('fast-check').commandsIterable;6const commands = commandsIterable(fc);7In this case, we can see that the code to use commandsIterable is the same in both test.js and test2.js. The only difference is the way we import fast-check. This is not a problem for test.js as it is in the same project as fast-check-monorepo. However, test2.js is not in the same project as fast-check. This means that, when running test2.js, the fast-check-monorepo node_modules directory will not be found. This is because when running test2.js, node will look for fast-check-monorepo in the node_modules directory of the project that test2.js is in. If it is not found, it will look in the node_modules directory of the project that test2.js is in, and so on. This is why the following error is produced when running test2.js:
Using AI Code Generation
1const { commandsIterable } = require('fast-check-monorepo');2const { command } = require('fast-check');3const { modelRun } = require('fast-check-monorepo');4const model = {5};6const inc = command(model => {7 model.counter += 1;8}, 'inc');9const dec = command(model => {10 model.counter -= 1;11}, 'dec');12const property = model => {13 return model.counter >= 0;14};15const commands = commandsIterable([inc, dec]);16modelRun(model, commands, property);17const { commandsIterable } = require('fast-check');18const { command } = require('fast-check');19const { modelRun } = require('fast-check');20const model = {21};22const inc = command(model => {23 model.counter += 1;24}, 'inc');25const dec = command(model => {26 model.counter -= 1;27}, 'dec');28const property = model => {29 return model.counter >= 0;30};31const commands = commandsIterable([inc, dec]);32modelRun(model, commands, property);33commandsIterable(commands: Command[], seed?: number | string): IterableIterator<Command>34import * as fc from 'fast-check';35import { command } from 'fast-check';36import { commandsIterable } from 'fast-check-monorepo';37const inc = command(model => {38 model.counter += 1;39}, 'inc');40const dec = command(model => {41 model.counter -= 1;42}, 'dec');43const commands = commandsIterable([inc, dec]);44fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (a, b, c) => {45 const model = { counter: a };46 inc.executeOn(model);47 dec.executeOn(model);48 inc.executeOn(model);49 dec.executeOn(model);50 inc.executeOn(model);51 dec.executeOn(model);52 return model.counter === a;53}));54modelRun<T>(model: T,
Using AI Code Generation
1const { commandsIterable } = require('fast-check-monorepo');2const { command } = require('fast-check');3const myCommand = command(4);5for (const cmd of commandsIterable(myCommand, { seed: 42 })) {6}7const { commandsIterable } = require('fast-check');8const { command } = require('fast-check');9const myCommand = command(10);11for (const cmd of commandsIterable(myCommand, { seed: 42 })) {12}13 at Object.<anonymous> (C:\Users\username\Desktop\fast-check-monorepo\test.js:5:28)
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!!