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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797 |
x60
x60
x60
x60
x60
x620
x620
x620
x620
x781
x922
x922
x781
x801
x801
x801
x781
x620
x620
x620
x620
x2480
x620
x60
x88
x88
x90
x90
x88
x145
x145
x148
x148
x145
x147
x147
x145
x60
x60
x356
x622
x622
x622
x881
x881
x622
x356
x357
x357
x651
x3784
x946
x958
x958
x958
x946
x1110
x1110
x946
x990
x990
x946
x1094
x1094
x946
x356
x60
x60
x66
x72
x66
x60
x60
x71
x82
x246
x82
x86
x86
x71
x60
x60
x76
x76
x92
x76
x60
x60
x66
x67
x67
x71
x71
x71
x71
x71
x71
x71
x76
x71
x60
x60
x72
x72
x72
x72
x76
x76
x72
x84
x88
x88
x72
x60
x60
x64
x65
x65
x67
x67
x67
x201
x64
x264
x66
x60
x60
x64
x68
x68
x68
x70
x70
x64
x60
x60
x78
x288
x96
x96
x97
x97
x113
x78
x60
x60
x70
x80
x80
x82
x82
x88
x88
x88
x88
x88
x88
x88
x70
x60
x60
x65
x210
x70
x70
x71
x71
x74
x65
x60
x60
x68
x76
x76
x76
x78
x78
x68
x60
x60
x64
x68
x64
x60
x60
x64
x68
x64
x60
x60
x64
x68
x64
x60
x60
x68
x76
x76
x68
x60
x60
x72
x84
x252
x72
x60
x60
x64
x68
x68
x340
x64
x60
x60
x64
x68
x340
x64
x60
x60
x65
x210
x65
x60
x60
x70
x80
x80
x80
x80
x80
x80
x70
x60
x60
x66
x72
x72
x66
x60
x60
x64
x68
x68
x68
x70
x70
x64
x60
x60
x66
x72
x72
x72
x66
x60
x60
x66
x72
x66
x60
x60
x64
x68
x68
x68
x70
x70
x64
x60
x60
x110
x160
x161
x161
x209
x209
x209
x209
x160
x160
x180
x180
x180
x160
x160
x168
x168
x168
x160
x160
x164
x164
x164
x160
x160
x164
x164
x164
x160
x160
x164
x164
x164
x329
x507
x169
x169
x169
x160
x209
x160
x172
x172
x160
x184
x184
x160
x209
x209
x110
x60
x60
x75
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x90
x101
x101
x102
x102
x109
x109
x90
x92
x92
x92
x91
x75
x60
x60
x68
x76
x68
x60
x60
x68
x76
x76
x80
x80
x68
x60
x60
x68
x76
x76
x80
x80
x68
x68
x60
x60
x62
x62
x63
x63
x63
x62
x60
x63
x63
x64
x64
x65
x63
x60
x60
|
I
|
import { type Async, expect as _expect, type Expected, fn } from "@std/expect"
import { assert, assertEquals, AssertionError, assertIsError, assertMatch, assertNotEquals, assertNotStrictEquals, assertObjectMatch, assertStrictEquals } from "@std/assert"
import { assertConsoleSnapshot } from "./assert.ts"
import type { Arg, Arrayable, Callback, Nullable, Promisable, TypeOfEnum } from "@libs/typing"
import type { testing } from "./test.ts"
import { STATUS_CODE as Status } from "@std/http/status"
export interface ExtendedExpected<IsAsync = false> extends Expected<IsAsync> {
toThrow: <E extends Error = Error>(error?: string | RegExp | E | (new (...args: any[]) => E), message?: string | RegExp) => void
toSatisfy: (evaluate: Callback) => unknown
toBeType: (type: string, options?: { nullable?: boolean }) => unknown
toHaveSize: (size: number) => unknown
toBeResolvedPromise: () => Promise<unknown>
toMatchConsoleSnapshot: (meta: ImportMeta, options: { capture?: boolean }) => Promise<unknown>
toHaveBeenCalledOnceWith(...expected: unknown[]): unknown
toBeStructuredClonable: () => unknown
toHaveDescribedProperty: (key: PropertyKey, expected: PropertyDescriptor) => unknown
toHaveImmutableProperty: (key: PropertyKey, testValue?: unknown) => unknown
toHaveEnumerableProperty: (key: PropertyKey) => unknown
toBeIterable: () => unknown
toBeSealed: () => unknown
toBeFrozen: () => unknown
toBeExtensible: () => unknown
toBeShallowCopyOf: (expected?: Iterable<unknown> | Record<PropertyKey, unknown>) => unknown
toBeEmpty: () => unknown
toBeSorted: (compare?: Arg<Array<unknown>["sort"]>) => unknown
toBeReverseSorted: (compare?: Arg<Array<unknown>["sort"]>) => unknown
toBeOneOf: (values: Iterable<unknown>) => unknown
toBeWithin: (range: [number, number], exclusive?: boolean) => unknown
toBeFinite: () => unknown
toBeParseableJSON: (reviver?: Arg<JSON["parse"], 1>) => unknown
toBeEmail(): () => unknown
toBeUrl(): () => unknown
toBeBase64: () => unknown
toRespondWithStatus: (status: Arrayable<number> | "informational" | "1XX" | "successful" | "2XX" | "redirect" | "3XX" | "client_error" | "4XX" | "server_error" | "5XX") => unknown
toBeHashed: (algorithm: string) => unknown
toBeDate: () => unknown
toBePast: (date?: number | string | Date) => unknown
toBeFuture: (date?: number | string | Date) => unknown
not: IsAsync extends true ? Async<ExtendedExpected<true>> : ExtendedExpected<false>
resolves: Async<ExtendedExpected<true>>
rejects: Async<ExtendedExpected<true>>
}
function process(not: boolean, evaluate: Callback, message = ""): { message: () => string; pass: boolean } {
let pass = true
try {
evaluate()
} catch (error) {
if (error.name === AssertionError.name) {
pass = false
message += message ? `${error.message.charAt(0).toLocaleLowerCase()}${error.message.substring(1)}` : error.message
} else {
pass = not
message = error.message
}
}
message = message
.replaceAll("{!NOT} ", not ? "NOT " : "")
.replaceAll("{NOT} ", not ? "" : "NOT")
.replace(/,\s*$/, "").trim()
return { message: () => message, pass }
}
function isIterable(value: testing): asserts value is Iterable<unknown> {
assertNotEquals(value, null)
if (typeof value[Symbol.iterator] !== "function") {
throw new TypeError("Value is not iterable")
}
}
function isType(value: testing, type: "string"): asserts value is string
function isType(value: testing, type: "number"): asserts value is number
function isType(value: testing, type: "bigint"): asserts value is bigint
function isType(value: testing, type: "boolean"): asserts value is boolean
function isType(value: testing, type: "symbol"): asserts value is symbol
function isType(value: testing, type: "undefined"): asserts value is undefined
function isType(value: testing, type: "object", options?: { nullable: true }): asserts value is Nullable<Record<PropertyKey, unknown>>
function isType(value: testing, type: "object", options: { nullable: false }): asserts value is Record<PropertyKey, unknown>
function isType(value: testing, type: "function"): asserts value is Callback
function isType(value: testing, type: TypeOfEnum, { nullable = false } = {}) {
if ((typeof value) !== type) {
throw new TypeError(`Value is not of type "${type}"`)
}
if ((!nullable) && (type === "object") && (value === null)) {
throw new TypeError(`Value is null`)
}
}
_expect.extend({
toThrow(context, error, message) {
type ErrorConstructor = new (...args: any[]) => Error
if (typeof context.value === "function") {
try {
context.value = context.value()
} catch (error) {
context.value = error
}
}
if ((message !== undefined) && ((typeof error === "string") || (error instanceof RegExp))) {
throw new TypeError("First argument must be an Error class or instance when second argument is a string or RegExp")
}
return process(context.isNot, () => {
const expect = { class: undefined as ErrorConstructor | undefined, message: undefined as string | RegExp | undefined }
if (error instanceof Error) {
expect.class = error.constructor as ErrorConstructor
expect.message = error.message
}
if (error instanceof Function) {
expect.class = error as ErrorConstructor
}
if ((typeof error === "string") || (error instanceof RegExp)) {
expect.message = error
}
if (message) {
expect.message = message
}
assertIsError(context.value, expect.class, expect.message)
}, context.isNot ? `Expected to NOT throw ${error}` : "")
},
toSatisfy(context, predicate) {
return process(context.isNot, () => {
assert(predicate(context.value))
}, "Expected value to {!NOT} satisfy predicate")
},
toBeType(context, type, { nullable = false } = {}) {
return process(context.isNot, () => {
try {
isType(context.value, type, { nullable })
} catch (error) {
throw new AssertionError(error.message)
}
}, `Expected value to {!NOT} be of type "${type}"${!nullable ? " and not null but " : ""}`)
},
toHaveSize(context, size) {
const actual = (context.value as { size: number })?.size
return process(context.isNot, () => {
assert(actual === size)
}, `Expected value to {!NOT} have size ${size}${size !== actual ? `: the value has size ${actual}` : ""}`)
},
async toBeResolvedPromise(context) {
if (!(context.value instanceof Promise)) {
throw new TypeError("Expected value to be a promise")
}
const test = new Promise<void>((resolve) => setTimeout(resolve, 0))
const status = await Promise.race([
context.value.then(() => "resolved"),
test.then(() => "pending"),
])
await test
return process(context.isNot, () => {
assert(status === "resolved")
}, "Expected value to {!NOT} be resolved")
},
async toMatchConsoleSnapshot(context, meta, options) {
if (typeof context.value !== "function") {
throw new TypeError("Expected value to be a function")
}
let error = null
try {
await assertConsoleSnapshot(meta, context.value as () => Promisable<unknown>, options)
} catch (_) {
error = _
}
return process(context.isNot, () => {
if (error) {
throw error
}
}, "Expected console output to {!NOT} match snapshot")
},
toHaveBeenCalledOnceWith(context, ...args) {
if (context.isNot) {
throw new TypeError("`.not` modifier is not supported for this matcher")
}
try {
_expect(context.value).toHaveBeenCalledTimes(1)
_expect(context.value).toHaveBeenCalledWith(...args)
return { message: () => "", pass: true }
} catch (error) {
return { message: () => error.message, pass: false }
}
},
toBeStructuredClonable(context) {
return process(context.isNot, () => {
try {
structuredClone(context.value)
} catch (error) {
throw new AssertionError(error.message)
}
}, "Expected value to {!NOT} be structured clonable")
},
toHaveDescribedProperty(context, key, expected) {
return process(context.isNot, () => {
isType(context.value, "object", { nullable: false })
const descriptor = Object.getOwnPropertyDescriptor(context.value, key)
if (!descriptor) {
throw new ReferenceError(`Property "${String(key)}" does not exist on object`)
}
assertObjectMatch(descriptor, expected)
}, `Property "${String(key)}" does {!NOT} match provided descriptor, `)
},
toHaveImmutableProperty(context, key, testValue = Symbol()) {
return process(context.isNot, () => {
const value = context.value as Nullable<Record<PropertyKey, unknown>>
if ((value === null) || ((typeof value !== "function") && (typeof value !== "object"))) {
throw new TypeError("Cannot be processed as value is not indexed")
}
const current = value[key]
try {
value[key] = testValue
assertStrictEquals(value[key], current)
} finally {
value[key] = current
}
}, `Expected property "${String(key)}" to {!NOT} be immutable, previous and current `)
},
toHaveEnumerableProperty(context, key) {
return process(context.isNot, () => {
isType(context.value, "object", { nullable: false })
const descriptor = Object.getOwnPropertyDescriptor(context.value, key)
if (!descriptor) {
throw new ReferenceError(`Property "${String(key)}" does not exist on object`)
}
assert(descriptor.enumerable, `Property "${String(key)}" is not enumerable`)
}, `Expected property "${String(key)}" to {!NOT} be enumerable, `)
},
toBeIterable(context) {
return process(context.isNot, () => {
try {
isIterable(context.value)
} catch (error) {
throw new AssertionError(error.message)
}
}, `Expected value to {!NOT} be iterable, `)
},
toBeSealed(context) {
return process(context.isNot, () => {
assert(Object.isSealed(context.value))
}, `Expected value to {!NOT} be sealed`)
},
toBeFrozen(context) {
return process(context.isNot, () => {
assert(Object.isFrozen(context.value))
}, `Expected value to {!NOT} be frozen`)
},
toBeExtensible(context) {
return process(context.isNot, () => {
assert(Object.isExtensible(context.value))
}, `Expected value to {!NOT} be extensible`)
},
toBeShallowCopyOf(context, expected) {
return process(context.isNot, () => {
assertEquals(context.value, expected)
assertNotStrictEquals(context.value, expected, `Detected same-reference`)
}, `Expected value to {!NOT} be a shallow copy, `)
},
toBeEmpty(context) {
return process(context.isNot, () => {
isIterable(context.value)
assertStrictEquals([...context.value].length, 0)
}, `Expected value to {!NOT} be empty, `)
},
toBeSorted(context, compare) {
return process(context.isNot, () => {
const value = context.value
isIterable(value)
assertEquals([...value], [...value].sort(compare))
}, `Expected value to {!NOT} be sorted, `)
},
toBeReverseSorted(context, compare) {
return process(context.isNot, () => {
isIterable(context.value)
assertEquals([...context.value], [...context.value].sort(compare).reverse())
}, `Expected value to {!NOT} be reverse sorted, `)
},
toBeOneOf(context, values) {
return process(context.isNot, () => {
assert([...values].includes(context.value))
}, `Expected value "${context.value}" to {!NOT} be one of expected values`)
},
toBeWithin(context, range, exclusive) {
return process(context.isNot, () => {
const value = context.value
const [min, max] = range
isType(value, "number")
isType(min, "number")
isType(max, "number")
exclusive ? assert(value > min && value < max) : assert(value >= min && value <= max)
}, `Expected value to {!NOT} be within range ${exclusive ? `]${range[0]}, ${range[1]}[` : `[${range[0]}, ${range[1]}]`}, `)
},
toBeFinite(context) {
return process(context.isNot, () => {
isType(context.value, "number")
assert(Number.isFinite(context.value))
}, `Expected value to {!NOT} be finite, `)
},
toBeParseableJSON(context, reviver) {
return process(context.isNot, () => {
try {
JSON.parse(`${context.value}`, reviver)
} catch (error) {
throw new AssertionError(error.message)
}
}, `Expected value to {!NOT} be parseable JSON, `)
},
toBeEmail(context) {
return process(context.isNot, () => {
assertMatch(
`${context.value}`,
/(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?: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\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*))*)?;\s*)/,
)
}, `Expected "${context.value}" to {!NOT} be a valid email`)
},
toBeUrl(context) {
return process(context.isNot, () => {
assert(URL.canParse(`${context.value}`))
}, `Expected "${context.value}" to {!NOT} be a valid URL`)
},
toBeBase64(context) {
return process(context.isNot, () => {
try {
atob(`${context.value}`)
} catch (error) {
throw new AssertionError(error.message)
}
}, `Expected "${context.value}" to {!NOT} be a valid base64 string`)
},
toRespondWithStatus(context, code) {
return process(context.isNot, () => {
if (!(context.value instanceof Response)) {
throw new TypeError("Value is not a Response object")
}
let ok = false
let message = ""
const status = context.value.status
switch (code) {
case "1XX":
case "informational":
ok = status >= 100 && status < 200
message = `"${code}" (100-199) but got ${status}`
break
case "2XX":
case "successful":
ok = status >= 200 && status < 300
message = `"${code}" (200-299) but got ${status}`
break
case "3XX":
case "redirect":
ok = status >= 300 && status < 400
message = `"${code}" (300-399) but got ${status}`
break
case "4XX":
case "client_error":
ok = status >= 400 && status < 500
message = `"${code}" (400-499) but got ${status}`
break
case "5XX":
case "server_error":
ok = status >= 500 && status < 600
message = `"${code}" (500-599) but got ${status}`
break
default: {
const codes = [code].flat()
ok = codes.includes(status)
message = `[${codes.join(", ")}] but got ${status}`
}
}
try {
if ((context.isNot) && (ok === context.isNot)) {
throw new TypeError(`Expected response status to {!NOT} be ${message}`)
}
if ((context.isNot) || (ok === context.isNot)) {
throw new AssertionError(`Expected response status to {!NOT} be ${message}`)
}
} finally {
context.value.body?.cancel()
}
})
},
toBeHashed(context, algorithm) {
return process(context.isNot, () => {
isType(context.value, "string")
algorithm = algorithm.toLocaleLowerCase().replace("-", "")
const algorithms = {
"bcrypt": 0,
"md5": 32,
"sha0": 40,
"sha1": 40,
"sha224": 56,
"sha256": 64,
"sha384": 96,
"sha512": 128,
"sha512/224": 56,
"sha512/256": 64,
} as Record<PropertyKey, number>
if (algorithms[algorithm]) {
assertStrictEquals(context.value.length, algorithms[algorithm])
if (!/^[a-z0-9]+$/i.test(context.value)) {
throw new TypeError("Value contains non-hexadecimal characters")
}
return
}
if (algorithm === "bcrypt") {
assertMatch(context.value, /^\$2[aby]?\$\d{2}\$[./A-Za-z0-9]{53}$/)
return
}
throw new RangeError(`Algorithm "${algorithm}" is unknown`)
}, `Expected value to {!NOT} be hashed by ${algorithm}, `)
},
toBeDate(context) {
return process(context.isNot, () => {
assert(Number.isFinite(new Date(context.value as number | string | Date).getTime()))
}, `Expected value to {!NOT} be a date, `)
},
toBePast(context, ref = new Date()) {
return process(context.isNot, () => {
const date = new Date(context.value as number | string | Date)
if (date > ref) {
throw new AssertionError(`${date.toISOString()} is after ${ref.toISOString()}`)
}
}, `Expected value to {!NOT} be in the past, `)
},
toBeFuture(context, ref = new Date()) {
return process(context.isNot, () => {
const date = new Date(context.value as number | string | Date)
if (date < ref) {
throw new AssertionError(`${date.toISOString()} is before ${ref.toISOString()}`)
}
}, `Expected value to {!NOT} be in the future, `)
},
})
export function reset(fn: any) {
const info = fn?.[Symbol.for("@MOCK")]
if (!info) {
throw new Error("Received function must be a mock or spy function")
}
info.calls.length = 0
}
export type MockCall = {
args: any[]
context?: any
returned?: any
thrown?: any
timestamp: number
returns: boolean
throws: boolean
}
export function calls(fn: any): MockCall[] {
const info = fn?.[Symbol.for("@MOCK")]
if (!info) {
throw new Error("Received function must be a mock or spy function")
}
return info.calls
}
const expect = _expect as unknown as ((...args: Parameters<typeof _expect>) => ExtendedExpected) & { [K in keyof typeof _expect]: typeof _expect[K] }
export { AssertionError, expect, fn, Status }
export type { _expect, Arg, Arrayable, Async, Callback, Expected, Nullable, TypeOfEnum }
|