/
TestLogger.ts
80 lines (70 loc) · 2.28 KB
/
TestLogger.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
import { Logger, LogLevel, removeIf } from "../lib/utils";
import { fail, ok } from "assert";
import * as ts from "typescript";
import { resolve } from "path";
const levelMap: Record<LogLevel, string> = {
[LogLevel.Error]: "error: ",
[LogLevel.Warn]: "warn: ",
[LogLevel.Info]: "info: ",
[LogLevel.Verbose]: "debug: ",
};
export class TestLogger extends Logger {
messages: string[] = [];
reset() {
this.resetErrors();
this.resetWarnings();
this.messages = [];
}
discardDebugMessages() {
removeIf(this.messages, (msg) => msg.startsWith("debug"));
}
expectMessage(message: string) {
const regex = createRegex(message);
const index = this.messages.findIndex((m) => regex.test(m));
if (index === -1) {
const messages = this.messages.join("\n\t") || "(none logged)";
fail(
`Expected "${message}" to be logged. The logged messages were:\n\t${messages}`
);
}
this.messages.splice(index, 1);
}
expectNoOtherMessages() {
ok(
this.messages.length === 0,
`Expected no other messages to be logged. The logged messages were:\n\t${this.messages.join(
"\n\t"
)}`
);
}
override diagnostic(diagnostic: ts.Diagnostic): void {
const output = ts.formatDiagnostic(diagnostic, {
getCanonicalFileName: resolve,
getCurrentDirectory: () => process.cwd(),
getNewLine: () => ts.sys.newLine,
});
switch (diagnostic.category) {
case ts.DiagnosticCategory.Error:
this.log(output, LogLevel.Error);
break;
case ts.DiagnosticCategory.Warning:
this.log(output, LogLevel.Warn);
break;
case ts.DiagnosticCategory.Message:
this.log(output, LogLevel.Info);
}
}
override log(message: string, level: LogLevel): void {
super.log(message, level);
this.messages.push(levelMap[level] + message);
}
}
function createRegex(s: string) {
return new RegExp(
[
"^",
s.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[\\s\\S]*"),
"$",
].join("")
);
}