deno.land / std@0.91.0 / testing / asserts.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.// This module is browser compatible. Do not rely on good formatting of values// for AssertionError messages in browsers.
import { bold, gray, green, red, stripColor, white } from "../fmt/colors.ts";import { diff, DiffResult, DiffType } from "./_diff.ts";
const CAN_NOT_DISPLAY = "[Cannot display]";
interface Constructor { // deno-lint-ignore no-explicit-any new (...args: any[]): any;}
export class AssertionError extends Error { constructor(message: string) { super(message); this.name = "AssertionError"; }}
/** * Converts the input into a string. Objects, Sets and Maps are sorted so as to * make tests less flaky * @param v Value to be formatted */export function _format(v: unknown): string { return globalThis.Deno ? Deno.inspect(v, { depth: Infinity, sorted: true, trailingComma: true, compact: false, iterableLimit: Infinity, }) : `"${String(v).replace(/(?=["\\])/g, "\\")}"`;}
/** * Colors the output of assertion diffs * @param diffType Difference type, either added or removed */function createColor(diffType: DiffType): (s: string) => string { switch (diffType) { case DiffType.added: return (s: string): string => green(bold(s)); case DiffType.removed: return (s: string): string => red(bold(s)); default: return white; }}
/** * Prefixes `+` or `-` in diff output * @param diffType Difference type, either added or removed */function createSign(diffType: DiffType): string { switch (diffType) { case DiffType.added: return "+ "; case DiffType.removed: return "- "; default: return " "; }}
function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] { const messages: string[] = []; messages.push(""); messages.push(""); messages.push( ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${ green(bold("Expected")) }`, ); messages.push(""); messages.push(""); diffResult.forEach((result: DiffResult<string>): void => { const c = createColor(result.type); messages.push(c(`${createSign(result.type)}${result.value}`)); }); messages.push("");
return messages;}
function isKeyedCollection(x: unknown): x is Set<unknown> { return [Symbol.iterator, "size"].every((k) => k in (x as Set<unknown>));}
/** * Deep equality comparison used in assertions * @param c actual value * @param d expected value */export function equal(c: unknown, d: unknown): boolean { const seen = new Map(); return (function compare(a: unknown, b: unknown): boolean { // Have to render RegExp & Date for string comparison // unless it's mistreated as object if ( a && b && ((a instanceof RegExp && b instanceof RegExp) || (a instanceof URL && b instanceof URL)) ) { return String(a) === String(b); } if (a instanceof Date && b instanceof Date) { const aTime = a.getTime(); const bTime = b.getTime(); // Check for NaN equality manually since NaN is not // equal to itself. if (Number.isNaN(aTime) && Number.isNaN(bTime)) { return true; } return a.getTime() === b.getTime(); } if (Object.is(a, b)) { return true; } if (a && typeof a === "object" && b && typeof b === "object") { if (seen.get(a) === b) { return true; } if (Object.keys(a || {}).length !== Object.keys(b || {}).length) { return false; } if (isKeyedCollection(a) && isKeyedCollection(b)) { if (a.size !== b.size) { return false; }
let unmatchedEntries = a.size;
for (const [aKey, aValue] of a.entries()) { for (const [bKey, bValue] of b.entries()) { /* Given that Map keys can be references, we need * to ensure that they are also deeply equal */ if ( (aKey === aValue && bKey === bValue && compare(aKey, bKey)) || (compare(aKey, bKey) && compare(aValue, bValue)) ) { unmatchedEntries--; } } }
return unmatchedEntries === 0; } const merged = { ...a, ...b }; for ( const key of [ ...Object.getOwnPropertyNames(merged), ...Object.getOwnPropertySymbols(merged), ] ) { type Key = keyof typeof merged; if (!compare(a && a[key as Key], b && b[key as Key])) { return false; } } seen.set(a, b); return true; } return false; })(c, d);}
/** Make an assertion, error will be thrown if `expr` does not have truthy value. */export function assert(expr: unknown, msg = ""): asserts expr { if (!expr) { throw new AssertionError(msg); }}
/** * Make an assertion that `actual` and `expected` are equal, deeply. If not * deeply equal, then throw. * * Type parameter can be specified to ensure values under comparison have the same type. * For example: *```ts *assertEquals<number>(1, 2) *``` */export function assertEquals( actual: unknown, expected: unknown, msg?: string,): void;export function assertEquals<T>(actual: T, expected: T, msg?: string): void;export function assertEquals( actual: unknown, expected: unknown, msg?: string,): void { if (equal(actual, expected)) { return; } let message = ""; const actualString = _format(actual); const expectedString = _format(expected); try { const diffResult = diff( actualString.split("\n"), expectedString.split("\n"), ); const diffMsg = buildMessage(diffResult).join("\n"); message = `Values are not equal:\n${diffMsg}`; } catch { message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; } if (msg) { message = msg; } throw new AssertionError(message);}
/** * Make an assertion that `actual` and `expected` are not equal, deeply. * If not then throw. * * Type parameter can be specified to ensure values under comparison have the same type. * For example: *```ts *assertNotEquals<number>(1, 2) *``` */export function assertNotEquals( actual: unknown, expected: unknown, msg?: string,): void;export function assertNotEquals<T>(actual: T, expected: T, msg?: string): void;export function assertNotEquals( actual: unknown, expected: unknown, msg?: string,): void { if (!equal(actual, expected)) { return; } let actualString: string; let expectedString: string; try { actualString = String(actual); } catch { actualString = "[Cannot display]"; } try { expectedString = String(expected); } catch { expectedString = "[Cannot display]"; } if (!msg) { msg = `actual: ${actualString} expected: ${expectedString}`; } throw new AssertionError(msg);}
/** * Make an assertion that `actual` and `expected` are strictly equal. If * not then throw. * ```ts * assertStrictEquals(1, 2) * ``` */export function assertStrictEquals( actual: unknown, expected: unknown, msg?: string,): void;export function assertStrictEquals<T>( actual: T, expected: T, msg?: string,): void;export function assertStrictEquals( actual: unknown, expected: unknown, msg?: string,): void { if (actual === expected) { return; }
let message: string;
if (msg) { message = msg; } else { const actualString = _format(actual); const expectedString = _format(expected);
if (actualString === expectedString) { const withOffset = actualString .split("\n") .map((l) => ` ${l}`) .join("\n"); message = `Values have the same structure but are not reference-equal:\n\n${ red(withOffset) }\n`; } else { try { const diffResult = diff( actualString.split("\n"), expectedString.split("\n"), ); const diffMsg = buildMessage(diffResult).join("\n"); message = `Values are not strictly equal:\n${diffMsg}`; } catch { message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; } } }
throw new AssertionError(message);}
/** * Make an assertion that `actual` and `expected` are not strictly equal. * If the values are strictly equal then throw. * ```ts * assertNotStrictEquals(1, 1) * ``` */export function assertNotStrictEquals( actual: unknown, expected: unknown, msg?: string,): void;export function assertNotStrictEquals<T>( actual: T, expected: T, msg?: string,): void;export function assertNotStrictEquals( actual: unknown, expected: unknown, msg?: string,): void { if (actual !== expected) { return; }
throw new AssertionError( msg ?? `Expected "actual" to be strictly unequal to: ${_format(actual)}\n`, );}
/** * Make an assertion that actual is not null or undefined. If not * then thrown. */export function assertExists( actual: unknown, msg?: string,): void { if (actual === undefined || actual === null) { if (!msg) { msg = `actual: "${actual}" expected to match anything but null or undefined`; } throw new AssertionError(msg); }}
/** * Make an assertion that actual includes expected. If not * then thrown. */export function assertStringIncludes( actual: string, expected: string, msg?: string,): void { if (!actual.includes(expected)) { if (!msg) { msg = `actual: "${actual}" expected to contain: "${expected}"`; } throw new AssertionError(msg); }}
/** * Make an assertion that `actual` includes the `expected` values. * If not then an error will be thrown. * * Type parameter can be specified to ensure values under comparison have the same type. * For example: *```ts *assertArrayIncludes<number>([1, 2], [2]) *``` */export function assertArrayIncludes( actual: ArrayLike<unknown>, expected: ArrayLike<unknown>, msg?: string,): void;export function assertArrayIncludes<T>( actual: ArrayLike<T>, expected: ArrayLike<T>, msg?: string,): void;export function assertArrayIncludes( actual: ArrayLike<unknown>, expected: ArrayLike<unknown>, msg?: string,): void { const missing: unknown[] = []; for (let i = 0; i < expected.length; i++) { let found = false; for (let j = 0; j < actual.length; j++) { if (equal(expected[i], actual[j])) { found = true; break; } } if (!found) { missing.push(expected[i]); } } if (missing.length === 0) { return; } if (!msg) { msg = `actual: "${_format(actual)}" expected to include: "${ _format(expected) }"\nmissing: ${_format(missing)}`; } throw new AssertionError(msg);}
/** * Make an assertion that `actual` match RegExp `expected`. If not * then thrown */export function assertMatch( actual: string, expected: RegExp, msg?: string,): void { if (!expected.test(actual)) { if (!msg) { msg = `actual: "${actual}" expected to match: "${expected}"`; } throw new AssertionError(msg); }}
/** * Make an assertion that `actual` not match RegExp `expected`. If match * then thrown */export function assertNotMatch( actual: string, expected: RegExp, msg?: string,): void { if (expected.test(actual)) { if (!msg) { msg = `actual: "${actual}" expected to not match: "${expected}"`; } throw new AssertionError(msg); }}
/** * Make an assertion that `actual` object is a subset of `expected` object, deeply. * If not, then throw. */export function assertObjectMatch( actual: Record<PropertyKey, unknown>, expected: Record<PropertyKey, unknown>,): void { type loose = Record<PropertyKey, unknown>; const seen = new WeakMap(); return assertEquals( (function filter(a: loose, b: loose): loose { // Prevent infinite loop with circular references with same filter if ((seen.has(a)) && (seen.get(a) === b)) { return a; } seen.set(a, b); // Filter keys and symbols which are present in both actual and expected const filtered = {} as loose; const entries = [ ...Object.getOwnPropertyNames(a), ...Object.getOwnPropertySymbols(a), ] .filter((key) => key in b) .map((key) => [key, a[key as string]]) as Array<[string, unknown]>; // Build filtered object and filter recursively on nested objects references for (const [key, value] of entries) { if (typeof value === "object") { const subset = (b as loose)[key]; if ((typeof subset === "object") && (subset)) { filtered[key] = filter(value as loose, subset as loose); continue; } } filtered[key] = value; } return filtered; })(actual, expected), expected, );}
/** * Forcefully throws a failed assertion */export function fail(msg?: string): void { // eslint-disable-next-line @typescript-eslint/no-use-before-define assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`);}
/** * Executes a function, expecting it to throw. If it does not, then it * throws. An error class and a string that should be included in the * error message can also be asserted. */export function assertThrows<T = void>( fn: () => T, ErrorClass?: Constructor, msgIncludes = "", msg?: string,): Error { let doesThrow = false; let error = null; try { fn(); } catch (e) { if (e instanceof Error === false) { throw new AssertionError("A non-Error object was thrown."); } if (ErrorClass && !(e instanceof ErrorClass)) { msg = `Expected error to be instance of "${ErrorClass.name}", but was "${e.constructor.name}"${ msg ? `: ${msg}` : "." }`; throw new AssertionError(msg); } if ( msgIncludes && !stripColor(e.message).includes(stripColor(msgIncludes)) ) { msg = `Expected error message to include "${msgIncludes}", but got "${e.message}"${ msg ? `: ${msg}` : "." }`; throw new AssertionError(msg); } doesThrow = true; error = e; } if (!doesThrow) { msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; throw new AssertionError(msg); } return error;}
/** * Executes a function which returns a promise, expecting it to throw or reject. * If it does not, then it throws. An error class and a string that should be * included in the error message can also be asserted. */export async function assertThrowsAsync<T = void>( fn: () => Promise<T>, ErrorClass?: Constructor, msgIncludes = "", msg?: string,): Promise<Error> { let doesThrow = false; let error = null; try { await fn(); } catch (e) { if (e instanceof Error === false) { throw new AssertionError("A non-Error object was thrown or rejected."); } if (ErrorClass && !(e instanceof ErrorClass)) { msg = `Expected error to be instance of "${ErrorClass.name}", but got "${e.name}"${ msg ? `: ${msg}` : "." }`; throw new AssertionError(msg); } if ( msgIncludes && !stripColor(e.message).includes(stripColor(msgIncludes)) ) { msg = `Expected error message to include "${msgIncludes}", but got "${e.message}"${ msg ? `: ${msg}` : "." }`; throw new AssertionError(msg); } doesThrow = true; error = e; } if (!doesThrow) { msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; throw new AssertionError(msg); } return error;}
/** Use this to stub out methods that will throw when invoked. */export function unimplemented(msg?: string): never { throw new AssertionError(msg || "unimplemented");}
/** Use this to assert unreachable code. */export function unreachable(): never { throw new AssertionError("unreachable");}
std

Version Info

Tagged at
3 years ago

External Dependencies

No external dependencies 🎉