How to use unboxedToString method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

stringify.ts

Source:stringify.ts Github

copy

Full Screen

1import {2 safeFilter,3 safeGetTime,4 safeIndexOf,5 safeJoin,6 safeMap,7 safePush,8 safeToISOString,9 safeToString,10 String,11} from './globals';12const safeArrayFrom = Array.from;13const safeBufferIsBuffer = typeof Buffer !== 'undefined' ? Buffer.isBuffer : undefined;14const safeJsonStringify = JSON.stringify;15const safeNumberIsNaN = Number.isNaN;16const safeObjectKeys = Object.keys;17const safeObjectGetOwnPropertySymbols = Object.getOwnPropertySymbols;18const safeObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;19const safeObjectGetPrototypeOf = Object.getPrototypeOf;20const safeNegativeInfinity = Number.NEGATIVE_INFINITY;21const safePositiveInfinity = Number.POSITIVE_INFINITY;22/**23 * Use this symbol to define a custom serializer for your instances.24 * Serializer must be a function returning a string (see {@link WithToStringMethod}).25 *26 * @remarks Since 2.17.027 * @public28 */29export const toStringMethod = Symbol('fast-check/toStringMethod');30/**31 * Interface to implement for {@link toStringMethod}32 *33 * @remarks Since 2.17.034 * @public35 */36export type WithToStringMethod = { [toStringMethod]: () => string };37/**38 * Check if an instance implements {@link WithToStringMethod}39 *40 * @remarks Since 2.17.041 * @public42 */43export function hasToStringMethod<T>(instance: T): instance is T & WithToStringMethod {44 return (45 instance !== null &&46 (typeof instance === 'object' || typeof instance === 'function') &&47 toStringMethod in instance &&48 typeof (instance as any)[toStringMethod] === 'function'49 );50}51/**52 * Use this symbol to define a custom serializer for your instances.53 * Serializer must be a function returning a promise of string (see {@link WithAsyncToStringMethod}).54 *55 * Please note that:56 * 1. It will only be useful for asynchronous properties.57 * 2. It has to return barely instantly.58 *59 * @remarks Since 2.17.060 * @public61 */62export const asyncToStringMethod = Symbol('fast-check/asyncToStringMethod');63/**64 * Interface to implement for {@link asyncToStringMethod}65 *66 * @remarks Since 2.17.067 * @public68 */69export type WithAsyncToStringMethod = { [asyncToStringMethod]: () => Promise<string> };70/**71 * Check if an instance implements {@link WithAsyncToStringMethod}72 *73 * @remarks Since 2.17.074 * @public75 */76export function hasAsyncToStringMethod<T>(instance: T): instance is T & WithAsyncToStringMethod {77 return (78 instance !== null &&79 (typeof instance === 'object' || typeof instance === 'function') &&80 asyncToStringMethod in instance &&81 typeof (instance as any)[asyncToStringMethod] === 'function'82 );83}84/** @internal */85const findSymbolNameRegex = /^Symbol\((.*)\)$/;86/** @internal */87type AsyncContent = { state: 'fulfilled' | 'rejected' | 'pending' | 'unknown'; value: unknown };88/**89 * Only called with symbol produced by Symbol(string | undefined)90 * Not Symbol.for(string)91 * @internal92 */93function getSymbolDescription(s: symbol): string | null {94 if (s.description !== undefined) return s.description;95 // description is always undefined in node 6, 8, 10 (not 12)96 const m = findSymbolNameRegex.exec(String(s));97 // '' considered equivalent to undefined for node <12 (unable to distinguish undefined from '')98 // s.description would have been equal to '' in node 12+99 return m && m[1].length ? m[1] : null;100}101/** @internal */102function stringifyNumber(numValue: number) {103 switch (numValue) {104 case 0:105 return 1 / numValue === safeNegativeInfinity ? '-0' : '0';106 case safeNegativeInfinity:107 return 'Number.NEGATIVE_INFINITY';108 case safePositiveInfinity:109 return 'Number.POSITIVE_INFINITY';110 default:111 return numValue === numValue ? String(numValue) : 'Number.NaN';112 }113}114/** @internal */115function isSparseArray(arr: unknown[]): boolean {116 let previousNumberedIndex = -1;117 for (const index in arr) {118 const numberedIndex = Number(index);119 if (numberedIndex !== previousNumberedIndex + 1) return true; // we've got a hole120 previousNumberedIndex = numberedIndex;121 }122 return previousNumberedIndex + 1 !== arr.length; // we've got a hole if length does not match123}124/** @internal */125export function stringifyInternal<Ts>(126 value: Ts,127 previousValues: any[],128 getAsyncContent: (p: Promise<unknown> | WithAsyncToStringMethod) => AsyncContent129): string {130 const currentValues = [...previousValues, value];131 if (typeof value === 'object') {132 // early cycle detection for objects133 if (safeIndexOf(previousValues, value) !== -1) {134 return '[cyclic]';135 }136 }137 if (hasAsyncToStringMethod(value)) {138 // if user defined custom async serialization function, we use it first139 const content = getAsyncContent(value);140 if (content.state === 'fulfilled') {141 return content.value as string;142 }143 }144 if (hasToStringMethod(value)) {145 // if user defined custom sync serialization function, we use it before next ones146 try {147 return value[toStringMethod]();148 } catch (err) {149 // fallback to defaults...150 }151 }152 switch (safeToString(value)) {153 case '[object Array]': {154 const arr = value as unknown as unknown[];155 if (arr.length >= 50 && isSparseArray(arr)) {156 const assignments: string[] = [];157 // Discarded: map then join will still show holes158 // Discarded: forEach is very long on large sparse arrays, but only iterates on non-holes integer keys159 for (const index in arr) {160 if (!safeNumberIsNaN(Number(index)))161 safePush(assignments, `${index}:${stringifyInternal(arr[index], currentValues, getAsyncContent)}`);162 }163 return assignments.length !== 0164 ? `Object.assign(Array(${arr.length}),{${safeJoin(assignments, ',')}})`165 : `Array(${arr.length})`;166 }167 // stringifiedArray results in: '' for [,]168 // stringifiedArray results in: ',' for [,,]169 // stringifiedArray results in: '1,' for [1,,]170 // stringifiedArray results in: '1,,2' for [1,,2]171 const stringifiedArray = safeJoin(172 safeMap(arr, (v) => stringifyInternal(v, currentValues, getAsyncContent)),173 ','174 );175 return arr.length === 0 || arr.length - 1 in arr ? `[${stringifiedArray}]` : `[${stringifiedArray},]`;176 }177 case '[object BigInt]':178 return `${value}n`;179 case '[object Boolean]': {180 // eslint-disable-next-line @typescript-eslint/ban-types181 const unboxedToString = (value as unknown as boolean | Boolean) == true ? 'true' : 'false'; // we rely on implicit unboxing182 return typeof value === 'boolean' ? unboxedToString : `new Boolean(${unboxedToString})`;183 }184 case '[object Date]': {185 const d = value as unknown as Date;186 return safeNumberIsNaN(safeGetTime(d)) ? `new Date(NaN)` : `new Date(${safeJsonStringify(safeToISOString(d))})`;187 }188 case '[object Map]':189 return `new Map(${stringifyInternal(Array.from(value as any), currentValues, getAsyncContent)})`;190 case '[object Null]':191 return `null`;192 case '[object Number]':193 return typeof value === 'number' ? stringifyNumber(value) : `new Number(${stringifyNumber(Number(value))})`;194 case '[object Object]': {195 try {196 const toStringAccessor = (value as any).toString; // <-- Can throw197 if (typeof toStringAccessor === 'function' && toStringAccessor !== Object.prototype.toString) {198 // Instance (or one of its parent prototypes) overrides the default toString of Object199 return (value as any).toString(); // <-- Can throw200 }201 } catch (err) {202 // Only return what would have been the default toString on Object203 return '[object Object]';204 }205 const mapper = (k: string | symbol) =>206 `${207 k === '__proto__'208 ? '["__proto__"]'209 : typeof k === 'symbol'210 ? `[${stringifyInternal(k, currentValues, getAsyncContent)}]`211 : safeJsonStringify(k)212 }:${stringifyInternal((value as any)[k], currentValues, getAsyncContent)}`;213 const stringifiedProperties = [214 ...safeMap(safeObjectKeys(value as object), mapper),215 ...safeMap(216 safeFilter(safeObjectGetOwnPropertySymbols(value), (s) => {217 const descriptor = safeObjectGetOwnPropertyDescriptor(value, s);218 return descriptor && descriptor.enumerable;219 }),220 mapper221 ),222 ];223 const rawRepr = '{' + safeJoin(stringifiedProperties, ',') + '}';224 if (safeObjectGetPrototypeOf(value) === null) {225 return rawRepr === '{}' ? 'Object.create(null)' : `Object.assign(Object.create(null),${rawRepr})`;226 }227 return rawRepr;228 }229 case '[object Set]':230 return `new Set(${stringifyInternal(Array.from(value as any), currentValues, getAsyncContent)})`;231 case '[object String]':232 return typeof value === 'string' ? safeJsonStringify(value) : `new String(${safeJsonStringify(value)})`;233 case '[object Symbol]': {234 const s = value as unknown as symbol;235 if (Symbol.keyFor(s) !== undefined) {236 return `Symbol.for(${safeJsonStringify(Symbol.keyFor(s))})`;237 }238 const desc = getSymbolDescription(s);239 if (desc === null) {240 return 'Symbol()';241 }242 const knownSymbol = desc.startsWith('Symbol.') && (Symbol as any)[desc.substring(7)];243 return s === knownSymbol ? desc : `Symbol(${safeJsonStringify(desc)})`;244 }245 case '[object Promise]': {246 const promiseContent = getAsyncContent(value as any as Promise<unknown>);247 switch (promiseContent.state) {248 case 'fulfilled':249 return `Promise.resolve(${stringifyInternal(promiseContent.value, currentValues, getAsyncContent)})`;250 case 'rejected':251 return `Promise.reject(${stringifyInternal(promiseContent.value, currentValues, getAsyncContent)})`;252 case 'pending':253 return `new Promise(() => {/*pending*/})`;254 case 'unknown':255 default:256 return `new Promise(() => {/*unknown*/})`;257 }258 }259 case '[object Error]':260 if (value instanceof Error) {261 return `new Error(${stringifyInternal(value.message, currentValues, getAsyncContent)})`;262 }263 break;264 case '[object Undefined]':265 return `undefined`;266 case '[object Int8Array]':267 case '[object Uint8Array]':268 case '[object Uint8ClampedArray]':269 case '[object Int16Array]':270 case '[object Uint16Array]':271 case '[object Int32Array]':272 case '[object Uint32Array]':273 case '[object Float32Array]':274 case '[object Float64Array]':275 case '[object BigInt64Array]':276 case '[object BigUint64Array]': {277 if (typeof safeBufferIsBuffer === 'function' && safeBufferIsBuffer(value)) {278 // Warning: value.values() may crash at runtime if Buffer got poisoned279 return `Buffer.from(${stringifyInternal(safeArrayFrom(value.values()), currentValues, getAsyncContent)})`;280 }281 const valuePrototype = safeObjectGetPrototypeOf(value);282 const className = valuePrototype && valuePrototype.constructor && valuePrototype.constructor.name;283 if (typeof className === 'string') {284 const typedArray = value as unknown as285 | Int8Array286 | Uint8Array287 | Uint8ClampedArray288 | Int16Array289 | Uint16Array290 | Int32Array291 | Uint32Array292 | Float32Array293 | Float64Array294 | BigInt64Array295 | BigUint64Array;296 // Warning: typedArray.values() may crash at runtime if type got poisoned297 const valuesFromTypedArr: IterableIterator<bigint | number> = typedArray.values();298 return `${className}.from(${stringifyInternal(299 safeArrayFrom(valuesFromTypedArr),300 currentValues,301 getAsyncContent302 )})`;303 }304 break;305 }306 }307 // default treatment, if none of the above are valid308 try {309 return (value as any).toString();310 } catch {311 return safeToString(value);312 }313}314/**315 * Convert any value to its fast-check string representation316 *317 * @param value - Value to be converted into a string318 *319 * @remarks Since 1.15.0320 * @public321 */322export function stringify<Ts>(value: Ts): string {323 return stringifyInternal(value, [], () => ({ state: 'unknown', value: undefined }));324}325/**326 * Mid-way between stringify and asyncStringify327 *328 * If the value can be stringified in a synchronous way then it returns a string.329 * Otherwise, it tries to go further in investigations and return a Promise<string>.330 *331 * Not publicly exposed yet!332 *333 * @internal334 */335export function possiblyAsyncStringify<Ts>(value: Ts): string | Promise<string> {336 const stillPendingMarker = Symbol();337 const pendingPromisesForCache: Promise<void>[] = [];338 const cache = new Map<unknown, AsyncContent>();339 function createDelay0(): { delay: Promise<typeof stillPendingMarker>; cancel: () => void } {340 let handleId: ReturnType<typeof setTimeout> | null = null;341 const cancel = () => {342 if (handleId !== null) {343 clearTimeout(handleId);344 }345 };346 const delay = new Promise<typeof stillPendingMarker>((resolve) => {347 // setTimeout allows to keep higher priority on any already resolved Promise (or close to)348 // including nested ones like:349 // > (async () => {350 // > await Promise.resolve();351 // > await Promise.resolve();352 // > })()353 handleId = setTimeout(() => {354 handleId = null;355 resolve(stillPendingMarker);356 }, 0);357 });358 return { delay, cancel };359 }360 const unknownState = { state: 'unknown', value: undefined } as const;361 const getAsyncContent = function getAsyncContent(data: Promise<unknown> | WithAsyncToStringMethod): AsyncContent {362 const cacheKey = data;363 if (cache.has(cacheKey)) {364 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion365 return cache.get(cacheKey)!;366 }367 const delay0 = createDelay0();368 const p: Promise<unknown> =369 asyncToStringMethod in data370 ? Promise.resolve().then(() => (data as WithAsyncToStringMethod)[asyncToStringMethod]())371 : (data as Promise<unknown>);372 // eslint-disable-next-line @typescript-eslint/no-empty-function373 p.catch(() => {}); // catching potential errors of p to avoid "Unhandled promise rejection"374 pendingPromisesForCache.push(375 // According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race376 // > If the iterable contains one or more non-promise value and/or an already settled promise,377 // > then Promise.race will resolve to the first of these values found in the iterable.378 Promise.race([p, delay0.delay]).then(379 (successValue) => {380 if (successValue === stillPendingMarker) cache.set(cacheKey, { state: 'pending', value: undefined });381 else cache.set(cacheKey, { state: 'fulfilled', value: successValue });382 delay0.cancel();383 },384 (errorValue) => {385 cache.set(cacheKey, { state: 'rejected', value: errorValue });386 delay0.cancel();387 }388 )389 );390 cache.set(cacheKey, unknownState);391 return unknownState;392 };393 function loop(): string | Promise<string> {394 // Rq.: While this implementation is not optimal in case we have deeply nested Promise395 // a single loop (or two) will must of the time be enough for most of the values.396 // Nested Promise will be a sub-optimal case, but given the fact that it barely never397 // happens in real world, we may pay the cost for it for time to time.398 const stringifiedValue = stringifyInternal(value, [], getAsyncContent);399 if (pendingPromisesForCache.length === 0) {400 return stringifiedValue;401 }402 return Promise.all(pendingPromisesForCache.splice(0)).then(loop);403 }404 return loop();405}406/**407 * Convert any value to its fast-check string representation408 *409 * This asynchronous version is also able to dig into the status of Promise410 *411 * @param value - Value to be converted into a string412 *413 * @remarks Since 2.17.0414 * @public415 */416export async function asyncStringify<Ts>(value: Ts): Promise<string> {417 return Promise.resolve(possiblyAsyncStringify(value));...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unboxedToString } = require('fast-check');2const { unboxedToString: unboxedToString2 } = require('fast-check');3const { unboxedToString: unboxedToString3 } = require('fast-check');4const { unboxedToString: unboxedToString4 } = require('fast-check');5const { unboxedToString: unboxedToString5 } = require('fast-check');6const { unboxedToString: unboxedToString6 } = require('fast-check');7const { unboxedToString: unboxedToString7 } = require('fast-check');8const { unboxedToString: unboxedToString8 } = require('fast-check');9const { unboxedToString: unboxedToString9 } = require('fast-check');10const { unboxedToString: unboxedToString10 } = require('fast-check');11const { unboxedToString: unboxedToString11 } = require('fast-check');12const { unboxedToString: unboxedToString12 } = require('fast-check');13const { unboxedToString: unboxedToString13 } = require('fast-check');14const { unboxedToString: unboxedToString14 } = require('fast-check');15const { unboxedToString: unboxedToString15 } = require('fast-check');16const { unboxedToString: unboxedToString16 } = require('fast-check');17const { unboxedToString: unboxedToString17 } = require('fast-check');18const { unboxedToString: unboxedToString18 } = require('fast-check');19const { unboxedToString: unboxedToString19 } = require('fast-check');20const { unboxedToString: unboxedToString20 } = require('fast-check');21const { unboxedToString: unboxedToString21 } = require('fast-check');22const { unboxedToString: unboxedToString22 } = require('fast-check');23const { unboxedToString: unboxedToString23 } = require('fast-check');24const { unboxedToString: un

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { unboxedToString } = require('fast-check/lib/utils/BoxedValue.js');3const { box } = require('fast-check/lib/utils/BoxedValue.js');4const { unbox } = require('fast-check/lib/utils/BoxedValue.js');5const { stringify } = require('fast-check/lib/utils/BoxedValue.js');6const { stringifyValue } = require('fast-check/lib/utils/BoxedValue.js');7const { stringifyValueWithMaxLength } = require('fast-check/lib/utils/BoxedValue.js');8const { stringifyValueWithMaxLengthAndQuotes } = require('fast-check/lib/utils/BoxedValue.js');9const { stringifyValueWithMaxLengthAndQuotesAndIndent } = require('fast-check/lib/utils/BoxedValue.js');10const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefix } = require('fast-check/lib/utils/BoxedValue.js');11const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffix } = require('fast-check/lib/utils/BoxedValue.js');12const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLine } = require('fast-check/lib/utils/BoxedValue.js');13const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContent } = require('fast-check/lib/utils/BoxedValue.js');14const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContentAndStartOfContent } = require('fast-check/lib/utils/BoxedValue.js');15const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContentAndStartOfContentAndEndOfLine } = require('fast-check/lib/utils/BoxedValue.js');16const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContentAndStartOfContentAndEndOfLineAndStartOfLine } = require('fast-check/lib/utils/BoxedValue.js');17const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContentAndStartOfContentAndEndOfLineAndStartOfLineAndEndOfLine } = require('fast-check/lib/utils/BoxedValue.js');18const { stringifyValueWithMaxLengthAndQuotesAndIndentAndPrefixAndSuffixAndEndOfLineAndEndOfContentAndStartOfContentAndEndOf

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { unboxedToString } = require('fast-check/lib/types/box');3const { box } = require('fast-check/lib/types/box');4fc.assert(5 fc.property(fc.integer(), fc.integer(), (a, b) => {6 return unboxedToString(box(a + b)) === unboxedToString(box(a)) + unboxedToString(box(b));7 })8);9const fc = require('fast-check');10const { unboxedToString } = require('fast-check/lib/types/box');11const { box } = require('fast-check/lib/types/box');12fc.assert(13 fc.property(fc.integer(), fc.integer(), (a, b) => {14 return unboxedToString(box(a + b)) === unboxedToString(box(a)) + unboxedToString(box(b));15 })16);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { unboxedToString } = require('fast-check/lib/types/UnboxedObjectArbitrary');3const arb = fc.record({ a: fc.nat(), b: fc.string() });4const arbUnboxed = arb.map(unboxedToString);5fc.assert(fc.property(arb, (obj) => {6 console.log(obj);7 console.log(typeof obj);8 return true;9}));10fc.assert(fc.property(arbUnboxed, (obj) => {11 console.log(obj);12 console.log(typeof obj);13 return true;14}));15{ a: 0, b: '' }16{ a: 0, b: '' }17{ a: 1, b: '0' }18{ a: 1, b: '0' }19{ a: 2, b: '00' }20{ a: 2, b: '00' }21{ a: 3, b: '000' }22{ a: 3, b: '000' }23{ a: 4, b: '0000' }24{ a: 4, b: '0000' }25{ a: 5, b: '00000' }26{ a: 5, b: '00000' }27{ a: 6, b: '000000' }28{ a: 6, b: '000000' }29{ a: 7, b: '0000000' }30{ a: 7, b: '0000000' }31{ a: 8, b: '00000000' }32{ a: 8, b: '00000000' }33{ a: 9, b: '000000000' }34{ a: 9, b: '000000000' }35{ a: 10, b: '0000000000' }36{ a: 10, b: '0000000000' }37{ a: 11, b: '00000000000' }38{ a: 11, b: '00000000000' }39{ a: 12, b:

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unboxToString } = require("fast-check");2const { fc, testProp } = require("fast-check");3const { unboxToString: unboxToString2 } = require("fast-check/lib/types/property/UnboxedValue");4const { unboxToString: unboxToString3 } = require("fast-check/lib/types/property/UnboxedValue");5testProp("unboxToString test", [fc.string()], (s) => {6 console.log(unboxToString(s));7 console.log(unboxToString2(s));8 console.log(unboxToString3(s));9 return true;10});11- [Fast-check](

Full Screen

Using AI Code Generation

copy

Full Screen

1import { unboxedToString } from 'fast-check';2import * as fc from 'fast-check';3import * as assert from 'assert';4const test = fc.property(5 fc.integer(1, 1000),6 (n) => {7 const str = fc.string({ minLength: n, maxLength: n });8 console.log(str);9 const strLength = unboxedToString(str);10 console.log(strLength);11 assert.strictEqual(strLength, n);12 }13);14fc.assert(test, { numRuns: 100 });

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