@fast-check/vitest
Version:
Property based testing for Vitest based on fast-check
72 lines (71 loc) • 3.16 kB
JavaScript
import { record } from 'fast-check';
import { buildTestWithPropRunner } from './TestWithPropRunnerBuilder.js';
function adaptParametersForRecord(parameters, originalParamaters) {
return {
...parameters,
examples: parameters.examples !== undefined ? parameters.examples.map((example) => example[0]) : undefined,
reporter: originalParamaters.reporter,
asyncReporter: originalParamaters.asyncReporter,
};
}
function adaptExecutionTreeForRecord(executionSummary) {
return executionSummary.map((summary) => ({
...summary,
value: summary.value[0],
children: adaptExecutionTreeForRecord(summary.children),
}));
}
function adaptRunDetailsForRecord(runDetails, originalParamaters) {
const adaptedRunDetailsCommon = {
...runDetails,
counterexample: runDetails.counterexample !== null ? runDetails.counterexample[0] : null,
failures: runDetails.failures.map((failure) => failure[0]),
executionSummary: adaptExecutionTreeForRecord(runDetails.executionSummary),
runConfiguration: adaptParametersForRecord(runDetails.runConfiguration, originalParamaters),
};
return adaptedRunDetailsCommon;
}
function buildTestProp(testFn, fc) {
return (arbitraries, params) => {
if (Array.isArray(arbitraries)) {
return (testName, prop, timeout) => buildTestWithPropRunner(testFn, testName, arbitraries, prop, params, timeout, fc);
}
return (testName, prop, timeout) => {
const recordArb = record(arbitraries);
const recordParams = params !== undefined
? {
...params,
examples: params.examples !== undefined ? params.examples.map((example) => [example]) : undefined,
reporter: params.reporter !== undefined
?
(runDetails) => params.reporter(adaptRunDetailsForRecord(runDetails, params))
: undefined,
asyncReporter: params.asyncReporter !== undefined
?
(runDetails) => params.asyncReporter(adaptRunDetailsForRecord(runDetails, params))
: undefined,
}
: undefined;
buildTestWithPropRunner(testFn, testName, [recordArb], (value) => prop(value), recordParams, timeout, fc);
};
};
}
export function buildTest(testFn, fc, ancestors = new Set()) {
let atLeastOneExtra = false;
const extraKeys = {};
for (const unsafeKey of Object.getOwnPropertyNames(testFn)) {
const key = unsafeKey;
if (!ancestors.has(key) && typeof testFn[key] === 'function') {
atLeastOneExtra = true;
extraKeys[key] = key !== 'each' ? buildTest(testFn[key], fc, new Set([...ancestors, key])) : testFn[key];
}
}
if (!atLeastOneExtra) {
return testFn;
}
const enrichedTestFn = (...args) => testFn(...args);
if ('each' in testFn) {
extraKeys['prop'] = buildTestProp(testFn, fc);
}
return Object.assign(enrichedTestFn, extraKeys);
}