-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
133 lines (121 loc) · 3.94 KB
/
utils.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
import { TestEvent } from "./model.js";
import { gray, red, green, italic, yellow } from "./colors.js";
/**
* Terminate a script (in Node.js or browser).
* @param code The exit code. Defaults to 0.
*/
export function exit(code?: number): void {
if (typeof process !== "undefined") {
process.exit(code || 0);
} else if (typeof window !== "undefined") {
const prevOnError = window.onerror;
window.onerror = () => {
window.onerror = prevOnError;
return true;
};
}
throw new Error(`Termination with exit code ${code || 0}.`);
}
/**
* Create a promise that resolves in `ms` milliseconds.
* @param ms The timeout in milliseconds.
*/
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Create a logger that can be enabled/disabled.
export const logger = (function () {
let oldConsoleLog: typeof globalThis.console.log | null = null;
return {
log: oldConsoleLog ?? globalThis.console.log,
enable: function () {
if (oldConsoleLog == null) return;
globalThis.console.log = oldConsoleLog;
},
disable: function disableLogger() {
oldConsoleLog = console.log;
// eslint-disable-next-line @typescript-eslint/no-empty-function
globalThis.console.log = function () {};
},
};
})();
export class TimeoutError extends Error {}
export const timeout = <T = unknown>(
promise: Promise<T> | T,
timeout?: number
): Promise<T> => {
let clear: ReturnType<typeof setTimeout>;
const t = new Promise<T>((_, reject) => {
if (timeout == null) return;
clear = setTimeout(
() => reject(new TimeoutError(`timeout after ${timeout}ms`)),
timeout
);
});
const p = Promise.resolve(promise).finally(() => clearTimeout(clear));
return Promise.race([p, t]);
};
function formatDuration(time = 0) {
const timeStr = `(${time}ms)`;
return gray(italic(timeStr));
}
export function print(message: TestEvent, log: (str: string) => void): void {
const redFailed = red("failed");
const greenOk = green("ok");
const yellowIgnored = yellow("ignored");
if (message.start != null) {
log(`running ${message.start.tests.length} tests`);
} else if (message.testStart != null) {
// const { name } = message.testStart;
// log(`test ${name} ... `);
// noop for the moment
return;
} else if (message.testEnd != null) {
const { name, status, duration } = message.testEnd;
switch (status) {
case "passed":
log(`test ${name} ... ${greenOk} ${formatDuration(duration)}`);
break;
case "failed":
log(`test ${name} ... ${redFailed} ${formatDuration(duration)}`);
break;
case "ignored":
log(`test ${name} ... ${yellowIgnored} ${formatDuration(duration)}`);
break;
}
} else if (message.end != null) {
/* c8 ignore next */
const failures = message.end.results?.filter((m) => m.error != null) ?? [];
if (failures.length > 0) {
log(`\nfailures:\n`);
for (const { name, error } of failures) {
if (!error) continue;
// const stackString = error.stack?.split("\n").slice(1).join("\n") ?? "";
log(name);
// const head = red(
// `${error.name}${error.code ? ` [${error.code}]` : ""}`
// );
// log(`${head}: ${error.message}\n${gray(stackString)}`);
log(String(error.stack));
log("");
}
}
if (message.end.timeout) {
log(`\n${redFailed} due to timeout after ${message.end.timeout}ms\n`);
return;
}
log(
`\ntest result: ${message.end.failed ? redFailed : greenOk}. ` +
`${message.end.passed} passed; ` +
`${message.end.failed} failed; ` +
`${message.end.ignored} ignored; ` +
`${message.end.filtered} filtered out ` +
`${formatDuration(message.end.duration)}\n`
);
if (message.end.usedOnly && message.end.failed == 0) {
log(`${redFailed} because the "only" option was used\n`);
}
}
}