-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest.mjs
901 lines (747 loc) · 26 KB
/
test.mjs
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
import * as l from './lang.mjs'
import * as cli from './cli.mjs'
/*
Base error class used by this module. Allows to differentiate errors generated
by test utils from errors generated by functions being tested.
*/
export class AssertError extends Error {
get name() {return this.constructor.name}
}
export class InternalError extends AssertError {}
/*
Describes a single test or benchmark run. All runs must have names. We recommend
using unique names but don't enforce uniqueness. Tests receive `Run` as an
input, and may use it for introspection, for example to test timing.
Leaves generation of timestamps and calculation of averages up to runners.
This makes it possible to implement runners that use different performance
APIs such as standard `performance.now` vs Node `process.hrtime`, or fudge
the averages.
*/
export class Run extends l.Emp {
constructor(name, parent) {
if (!l.reqStr(name)) throw new SyntaxError(`missing run name`)
super()
this.name = name
this.parent = l.optInst(parent, Run)
}
#runs = 0
get runs() {return this.#runs}
set runs(val) {this.#runs = l.reqIntPos(val)}
#start = NaN
get start() {return this.#start}
set start(val) {this.#start = l.reqFinPos(val)}
#end = NaN
get end() {return this.#end}
set end(val) {this.#end = l.reqFinPos(val)}
#avg = NaN
get avg() {return this.#avg}
set avg(val) {this.#avg = l.reqFin(val)}
root() {return this.parent?.root() ?? this}
level() {return (this.parent?.level() + 1) | 0}
time() {return this.end - this.start}
elapsed() {return (l.onlyFin(this.end) ?? now()) - this.start}
done(end, runs) {
this.end = end
this.runs = runs
this.avg = this.time() / this.runs
}
reset() {
this.#runs = 0
this.#start = NaN
this.#end = NaN
this.#avg = NaN
}
reqDone() {
const {name, runs, end, avg} = this
if (!l.isIntPos(runs)) {
throw new InternalError(`internal error: expected run ${l.show(name)} to have at least 1 run, got ${l.show(runs)} runs`)
}
if (!l.isFinPos(end)) {
throw new InternalError(`internal error: expected run ${l.show(name)} to have an end time, found ${l.show(end)}`)
}
if (!l.isFin(avg)) {
throw new InternalError(`internal error: expected run ${l.show(name)} to have an average time, found ${l.show(avg)}`)
}
}
// Inverse of `toFilter`. TODO symmetric naming.
nameFull() {
const name = l.reqStr(this.name)
const parent = this.parent
return parent ? (l.reqStr(parent.nameFull()) + `/` + name) : name
}
allow(filter) {
return (
this.constructor.allow(filter, this.name, this.level()) &&
(this.parent?.allow(filter) ?? true)
)
}
static allow(filter, name, level) {
l.optArr(filter)
l.reqStr(name)
level = l.laxNat(level)
return l.optReg(filter?.[level])?.test(name) ?? true
}
}
export class FinRunner extends Number {
constructor(val) {super(l.reqFin(val))}
run() {throw new AssertError(`must be implemented in subclass`)}
static default() {return new this(this.defaultSize)}
static defaultSize = 0
static defaultWarmup() {return new this(this.defaultWarmupSize)}
static defaultWarmupSize = 1
static warmup() {
/*
Note: subclasses require their own warmup and thus their own property. A
regular static property would be automatically shared between super- and
sub-classes. We must get and set it on each class separately.
Reentrant calls are allowed, as nops, because this method is called by
runner instances DURING the warmup.
*/
if (l.hasOwn(this, `warm`)) return
this.warm = false
// Must pass different functions for deoptimization.
this.defaultWarmup().run(function warmup0() {}, new Run(`warmup_${this.name}_0`))
this.defaultWarmup().run(function warmup1() {}, new Run(`warmup_${this.name}_1`))
this.defaultWarmup().run(function warmup2() {}, new Run(`warmup_${this.name}_2`))
this.defaultWarmup().run(function warmup3() {}, new Run(`warmup_${this.name}_3`))
this.nowAvg = l.req(nowAvg(), l.isFinPos)
const run = new Run(`overhead_${this.name}`)
this.defaultWarmup().run(function overhead() {}, run)
this.overhead = l.req(run.avg, l.isFinPos)
this.warm = true
conf.verbLog(`[warmup] warmed up ${this.name}`)
}
static getOverhead() {return l.hasOwn(this, `overhead`) ? this.overhead : 0}
static getNowAvg() {return l.hasOwn(this, `nowAvg`) ? this.nowAvg : nowAvg(1024)}
}
/*
Runs a benchmark for N amount of runs, recording the timing. Passes the current
run to the given benchmark function.
*/
export class CountRunner extends FinRunner {
constructor(runs) {super(l.reqIntPos(runs))}
run(fun, run) {
this.constructor.warmup()
const nowAvg = this.constructor.getNowAvg()
let runs = 0
const thresh = this.valueOf()
const start = run.start = now()
do {fun()} while (++runs < thresh)
const end = run.end = now()
run.runs = runs
run.avg = ((end - start - nowAvg) / runs) - this.constructor.getOverhead()
conf.verbLog(`[${run.name}] runs: ${runs}, runtime: ${tsMilli(end - start)}, nowAvg: ${tsNano(nowAvg)} avg: ${tsNano(run.avg)}`)
}
static defaultSize = 1024
static defaultWarmupSize = 2 << 24
}
/*
Runs a benchmark for approximately N amount of milliseconds (no more than twice
that amount), recording the number of runs and the timing. Passes the current
run to the given benchmark function.
*/
export class TimeRunner extends FinRunner {
constructor(ms) {super(l.reqFinPos(ms))}
/*
Performance cost distribution should be:
* Calls to the function we're benchmarking: dominant.
* Calls to `now`: amortized through batching.
* Everything else: excluded from timing.
Despite the optimization and amortization, this machinery has measurable
overhead. To improve precision, we measure the overhead of measurement and
subtract it from measurements. An empty benchmark should clock at ±0.
*/
run(fun, run) {
this.constructor.warmup()
const nowAvg = this.constructor.getNowAvg()
let runs = 0
let nows = 0
let end = undefined
let batch = 1
const start = run.start = now()
const timeThresh = start + this.valueOf()
do {
let rem = batch
do {runs++, fun()} while (rem-- > 0)
batch *= 2
nows++
end = now()
}
while (end < timeThresh)
run.end = now()
run.runs = runs
run.avg = ((end - start - (nowAvg * nows)) / runs) - this.constructor.getOverhead()
conf.verbLog(`[${run.name}] runs: ${runs}, nows: ${nows}, runtime: ${tsMilli(end - start)}, nowAvg: ${tsNano(nowAvg)} avg: ${tsNano(run.avg)}`)
}
static defaultSize = 128
static defaultWarmupSize = 128
}
export class DeoptRunner extends CountRunner {
constructor() {super(1)}
static getNowAvg() {return 0}
static warmup() {}
}
/*
Base class for reporters that use strings, as opposed to reporters that render
DOM nodes or ring bells. Has no side effects. Reporting methods are nops.
*/
export class StringReporter extends l.Emp {
constructor(pad) {super().pad = l.reqStr(pad)}
// Nop implementation of `isReporter`.
reportStart(run) {l.reqInst(run, Run)}
reportEnd(run) {l.reqInst(run, Run)}
cols() {return 0}
str(pre, suf) {
l.reqStr(pre)
l.reqStr(suf)
if (!suf) return pre
if (!pre) return suf
const space = ` `
// Semi-placeholder. See comments on `test_string_length`.
const infix = this.pad.repeat(pos(
this.cols() - pre.length - (space.length * 2) - suf.length,
))
return pre + space + infix + (infix && space) + suf
}
runPrefix(run) {
l.reqInst(run, Run)
return this.pad.repeat(run.level() * 2) + `[${run.name}]`
}
static default() {return new this(`·`)}
}
/*
Base class used by specialized console reporters such as `ConsoleOkReporter`.
Has utility methods for console printing, but its `isReporter` methods are
still nops.
*/
export class ConsoleReporter extends StringReporter {
cols() {return cli.consoleCols()}
report(pre, suf) {this.log(this.str(pre, suf))}
log() {console.log(...arguments)}
err() {console.error(...arguments)}
}
/*
Reports runs by printing the name of each run before starting it.
TODO implement an alternative DOM reporter that renders a table.
*/
export class ConsoleStartReporter extends ConsoleReporter {
reportStart(run) {
l.reqInst(run, Run)
this.log(this.runPrefix(run) + ` [start]`)
}
}
// Reports runs by printing name and average time.
// Usable only for benchmarks.
// For tests, prefer `ConsoleStartReporter`.
export class ConsoleAvgReporter extends ConsoleReporter {
constructor(pad, fun) {
super(pad)
this.fun = l.reqFun(fun)
}
reportEnd(run) {
l.reqInst(run, Run)
const {fun} = this
this.report(this.runPrefix(run), l.req(fun(run.avg), l.isStr))
}
static default() {return this.with(tsNano)}
static with(fun) {return new this(`·`, fun)}
}
// TODO dedup with above.
export class ConsoleStartEndAvgReporter extends ConsoleAvgReporter {
reportStart(run) {
l.reqInst(run, Run)
this.log(this.runPrefix(run) + ` [start]`)
}
reportEnd(run) {
l.reqInst(run, Run)
const {fun} = this
this.report(this.runPrefix(run) + ` [end]`, l.req(fun(run.avg), l.isStr))
}
}
// Reports runs by printing name and amount of runs.
export class ConsoleRunsReporter extends ConsoleReporter {
reportEnd(run) {
l.reqInst(run, Run)
this.report(this.runPrefix(run), String(run.runs))
}
}
/*
Reports benchmark runs by printing name, amount of runs, average timing.
TODO accumulate results, printing a table on `.flush`.
TODO variant that re-prints a table on the fly, clearing the terminal each time.
TODO alternative DOM reporter that renders a table.
*/
export class ConsoleBenchReporter extends ConsoleAvgReporter {
reportEnd(run) {
l.reqInst(run, Run)
const {fun} = this
this.report(this.runPrefix(run), `x${run.runs} ${l.req(fun(run.avg), l.isStr)}`)
}
}
// TODO consider using utils from `time.mjs`.
export function tsMilli(val) {return `${(l.reqFin(val)).toFixed(6)} ms`}
export function tsMicro(val) {return `${(l.reqFin(val) * 1000).toFixed(3)} µs`}
export function tsNano(val) {return `${(l.reqFin(val) * 1_000_000).toFixed(0)} ns`}
export function tsPico(val) {return `${(l.reqFin(val) * 1_000_000_000).toFixed(0)} ps`}
// Global config and global state.
export const conf = new class Conf extends l.Emp {
#testFilter = undefined
get testFilter() {return this.#testFilter}
set testFilter(val) {this.#testFilter = l.optArrOf(val, l.isReg)}
#benchFilter = undefined
get benchFilter() {return this.#benchFilter}
set benchFilter(val) {this.#benchFilter = l.optArrOf(val, l.isReg)}
#benchRunner = TimeRunner.default()
get benchRunner() {return this.#benchRunner}
set benchRunner(val) {this.#benchRunner = l.req(val, isRunner)}
#testRep = undefined
get testRep() {return this.#testRep}
set testRep(val) {this.#testRep = l.opt(val, isReporter)}
#benchRep = ConsoleAvgReporter.default()
get benchRep() {return this.#benchRep}
set benchRep(val) {this.#benchRep = l.opt(val, isReporter)}
#run = undefined
get run() {return this.#run}
set run(val) {this.#run = l.optInst(val, Run)}
#benches = new Set()
get benches() {return this.#benches}
set benches(val) {this.#benches = l.reqSet(val)}
#verb = false
get verb() {return this.#verb}
set verb(val) {this.#verb = l.reqBool(val)}
setTestFilter(val) {return this.testFilter = toFilter(val), this}
setBenchFilter(val) {return this.benchFilter = toFilter(val), this}
isTop() {return !this.run}
verbLog(...val) {if (this.verb) console.log(...val)}
verbErr(...val) {if (this.verb) console.error(...val)}
}()
/*
Runs a named test function. May skip depending on `conf.testFilter`. Uses
optional `conf.testRep` to report start and end of the test. Records test
timing, which may be used by the reporter. Passes the current `Run` to the test
function.
*/
export function test(fun) {
reqNamedFun(fun, `test`)
const run = new Run(fun.name, conf.run)
if (!run.allow(conf.testFilter)) return run
conf.testRep?.reportStart(run)
run.start = now()
if (l.isFunAsync(fun)) return testAsync(run, fun)
let out
conf.run = run
try {out = fun(run)}
finally {conf.run = run.parent}
testDone(run)
return out
}
async function testAsync(run, fun) {
let out
conf.run = run
try {out = await fun(run)}
finally {conf.run = run.parent}
testDone(run)
return out
}
function testDone(run) {
run.done(now(), 1)
conf.testRep?.reportEnd(run)
}
/*
Registers a function for benchmarking, returning the resulting `Bench`.
Registered benchmarks can be run by calling `benches`.
*/
export function bench(fun, runner) {
const bench = new Bench(fun, runner)
conf.benches.add(bench)
return bench
}
/*
Named benchmark. Accepts an optional runner, falling back on default
`conf.benchRunner`. Expects the runner to run the given function multiple
times, recording the amount of runs and the timing. Uses `conf.benchRep` to
report start and end of the benchmark.
*/
export class Bench extends l.Emp {
constructor(fun, runner) {
super()
this.fun = reqNamedFun(fun, `bench`)
this.runner = optRunner(runner)
}
getName() {return this.fun.name}
run(runner = this.runner ?? conf.benchRunner) {
const run = new Run(this.getName())
conf.benchRep?.reportStart(run)
conf.run = run
try {runner.run(this.fun, run)}
finally {conf.run = run.parent}
run.reqDone()
conf.benchRep?.reportEnd(run)
return run
}
allow(filter) {return Run.allow(filter, this.getName())}
}
/*
Runs all registered benchmarks, using a single-pass runner, without filtering.
May cause deoptimization of polymorphic code. Leads to more predictable
benchmark results. Run this before `benches`.
*/
export function deopt() {
const runner = new DeoptRunner()
const rep = conf.benchRep
conf.benchRep = conf.verb ? rep : undefined
try {for (const bench of conf.benches) bench.run(runner)}
finally {conf.benchRep = rep}
}
// Runs registered benchmarks, filtering them via `conf.benchFilter`.
export function benches() {
for (const bench of conf.benches) {
if (bench.allow(conf.benchFilter)) bench.run()
}
}
function reqNamedFun(fun, type) {
const {name} = l.reqFun(fun)
if (!name) {
throw new SyntaxError(`${type} functions must have names for clearer stacktraces and easier search; missing name on ${fun}`)
}
if (!name.startsWith(type)) {
throw new SyntaxError(`names of ${type} functions must begin with ${l.show(type)} for clearer stacktraces and easier search; invalid name on the following function:
${fun}`)
}
return fun
}
export {ok as true}
// Asserts that the given value is exactly `true`. Otherwise throws `AssertError`.
export function ok(val, ...info) {
if (val === true) return
throw new AssertError(joinParagraphs(
joinParagraphs(`actual:`, indent(showSimple(val))),
joinParagraphs(`expected:`, indent(`true`)),
optInfo(...info),
))
}
function optInfo(...val) {
val = val.filter(l.isSome).map(showInfo).map(indent).join(`\n`)
if (!val) return ``
return joinParagraphs(`info:`, val)
}
function showErr(err) {return l.isInst(err, Error) ? err.stack : l.show(err)}
function showInfo(val) {return l.isScalar(val) ? l.render(val) : l.show(val)}
function showSimple(val) {return l.isStr(val) ? val : l.show(val)}
function indent(val) {return ` ` + l.reqStr(val)}
export {no as false}
// Asserts that the given value is exactly `false`. Otherwise throws `AssertError`.
export function no(val, ...info) {
if (val === false) return
throw new AssertError(joinParagraphs(
joinParagraphs(`actual:`, indent(showSimple(val))),
joinParagraphs(`expected:`, indent(`false`)),
optInfo(...info),
))
}
/*
Asserts that the inputs are identical, using `Object.is`.
Otherwise throws `AssertError`.
*/
export function is(act, exp, ...info) {
if (Object.is(act, exp)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`actual:`, indent(showSimple(act))),
joinParagraphs(`expected:`, indent(showSimple(exp))),
(
equal(act, exp)
? joinParagraphs(`note:`, `equivalent structure, different reference`)
: ``
),
optInfo(...info),
))
}
/*
Asserts that the inputs are NOT identical, using `Object.is`.
Otherwise throws `AssertError`.
*/
export function isnt(act, exp, ...info) {
if (!Object.is(act, exp)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`expected distinct values, but both inputs were:`, indent(showSimple(act))),
optInfo(...info),
))
}
/*
Asserts that the inputs have equivalent structure, using `equal`.
Otherwise throws `AssertError`.
*/
export function eq(act, exp, ...info) {
if (equal(act, exp)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`actual:`, indent(showSimple(act))),
joinParagraphs(`expected:`, indent(showSimple(exp))),
optInfo(...info),
))
}
/*
Asserts that the inputs DO NOT have equivalent structure, using `equal`.
Otherwise throws `AssertError`.
*/
export function notEq(act, exp, ...info) {
if (!equal(act, exp)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`expected distinct values, but both inputs were:`, indent(showSimple(act))),
optInfo(...info),
))
}
// Tentative. May need to improve the error message.
export function own(act, exp, ...info) {
const actDesc = Object.getOwnPropertyDescriptors(act)
const expDesc = Object.getOwnPropertyDescriptors(exp)
if (new Eq().equalDescs(actDesc, expDesc)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`actual properties:`, indent(l.show({...act}))),
joinParagraphs(`expected properties:`, indent(l.show({...exp}))),
joinParagraphs(`actual descriptors:`, indent(l.show(actDesc))),
joinParagraphs(`expected descriptors:`, indent(l.show(expDesc))),
optInfo(...info),
))
}
/*
Asserts that the given value is an instance of the given class. Otherwise throws
`AssertError`. The argument order matches `instanceof` and `l.isInst`.
*/
export function inst(val, cls, ...info) {
if (l.isInst(val, cls)) return
throw new AssertError(joinParagraphs(
joinParagraphs(`got:`, indent(showSimple(val))),
joinParagraphs(`expected instance of:`, indent(l.show(cls))),
optInfo(...info),
))
}
/*
Asserts that the given value is either nil or an instance of the given class.
Otherwise throws `AssertError`. The argument order matches `instanceof` and
`l.isInst`.
*/
export function optInst(val, cls) {
l.reqCls(cls)
if (l.isNil(val)) return
inst(val, cls)
}
/*
Asserts that the given function throws an instance of the given error class,
with a given non-empty error message.
TODO consider supporting verifying error causes in addition to the topmost
error. Unclear how to express that in user code.
*/
export function throws(fun, cls, msg) {
if (!l.isFun(fun)) {
throw TypeError(`expected function, got ${l.show(fun)}`)
}
if (!l.isCls(cls) || !l.isSubCls(cls, Error)) {
throw TypeError(`expected error class, got ${l.show(cls)}`)
}
if (!l.isStr(msg) || !msg) {
throw TypeError(`expected error message, got ${l.show(msg)}`)
}
if (l.isFunAsync(fun)) return throwsAsync(fun, cls, msg)
let val
try {val = fun()}
catch (err) {return throwsCaught(fun, cls, msg, err)}
return throwsReturned(fun, cls, msg, val)
}
async function throwsAsync(fun, cls, msg) {
let val
try {val = await fun()}
catch (err) {return throwsCaught(fun, cls, msg, err)}
return throwsReturned(fun, cls, msg, val)
}
export function throwsCaught(fun, cls, msg, err) {
if (!l.isInst(err, cls)) {
throw new AssertError(joinParagraphs(
throwsFunMsg(fun),
throwsErrMsg(cls, msg),
throwsGotErr(err),
))
}
if (!err.message.includes(msg)) {
throw new AssertError(joinParagraphs(
throwsFunMsg(fun),
throwsErrMsg(cls, msg),
throwsGotErr(err),
))
}
return err
}
export function throwsGotErr(err) {
return joinParagraphs(
joinParagraphs(`got error:`, indent(showErr(err))),
causedBy(err),
)
}
function causedBy(err) {
err = l.get(err, `cause`)
if (l.isNil(err)) return ``
return joinParagraphs(
joinParagraphs(`caused by:`, indent(showErr(err))),
causedBy(err),
)
}
export function throwsReturned(fun, cls, msg, val) {
throw new AssertError(joinParagraphs(
throwsFunMsg(fun),
throwsErrMsg(cls, msg),
joinParagraphs(`got return value:`, indent(showSimple(val))),
))
}
export function throwsFunMsg(fun) {
l.reqFun(fun)
return joinParagraphs(`expected function to throw:`, indent(fun.toString()))
}
export function throwsErrMsg(cls, msg) {
return joinParagraphs(`expected error:`, indent(errClsName(cls) + `: ` + msg))
}
function errClsName(cls) {return cls.name || l.show(cls)}
/*
Simple, naive version for internal use in test utils.
Application code should use join functions in `str.mjs`.
*/
function joinParagraphs(...src) {return src.filter(Boolean).join(`\n\n`)}
/*
Returns true if the inputs have an equivalent structure. Supports plain dicts,
arrays, maps, sets, and arbitrary objects with enumerable properties.
This is confined to the testing module, instead of being part of the "normal"
API, because deeply traversing and comparing data structures is a popular JS
antipattern that should be discouraged, not encouraged. The existence of this
function proves the occasional need, but live apps should avoid wasting
performance on this.
*/
export function equal(one, two) {
return new Eq().equal(one, two)
}
export class Eq extends WeakSet {
equal(one, two) {
if (Object.is(one, two)) return true
if (!(l.isObj(one) && l.isObj(two))) return false
if (this.has(one) || this.has(two)) return false
return this.add(one).add(two).equalObj(one, two)
}
equalObj(one, two) {
// Probably faster than letting `.equalList` compare them.
if (l.isInst(one, String)) return equalCons(one, two) && one.valueOf() === two.valueOf()
if (l.isList(one)) return equalCons(one, two) && this.equalList(one, two)
if (l.isSet(one)) return equalCons(one, two) && this.equalSet(one, two)
if (l.isMap(one)) return equalCons(one, two) && this.equalMap(one, two)
if (l.isInst(one, URL)) return equalCons(one, two) && one.href === two.href
if (l.isInst(one, Date)) return equalCons(one, two) && one.valueOf() === two.valueOf()
if (l.isDict(one)) return l.isDict(two) && this.equalStruct(one, two)
if (l.isDict(two)) return l.isDict(one) && this.equalStruct(one, two)
return equalCons(one, two) && this.equalStruct(one, two)
}
equalList(one, two) {
if (one.length !== two.length) return false
let ind = -1
while (++ind < one.length) if (!this.equal(one[ind], two[ind])) return false
return true
}
equalSet(one, two) {
if (one.size !== two.size) return false
outer:
for (const valOne of setVals(one)) {
if (two.has(valOne)) continue outer
for (const valTwo of setVals(two)) {
if (this.equal(valOne, valTwo)) continue outer
}
return false
}
return true
}
equalMap(one, two) {
if (one.size !== two.size) return false
for (const [key, val] of Map.prototype.entries.call(one)) {
if (!this.equal(val, Map.prototype.get.call(two, key))) return false
}
return true
}
equalStruct(one, two) {
// Takes care of primitive wrapper objects such as `new Number`,
// as well as arbitrary classes with a custom `.valueOf`.
const oneVal = maybeValueOf(one)
const twoVal = maybeValueOf(two)
if (one !== oneVal && two !== twoVal) return this.equal(oneVal, twoVal)
return this.equalDescs(
Object.getOwnPropertyDescriptors(one),
Object.getOwnPropertyDescriptors(two),
)
}
equalDescs(one, two) {
for (const key of Object.getOwnPropertySymbols(one)) {
if (!(key in two && this.equalDesc(one[key], two[key]))) return false
}
for (const key of Object.getOwnPropertyNames(one)) {
if (!(key in two && this.equalDesc(one[key], two[key]))) return false
}
for (const key of Object.getOwnPropertySymbols(two)) {
if (!(key in one)) return false
}
for (const key of Object.getOwnPropertyNames(two)) {
if (!(key in one)) return false
}
return true
}
equalDesc(one, two) {
return (
true
&& one.get === two.get
&& one.set === two.set
&& this.equal(one.value, two.value)
)
}
}
function equalCons(one, two) {
return l.isComp(one) && l.isComp(two) && equal(one.constructor, two.constructor)
}
function setVals(val) {return Set.prototype.values.call(val)}
function maybeValueOf(val) {
if (l.hasMeth(val, `valueOf`)) return val.valueOf()
return val
}
function pos(val) {return Math.max(0, l.laxInt(val))}
function toFilter(src) {
if (l.isNil(src)) return src
if (l.isStr(src)) return src.split(`/`).map(toReg)
if (l.isReg(src)) return [src]
if (l.isArr(src)) return src.map(toReg)
throw l.errConv(src, `test or benchmark filter`)
}
function toReg(src) {return l.isReg(src) ? src : new RegExp(l.reqStr(src))}
/*
Used for all measurements. Semi-placeholder. In the future we may decide to
auto-detect the best available timing API depending on the environment. For
example, in Node we might use `process.hrtime`.
*/
export function now() {return performance.now()}
/*
Average overhead of the timing API. VERY approximate. The overhead varies,
possibly due to factors such as JIT tiers, CPU boost state, and possibly more.
Observed variance in Deno: 200ns, 600ns, 2µs.
The unstable performance of `performance.now` is responsible for a significant
portion of our warmup time. We would prefer to measure this just once, but due
to its variance, we end up measuring multiple times, which is relatively slow.
*/
export function nowAvg(runs = 65536) {
l.reqIntPos(runs)
const start = now()
let rem = runs
while (rem-- > 0) now()
const end = now()
return (end - start) / runs
}
function reqRunner(val) {
if (!isRunner(val)) {
throw TypeError(`benchmarks require a valid runner, got ${l.show(val)}`)
}
return val
}
function optRunner(val) {return l.isNil(val) ? undefined : reqRunner(val)}
export function isRunner(val) {return l.isComp(val) && l.hasMeth(val, `run`)}
export function isReporter(val) {
return l.isComp(val) && l.hasMeth(val, `reportStart`) && l.hasMeth(val, `reportEnd`)
}