How to use biasMeta method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

ArrayArbitrary.ts

Source:ArrayArbitrary.ts Github

copy

Full Screen

1import { Random } from '../../random/generator/Random';2import { Stream } from '../../stream/Stream';3import { cloneIfNeeded, cloneMethod } from '../../check/symbols';4import { integer } from '../integer';5import { makeLazy } from '../../stream/LazyIterableIterator';6import { Arbitrary } from '../../check/arbitrary/definition/Arbitrary';7import { Value } from '../../check/arbitrary/definition/Value';8import { CustomSetBuilder } from './interfaces/CustomSet';9import { DepthContext, DepthIdentifier, getDepthContextFor } from './helpers/DepthContext';10import { buildSlicedGenerator } from './helpers/BuildSlicedGenerator';11import { safeMap, safePush, safeSlice } from '../../utils/globals';12const safeMathFloor = Math.floor;13const safeMathLog = Math.log;14const safeMathMax = Math.max;15const safeArrayIsArray = Array.isArray;16/** @internal */17type ArrayArbitraryContext = {18 shrunkOnce: boolean;19 lengthContext: unknown;20 itemsContexts: unknown[];21 startIndex: number;22};23/** @internal */24function biasedMaxLength(minLength: number, maxLength: number): number {25 if (minLength === maxLength) {26 return minLength;27 }28 return minLength + safeMathFloor(safeMathLog(maxLength - minLength) / safeMathLog(2));29}30/** @internal */31export class ArrayArbitrary<T> extends Arbitrary<T[]> {32 readonly lengthArb: Arbitrary<number>;33 readonly depthContext: DepthContext;34 constructor(35 readonly arb: Arbitrary<T>,36 readonly minLength: number,37 readonly maxGeneratedLength: number,38 readonly maxLength: number,39 depthIdentifier: DepthIdentifier | string | undefined,40 // Whenever passing a isEqual to ArrayArbitrary, you also have to filter41 // it's output just in case produced values are too small (below minLength)42 readonly setBuilder: CustomSetBuilder<Value<T>> | undefined,43 readonly customSlices: T[][]44 ) {45 super();46 this.lengthArb = integer({ min: minLength, max: maxGeneratedLength });47 this.depthContext = getDepthContextFor(depthIdentifier);48 }49 private preFilter(tab: Value<T>[]): Value<T>[] {50 if (this.setBuilder === undefined) {51 return tab;52 }53 const s = this.setBuilder();54 for (let index = 0; index !== tab.length; ++index) {55 s.tryAdd(tab[index]);56 }57 return s.getData();58 }59 private static makeItCloneable<T>(vs: T[], shrinkables: Value<T>[]) {60 (vs as any)[cloneMethod] = () => {61 const cloned: T[] = [];62 for (let idx = 0; idx !== shrinkables.length; ++idx) {63 safePush(cloned, shrinkables[idx].value); // push potentially cloned values64 }65 this.makeItCloneable(cloned, shrinkables);66 return cloned;67 };68 return vs;69 }70 private generateNItemsNoDuplicates(71 setBuilder: CustomSetBuilder<Value<T>>,72 N: number,73 mrng: Random,74 biasFactorItems: number | undefined75 ): Value<T>[] {76 let numSkippedInRow = 0;77 const s = setBuilder();78 const slicedGenerator = buildSlicedGenerator(this.arb, mrng, this.customSlices, biasFactorItems);79 // Try to append into items up to the target size80 // We may reject some items as they are already part of the set81 // so we need to retry and generate other ones. In order to prevent infinite loop,82 // we accept a max of maxGeneratedLength consecutive failures. This circuit breaker may cause83 // generated to be smaller than the minimal accepted one.84 while (s.size() < N && numSkippedInRow < this.maxGeneratedLength) {85 const current = slicedGenerator.next();86 if (s.tryAdd(current)) {87 numSkippedInRow = 0;88 } else {89 numSkippedInRow += 1;90 }91 }92 return s.getData();93 }94 private safeGenerateNItemsNoDuplicates(95 setBuilder: CustomSetBuilder<Value<T>>,96 N: number,97 mrng: Random,98 biasFactorItems: number | undefined99 ): Value<T>[] {100 const depthImpact = safeMathMax(0, N - biasedMaxLength(this.minLength, this.maxGeneratedLength)); // no depth impact for biased lengths101 this.depthContext.depth += depthImpact; // increase depth102 try {103 return this.generateNItemsNoDuplicates(setBuilder, N, mrng, biasFactorItems);104 } finally {105 this.depthContext.depth -= depthImpact; // decrease depth (reset depth)106 }107 }108 private generateNItems(N: number, mrng: Random, biasFactorItems: number | undefined): Value<T>[] {109 const items: Value<T>[] = [];110 const slicedGenerator = buildSlicedGenerator(this.arb, mrng, this.customSlices, biasFactorItems);111 slicedGenerator.attemptExact(N);112 for (let index = 0; index !== N; ++index) {113 const current = slicedGenerator.next();114 safePush(items, current);115 }116 return items;117 }118 private safeGenerateNItems(N: number, mrng: Random, biasFactorItems: number | undefined): Value<T>[] {119 const depthImpact = safeMathMax(0, N - biasedMaxLength(this.minLength, this.maxGeneratedLength)); // no depth impact for biased lengths120 this.depthContext.depth += depthImpact; // increase depth121 try {122 return this.generateNItems(N, mrng, biasFactorItems);123 } finally {124 this.depthContext.depth -= depthImpact; // decrease depth (reset depth)125 }126 }127 private wrapper(128 itemsRaw: Value<T>[],129 shrunkOnce: boolean,130 itemsRawLengthContext: unknown,131 startIndex: number132 ): Value<T[]> {133 // We need to explicitly apply filtering on shrink items134 // has they might have duplicates (on non shrunk it is not the case by construct)135 const items = shrunkOnce ? this.preFilter(itemsRaw) : itemsRaw;136 let cloneable = false;137 const vs: T[] = [];138 const itemsContexts: unknown[] = [];139 for (let idx = 0; idx !== items.length; ++idx) {140 const s = items[idx];141 cloneable = cloneable || s.hasToBeCloned;142 safePush(vs, s.value);143 safePush(itemsContexts, s.context);144 }145 if (cloneable) {146 ArrayArbitrary.makeItCloneable(vs, items);147 }148 const context: ArrayArbitraryContext = {149 shrunkOnce,150 lengthContext:151 itemsRaw.length === items.length && itemsRawLengthContext !== undefined152 ? itemsRawLengthContext // items and itemsRaw have the same length context is applicable153 : undefined,154 itemsContexts,155 startIndex,156 };157 return new Value(vs, context);158 }159 generate(mrng: Random, biasFactor: number | undefined): Value<T[]> {160 const biasMeta = this.applyBias(mrng, biasFactor);161 const targetSize = biasMeta.size;162 const items =163 this.setBuilder !== undefined164 ? this.safeGenerateNItemsNoDuplicates(this.setBuilder, targetSize, mrng, biasMeta.biasFactorItems)165 : this.safeGenerateNItems(targetSize, mrng, biasMeta.biasFactorItems);166 return this.wrapper(items, false, undefined, 0);167 }168 private applyBias(mrng: Random, biasFactor: number | undefined): { size: number; biasFactorItems?: number } {169 if (biasFactor === undefined) {170 // We don't bias anything171 return { size: this.lengthArb.generate(mrng, undefined).value };172 }173 // We directly forward bias to items whenever no bias applicable onto length174 if (this.minLength === this.maxGeneratedLength) {175 // We only apply bias on items176 return { size: this.lengthArb.generate(mrng, undefined).value, biasFactorItems: biasFactor };177 }178 if (mrng.nextInt(1, biasFactor) !== 1) {179 // We don't bias anything180 return { size: this.lengthArb.generate(mrng, undefined).value };181 }182 // We apply bias (1 chance over biasFactor)183 if (mrng.nextInt(1, biasFactor) !== 1 || this.minLength === this.maxGeneratedLength) {184 // We only apply bias on items ((biasFactor-1) chances over biasFactor²)185 return { size: this.lengthArb.generate(mrng, undefined).value, biasFactorItems: biasFactor };186 }187 // We apply bias for both items and length (1 chance over biasFactor²)188 const maxBiasedLength = biasedMaxLength(this.minLength, this.maxGeneratedLength);189 const targetSizeValue = integer({ min: this.minLength, max: maxBiasedLength }).generate(mrng, undefined);190 return { size: targetSizeValue.value, biasFactorItems: biasFactor };191 }192 canShrinkWithoutContext(value: unknown): value is T[] {193 if (!safeArrayIsArray(value) || this.minLength > value.length || value.length > this.maxLength) {194 return false;195 }196 for (let index = 0; index !== value.length; ++index) {197 if (!(index in value)) {198 // sparse array cannot be produced by this instance199 return false;200 }201 if (!this.arb.canShrinkWithoutContext(value[index])) {202 // item at index cannot be produced by our arbitrary203 return false;204 }205 }206 // `preFilter` only drops items, it does not reorder them or add some more207 // if calling it with `value` results into a smaller array it means that the value was not generated by this instance208 const filtered = this.preFilter(safeMap(value, (item) => new Value(item, undefined)));209 return filtered.length === value.length;210 }211 private shrinkItemByItem(212 value: T[],213 safeContext: ArrayArbitraryContext,214 endIndex: number215 ): IterableIterator<[Value<T>[], unknown, number]> {216 let shrinks = Stream.nil<[Value<T>[], unknown, number]>();217 for (let index = safeContext.startIndex; index < endIndex; ++index) {218 shrinks = shrinks.join(219 makeLazy(() =>220 this.arb.shrink(value[index], safeContext.itemsContexts[index]).map((v): [Value<T>[], unknown, number] => {221 const beforeCurrent = safeMap(222 safeSlice(value, 0, index),223 (v, i) => new Value(cloneIfNeeded(v), safeContext.itemsContexts[i])224 );225 const afterCurrent = safeMap(226 safeSlice(value, index + 1),227 (v, i) => new Value(cloneIfNeeded(v), safeContext.itemsContexts[i + index + 1])228 );229 return [230 [...beforeCurrent, v, ...afterCurrent],231 undefined, // no length context232 index, // avoid shrinking entries before index in sub-shrinks233 ];234 })235 )236 );237 }238 return shrinks;239 }240 private shrinkImpl(value: T[], context?: unknown): Stream<[Value<T>[], unknown, number]> {241 if (value.length === 0) {242 return Stream.nil();243 }244 const safeContext: ArrayArbitraryContext =245 context !== undefined246 ? (context as ArrayArbitraryContext)247 : { shrunkOnce: false, lengthContext: undefined, itemsContexts: [], startIndex: 0 };248 return (249 this.lengthArb250 .shrink(251 value.length,252 // lengthContext is a context returned by a previous call to the integer253 // arbitrary and the integer value items.length.254 safeContext.lengthContext255 )256 // in case we already shrunk once but don't have any dedicated context to help the shrinker, we drop the first item257 // except if reached we have the minimal size +1, in that case we apply a last chance try policy258 .drop(259 safeContext.shrunkOnce && safeContext.lengthContext === undefined && value.length > this.minLength + 1 ? 1 : 0260 )261 .map((lengthValue): [Value<T>[], unknown, number] => {262 const sliceStart = value.length - lengthValue.value;263 return [264 safeMap(265 safeSlice(value, sliceStart),266 (v, index) => new Value(cloneIfNeeded(v), safeContext.itemsContexts[index + sliceStart])267 ), // array of length lengthValue.value268 lengthValue.context, // integer context for value lengthValue.value (the length)269 0,270 ];271 })272 // Length context value will be set to undefined for remaining shrinking values273 // as they are outside of our shrinking process focused on items.length.274 // None of our computed contexts will apply for them.275 .join(276 makeLazy(() =>277 value.length > this.minLength278 ? this.shrinkItemByItem(value, safeContext, 1)279 : this.shrinkItemByItem(value, safeContext, value.length)280 )281 )282 .join(283 value.length > this.minLength284 ? makeLazy(() => {285 // We pass itemsLengthContext=undefined to next shrinker to start shrinking286 // without any assumptions on the current state (we never explored that one)287 const subContext: ArrayArbitraryContext = {288 shrunkOnce: false,289 lengthContext: undefined,290 itemsContexts: safeSlice(safeContext.itemsContexts, 1),291 startIndex: 0,292 };293 return this.shrinkImpl(safeSlice(value, 1), subContext)294 .filter((v) => this.minLength <= v[0].length + 1)295 .map((v): [Value<T>[], unknown, number] => {296 return [[new Value(cloneIfNeeded(value[0]), safeContext.itemsContexts[0]), ...v[0]], undefined, 0];297 });298 })299 : Stream.nil()300 )301 );302 }303 shrink(value: T[], context?: unknown): Stream<Value<T[]>> {304 return this.shrinkImpl(value, context).map((contextualValue) =>305 this.wrapper(contextualValue[0], true, contextualValue[1], contextualValue[2])306 );307 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const biasMeta = require("fast-check").biasMeta;2const biasMeta = require("fast-check").biasMeta;3const biasMeta = require("fast-check").biasMeta;4const biasMeta = require("fast-check").biasMeta;5const biasMeta = require("fast-check").biasMeta;6const biasMeta = require("fast-check").biasMeta;7const biasMeta = require("fast-check").biasMeta;8const biasMeta = require("fast-check").biasMeta;9const biasMeta = require("fast-check").biasMeta;10const biasMeta = require("fast-check").biasMeta;11const biasMeta = require("fast-check").biasMeta;12const biasMeta = require("fast-check").biasMeta;13const biasMeta = require("fast-check").biasMeta;14const biasMeta = require("fast-check").biasMeta;15const biasMeta = require("fast-check").biasMeta;

Full Screen

Using AI Code Generation

copy

Full Screen

1const biasMeta = require('fast-check/lib/check/arbitrary/BiasArbitraryWrapper').biasMeta;2const biasMetaResult = biasMeta(1, 2, 3, 4, 5, 6);3console.log(biasMetaResult);4const biasMetaResult = biasMeta(1, 2, 3, 4, 5, 6);5expect(biasMetaResult).toHaveLength(6);6TypeError: expect(...).toHaveLength is not a function7I am using Jest for my testing. I have tried to import the toHaveLength method but I get the following error:8TypeError: expect(...).toHaveLength is not a function9I have tried the following code to import the toHaveLength method:10const toHaveLength = require('jest').toHaveLength;11I have also tried the following code to import the toHaveLength method:12const toHaveLength = require('jest').toHaveLength;13I have also tried the following code to import the toHaveLength method:14const toHaveLength = require('jest').expect.toHaveLength;15I have also tried the following code to import the toHaveLength method:16const toHaveLength = require('jest').expect().toHaveLength;17I have also tried the following code to import the toHaveLength method:18const toHaveLength = require('jest').expect().toHaveLength;19I have also tried the following code to import the toHaveLength method:20const toHaveLength = require('jest').expect().expect.toHaveLength;21I have also tried the following code to import the toHaveLength method:22const toHaveLength = require('jest').expect().expect().toHaveLength;23I have also tried the following code to import the toHaveLength method:24const toHaveLength = require('jest').expect().expect().expect.toHaveLength;25I have also tried the following code to import the toHaveLength method:26const toHaveLength = require('jest').expect().expect().expect().toHaveLength;27I have also tried the following code to import the toHaveLength method:28const toHaveLength = require('jest').expect().expect().expect().expect.toHaveLength;29I have also tried the following code to import the

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { biasMeta } = require("fast-check-monorepo");3const { biasMeta } = require("fast-check-monorepo");4const arb = fc.array(fc.integer(), 1, 10);5const biasedArb = biasMeta(arb, { bias: 0.5 });6fc.assert(7 fc.property(biasedArb, (arr) => {8 return arr.length <= 5;9 })10);11const fc = require("fast-check");12const { biasMeta } = require("fast-check-monorepo");13const arb = fc.array(fc.integer(), 1, 10);14const biasedArb = biasMeta(arb, { bias: 1.5 });15fc.assert(16 fc.property(biasedArb, (arr) => {17 return arr.length >= 15;18 })19);20const fc = require("fast-check");21const { biasMeta } = require("fast-check-monorepo");22const arb = fc.array(fc.integer(), 1, 10);23const biasedArb = biasMeta(arb, { bias: 1.5 });24fc.assert(25 fc.property(biasedArb, (arr) => {26 return arr.length >= 15;27 })28);29const fc = require("fast-check");30const { biasMeta } = require("fast-check-monorepo");31const arb = fc.array(fc.integer(), 1, 10);32const biasedArb = biasMeta(arb, { bias: 1.5 });33fc.assert(34 fc.property(biasedArb, (arr) => {35 return arr.length >= 15;36 })37);38const fc = require("fast-check");39const { biasMeta } = require("fast-check-monore

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const biasMeta = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js")3 .biasMeta;4const { biasWrapper } = biasMeta;5const { bias } = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js");6const { biasWrapper } = biasMeta;7const arb = fc.integer();8const biasedArb = biasWrapper(arb, 0.2);9const biasedArb2 = biasWrapper(arb, 0.2);10console.log(biasedArb);11console.log(biasedArb2);12const fc = require("fast-check");13const biasMeta = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js")14 .biasMeta;15const { biasWrapper } = biasMeta;16const { bias } = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js");17const { biasWrapper } = biasMeta;18const arb = fc.integer();19const biasedArb = biasWrapper(arb, 0.2);20console.log(biasedArb);21const fc = require("fast-check");22const biasMeta = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js")23 .biasMeta;24const { biasWrapper } = biasMeta;25const { bias } = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js");26const { biasWrapper } = biasMeta;27const arb = fc.integer();28const biasedArb = biasWrapper(arb, 0.2);29console.log(biasedArb);30const fc = require("fast-check");31const biasMeta = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js")32 .biasMeta;33const { biasWrapper } = biasMeta;34const { bias } = require("fast-check/lib/arbitrary/_internals/BiasArbitraryWrapper.js");35const { biasWrapper } = biasMeta;36const arb = fc.integer();37const biasedArb = biasWrapper(arb, 0.2);38console.log(biasedAr

