-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathutil.mjs
57 lines (51 loc) · 1.3 KB
/
util.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
// test utils
function ok(assert, test) {
console.assert(true, assert.name, test)
}
function fail(assert, test, error) {
console.assert(false, assert.name, test, error || '')
}
export function assert(test) {
try {
if (test()) ok(assert, test)
else fail(assert, test)
} catch (e) {
fail(assert, test, e)
}
}
export function assertThrow(test, what) {
try {
test()
fail(assertThrow, test)
} catch (e) {
const r = checkError(e, what)
if (r) fail(assertThrow, test, r)
else ok(assertThrow, test)
}
}
function checkError(error, what) {
try {
if (what === undefined) return null
if (error instanceof Error && Error.isPrototypeOf(what)) {
if (error instanceof what) return null
return {reason: 'instanceof', error, what}
}
if (likePlainObject(what)) {
const diff = Object.entries(what).find(([k, v]) => error[k] !== v)
if (diff == null) return null
const [k, v] = diff
return {reason: `expect key ${k} to be ${v}, actual ${what[k]}`, error, what}
}
if (typeof what === 'function') {
if (what(error)) return null
return {reason: 'match', error, what}
}
if (what === error) return null
return {reason: '===', error, what}
} catch (reason) {
return {reason, error, what}
}
}
function likePlainObject(o) {
return Object.getPrototypeOf(o) === Object.prototype
}