How to use chainedArbitrary method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

Arbitrary.ts

Source:Arbitrary.ts Github

copy

Full Screen

1import { Random } from '../../../random/generator/Random';2import { Stream } from '../../../stream/Stream';3import { cloneMethod, hasCloneMethod } from '../../symbols';4import { Value } from './Value';5const safeObjectAssign = Object.assign;6/**7 * Abstract class able to generate values on type `T`8 *9 * The values generated by an instance of Arbitrary can be previewed - with {@link sample} - or classified - with {@link statistics}.10 *11 * @remarks Since 0.0.712 * @public13 */14export abstract class Arbitrary<T> {15 /**16 * Generate a value of type `T` along with its context (if any)17 * based on the provided random number generator18 *19 * @param mrng - Random number generator20 * @param biasFactor - If taken into account 1 value over biasFactor must be biased. Either integer value greater or equal to 2 (bias) or undefined (no bias)21 * @returns Random value of type `T` and its context22 *23 * @remarks Since 0.0.1 (return type changed in 3.0.0)24 */25 abstract generate(mrng: Random, biasFactor: number | undefined): Value<T>;26 /**27 * Check if a given value could be pass to `shrink` without providing any context.28 *29 * In general, `canShrinkWithoutContext` is not designed to be called for each `shrink` but rather on very special cases.30 * Its usage must be restricted to `canShrinkWithoutContext` or in the rare* contexts of a `shrink` method being called without31 * any context. In this ill-formed case of `shrink`, `canShrinkWithoutContext` could be used or called if needed.32 *33 * *we fall in that case when fast-check is asked to shrink a value that has been provided manually by the user,34 * in other words: a value not coming from a call to `generate` or a normal `shrink` with context.35 *36 * @param value - Value to be assessed37 * @returns `true` if and only if the value could have been generated by this instance38 *39 * @remarks Since 3.0.040 */41 abstract canShrinkWithoutContext(value: unknown): value is T;42 /**43 * Shrink a value of type `T`, may rely on the context previously provided to shrink efficiently44 *45 * Must never be called with possibly invalid values and no context without ensuring that such call is legal46 * by calling `canShrinkWithoutContext` first on the value.47 *48 * @param value - The value to shrink49 * @param context - Its associated context (the one returned by generate) or `undefined` if no context but `canShrinkWithoutContext(value) === true`50 * @returns Stream of shrinks for value based on context (if provided)51 *52 * @remarks Since 3.0.053 */54 abstract shrink(value: T, context: unknown | undefined): Stream<Value<T>>;55 /**56 * Create another arbitrary by filtering values against `predicate`57 *58 * All the values produced by the resulting arbitrary59 * satisfy `predicate(value) == true`60 *61 * Be aware that using filter may highly impact the time required to generate a valid entry62 *63 * @example64 * ```typescript65 * const integerGenerator: Arbitrary<number> = ...;66 * const evenIntegerGenerator: Arbitrary<number> = integerGenerator.filter(e => e % 2 === 0);67 * // new Arbitrary only keeps even values68 * ```69 *70 * @param refinement - Predicate, to test each produced element. Return true to keep the element, false otherwise71 * @returns New arbitrary filtered using predicate72 *73 * @remarks Since 1.23.074 */75 filter<U extends T>(refinement: (t: T) => t is U): Arbitrary<U>;76 /**77 * Create another arbitrary by filtering values against `predicate`78 *79 * All the values produced by the resulting arbitrary80 * satisfy `predicate(value) == true`81 *82 * Be aware that using filter may highly impact the time required to generate a valid entry83 *84 * @example85 * ```typescript86 * const integerGenerator: Arbitrary<number> = ...;87 * const evenIntegerGenerator: Arbitrary<number> = integerGenerator.filter(e => e % 2 === 0);88 * // new Arbitrary only keeps even values89 * ```90 *91 * @param predicate - Predicate, to test each produced element. Return true to keep the element, false otherwise92 * @returns New arbitrary filtered using predicate93 *94 * @remarks Since 0.0.195 */96 filter(predicate: (t: T) => boolean): Arbitrary<T>;97 filter<U extends T>(refinement: (t: T) => t is U): Arbitrary<U> {98 // eslint-disable-next-line @typescript-eslint/no-use-before-define99 return new FilterArbitrary(this, refinement);100 }101 /**102 * Create another arbitrary by mapping all produced values using the provided `mapper`103 * Values produced by the new arbitrary are the result of applying `mapper` value by value104 *105 * @example106 * ```typescript107 * const rgbChannels: Arbitrary<{r:number,g:number,b:number}> = ...;108 * const color: Arbitrary<string> = rgbChannels.map(ch => `#${(ch.r*65536 + ch.g*256 + ch.b).toString(16).padStart(6, '0')}`);109 * // transform an Arbitrary producing {r,g,b} integers into an Arbitrary of '#rrggbb'110 * ```111 *112 * @param mapper - Map function, to produce a new element based on an old one113 * @param unmapper - Optional unmap function, it will never be used except when shrinking user defined values. Must throw if value is not compatible (since 3.0.0)114 * @returns New arbitrary with mapped elements115 *116 * @remarks Since 0.0.1117 */118 map<U>(mapper: (t: T) => U, unmapper?: (possiblyU: unknown) => T): Arbitrary<U> {119 // eslint-disable-next-line @typescript-eslint/no-use-before-define120 return new MapArbitrary(this, mapper, unmapper);121 }122 /**123 * Create another arbitrary by mapping a value from a base Arbirary using the provided `fmapper`124 * Values produced by the new arbitrary are the result of the arbitrary generated by applying `fmapper` to a value125 * @example126 * ```typescript127 * const arrayAndLimitArbitrary = fc.nat().chain((c: number) => fc.tuple( fc.array(fc.nat(c)), fc.constant(c)));128 * ```129 *130 * @param chainer - Chain function, to produce a new Arbitrary using a value from another Arbitrary131 * @returns New arbitrary of new type132 *133 * @remarks Since 1.2.0134 */135 chain<U>(chainer: (t: T) => Arbitrary<U>): Arbitrary<U> {136 // eslint-disable-next-line @typescript-eslint/no-use-before-define137 return new ChainArbitrary(this, chainer);138 }139 /**140 * Create another Arbitrary with no shrink values141 *142 * @example143 * ```typescript144 * const dataGenerator: Arbitrary<string> = ...;145 * const unshrinkableDataGenerator: Arbitrary<string> = dataGenerator.noShrink();146 * // same values no shrink147 * ```148 *149 * @returns Create another arbitrary with no shrink values150 * @remarks Since 0.0.9151 */152 noShrink(): Arbitrary<T> {153 // eslint-disable-next-line @typescript-eslint/no-use-before-define154 return new NoShrinkArbitrary(this);155 }156 /**157 * Create another Arbitrary that cannot be biased158 *159 * @param freq - The biased version will be used one time over freq - if it exists160 * @remarks Since 1.1.0161 */162 noBias(): Arbitrary<T> {163 // eslint-disable-next-line @typescript-eslint/no-use-before-define164 return new NoBiasArbitrary(this);165 }166}167/** @internal */168type ChainArbitraryContext<T, U> = {169 originalBias: number | undefined;170 originalValue: T;171 originalContext: unknown;172 stoppedForOriginal: boolean;173 chainedArbitrary: Arbitrary<U>;174 chainedContext: unknown;175 clonedMrng: Random;176};177/** @internal */178class ChainArbitrary<T, U> extends Arbitrary<U> {179 constructor(readonly arb: Arbitrary<T>, readonly chainer: (t: T) => Arbitrary<U>) {180 super();181 }182 generate(mrng: Random, biasFactor: number | undefined): Value<U> {183 const clonedMrng = mrng.clone();184 const src = this.arb.generate(mrng, biasFactor);185 return this.valueChainer(src, mrng, clonedMrng, biasFactor);186 }187 canShrinkWithoutContext(value: unknown): value is U {188 // TODO Need unchainer189 return false;190 }191 shrink(value: U, context?: unknown): Stream<Value<U>> {192 if (this.isSafeContext(context)) {193 return (194 !context.stoppedForOriginal195 ? this.arb196 .shrink(context.originalValue, context.originalContext)197 .map((v) => this.valueChainer(v, context.clonedMrng.clone(), context.clonedMrng, context.originalBias))198 : Stream.nil<Value<U>>()199 ).join(200 context.chainedArbitrary.shrink(value, context.chainedContext).map((dst) => {201 // TODO - Move back to object spreading as soon as we bump support from es2017 to es2018+202 const newContext: ChainArbitraryContext<T, U> = safeObjectAssign(safeObjectAssign({}, context), {203 chainedContext: dst.context,204 stoppedForOriginal: true,205 });206 return new Value(dst.value_, newContext);207 })208 );209 }210 // TODO Need unchainer211 return Stream.nil();212 }213 private valueChainer(214 v: Value<T>,215 generateMrng: Random,216 clonedMrng: Random,217 biasFactor: number | undefined218 ): Value<U> {219 const chainedArbitrary = this.chainer(v.value_);220 const dst = chainedArbitrary.generate(generateMrng, biasFactor);221 const context: ChainArbitraryContext<T, U> = {222 originalBias: biasFactor,223 originalValue: v.value_,224 originalContext: v.context,225 stoppedForOriginal: false,226 chainedArbitrary,227 chainedContext: dst.context,228 clonedMrng,229 };230 return new Value(dst.value_, context);231 }232 private isSafeContext(context: unknown): context is ChainArbitraryContext<T, U> {233 return (234 context != null &&235 typeof context === 'object' &&236 'originalBias' in (context as any) &&237 'originalValue' in (context as any) &&238 'originalContext' in (context as any) &&239 'stoppedForOriginal' in (context as any) &&240 'chainedArbitrary' in (context as any) &&241 'chainedContext' in (context as any) &&242 'clonedMrng' in (context as any)243 );244 }245}246/** @internal */247type MapArbitraryContext<T> = {248 originalValue: T;249 originalContext: unknown;250};251/** @internal */252class MapArbitrary<T, U> extends Arbitrary<U> {253 readonly bindValueMapper: (v: Value<T>) => Value<U>;254 constructor(readonly arb: Arbitrary<T>, readonly mapper: (t: T) => U, readonly unmapper?: (possiblyU: unknown) => T) {255 super();256 this.bindValueMapper = (v: Value<T>): Value<U> => this.valueMapper(v);257 }258 generate(mrng: Random, biasFactor: number | undefined): Value<U> {259 const g = this.arb.generate(mrng, biasFactor);260 return this.valueMapper(g);261 }262 canShrinkWithoutContext(value: unknown): value is U {263 if (this.unmapper !== undefined) {264 try {265 const unmapped = this.unmapper(value);266 return this.arb.canShrinkWithoutContext(unmapped);267 } catch (_err) {268 return false;269 }270 }271 return false;272 }273 shrink(value: U, context?: unknown): Stream<Value<U>> {274 if (this.isSafeContext(context)) {275 return this.arb.shrink(context.originalValue, context.originalContext).map(this.bindValueMapper);276 }277 if (this.unmapper !== undefined) {278 const unmapped = this.unmapper(value);279 // As `shrink` should never be called without a valid context280 // except if `canShrinkWithoutContext` tells that the value was compatible with a shrink without any context281 // we can safely consider `this.arb.canShrinkWithoutContext(unmapped)` to be true at that point.282 return this.arb.shrink(unmapped, undefined).map(this.bindValueMapper);283 }284 return Stream.nil();285 }286 private mapperWithCloneIfNeeded(v: Value<T>): [U, T] {287 const sourceValue = v.value;288 const mappedValue = this.mapper(sourceValue);289 if (290 v.hasToBeCloned &&291 ((typeof mappedValue === 'object' && mappedValue !== null) || typeof mappedValue === 'function') &&292 Object.isExtensible(mappedValue) &&293 !hasCloneMethod(mappedValue)294 ) {295 // WARNING: In case the mapped value is not extensible it will not be extended296 Object.defineProperty(mappedValue, cloneMethod, { get: () => () => this.mapperWithCloneIfNeeded(v)[0] });297 }298 return [mappedValue, sourceValue];299 }300 private valueMapper(v: Value<T>): Value<U> {301 const [mappedValue, sourceValue] = this.mapperWithCloneIfNeeded(v);302 const context: MapArbitraryContext<T> = { originalValue: sourceValue, originalContext: v.context };303 return new Value(mappedValue, context);304 }305 private isSafeContext(context: unknown): context is MapArbitraryContext<T> {306 return (307 context != null &&308 typeof context === 'object' &&309 'originalValue' in (context as any) &&310 'originalContext' in (context as any)311 );312 }313}314/** @internal */315class FilterArbitrary<T, U extends T> extends Arbitrary<U> {316 readonly bindRefinementOnValue: (v: Value<T>) => v is Value<U>;317 constructor(readonly arb: Arbitrary<T>, readonly refinement: (t: T) => t is U) {318 super();319 this.bindRefinementOnValue = (v: Value<T>): v is Value<U> => this.refinementOnValue(v);320 }321 generate(mrng: Random, biasFactor: number | undefined): Value<U> {322 // eslint-disable-next-line no-constant-condition323 while (true) {324 const g = this.arb.generate(mrng, biasFactor);325 if (this.refinementOnValue(g)) {326 return g;327 }328 }329 }330 canShrinkWithoutContext(value: unknown): value is U {331 return this.arb.canShrinkWithoutContext(value) && this.refinement(value);332 }333 shrink(value: U, context?: unknown): Stream<Value<U>> {334 return this.arb.shrink(value, context).filter(this.bindRefinementOnValue);335 }336 private refinementOnValue(v: Value<T>): v is Value<U> {337 return this.refinement(v.value);338 }339}340/** @internal */341class NoShrinkArbitrary<T> extends Arbitrary<T> {342 constructor(readonly arb: Arbitrary<T>) {343 super();344 }345 generate(mrng: Random, biasFactor: number | undefined): Value<T> {346 return this.arb.generate(mrng, biasFactor);347 }348 canShrinkWithoutContext(value: unknown): value is T {349 return this.arb.canShrinkWithoutContext(value);350 }351 shrink(_value: T, _context?: unknown): Stream<Value<T>> {352 return Stream.nil();353 }354 noShrink() {355 return this;356 }357}358/** @internal */359class NoBiasArbitrary<T> extends Arbitrary<T> {360 constructor(readonly arb: Arbitrary<T>) {361 super();362 }363 generate(mrng: Random, _biasFactor: number | undefined): Value<T> {364 return this.arb.generate(mrng, undefined);365 }366 canShrinkWithoutContext(value: unknown): value is T {367 return this.arb.canShrinkWithoutContext(value);368 }369 shrink(value: T, context?: unknown): Stream<Value<T>> {370 return this.arb.shrink(value, context);371 }372 noBias() {373 return this;374 }375}376/**377 * Ensure an instance is an instance of Arbitrary378 * @param instance - The instance to be checked379 * @internal380 */381export function isArbitrary(instance: unknown): instance is Arbitrary<unknown> {382 return (383 typeof instance === 'object' &&384 instance !== null &&385 'generate' in instance &&386 'shrink' in instance &&387 'canShrinkWithoutContext' in instance388 );389}390/**391 * Ensure an instance is an instance of Arbitrary392 * @param instance - The instance to be checked393 * @internal394 */395export function assertIsArbitrary(instance: unknown): asserts instance is Arbitrary<unknown> {396 if (!isArbitrary(instance)) {397 throw new Error('Unexpected value received: not an instance of Arbitrary');398 }...

Full Screen

Full Screen

ChainedArbitrary.ts

Source:ChainedArbitrary.ts Github

copy

Full Screen

1import {FluentPick} from './types'2import {Arbitrary} from './internal'3export class ChainedArbitrary<A, B> extends Arbitrary<B> {4 constructor(public readonly baseArbitrary: Arbitrary<A>, public readonly f: (a: A) => Arbitrary<B>) {5 super()6 }7 size() { return this.baseArbitrary.size() }8 pick(generator: () => number): FluentPick<B> | undefined {9 const pick = this.baseArbitrary.pick(generator)10 return pick === undefined ? undefined : this.f(pick.value).pick(generator)11 }12 cornerCases(): FluentPick<B>[] {13 return this.baseArbitrary.cornerCases().flatMap(p => this.f(p.value).cornerCases())14 }15 canGenerate<B>(_: FluentPick<B>): boolean {16 return true17 }18 toString(depth = 0) {19 return ' '.repeat(depth * 2) +20 `Chained Arbitrary: f = ${this.f.toString()}\n` + this.baseArbitrary.toString(depth + 1)21 }...

Full Screen

Full Screen

internal.ts

Source:internal.ts Github

copy

Full Screen

1export * from './Arbitrary'2export * from './NoArbitrary'3export * from './WrappedArbitrary'4export * from './ArbitraryArray'5export * from './ArbitrarySet'6export * from './FilteredArbitrary'7export * from './MappedArbitrary'8export * from './ChainedArbitrary'9export * from './ArbitraryConstant'10export * from './ArbitraryComposite'11export * from './ArbitraryTuple'12export * from './ArbitraryInteger'13export * from './ArbitraryBoolean'...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const {chainedArbitrary} = require('fast-check-monorepo');3const {chainedArbitrary: chainedArbitrary2} = require('fast-check-monorepo');4const a = fc.array(fc.integer(1, 100), 1, 10);5const b = fc.array(fc.integer(1, 100), 1, 10);6const c = fc.array(fc.integer(1, 100), 1, 10);7const result = chainedArbitrary([a, b, c], (x, y, z) => x.concat(y).concat(z));8const result2 = chainedArbitrary2([a, b, c], (x, y, z) => x.concat(y).concat(z));9fc.assert(10 fc.property(result, (x) => x.length >= 2 && x.length <= 30)11);12fc.assert(13 fc.property(result2, (x) => x.length >= 2 && x.length <= 30)14);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const {chain, string} = require('fast-check');3const arbitrary = chain(string(), (s) => {4 return fc.constant(s + 'abc');5});6arbitrary.generate(mrng).value;7const fc = require('fast-check');8const {chain, string} = require('fast-check');9const arbitrary = chain(string(), (s) => {10 return fc.constant(s + 'abc');11});12arbitrary.generate(mrng).value;13const fc = require('fast-check');14const {chain, string} = require('fast-check');15const arbitrary = chain(string(), (s) => {16 return fc.constant(s + 'abc');17});18arbitrary.generate(mrng).value;19const fc = require('fast-check');20const {chain, string} = require('fast-check');21const arbitrary = chain(string(), (s) => {22 return fc.constant(s + 'abc');23});24arbitrary.generate(mrng).value;25const fc = require('fast-check');26const {chain, string} = require('fast-check');27const arbitrary = chain(string(), (s) => {28 return fc.constant(s + 'abc');29});30arbitrary.generate(mrng).value;31const fc = require('fast-check');32const {chain, string} = require('fast-check');33const arbitrary = chain(string(), (s) => {34 return fc.constant(s + 'abc');35});36arbitrary.generate(mrng).value;

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const {chain, string} = require('fast-check');3const myString = string({ minLength: 3, maxLength: 5});4const myChain = chain(myString, (s) => {5 return string({ minLength: 3, maxLength: 5})6 .map((s2) => s + s2);7});8fc.assert(fc.property(myChain, (s) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { check, property } = require("fast-check");2const { arbitrary, oneof } = require("fast-check-monorepo");3const testFunction = (a, b) => a + b;4const aArbitrary = arbitrary().int32();5const bArbitrary = arbitrary().int32();6const aPlusBArbitrary = aArbitrary.chain(a =>7 bArbitrary.map(b => testFunction(a, b))8);9check(property(aPlusBArbitrary, aPlusB => aPlusB > 0), {10}).then(console.log);11const { check, property } = require("fast-check");12const { arbitrary, oneof } = require("fast-check-monorepo");13const testFunction = (a, b) => a + b;14const aArbitrary = arbitrary().int32();15const bArbitrary = arbitrary().int32();16const aPlusBArbitrary = aArbitrary.chain(a =>17 bArbitrary.map(b => testFunction(a, b))18);19check(property(aPlusBArbitrary, aPlusB => aPlusB > 0), {20}).then(console.log);21const { check, property } = require("fast-check");22const { arbitrary, oneof } = require("fast-check-monorepo");23const testFunction = (a, b) => a + b;24const aArbitrary = arbitrary().int32();25const bArbitrary = arbitrary().int32();26const aPlusBArbitrary = aArbitrary.chain(a =>27 bArbitrary.map(b => testFunction(a, b))28);29check(property(aPlusBArbitrary, aPlusB => aPlusB > 0), {

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { chain, frequency, constant } = fc;3const myGenerator = fc.frequency({4 arbitrary: fc.constant('a'),5}, {6 arbitrary: fc.constant('b'),7}, {8 arbitrary: fc.constant('c'),9});10const myChainedGenerator = chain(myGenerator, (value) => {11 switch (value) {12 return fc.constant('d');13 return fc.constant('e');14 return fc.constant('f');15 return fc.constant('g');16 }17});18fc.assert(19 fc.property(myChainedGenerator, (value) => value.length === 1)20);21I am using the latest version of fast-check (2.11.0) and fast-check-monorepo (0.0.1-alpha.1). I am using the following versions of node and npm:22"dependencies": {23 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { arbitrary, property, fc } = require("fast-check");2const { any } = arbitrary;3const { chain } = any;4const { chainedArbitrary } = chain;5const { array } = arbitrary;6const { tuple } = arbitrary;7const { integer } = arbitrary;8const { constantFrom } = arbitrary;9const { constant } = arbitrary;10const { string } = arbitrary;11const { record } = arbitra

Full Screen

Using AI Code Generation

copy

Full Screen

1it("should return the same result as the chained arbitrary method", () => {2 .chainedArbitrary(fc.nat(), n => fc.tuple(fc.nat(n), fc.nat(n)))3 .map(([a, b]) => a + b);4 fc.assert(5 fc.property(arb, n => {6 expect(n).toBeGreaterThanOrEqual(0);7 })8 );9});10it("should return the same result as the nat method", () => {11 const arb = fc.tuple(fc.nat(), fc.nat()).map(([a, b]) => a + b);12 fc.assert(13 fc.property(arb, n => {14 expect(n).toBeGreaterThanOrEqual(0);15 })16 );17});18it("should return the same result as the nat method", () => {19 const arb = fc.tuple(fc.nat(), fc.nat()).map(([a, b]) => a + b);20 fc.assert(21 fc.property(arb, n => {22 expect(n).toBeGreaterThanOrEqual(0);23 })24 );25});26it("should return the same result as the nat method", () => {27 const arb = fc.tuple(fc.nat(), fc.nat()).map(([a, b]) => a + b);28 fc.assert(29 fc.property(arb, n => {30 expect(n).toBeGreaterThanOrEqual(0);31 })32 );33});34it("should return the same result as the nat method", () => {35 const arb = fc.tuple(fc.nat(), fc.nat()).map(([a, b]) => a + b);36 fc.assert(37 fc.property(arb, n => {38 expect(n).toBeGreaterThanOrEqual(0);39 })40 );41});42it("should return the same result as the nat method", () => {43 const arb = fc.tuple(fc.nat(), fc.nat()).map(([a, b]) => a + b);

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