Full Screen

Using AI Code Generation

copy

Full Screen

1const { biasMeta } = require('fast-check');2const { bias } = require('@fast-check/arbitrary/Bias');3const { integer } = require('@fast-check/arbitrary/IntegerArbitrary');4const { tuple } = require('@fast-check/arbitrary/TupleArbitrary');5const { oneof } = require('@fast-check/arbitrary/OneOfArbitrary');6const { frequency } = require('@fast-check/arbitrary/FrequencyArbitrary');7const { record } = require('@fast-check/arbitrary/RecordArbitrary');8const intArb = integer(0, 100);9const tupleArb = tuple(intArb, intArb);10const oneofArb = oneof(tupleArb, intArb);11const frequencyArb = frequency({ arbitrary: tupleArb, weight: 1 }, { arbitrary: intArb, weight: 1 });12const recordArb = record({ key: intArb, values: intArb });13const biasFn = (meta, depth) => {14 if (depth > 0) {15 return bias(meta, depth);16 }17 return meta;18};19const biasedIntArb = biasMeta(intArb, biasFn);20const biasedTupleArb = biasMeta(tupleArb, biasFn);21const biasedOneofArb = biasMeta(oneofArb, biasFn);22const biasedFrequencyArb = biasMeta(frequencyArb, biasFn);23const biasedRecordArb = biasMeta(recordArb, biasFn);24console.log('intArb bias: ' + biasedIntArb.canGenerateSameValueGivenSameSeed());25console.log('tupleArb bias: ' + biasedTupleArb.canGenerateSameValueGivenSameSeed());26console.log('oneofArb bias: ' + biasedOneofArb.canGenerateSameValueGivenSameSeed());27console.log('frequencyArb bias: ' + biasedFrequencyArb.canGenerateSameValueGivenSameSeed());28console.log('recordArb bias: ' + biasedRecordArb.canGenerateSameValueGivenSameSeed());

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { biasMeta } = require('fast-check-monorepo');3 .array(fc.integer(), 5)4 .filter(arr => arr.length === 5)5 .map(arr => arr.sort((a, b) => a - b));6const myBias = meta => {7 if (meta.depth > 5) return 1;8 return 0;9};10const myArbWithBias = biasMeta(myArb, myBias);11fc.assert(fc.property(myArbWithBias, arr => {12 return arr.length === 5;13}));14const fc = require('fast-check');15const { biasMeta } = require('fast-check-monorepo');16 .array(fc.integer(), 5)17 .filter(arr => arr.length === 5)18 .map(arr => arr.sort((a, b) => a - b));19const myBias = meta => {20 if (meta.depth > 5) return 1;21 return 0;22};23const myArbWithBias = biasMeta(myArb, myBias);24fc.assert(fc.property(myArbWithBias, arr => {25 return arr.length === 5;26}));27const fc = require('fast-check');28const { biasMeta } = require('fast-check-monorepo');29 .array(fc.integer(), 5)30 .filter(arr => arr.length === 5)31 .map(arr => arr.sort((a, b) => a - b));32const myBias = meta => {33 if (meta.depth > 5) return 1;34 return 0;35};36const myArbWithBias = biasMeta(myArb, myBias);37fc.assert(fc.property(myArbWithBias, arr => {38 return arr.length === 5;39}));40const fc = require('fast-check');41const { biasMeta } = require('fast-check-monorepo');42 .array(fc.integer(), 5)43 .filter(arr => arr.length

Full Screen

Using AI Code Generation

copy

Full Screen

1const { biasMeta } = require('fast-check');2const meta = biasMeta({3});4const myGenerator = meta(nat());5fc.assert(6 fc.property(myGenerator, (n) => {7 })8);

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