fast-check
Version:
Property based testing framework for JavaScript (like QuickCheck)
1,528 lines (1,527 loc) • 157 kB
TypeScript
import { RandomGenerator as RandomGenerator$1 } from "pure-rand/types/RandomGenerator";
import { JumpableRandomGenerator } from "pure-rand/types/JumpableRandomGenerator";
//#region src/check/precondition/Pre.d.ts
/**
* Add pre-condition checks inside a property execution
* @param expectTruthy - cancel the run whenever this value is falsy
* @remarks Since 1.3.0
* @public
*/
declare function pre(expectTruthy: boolean): asserts expectTruthy;
//#endregion
//#region src/random/generator/RandomGenerator.d.ts
interface RandomGenerator7x {
clone(): RandomGenerator7x;
next(): [number, RandomGenerator7x];
jump?(): RandomGenerator7x;
unsafeNext(): number;
unsafeJump?(): void;
getState(): readonly number[];
}
/**
* Merged type supporting both pure-rand v7 and v8 random generators.
* Keeping compatibility with v7 avoids a breaking API change and a new major version.
* @remarks Since 4.6.0
* @public
*/
type RandomGenerator = RandomGenerator7x | RandomGenerator$1 | JumpableRandomGenerator;
//#endregion
//#region src/random/generator/Random.d.ts
/**
* Wrapper around an instance of a `pure-rand`'s random number generator
* offering a simpler interface to deal with random with impure patterns
*
* @public
*/
declare class Random {
/**
* Create a mutable random number generator by cloning the passed one and mutate it
* @param sourceRng - Immutable random generator from pure-rand library, will not be altered (a clone will be)
*/
constructor(sourceRng: RandomGenerator);
/**
* Clone the random number generator
*/
clone(): Random;
/**
* Generate an integer having `bits` random bits
* @param bits - Number of bits to generate
* @deprecated Prefer {@link nextInt} with explicit bounds: `nextInt(0, (1 << bits) - 1)`
*/
next(bits: number): number;
/**
* Generate a random boolean
*/
nextBoolean(): boolean;
/**
* Generate a random integer (32 bits)
* @deprecated Prefer {@link nextInt} with explicit bounds: `nextInt(-2147483648, 2147483647)`
*/
nextInt(): number;
/**
* Generate a random integer between min (included) and max (included)
* @param min - Minimal integer value
* @param max - Maximal integer value
*/
nextInt(min: number, max: number): number;
/**
* Generate a random bigint between min (included) and max (included)
* @param min - Minimal bigint value
* @param max - Maximal bigint value
*/
nextBigInt(min: bigint, max: bigint): bigint;
/**
* Generate a random floating point number between 0.0 (included) and 1.0 (excluded)
*/
nextDouble(): number;
/**
* Extract the internal state of the internal RandomGenerator backing the current instance of Random
*/
getState(): readonly number[] | undefined;
}
//#endregion
//#region src/stream/Stream.d.ts
/**
* Wrapper around `IterableIterator` interface
* offering a set of helpers to deal with iterations in a simple way
*
* @remarks Since 0.0.7
* @public
*/
declare class Stream<T> implements IterableIterator<T> {
/** @internal */
private readonly g;
/**
* Create an empty stream of T
* @remarks Since 0.0.1
*/
static nil<T>(): Stream<T>;
/**
* Create a stream of T from a variable number of elements
*
* @param elements - Elements used to create the Stream
* @remarks Since 2.12.0
*/
static of<T>(...elements: T[]): Stream<T>;
/**
* Create a Stream based on `g`
* @param g - Underlying data of the Stream
*/
constructor(g: IterableIterator<T>);
next(): IteratorResult<T>;
[Symbol.iterator](): IterableIterator<T>;
/**
* Map all elements of the Stream using `f`
*
* WARNING: It closes the current stream
*
* @param f - Mapper function
* @remarks Since 0.0.1
*/
map<U>(f: (v: T) => U): Stream<U>;
/**
* Flat map all elements of the Stream using `f`
*
* WARNING: It closes the current stream
*
* @param f - Mapper function
* @remarks Since 0.0.1
*/
flatMap<U>(f: (v: T) => IterableIterator<U>): Stream<U>;
/**
* Drop elements from the Stream while `f(element) === true`
*
* WARNING: It closes the current stream
*
* @param f - Drop condition
* @remarks Since 0.0.1
*/
dropWhile(f: (v: T) => boolean): Stream<T>;
/**
* Drop `n` first elements of the Stream
*
* WARNING: It closes the current stream
*
* @param n - Number of elements to drop
* @remarks Since 0.0.1
*/
drop(n: number): Stream<T>;
/**
* Take elements from the Stream while `f(element) === true`
*
* WARNING: It closes the current stream
*
* @param f - Take condition
* @remarks Since 0.0.1
*/
takeWhile(f: (v: T) => boolean): Stream<T>;
/**
* Take `n` first elements of the Stream
*
* WARNING: It closes the current stream
*
* @param n - Number of elements to take
* @remarks Since 0.0.1
*/
take(n: number): Stream<T>;
/**
* Filter elements of the Stream
*
* WARNING: It closes the current stream
*
* @param f - Elements to keep
* @remarks Since 1.23.0
*/
filter<U extends T>(f: (v: T) => v is U): Stream<U>;
/**
* Filter elements of the Stream
*
* WARNING: It closes the current stream
*
* @param f - Elements to keep
* @remarks Since 0.0.1
*/
filter(f: (v: T) => boolean): Stream<T>;
/**
* Check whether all elements of the Stream are successful for `f`
*
* WARNING: It closes the current stream
*
* @param f - Condition to check
* @remarks Since 0.0.1
*/
every(f: (v: T) => boolean): boolean;
/**
* Check whether one of the elements of the Stream is successful for `f`
*
* WARNING: It closes the current stream
*
* @param f - Condition to check
* @remarks Since 0.0.1
*/
has(f: (v: T) => boolean): [boolean, T | null];
/**
* Join `others` Stream to the current Stream
*
* WARNING: It closes the current stream and the other ones (as soon as it iterates over them)
*
* @param others - Streams to join to the current Stream
* @remarks Since 0.0.1
*/
join(...others: IterableIterator<T>[]): Stream<T>;
/**
* Take the `nth` element of the Stream of the last (if it does not exist)
*
* WARNING: It closes the current stream
*
* @param nth - Position of the element to extract
* @remarks Since 0.0.12
*/
getNthOrLast(nth: number): T | null;
}
/**
* Create a Stream based on `g`
*
* @param g - Underlying data of the Stream
*
* @remarks Since 0.0.7
* @public
*/
declare function stream<T>(g: IterableIterator<T>): Stream<T>;
//#endregion
//#region src/check/arbitrary/definition/Value.d.ts
/**
* A `Value<T, TShrink = T>` holds an internal value of type `T`
* and its associated context
*
* @remarks Since 3.0.0 (previously called `NextValue` in 2.15.0)
* @public
*/
declare class Value<T> {
/**
* State storing the result of hasCloneMethod
* If `true` the value will be cloned each time it gets accessed
* @remarks Since 2.15.0
*/
readonly hasToBeCloned: boolean;
/**
* Safe value of the shrinkable
* Depending on `hasToBeCloned` it will either be `value_` or a clone of it
* @remarks Since 2.15.0
*/
readonly value: T;
/**
* Internal value of the shrinkable
* @remarks Since 2.15.0
*/
readonly value_: T;
/**
* Context for the generated value
* TODO - Do we want to clone it too?
* @remarks 2.15.0
*/
readonly context: unknown;
/**
* @param value_ - Internal value of the shrinkable
* @param context - Context associated to the generated value (useful for shrink)
* @param customGetValue - Limited to internal usages (to ease migration to next), it will be removed on next major
*/
constructor(value_: T, context: unknown, customGetValue?: (() => T) | undefined);
}
//#endregion
//#region src/check/arbitrary/definition/Arbitrary.d.ts
/**
* Abstract class able to generate values on type `T`
*
* The values generated by an instance of Arbitrary can be previewed - with {@link sample} - or classified - with {@link statistics}.
*
* @remarks Since 0.0.7
* @public
*/
declare abstract class Arbitrary<T> {
/**
* Generate a value of type `T` along with its context (if any)
* based on the provided random number generator
*
* @param mrng - Random number generator
* @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)
* @returns Random value of type `T` and its context
*
* @remarks Since 0.0.1 (return type changed in 3.0.0)
*/
abstract generate(mrng: Random, biasFactor: number | undefined): Value<T>;
/**
* Check if a given value could be pass to `shrink` without providing any context.
*
* In general, `canShrinkWithoutContext` is not designed to be called for each `shrink` but rather on very special cases.
* Its usage must be restricted to `canShrinkWithoutContext` or in the rare* contexts of a `shrink` method being called without
* any context. In this ill-formed case of `shrink`, `canShrinkWithoutContext` could be used or called if needed.
*
* *we fall in that case when fast-check is asked to shrink a value that has been provided manually by the user,
* in other words: a value not coming from a call to `generate` or a normal `shrink` with context.
*
* @param value - Value to be assessed
* @returns `true` if and only if the value could have been generated by this instance
*
* @remarks Since 3.0.0
*/
abstract canShrinkWithoutContext(value: unknown): value is T;
/**
* Shrink a value of type `T`, may rely on the context previously provided to shrink efficiently
*
* Must never be called with possibly invalid values and no context without ensuring that such call is legal
* by calling `canShrinkWithoutContext` first on the value.
*
* @param value - The value to shrink
* @param context - Its associated context (the one returned by generate) or `undefined` if no context but `canShrinkWithoutContext(value) === true`
* @returns Stream of shrinks for value based on context (if provided)
*
* @remarks Since 3.0.0
*/
abstract shrink(value: T, context: unknown | undefined): Stream<Value<T>>;
/**
* Create another arbitrary by filtering values against `predicate`
*
* All the values produced by the resulting arbitrary
* satisfy `predicate(value) == true`
*
* Be aware that using filter may highly impact the time required to generate a valid entry
*
* @example
* ```typescript
* const integerGenerator: Arbitrary<number> = ...;
* const evenIntegerGenerator: Arbitrary<number> = integerGenerator.filter(e => e % 2 === 0);
* // new Arbitrary only keeps even values
* ```
*
* @param refinement - Predicate, to test each produced element. Return true to keep the element, false otherwise
* @returns New arbitrary filtered using predicate
*
* @remarks Since 1.23.0
*/
filter<U extends T>(refinement: (t: T) => t is U): Arbitrary<U>;
/**
* Create another arbitrary by filtering values against `predicate`
*
* All the values produced by the resulting arbitrary
* satisfy `predicate(value) == true`
*
* Be aware that using filter may highly impact the time required to generate a valid entry
*
* @example
* ```typescript
* const integerGenerator: Arbitrary<number> = ...;
* const evenIntegerGenerator: Arbitrary<number> = integerGenerator.filter(e => e % 2 === 0);
* // new Arbitrary only keeps even values
* ```
*
* @param predicate - Predicate, to test each produced element. Return true to keep the element, false otherwise
* @returns New arbitrary filtered using predicate
*
* @remarks Since 0.0.1
*/
filter(predicate: (t: T) => boolean): Arbitrary<T>;
/**
* Create another arbitrary by mapping all produced values using the provided `mapper`
* Values produced by the new arbitrary are the result of applying `mapper` value by value
*
* @example
* ```typescript
* const rgbChannels: Arbitrary<{r:number,g:number,b:number}> = ...;
* const color: Arbitrary<string> = rgbChannels.map(ch => `#${(ch.r*65536 + ch.g*256 + ch.b).toString(16).padStart(6, '0')}`);
* // transform an Arbitrary producing {r,g,b} integers into an Arbitrary of '#rrggbb'
* ```
*
* @param mapper - Map function, to produce a new element based on an old one
* @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)
* @returns New arbitrary with mapped elements
*
* @remarks Since 0.0.1
*/
map<U>(mapper: (t: T) => U, unmapper?: (possiblyU: unknown) => T): Arbitrary<U>;
/**
* Create another arbitrary by mapping a value from a base Arbirary using the provided `fmapper`
* Values produced by the new arbitrary are the result of the arbitrary generated by applying `fmapper` to a value
* @example
* ```typescript
* const arrayAndLimitArbitrary = fc.nat().chain((c: number) => fc.tuple( fc.array(fc.nat(c)), fc.constant(c)));
* ```
*
* @param chainer - Chain function, to produce a new Arbitrary using a value from another Arbitrary
* @returns New arbitrary of new type
*
* @remarks Since 1.2.0
*/
chain<U>(chainer: (t: T) => Arbitrary<U>): Arbitrary<U>;
}
//#endregion
//#region src/check/precondition/PreconditionFailure.d.ts
/**
* Error type produced whenever a precondition fails
* @remarks Since 2.2.0
* @public
*/
declare class PreconditionFailure extends Error {
readonly interruptExecution: boolean;
constructor(interruptExecution?: boolean);
static isFailure(err: unknown): err is PreconditionFailure;
}
//#endregion
//#region src/check/property/IRawProperty.d.ts
/**
* Represent failures of the property
* @remarks Since 3.0.0
* @public
*/
type PropertyFailure = {
/**
* The original error that has been intercepted.
* Possibly not an instance Error as users can throw anything.
* @remarks Since 3.0.0
*/
error: unknown;
};
/**
* Property
*
* A property is the combination of:
* - Arbitraries: how to generate the inputs for the algorithm
* - Predicate: how to confirm the algorithm succeeded?
*
* @remarks Since 1.19.0
* @public
*/
interface IRawProperty<Ts, IsAsync extends boolean = boolean> {
/**
* Is the property asynchronous?
*
* true in case of asynchronous property, false otherwise
* @remarks Since 0.0.7
*/
isAsync(): IsAsync;
/**
* Generate values of type Ts
*
* @param mrng - Random number generator
* @param runId - Id of the generation, starting at 0 - if set the generation might be biased
*
* @remarks Since 0.0.7 (return type changed in 3.0.0)
*/
generate(mrng: Random, runId?: number): Value<Ts>;
/**
* Shrink value of type Ts
*
* @param value - The value to be shrunk, it can be context-less
*
* @remarks Since 3.0.0
*/
shrink(value: Value<Ts>): Stream<Value<Ts>>;
/**
* Check the predicate for v
* @param v - Value of which we want to check the predicate
* @remarks Since 0.0.7
*/
run(v: Ts): (IsAsync extends true ? Promise<PreconditionFailure | PropertyFailure | null> : never) | (IsAsync extends false ? PreconditionFailure | PropertyFailure | null : never);
/**
* Run before each hook
* @remarks Since 3.4.0
*/
runBeforeEach: () => (IsAsync extends true ? Promise<void> : never) | (IsAsync extends false ? void : never);
/**
* Run after each hook
* @remarks Since 3.4.0
*/
runAfterEach: () => (IsAsync extends true ? Promise<void> : never) | (IsAsync extends false ? void : never);
}
//#endregion
//#region src/arbitrary/_internals/helpers/MaxLengthFromMinLength.d.ts
/**
* The size parameter defines how large the generated values could be.
*
* The default in fast-check is 'small' but it could be increased (resp. decreased)
* to ask arbitraries for larger (resp. smaller) values.
*
* @remarks Since 2.22.0
* @public
*/
type Size = "xsmall" | "small" | "medium" | "large" | "xlarge";
/**
* @remarks Since 2.22.0
* @public
*/
type RelativeSize = "-4" | "-3" | "-2" | "-1" | "=" | "+1" | "+2" | "+3" | "+4";
/**
* Superset of {@link Size} to override the default defined for size
* @remarks Since 2.22.0
* @public
*/
type SizeForArbitrary = RelativeSize | Size | "max" | undefined;
/**
* Superset of {@link Size} to override the default defined for size.
* It can either be based on a numeric value manually selected by the user (not recommended)
* or rely on presets based on size (recommended).
*
* This size will be used to infer a bias to limit the depth, used as follow within recursive structures:
* While going deeper, the bias on depth will increase the probability to generate small instances.
*
* When used with {@link Size}, the larger the size the deeper the structure.
* When used with numeric values, the larger the number (floating point number >= 0),
* the deeper the structure. `+0` means extremelly biased depth meaning barely impossible to generate
* deep structures, while `Number.POSITIVE_INFINITY` means "depth has no impact".
*
* Using `max` or `Number.POSITIVE_INFINITY` is fully equivalent.
*
* @remarks Since 2.25.0
* @public
*/
type DepthSize = RelativeSize | Size | "max" | number | undefined;
//#endregion
//#region src/check/runner/configuration/RandomType.d.ts
/**
* Random generators automatically recognized by the framework
* without having to pass a builder function
* @remarks Since 2.2.0
* @public
*/
type RandomType = "mersenne" | "congruential" | "congruential32" | "xorshift128plus" | "xoroshiro128plus";
//#endregion
//#region src/check/runner/configuration/VerbosityLevel.d.ts
/**
* Verbosity level
* @remarks Since 1.9.1
* @public
*/
declare enum VerbosityLevel {
/**
* Level 0 (default)
*
* Minimal reporting:
* - minimal failing case
* - error log corresponding to the minimal failing case
*
* @remarks Since 1.9.1
*/
None = 0,
/**
* Level 1
*
* Failures reporting:
* - same as `VerbosityLevel.None`
* - list all the failures encountered during the shrinking process
*
* @remarks Since 1.9.1
*/
Verbose = 1,
/**
* Level 2
*
* Execution flow reporting:
* - same as `VerbosityLevel.None`
* - all runs with their associated status displayed as a tree
*
* @remarks Since 1.9.1
*/
VeryVerbose = 2
}
//#endregion
//#region src/check/runner/reporter/ExecutionStatus.d.ts
/**
* Status of the execution of the property
* @remarks Since 1.9.0
* @public
*/
declare enum ExecutionStatus {
Success = 0,
Skipped = -1,
Failure = 1
}
//#endregion
//#region src/check/runner/reporter/ExecutionTree.d.ts
/**
* Summary of the execution process
* @remarks Since 1.9.0
* @public
*/
interface ExecutionTree<Ts> {
/**
* Status of the property
* @remarks Since 1.9.0
*/
status: ExecutionStatus;
/**
* Generated value
* @remarks Since 1.9.0
*/
value: Ts;
/**
* Values derived from this value
* @remarks Since 1.9.0
*/
children: ExecutionTree<Ts>[];
}
//#endregion
//#region src/check/runner/reporter/RunDetails.d.ts
/**
* Post-run details produced by {@link check}
*
* A failing property can easily detected by checking the `failed` flag of this structure
*
* @remarks Since 0.0.7
* @public
*/
type RunDetails<Ts> = RunDetailsFailureProperty<Ts> | RunDetailsFailureTooManySkips<Ts> | RunDetailsFailureInterrupted<Ts> | RunDetailsSuccess<Ts>;
/**
* Run reported as failed because
* the property failed
*
* Refer to {@link RunDetailsCommon} for more details
*
* @remarks Since 1.25.0
* @public
*/
interface RunDetailsFailureProperty<Ts> extends RunDetailsCommon<Ts> {
failed: true;
interrupted: boolean;
counterexample: Ts;
counterexamplePath: string;
errorInstance: unknown;
}
/**
* Run reported as failed because
* too many retries have been attempted to generate valid values
*
* Refer to {@link RunDetailsCommon} for more details
*
* @remarks Since 1.25.0
* @public
*/
interface RunDetailsFailureTooManySkips<Ts> extends RunDetailsCommon<Ts> {
failed: true;
interrupted: false;
counterexample: null;
counterexamplePath: null;
errorInstance: null;
}
/**
* Run reported as failed because
* it took too long and thus has been interrupted
*
* Refer to {@link RunDetailsCommon} for more details
*
* @remarks Since 1.25.0
* @public
*/
interface RunDetailsFailureInterrupted<Ts> extends RunDetailsCommon<Ts> {
failed: true;
interrupted: true;
counterexample: null;
counterexamplePath: null;
errorInstance: null;
}
/**
* Run reported as success
*
* Refer to {@link RunDetailsCommon} for more details
*
* @remarks Since 1.25.0
* @public
*/
interface RunDetailsSuccess<Ts> extends RunDetailsCommon<Ts> {
failed: false;
interrupted: boolean;
counterexample: null;
counterexamplePath: null;
errorInstance: null;
}
/**
* Shared part between variants of RunDetails
* @remarks Since 2.2.0
* @public
*/
interface RunDetailsCommon<Ts> {
/**
* Does the property failed during the execution of {@link check}?
* @remarks Since 0.0.7
*/
failed: boolean;
/**
* Was the execution interrupted?
* @remarks Since 1.19.0
*/
interrupted: boolean;
/**
* Number of runs
*
* - In case of failed property: Number of runs up to the first failure (including the failure run)
* - Otherwise: Number of successful executions
*
* @remarks Since 1.0.0
*/
numRuns: number;
/**
* Number of skipped entries due to failed pre-condition
*
* As `numRuns` it only takes into account the skipped values that occured before the first failure.
* Refer to {@link pre} to add such pre-conditions.
*
* @remarks Since 1.3.0
*/
numSkips: number;
/**
* Number of shrinks required to get to the minimal failing case (aka counterexample)
* @remarks Since 1.0.0
*/
numShrinks: number;
/**
* Seed that have been used by the run
*
* It can be forced in {@link assert}, {@link check}, {@link sample} and {@link statistics} using `Parameters`
* @remarks Since 0.0.7
*/
seed: number;
/**
* In case of failure: the counterexample contains the minimal failing case (first failure after shrinking)
* @remarks Since 0.0.7
*/
counterexample: Ts | null;
/**
* In case of failure: it contains the error that has been thrown if any
* @remarks Since 3.0.0
*/
errorInstance: unknown | null;
/**
* In case of failure: path to the counterexample
*
* For replay purposes, it can be forced in {@link assert}, {@link check}, {@link sample} and {@link statistics} using `Parameters`
*
* @remarks Since 1.0.0
*/
counterexamplePath: string | null;
/**
* List all failures that have occurred during the run
*
* You must enable verbose with at least `Verbosity.Verbose` in `Parameters`
* in order to have values in it
*
* @remarks Since 1.1.0
*/
failures: Ts[];
/**
* Execution summary of the run
*
* Traces the origin of each value encountered during the test and its execution status.
* Can help to diagnose shrinking issues.
*
* You must enable verbose with at least `Verbosity.Verbose` in `Parameters`
* in order to have values in it:
* - Verbose: Only failures
* - VeryVerbose: Failures, Successes and Skipped
*
* @remarks Since 1.9.0
*/
executionSummary: ExecutionTree<Ts>[];
/**
* Verbosity level required by the user
* @remarks Since 1.9.0
*/
verbose: VerbosityLevel;
/**
* Configuration of the run
*
* It includes both local parameters set on {@link check} or {@link assert}
* and global ones specified using {@link configureGlobal}
*
* @remarks Since 1.25.0
*/
runConfiguration: Parameters<Ts>;
}
//#endregion
//#region src/check/runner/configuration/Parameters.d.ts
/**
* Customization of the parameters used to run the properties
* @remarks Since 0.0.6
* @public
*/
interface Parameters<T = void> {
/**
* Initial seed of the generator: `Date.now()` by default
*
* It can be forced to replay a failed run.
*
* In theory, seeds are supposed to be 32-bit integers.
* In case of double value, the seed will be rescaled into a valid 32-bit integer (eg.: values between 0 and 1 will be evenly spread into the range of possible seeds).
*
* @remarks Since 0.0.6
*/
seed?: number;
/**
* Random number generator: `xorshift128plus` by default
*
* Random generator is the core element behind the generation of random values - changing it might directly impact the quality and performances of the generation of random values.
* It can be one of: 'mersenne', 'congruential', 'congruential32', 'xorshift128plus', 'xoroshiro128plus'
* Or any function able to build a `RandomGenerator` based on a seed
*
* As required since pure-rand v6.0.0, when passing a builder for {@link RandomGenerator},
* the random number generator must generate values between -0x80000000 and 0x7fffffff.
*
* @remarks Since 1.6.0
*/
randomType?: RandomType | ((seed: number) => RandomGenerator);
/**
* Number of runs before success: 100 by default
* @remarks Since 1.0.0
*/
numRuns?: number;
/**
* Maximal number of skipped values per run
*
* Skipped is considered globally, so this value is used to compute maxSkips = maxSkipsPerRun * numRuns.
* Runner will consider a run to have failed if it skipped maxSkips+1 times before having generated numRuns valid entries.
*
* See {@link pre} for more details on pre-conditions
*
* @remarks Since 1.3.0
*/
maxSkipsPerRun?: number;
/**
* Maximum time in milliseconds for the predicate to answer: disabled by default
*
* WARNING: Only works for async code (see {@link asyncProperty}), will not interrupt a synchronous code.
* @remarks Since 0.0.11
*/
timeout?: number;
/**
* Skip all runs after a given time limit: disabled by default
*
* NOTE: Relies on `Date.now()`.
*
* NOTE:
* Useful to stop too long shrinking processes.
* Replay capability (see `seed`, `path`) can resume the shrinking.
*
* WARNING:
* It skips runs. Thus test might be marked as failed.
* Indeed, it might not reached the requested number of successful runs.
*
* @remarks Since 1.15.0
*/
skipAllAfterTimeLimit?: number;
/**
* Interrupt test execution after a given time limit: disabled by default
*
* NOTE: Relies on `Date.now()`.
*
* NOTE:
* Useful to avoid having too long running processes in your CI.
* Replay capability (see `seed`, `path`) can still be used if needed.
*
* WARNING:
* If the test got interrupted before any failure occured
* and before it reached the requested number of runs specified by `numRuns`
* it will be marked as success. Except if `markInterruptAsFailure` has been set to `true`
*
* @remarks Since 1.19.0
*/
interruptAfterTimeLimit?: number;
/**
* Mark interrupted runs as failed runs if preceded by one success or more: disabled by default
* Interrupted with no success at all always defaults to failure whatever the value of this flag.
* @remarks Since 1.19.0
*/
markInterruptAsFailure?: boolean;
/**
* Skip runs corresponding to already tried values.
*
* WARNING:
* Discarded runs will be retried. Under the hood they are simple calls to `fc.pre`.
* In other words, if you ask for 100 runs but your generator can only generate 10 values then the property will fail as 100 runs will never be reached.
* Contrary to `ignoreEqualValues` you always have the number of runs you requested.
*
* NOTE: Relies on `fc.stringify` to check the equality.
*
* @remarks Since 2.14.0
*/
skipEqualValues?: boolean;
/**
* Discard runs corresponding to already tried values.
*
* WARNING:
* Discarded runs will not be replaced.
* In other words, if you ask for 100 runs and have 2 discarded runs you will only have 98 effective runs.
*
* NOTE: Relies on `fc.stringify` to check the equality.
*
* @remarks Since 2.14.0
*/
ignoreEqualValues?: boolean;
/**
* Way to replay a failing property directly with the counterexample.
* It can be fed with the counterexamplePath returned by the failing test (requires `seed` too).
* @remarks Since 1.0.0
*/
path?: string;
/**
* Logger (see {@link statistics}): `console.log` by default
* @remarks Since 0.0.6
*/
logger?(v: string): void;
/**
* Force the use of unbiased arbitraries: biased by default
* @remarks Since 1.1.0
*/
unbiased?: boolean;
/**
* Enable verbose mode: {@link VerbosityLevel.None} by default
*
* Using `verbose: true` is equivalent to `verbose: VerbosityLevel.Verbose`
*
* It can prove very useful to troubleshoot issues.
* See {@link VerbosityLevel} for more details on each level.
*
* @remarks Since 1.1.0
*/
verbose?: boolean | VerbosityLevel;
/**
* Custom values added at the beginning of generated ones
*
* It enables users to come with examples they want to test at every run
*
* @remarks Since 1.4.0
*/
examples?: T[];
/**
* Stop run on failure
*
* It makes the run stop at the first encountered failure without shrinking.
*
* When used in complement to `seed` and `path`,
* it replays only the minimal counterexample.
*
* @remarks Since 1.11.0
*/
endOnFailure?: boolean;
/**
* Replace the default reporter handling errors by a custom one
*
* Reporter is responsible to throw in case of failure: default one throws whenever `runDetails.failed` is true.
* But you may want to change this behaviour in yours.
*
* Only used when calling {@link assert}
* Cannot be defined in conjonction with `asyncReporter`
*
* @remarks Since 1.25.0
*/
reporter?: (runDetails: RunDetails<T>) => void;
/**
* Replace the default reporter handling errors by a custom one
*
* Reporter is responsible to throw in case of failure: default one throws whenever `runDetails.failed` is true.
* But you may want to change this behaviour in yours.
*
* Only used when calling {@link assert}
* Cannot be defined in conjonction with `reporter`
* Not compatible with synchronous properties: runner will throw
*
* @remarks Since 1.25.0
*/
asyncReporter?: (runDetails: RunDetails<T>) => Promise<void>;
/**
* By default the Error causing the failure of the predicate will not be directly exposed within the message
* of the Error thown by fast-check. It will be exposed by a cause field attached to the Error.
*
* The Error with cause has been supported by Node since 16.14.0 and is properly supported in many test runners.
*
* But if the original Error fails to appear within your test runner,
* Or if you prefer the Error to be included directly as part of the message of the resulted Error,
* you can toggle this flag and the Error produced by fast-check in case of failure will expose the source Error
* as part of the message and not as a cause.
*/
includeErrorInReport?: boolean;
}
//#endregion
//#region src/check/runner/configuration/GlobalParameters.d.ts
/**
* Type of legal hook function that can be used in the global parameter `beforeEach` and/or `afterEach`
* @remarks Since 2.3.0
* @public
*/
type GlobalPropertyHookFunction = () => void;
/**
* Type of legal hook function that can be used in the global parameter `asyncBeforeEach` and/or `asyncAfterEach`
* @remarks Since 2.3.0
* @public
*/
type GlobalAsyncPropertyHookFunction = (() => Promise<unknown>) | (() => void);
/**
* Type describing the global overrides
* @remarks Since 1.18.0
* @public
*/
type GlobalParameters = Pick<Parameters<unknown>, Exclude<keyof Parameters<unknown>, "path" | "examples">> & {
/**
* Specify a function that will be called before each execution of a property.
* It behaves as-if you manually called `beforeEach` method on all the properties you execute with fast-check.
*
* The function will be used for both {@link fast-check#property} and {@link fast-check#asyncProperty}.
* This global override should never be used in conjunction with `asyncBeforeEach`.
*
* @remarks Since 2.3.0
*/
beforeEach?: GlobalPropertyHookFunction;
/**
* Specify a function that will be called after each execution of a property.
* It behaves as-if you manually called `afterEach` method on all the properties you execute with fast-check.
*
* The function will be used for both {@link fast-check#property} and {@link fast-check#asyncProperty}.
* This global override should never be used in conjunction with `asyncAfterEach`.
*
* @remarks Since 2.3.0
*/
afterEach?: GlobalPropertyHookFunction;
/**
* Specify a function that will be called before each execution of an asynchronous property.
* It behaves as-if you manually called `beforeEach` method on all the asynchronous properties you execute with fast-check.
*
* The function will be used only for {@link fast-check#asyncProperty}. It makes synchronous properties created by {@link fast-check#property} unable to run.
* This global override should never be used in conjunction with `beforeEach`.
*
* @remarks Since 2.3.0
*/
asyncBeforeEach?: GlobalAsyncPropertyHookFunction;
/**
* Specify a function that will be called after each execution of an asynchronous property.
* It behaves as-if you manually called `afterEach` method on all the asynchronous properties you execute with fast-check.
*
* The function will be used only for {@link fast-check#asyncProperty}. It makes synchronous properties created by {@link fast-check#property} unable to run.
* This global override should never be used in conjunction with `afterEach`.
*
* @remarks Since 2.3.0
*/
asyncAfterEach?: GlobalAsyncPropertyHookFunction;
/**
* Define the base size to be used by arbitraries.
*
* By default arbitraries not specifying any size will default to it (except in some cases when used defaultSizeToMaxWhenMaxSpecified is true).
* For some arbitraries users will want to override the default and either define another size relative to this one,
* or a fixed one.
*
* @defaultValue `"small"`
* @remarks Since 2.22.0
*/
baseSize?: Size;
/**
* When set to `true` and if the size has not been defined for this precise instance,
* it will automatically default to `"max"` if the user specified a upper bound for the range
* (applies to length and to depth).
*
* When `false`, the size will be defaulted to `baseSize` even if the user specified
* a upper bound for the range.
*
* @remarks Since 2.22.0
*/
defaultSizeToMaxWhenMaxSpecified?: boolean;
};
/**
* Define global parameters that will be used by all the runners
*
* @example
* ```typescript
* fc.configureGlobal({ numRuns: 10 });
* //...
* fc.assert(
* fc.property(
* fc.nat(), fc.nat(),
* (a, b) => a + b === b + a
* ), { seed: 42 }
* ) // equivalent to { numRuns: 10, seed: 42 }
* ```
*
* @param parameters - Global parameters
*
* @remarks Since 1.18.0
* @public
*/
declare function configureGlobal(parameters: GlobalParameters): void;
/**
* Read global parameters that will be used by runners
* @remarks Since 1.18.0
* @public
*/
declare function readConfigureGlobal(): GlobalParameters;
/**
* Reset global parameters
* @remarks Since 1.18.0
* @public
*/
declare function resetConfigureGlobal(): void;
//#endregion
//#region src/check/property/AsyncProperty.generic.d.ts
/**
* Type of legal hook function that can be used to call `beforeEach` or `afterEach`
* on a {@link IAsyncPropertyWithHooks}
*
* @remarks Since 2.2.0
* @public
*/
type AsyncPropertyHookFunction = ((previousHookFunction: GlobalAsyncPropertyHookFunction) => Promise<unknown>) | ((previousHookFunction: GlobalAsyncPropertyHookFunction) => void);
/**
* Interface for asynchronous property, see {@link IRawProperty}
* @remarks Since 1.19.0
* @public
*/
interface IAsyncProperty<Ts> extends IRawProperty<Ts, true> {}
/**
* Interface for asynchronous property defining hooks, see {@link IAsyncProperty}
* @remarks Since 2.2.0
* @public
*/
interface IAsyncPropertyWithHooks<Ts> extends IAsyncProperty<Ts> {
/**
* Define a function that should be called before all calls to the predicate
* @param hookFunction - Function to be called
* @remarks Since 1.6.0
*/
beforeEach(hookFunction: AsyncPropertyHookFunction): IAsyncPropertyWithHooks<Ts>;
/**
* Define a function that should be called after all calls to the predicate
* @param hookFunction - Function to be called
* @remarks Since 1.6.0
*/
afterEach(hookFunction: AsyncPropertyHookFunction): IAsyncPropertyWithHooks<Ts>;
}
//#endregion
//#region src/check/property/AsyncProperty.d.ts
/**
* Instantiate a new {@link fast-check#IAsyncProperty}
* @param predicate - Assess the success of the property. Would be considered falsy if it throws or if its output evaluates to false
* @remarks Since 0.0.7
* @public
*/
declare function asyncProperty<Ts extends [unknown, ...unknown[]]>(...args: [...arbitraries: { [K in keyof Ts]: Arbitrary<Ts[K]> }, predicate: (...args: Ts) => Promise<boolean | void>]): IAsyncPropertyWithHooks<Ts>;
//#endregion
//#region src/check/property/Property.generic.d.ts
/**
* Type of legal hook function that can be used to call `beforeEach` or `afterEach`
* on a {@link IPropertyWithHooks}
*
* @remarks Since 2.2.0
* @public
*/
type PropertyHookFunction = (globalHookFunction: GlobalPropertyHookFunction) => void;
/**
* Interface for synchronous property, see {@link IRawProperty}
* @remarks Since 1.19.0
* @public
*/
interface IProperty<Ts> extends IRawProperty<Ts, false> {}
/**
* Interface for synchronous property defining hooks, see {@link IProperty}
* @remarks Since 2.2.0
* @public
*/
interface IPropertyWithHooks<Ts> extends IProperty<Ts> {
/**
* Define a function that should be called before all calls to the predicate
* @param invalidHookFunction - Function to be called, please provide a valid hook function
* @remarks Since 1.6.0
*/
beforeEach(invalidHookFunction: (hookFunction: GlobalPropertyHookFunction) => Promise<unknown>): "beforeEach expects a synchronous function but was given a function returning a Promise";
/**
* Define a function that should be called before all calls to the predicate
* @param hookFunction - Function to be called
* @remarks Since 1.6.0
*/
beforeEach(hookFunction: PropertyHookFunction): IPropertyWithHooks<Ts>;
/**
* Define a function that should be called after all calls to the predicate
* @param invalidHookFunction - Function to be called, please provide a valid hook function
* @remarks Since 1.6.0
*/
afterEach(invalidHookFunction: (hookFunction: GlobalPropertyHookFunction) => Promise<unknown>): "afterEach expects a synchronous function but was given a function returning a Promise";
/**
* Define a function that should be called after all calls to the predicate
* @param hookFunction - Function to be called
* @remarks Since 1.6.0
*/
afterEach(hookFunction: PropertyHookFunction): IPropertyWithHooks<Ts>;
}
//#endregion
//#region src/check/property/Property.d.ts
/**
* Instantiate a new {@link fast-check#IProperty}
* @param predicate - Assess the success of the property. Would be considered falsy if it throws or if its output evaluates to false
* @remarks Since 0.0.1
* @public
*/
declare function property<Ts extends [unknown, ...unknown[]]>(...args: [...arbitraries: { [K in keyof Ts]: Arbitrary<Ts[K]> }, predicate: (...args: Ts) => boolean | void]): IPropertyWithHooks<Ts>;
//#endregion
//#region src/check/runner/Runner.d.ts
/**
* Run the property, do not throw contrary to {@link assert}
*
* WARNING: Has to be awaited
*
* @param property - Asynchronous property to be checked
* @param params - Optional parameters to customize the execution
*
* @returns Test status and other useful details
*
* @remarks Since 0.0.7
* @public
*/
declare function check<Ts>(property: IAsyncProperty<Ts>, params?: Parameters<Ts>): Promise<RunDetails<Ts>>;
/**
* Run the property, do not throw contrary to {@link assert}
*
* @param property - Synchronous property to be checked
* @param params - Optional parameters to customize the execution
*
* @returns Test status and other useful details
*
* @remarks Since 0.0.1
* @public
*/
declare function check<Ts>(property: IProperty<Ts>, params?: Parameters<Ts>): RunDetails<Ts>;
/**
* Run the property, do not throw contrary to {@link assert}
*
* WARNING: Has to be awaited if the property is asynchronous
*
* @param property - Property to be checked
* @param params - Optional parameters to customize the execution
*
* @returns Test status and other useful details
*
* @remarks Since 0.0.7
* @public
*/
declare function check<Ts>(property: IRawProperty<Ts>, params?: Parameters<Ts>): Promise<RunDetails<Ts>> | RunDetails<Ts>;
/**
* Run the property, throw in case of failure
*
* It can be called directly from describe/it blocks of Mocha.
* No meaningful results are produced in case of success.
*
* WARNING: Has to be awaited
*
* @param property - Asynchronous property to be checked
* @param params - Optional parameters to customize the execution
*
* @remarks Since 0.0.7
* @public
*/
declare function assert<Ts>(property: IAsyncProperty<Ts>, params?: Parameters<Ts>): Promise<void>;
/**
* Run the property, throw in case of failure
*
* It can be called directly from describe/it blocks of Mocha.
* No meaningful results are produced in case of success.
*
* @param property - Synchronous property to be checked
* @param params - Optional parameters to customize the execution
*
* @remarks Since 0.0.1
* @public
*/
declare function assert<Ts>(property: IProperty<Ts>, params?: Parameters<Ts>): void;
/**
* Run the property, throw in case of failure
*
* It can be called directly from describe/it blocks of Mocha.
* No meaningful results are produced in case of success.
*
* WARNING: Returns a promise to be awaited if the property is asynchronous
*
* @param property - Synchronous or asynchronous property to be checked
* @param params - Optional parameters to customize the execution
*
* @remarks Since 0.0.7
* @public
*/
declare function assert<Ts>(property: IRawProperty<Ts>, params?: Parameters<Ts>): Promise<void> | void;
//#endregion
//#region src/check/runner/Sampler.d.ts
/**
* Generate an array containing all the values that would have been generated during {@link assert} or {@link check}
*
* @example
* ```typescript
* fc.sample(fc.nat(), 10); // extract 10 values from fc.nat() Arbitrary
* fc.sample(fc.nat(), {seed: 42}); // extract values from fc.nat() as if we were running fc.assert with seed=42
* ```
*
* @param generator - {@link IProperty} or {@link Arbitrary} to extract the values from
* @param params - Integer representing the number of values to generate or `Parameters` as in {@link assert}
*
* @remarks Since 0.0.6
* @public
*/
declare function sample<Ts>(generator: IRawProperty<Ts> | Arbitrary<Ts>, params?: Parameters<Ts> | number): Ts[];
/**
* Gather useful statistics concerning generated values
*
* Print the result in `console.log` or `params.logger` (if defined)
*
* @example
* ```typescript
* fc.statistics(
* fc.nat(999),
* v => v < 100 ? 'Less than 100' : 'More or equal to 100',
* {numRuns: 1000, logger: console.log});
* // Classify 1000 values generated by fc.nat(999) into two categories:
* // - Less than 100
* // - More or equal to 100
* // The output will be sent line by line to the logger
* ```
*
* @param generator - {@link IProperty} or {@link Arbitrary} to extract the values from
* @param classify - Classifier function that can classify the generated value in zero, one or more categories (with free labels)
* @param params - Integer representing the number of values to generate or `Parameters` as in {@link assert}
*
* @remarks Since 0.0.6
* @public
*/
declare function statistics<Ts>(generator: IRawProperty<Ts> | Arbitrary<Ts>, classify: (v: Ts) => string | string[], params?: Parameters<Ts> | number): void;
//#endregion
//#region src/arbitrary/_internals/builders/GeneratorValueBuilder.d.ts
/**
* Take an arbitrary builder and all its arguments separatly.
* Generate a value out of it.
*
* @remarks Since 3.8.0
* @public
*/
type GeneratorValueFunction = <T, TArgs extends unknown[]>(arb: (...params: TArgs) => Arbitrary<T>, ...args: TArgs) => T;
/**
* The values part is mostly exposed for the purpose of the tests.
* Or if you want to have a custom error formatter for this kind of values.
*
* @remarks Since 3.8.0
* @public
*/
type GeneratorValueMethods = {
values: () => unknown[];
};
/**
* An instance of {@link GeneratorValue} can be leveraged within predicates themselves to produce extra random values
* while preserving part of the shrinking capabilities on the produced values.
*
* It can be seen as a way to start property based testing within something looking closer from what users will
* think about when thinking about random in tests. But contrary to raw random, it comes with many useful strengths
* such as: ability to re-run the test (seeded), shrinking...
*
* @remarks Since 3.8.0
* @public
*/
type GeneratorValue = GeneratorValueFunction & GeneratorValueMethods;
//#endregion
//#region src/arbitrary/gen.d.ts
/**
* Generate values within the test execution itself by leveraging the strength of `gen`
*
* @example
* ```javascript
* fc.assert(
* fc.property(fc.gen(), gen => {
* const size = gen(fc.nat, {max: 10});
* const array = [];
* for (let index = 0 ; index !== size ; ++index) {
* array.push(gen(fc.integer));
* }
* // Here is an array!
* // Note: Prefer fc.array(fc.integer(), {maxLength: 10}) if you want to produce such array
* })
* )
* ```
*
* ⚠️ WARNING:
* While `gen` is easy to use, it may not shrink as well as tailored arbitraries based on `filter` or `map`.
*
* ⚠️ WARNING:
* Additionally it cannot run back the test properly when attempting to replay based on a seed and a path.
* You'll need to limit yourself to the seed and drop the path from the options if you attempt to replay something
* implying it. More precisely, you may keep the very first part of the path but have to drop anything after the
* first ":".
*
* ⚠️ WARNING:
* It also does not support custom examples.
*
* @remarks Since 3.8.0
* @public
*/
declare function gen(): Arbitrary<GeneratorValue>;
//#endregion
//#region src/arbitrary/_internals/helpers/DepthContext.d.ts
/**
* Type used to strongly type instances of depth identifier while keeping internals
* what they contain internally
*
* @remarks Since 2.25.0
* @public
*/
type DepthIdentifier = {} & DepthContext;
/**
* Instance of depth, can be used to alter the depth perceived by an arbitrary
* or to bias your own arbitraries based on the current depth
*
* @remarks Since 2.25.0
* @public
*/
type DepthContext = {
/**
* Current depth (starts at 0, continues with 1, 2...).
* Only made of integer values superior or equal to 0.
*
* Remark: Whenever altering the `depth` during a `generate`, please make sure to ALWAYS
* reset it to its original value before you leave the `generate`. Otherwise the execution
* will imply side-effects that will potentially impact the following runs and make replay
* of the issue barely impossible.
*/
depth: number;
};
/**
* Get back the requested DepthContext
* @remarks Since 2.25.0
* @public
*/
declare function getDepthContextFor(contextMeta: DepthContext | DepthIdentifier | string | undefined): DepthContext;
/**
* Create a new and unique instance of DepthIdentifier
* that can be shared across multiple arbitraries if needed
* @public
*/
declare function createDepthIdentifier(): DepthIdentifier;
//#endregion
//#region src/arbitrary/array.d.ts
/**
* Constraints to be applied on {@link array}
* @remarks Since 2.4.0
* @public
*/
interface ArrayConstraints {
/**
* Lower bound of the generated array size
* @defaultValue 0
* @remarks Since 2.4.0
*/
minLength?: number;
/**
* Upper bound of the generated array size
* @defaultValue 0x7fffffff — _defaulting seen as "max non specified" when `defaultSizeToMaxWhenMaxSpecified=true`_
* @remarks Since 2.4.0
*/
maxLength?: number;
/**
* Define how large the generated values should be (at max)
*
* When used in conjonction with `maxLength`, `size` will be used to define
* the upper bound of the generated array size while `maxLength` will be used
* to define and document the general maximal length allowed for this case.
*
* @remarks Since 2.22.0
*/
size?: SizeForArbitrary;
/**
* When receiving a depth identifier, the arbitrary will impact the depth
* attached to it to avoid going too deep if it already generated lots of items.
*
* In other words, if the number of generated values within the collection is large
* then the generated items will tend to be less deep to avoid creating structures a lot
* larger than expected.
*
* For the moment, the depth is not taken into account to compute the number of items to
* define for a precise generate call of the array. Just applied onto eligible items.
*
* @remarks Since 2.25.0
*/
depthIdentifier?: DepthIdentifier | string;
}
/**
* For arrays of values coming from `arb`
*
* @param arb - Arbitrary used to generate the values inside the array
* @param constraints - Constraints to apply when building instances (since 2.4.0)
*
* @remarks Since 0.0.1
* @public
*/
declare function array<T>(arb: Arbitrary<T>, constraints?: ArrayConstraints): Arbitrary<T[]>;
//#endregion
//#region src/arbitrary/bigInt.d.ts
/**
* Constraints to be applied on {@link bigInt}
* @remarks Since 2.6.0
* @public
*/
interface BigIntConstraints {
/**
* Lower bound for the generated bigints (eg.: -5n, 0n, BigInt(Number.MIN_SAFE_INTEGER))
* @remarks Since 2.6.0
*/
min?: bigint;
/**
* Upper bound for the generated bigints (eg.: -2n, 2147483647n, BigInt(Number.MAX_SAFE_INTEGER))
* @remarks Since 2.6.0
*/
max?: bigint;
}
/**
* For bigint
* @remarks Since 1.9.0
* @public
*/
declare function bigInt(): Arbitrary<bigint>;
/**
* For bigint between min (included) and max (included)
*
* @param min - Lower bound for the generated bigints (eg.: -5n, 0n, BigInt(Number.MIN_SAFE_INTEGER))
* @param max - Upper bound for the generated bigints (eg.: -2n, 2147483647n, BigInt(Number.MAX_SAFE_INTEGER))
*
* @remarks Since 1.9.0
* @public
*/
declare function bigInt(min: bigint, max: bigint): Arbitrary<bigint>;
/**
* For bigint between min (included) and max (included)
*
* @param constraints - Constraints to apply when building instanc