How to use restrictedIntegerArbitraryBuilder method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

sparseArray.spec.ts

Source:sparseArray.spec.ts Github

copy

Full Screen

1/* eslint-disable no-sparse-arrays */2import * as fc from 'fast-check';3import { sparseArray, SparseArrayConstraints } from '../../../src/arbitrary/sparseArray';4import { FakeIntegerArbitrary, fakeArbitrary, fakeArbitraryStaticValue } from './__test-helpers__/ArbitraryHelpers';5import * as RestrictedIntegerArbitraryBuilderMock from '../../../src/arbitrary/_internals/builders/RestrictedIntegerArbitraryBuilder';6import * as TupleMock from '../../../src/arbitrary/tuple';7import * as UniqueMock from '../../../src/arbitrary/uniqueArray';8import {9 assertProduceCorrectValues,10 assertProduceSameValueGivenSameSeed,11 assertProduceValuesShrinkableWithoutContext,12} from './__test-helpers__/ArbitraryAssertions';13import { Value } from '../../../src/check/arbitrary/definition/Value';14import { buildShrinkTree, renderTree } from './__test-helpers__/ShrinkTree';15import { MaxLengthUpperBound } from '../../../src/arbitrary/_internals/helpers/MaxLengthFromMinLength';16function beforeEachHook() {17 jest.resetModules();18 jest.restoreAllMocks();19}20beforeEach(beforeEachHook);21fc.configureGlobal({22 ...fc.readConfigureGlobal(),23 beforeEach: beforeEachHook,24});25describe('sparseArray', () => {26 it('should always specify a minLength and maxLength on the underlying set', () => {27 fc.assert(28 fc.property(fc.option(validSparseArrayConstraints(), { nil: undefined }), (ct) => {29 // Arrange30 fc.pre(!isLimitNoTrailingCase(ct));31 const tuple = jest.spyOn(TupleMock, 'tuple');32 const uniqueArray = jest.spyOn(UniqueMock, 'uniqueArray');33 const { instance: tupleInstance } = fakeArbitraryStaticValue(() => []);34 const { instance: uniqueInstance } = fakeArbitraryStaticValue(() => []);35 tuple.mockReturnValueOnce(tupleInstance);36 uniqueArray.mockReturnValueOnce(uniqueInstance);37 const { instance: arb } = fakeArbitrary();38 // Act39 sparseArray(arb, ct);40 // Assert41 expect(uniqueArray).toHaveBeenCalledTimes(1);42 expect(uniqueArray).toHaveBeenCalledWith(43 expect.anything(),44 expect.objectContaining({ minLength: expect.any(Number), maxLength: expect.any(Number) })45 );46 })47 );48 });49 it('should always pass a not too large maxLength or with a size to set given the length we expect at the end', () => {50 fc.assert(51 fc.property(fc.option(validSparseArrayConstraints(), { nil: undefined }), (ct) => {52 // Arrange53 fc.pre(!isLimitNoTrailingCase(ct));54 const tuple = jest.spyOn(TupleMock, 'tuple');55 const uniqueArray = jest.spyOn(UniqueMock, 'uniqueArray');56 const restrictedIntegerArbitraryBuilder = jest.spyOn(57 RestrictedIntegerArbitraryBuilderMock,58 'restrictedIntegerArbitraryBuilder'59 ); // called to build indexes60 const { instance: tupleInstance } = fakeArbitraryStaticValue(() => []);61 const { instance: uniqueArrayInstance } = fakeArbitraryStaticValue(() => []);62 tuple.mockReturnValueOnce(tupleInstance);63 uniqueArray.mockReturnValueOnce(uniqueArrayInstance);64 const { instance: arb } = fakeArbitrary();65 // Act66 sparseArray(arb, ct);67 // Assert68 expect(restrictedIntegerArbitraryBuilder).toHaveBeenCalled(); // at least once69 expect(uniqueArray).toHaveBeenCalledTimes(1);70 // First call is to configure items coming with data71 const maxGeneratedIndexes = restrictedIntegerArbitraryBuilder.mock.calls[0][1]; // ie maxGenerated72 const maxRequestedIndexes = restrictedIntegerArbitraryBuilder.mock.calls[0][2]; // ie max73 expect(maxGeneratedIndexes).toBeLessThanOrEqual(maxRequestedIndexes);74 const maxRequestedLength = uniqueArray.mock.calls[0][1].maxLength!;75 if (ct !== undefined && ct.noTrailingHole) {76 // maxRequestedIndexes is the maximal index we may have for the current instance (+1 is the length)77 // maxRequestedLength is the maximal number of elements we ask to the set78 const maxElementsToGenerateForArray = maxRequestedLength;79 const maxResultingArrayLength = maxRequestedIndexes + 1;80 expect(maxElementsToGenerateForArray).toBeLessThanOrEqual(maxResultingArrayLength);81 } else {82 // In the default case, for falsy noTrailingHole:83 // - nat will be called with the maximal length allowed for the requested array84 // - set with the maximal number of elements +185 const maxElementsToGenerateForArray = maxRequestedLength - 1;86 const maxResultingArrayLength = maxRequestedIndexes;87 expect(maxElementsToGenerateForArray).toBeLessThanOrEqual(maxResultingArrayLength);88 }89 // Second call is only to handle the length computation in case we allow trailing holes90 const resultedMinNumElements = ct !== undefined ? ct.minNumElements || 0 : 0;91 const resultedMaxLength = ct !== undefined && ct.maxLength !== undefined ? ct.maxLength : MaxLengthUpperBound;92 if (ct === undefined || (!ct.noTrailingHole && resultedMaxLength > resultedMinNumElements)) {93 expect(restrictedIntegerArbitraryBuilder).toHaveBeenCalledTimes(2);94 const [min, maxGenerated, max] = restrictedIntegerArbitraryBuilder.mock.calls[1];95 expect(min).toBe(resultedMinNumElements);96 expect(maxGenerated).toBe(maxGeneratedIndexes + 1);97 expect(max).toBe(maxRequestedIndexes + 1);98 }99 })100 );101 });102 it('should reject constraints having minNumElements > maxLength', () => {103 fc.assert(104 fc.property(105 validSparseArrayConstraints(['minNumElements', 'maxLength']),106 fc.nat({ max: 4294967295 }),107 fc.nat({ max: 4294967295 }),108 (draftCt, a, b) => {109 // Arrange110 fc.pre(a !== b);111 const ct = { ...draftCt, minNumElements: a > b ? a : b, maxLength: a > b ? b : a };112 const { instance: arb } = fakeArbitrary();113 // Act / Assert114 expect(() => sparseArray(arb, ct)).toThrowError(/non-hole/);115 }116 )117 );118 });119 it('should reject constraints having minNumElements > maxNumElements', () => {120 fc.assert(121 fc.property(122 validSparseArrayConstraints(['minNumElements', 'maxNumElements']),123 fc.nat({ max: 4294967295 }),124 fc.nat({ max: 4294967295 }),125 (draftCt, a, b) => {126 // Arrange127 fc.pre(a !== b);128 const ct = { ...draftCt, minNumElements: a > b ? a : b, maxNumElements: a > b ? b : a };129 const { instance: arb } = fakeArbitrary();130 // Act / Assert131 expect(() => sparseArray(arb, ct)).toThrowError(/non-hole/);132 }133 )134 );135 });136});137describe('sparseArray (integration)', () => {138 type Extra = SparseArrayConstraints | undefined;139 // Even if full of holes, they still are memory intensive we explicitely140 // limit num elements in order to avoid running our tests for too long141 const extraParameters: fc.Arbitrary<Extra> = fc.option(validSparseArrayConstraints([], 100), { nil: undefined });142 const isEqual = (v1: number[], v2: number[]): boolean => {143 // WARNING: Very long loops in Jest when comparing two very large sparse arrays144 expect(v1.length).toBe(v2.length);145 expect(Object.entries(v1)).toEqual(Object.entries(v2));146 return true;147 };148 const isCorrect = (v: number[], extra: Extra = {}) => {149 // Should be an array150 if (!Array.isArray(v)) return false;151 // Should not have a length greater than the requested one (if any)152 if (extra.maxLength !== undefined && v.length > extra.maxLength) return false;153 // Should contain at least the minimal number of requested items (if specified)154 if (extra.minNumElements !== undefined && Object.keys(v).length < extra.minNumElements) return false;155 // Should contain at most the maxiaml number of requested items (if specified)156 if (extra.maxNumElements !== undefined && Object.keys(v).length > extra.maxNumElements) return false;157 // Should only contain valid keys: numbers within 0 and length-1158 for (const k of Object.keys(v)) {159 const i = Number(k);160 if (Number.isNaN(i) || i < 0 || i >= v.length) return false;161 }162 // Should never end by a hole if user activated noTrailingHole163 if (extra.noTrailingHole && v.length > 0 && !(v.length - 1 in v)) return false;164 // If all the previous checks passed, then array should be ok165 return true;166 };167 const sparseArrayBuilder = (extra: Extra) => sparseArray(new FakeIntegerArbitrary(), extra);168 it('should produce the same values given the same seed', () => {169 assertProduceSameValueGivenSameSeed(sparseArrayBuilder, { extraParameters, isEqual });170 });171 it('should only produce correct values', () => {172 assertProduceCorrectValues(sparseArrayBuilder, isCorrect, { extraParameters });173 });174 it('should produce values seen as shrinkable without any context', () => {175 // Remark: It will not shrink towards the exact same values for various reasons,176 // - when noTrailingHole=false, there is no real way to buid back the targetLength177 // - the key-value pairs will most of the time not be in the same ordered as the build order,178 // thus it will lead to a different shrink order179 assertProduceValuesShrinkableWithoutContext(sparseArrayBuilder, { extraParameters });180 });181 it.each`182 source | constraints183 ${['1'] /* unsupported value */} | ${{}}184 ${[1, , , , ,] /* ending by a hole not allowed */} | ${{ noTrailingHole: true }}185 ${[, , , , , 3, , , , , , , , , , 6] /* not enough non-holey items */} | ${{ minNumElements: 3 }}186 ${[, , , , , 3, 4, , , 5, , , , , , 6] /* too many non-holey items */} | ${{ maxNumElements: 3 }}187 ${[, , , 4] /* too long (length is 4) */} | ${{ maxLength: 3 }}188 `('should not be able to generate $source with fc.sparseArray(..., $constraints)', ({ source, constraints }) => {189 // Arrange / Act190 const arb = sparseArray(new FakeIntegerArbitrary(), constraints);191 const out = arb.canShrinkWithoutContext(source);192 // Assert193 expect(out).toBe(false);194 });195 it.each`196 rawValue | constraints197 ${[1, , , , ,]} | ${{ noTrailingHole: false }}198 ${[, , , , , 3, , , , , , , , , , 6]} | ${{ minNumElements: 2 }}199 ${[, , , , , 3, 4, , , 5, , , , , , 6]} | ${{ maxNumElements: 4 }}200 ${[, , , 4]} | ${{ maxLength: 4 }}201 ${Object.assign(Array(200), { 1: 7 }) /* length longer than default maxGeneratedLength but ok for shrink */} | ${{}}202 ${[...Array(50)].map((_, i) => i) /* non-holey items higher than default maxGeneratedLength but ok for shrink */} | ${{}}203 `('should be able to shrink $rawValue with fc.sparseArray(..., $constraints)', ({ rawValue, constraints }) => {204 // Arrange205 const arb = sparseArray(new FakeIntegerArbitrary(), constraints);206 const value = new Value(rawValue, undefined);207 // Act208 const renderedTree = renderTree(buildShrinkTree(arb, value, { numItems: 100 })).join('\n');209 // Assert210 expect(arb.canShrinkWithoutContext(rawValue)).toBe(true);211 expect(renderedTree).toMatchSnapshot();212 });213});214// Helpers215function validSparseArrayConstraints(216 removedKeys: (keyof SparseArrayConstraints)[] = [],217 max: number | undefined = undefined218) {219 return fc220 .record(221 {222 maxLength: removedKeys.includes('maxLength') ? fc.constant(undefined) : fc.nat({ max }),223 minNumElements: removedKeys.includes('minNumElements')224 ? fc.constant(undefined)225 : fc.nat({ max: max !== undefined ? Math.min(5, max) : undefined }),226 maxNumElements: removedKeys.includes('maxNumElements') ? fc.constant(undefined) : fc.nat({ max }),227 noTrailingHole: removedKeys.includes('noTrailingHole') ? fc.constant(undefined) : fc.boolean(),228 },229 { requiredKeys: [] }230 )231 .map((ct) => {232 // We use map there in order not to filter on generated values233 if (ct.minNumElements !== undefined && ct.maxNumElements !== undefined && ct.minNumElements > ct.maxNumElements) {234 return { ...ct, minNumElements: ct.maxNumElements, maxNumElements: ct.minNumElements };235 }236 return ct;237 })238 .map((ct) => {239 // We use map there in order not to filter on generated values240 if (ct.minNumElements !== undefined && ct.maxLength !== undefined && ct.minNumElements > ct.maxLength) {241 return { ...ct, minNumElements: ct.maxLength, maxLength: ct.minNumElements };242 }243 return ct;244 });245}246function isLimitNoTrailingCase(ct?: SparseArrayConstraints): boolean {247 // In that precise case the only solution is a simple constant equal to []248 return ct !== undefined && !!ct.noTrailingHole && ct.maxLength === 0;...

Full Screen

Full Screen

CommandsArbitrary.ts

Source:CommandsArbitrary.ts Github

copy

Full Screen

...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);...

Full Screen

Full Screen

sparseArray.ts

Source:sparseArray.ts Github

copy

Full Screen

...114 const resultedSizeMaxNumElements = constraints.maxNumElements !== undefined || size !== undefined ? size : '=';115 const maxGeneratedIndexAuthorized = safeMathMax(maxGeneratedLength - 1, 0); // just preventing special case for maxGeneratedLength=0116 const maxIndexAuthorized = safeMathMax(maxLength - 1, 0); // just preventing special case for maxLength=0117 const sparseArrayNoTrailingHole = uniqueArray(118 tuple(restrictedIntegerArbitraryBuilder(0, maxGeneratedIndexAuthorized, maxIndexAuthorized), arb),119 {120 size: resultedSizeMaxNumElements,121 minLength: minNumElements,122 maxLength: resultedMaxNumElements,123 selector: (item) => item[0],124 depthIdentifier,125 }126 ).map(127 (items) => {128 // When maxLength=0 (implies resultedMaxNumElements=0) we will have items=[] leading to lastIndex=-1129 // resulting in an empty array130 const lastIndex = extractMaxIndex(items);131 return arrayFromItems(lastIndex + 1, items);132 },133 (value: unknown): [number, T][] => {134 if (!safeArrayIsArray(value)) {135 throw new Error('Not supported entry type');136 }137 if (noTrailingHole && value.length !== 0 && !(value.length - 1 in value)) {138 throw new Error('No trailing hole');139 }140 return safeMap(safeObjectEntries(value as T[]), (entry): [number, T] => [Number(entry[0]), entry[1]]);141 }142 );143 if (noTrailingHole || maxLength === minNumElements) {144 return sparseArrayNoTrailingHole;145 }146 return tuple(147 sparseArrayNoTrailingHole,148 restrictedIntegerArbitraryBuilder(minNumElements, maxGeneratedLength, maxLength)149 ).map(150 (data) => {151 const sparse = data[0];152 const targetLength = data[1];153 if (sparse.length >= targetLength) {154 return sparse;155 }156 const longerSparse = safeSlice(sparse);157 longerSparse.length = targetLength;158 return longerSparse;159 },160 (value: unknown): [T[], number] => {161 if (!safeArrayIsArray(value)) {162 throw new Error('Not supported entry type');...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { restrictedIntegerArbitraryBuilder } = require('fast-check');2const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder();3const { property } = require('fast-check');4property(restrictedIntegerArbitrary, (value) => {5 return value >= 0 && value <= 100;6});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { restrictedIntegerArbitraryBuilder } from 'fast-check-monorepo';2const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(1, 100);3restrictedIntegerArbitrary.sample();4import { restrictedIntegerArbitraryBuilder } from 'fast-check';5const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(1, 100);6restrictedIntegerArbitrary.sample();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {2} = require("@microsoft/fast-check-monorepo");3const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({4});5const {6} = require("@microsoft/fast-check-monorepo");7const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({8});9const {10} = require("@microsoft/fast-check-monorepo");11const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({12});13const {14} = require("@microsoft/fast-check-monorepo");15const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({16});17const {18} = require("@microsoft/fast-check-monorepo");19const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { restrictedIntegerArbitraryBuilder } = require("fast-check-monorepo");3const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({4});5fc.assert(6 fc.property(restrictedIntegerArbitrary, (value) => {7 return value >= 1 && value <= 10;8 })9);10const fc = require("fast-check");11const { restrictedIntegerArbitraryBuilder } = require("fast-check-monorepo");12const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({13});14fc.assert(15 fc.property(restrictedIntegerArbitrary, (value) => {16 return value >= 1 && value <= 10;17 })18);19const fc = require("fast-check");20const { restrictedIntegerArbitraryBuilder } = require("fast-check-monorepo");21const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({22});23fc.assert(24 fc.property(restrictedIntegerArbitrary, (value) => {25 return value >= 1 && value <= 10;26 })27);28const fc = require("fast-check");29const { restrictedIntegerArbitraryBuilder } = require("fast-check-monorepo");30const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({31});32fc.assert(33 fc.property(restrictedIntegerArbitrary, (value) => {34 return value >= 1 && value <= 10;35 })36);37const fc = require("fast-check");38const { restrictedIntegerArbitraryBuilder } = require("

Full Screen

Using AI Code Generation

copy

Full Screen

1const { restrictedIntegerArbitraryBuilder } = require('fast-check-monorepo');2const { random } = require('fast-check');3const { integer } = require('fast-check');4const { oneof } = require('fast-check');5const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder({6});7const arb = oneof(restrictedIntegerArbitrary, integer());8console.log(random(arb));

Full Screen

Using AI Code Generation

copy

Full Screen

1const { restrictedIntegerArbitraryBuilder } = require('@fast-check/arbitrary-builder');2const fc = require('fast-check');3const { mock, instance, when, anything, deepEqual } = require('ts-mockito');4const { expect } = require('chai');5const { createMock } = require('ts-auto-mock');6const { Test3 } = require('../src/Test3');7describe('Test3', () => {8 it('should return 1', () => {9 const test3 = new Test3();10 const result = test3.testMethod();11 expect(result).to.equal(1);12 });13 it('should return 2', () => {14 const test3 = new Test3();15 const result = test3.testMethod2();16 expect(result).to.equal(2);17 });18 it('should return 3', () => {19 const test3 = new Test3();20 const result = test3.testMethod3();21 expect(result).to.equal(3);22 });23 it('should return 4', () => {24 const test3 = new Test3();25 const result = test3.testMethod4();26 expect(result).to.equal(4);27 });28 it('should return 5', () => {29 const test3 = new Test3();30 const result = test3.testMethod5();31 expect(result).to.equal(5);32 });33 it('should return 6', () => {34 const test3 = new Test3();35 const result = test3.testMethod6();36 expect(result).to.equal(6);37 });38 it('should return 7', () => {39 const test3 = new Test3();40 const result = test3.testMethod7();41 expect(result).to.equal(7);42 });43 it('should return 8', () => {44 const test3 = new Test3();45 const result = test3.testMethod8();46 expect(result).to.equal(8);47 });48 it('should return 9', () => {49 const test3 = new Test3();50 const result = test3.testMethod9();51 expect(result).to.equal(9);52 });53 it('should return 10', () => {54 const test3 = new Test3();55 const result = test3.testMethod10();56 expect(result).to.equal(10);57 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { restrictedIntegerArbitraryBuilder } = require('fast-check');2const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(0, 10);3const result = restrictedIntegerArbitrary.sampleOne();4console.log(result);5const { restrictedIntegerArbitraryBuilder } = require('fast-check');6const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(0, 10);7const result = restrictedIntegerArbitrary.sampleOne();8console.log(result);9const { restrictedIntegerArbitraryBuilder } = require('fast-check');10const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(0, 10);11const result = restrictedIntegerArbitrary.sampleOne();12console.log(result);13const { restrictedIntegerArbitraryBuilder } = require('fast-check');14const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(0, 10);15const result = restrictedIntegerArbitrary.sampleOne();16console.log(result);17const { restrictedIntegerArbitraryBuilder } = require('fast-check');18const restrictedIntegerArbitrary = restrictedIntegerArbitraryBuilder(0, 10);19const result = restrictedIntegerArbitrary.sampleOne();20console.log(result);

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