-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.ts
365 lines (320 loc) · 10.2 KB
/
render.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
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
import type { ExecutionContext } from "./execution.ts";
import { type ANSI_COLORS, colorize } from "./colors.ts";
import type { DisplayFormat, RenderConfig } from "./config.ts";
/**
* The interface that all matchers error renderers must implement.
*/
export interface MatcherErrorRenderer {
render(info: RenderedErrorInfo, config: RenderConfig): string;
}
/**
* The data structure holding all info to be rendered when a matcher fails.
*
* Because some matchers require additional info to be rendered, we use a generic type
* to allow for additional properties to be added to the info structure.
*/
export interface MatcherErrorInfo extends RenderedErrorInfo {
matcherSpecific?: Record<string, unknown>;
customMessage?: string;
}
/**
* The data structure holding all info to be rendered.
*/
export interface RenderedErrorInfo {
// The execution context of the assertion, holding the file name, line number, and column number
// where the assertion was called.
executionContext: ExecutionContext;
// This would be something like: "expect(received).toBe(expected)"
// plus color info or text appended for extra context.
matcherName: string;
// The underlying operation that was used to make the assertion. e.g. "Object.is".
matcherOperation?: string;
// The expected value. e.g. "false".
expected: string;
// The received value. e.g. "true".
received: string;
// The stacktrace of the assertion. e.g. "Error".
stacktrace?: string;
}
/**
* A registry of matchers error renderers.
*/
export class MatcherErrorRendererRegistry {
private static renderers: Map<string, MatcherErrorRenderer> = new Map();
private static config: RenderConfig = { colorize: true, display: "pretty" };
static register(matcherName: string, renderer: MatcherErrorRenderer) {
this.renderers.set(matcherName, renderer);
}
static getRenderer(matcherName: string): MatcherErrorRenderer {
return this.renderers.get(matcherName) || new DefaultMatcherErrorRenderer();
}
static configure(config: RenderConfig) {
this.config = { ...this.config, ...config };
}
static getConfig(): RenderConfig {
return this.config;
}
}
/**
* Base class for all matcher error renderers that implements common functionality
*/
export abstract class BaseMatcherErrorRenderer implements MatcherErrorRenderer {
protected getReceivedPlaceholder(): string {
return "received";
}
protected getExpectedPlaceholder(): string {
return "expected";
}
protected abstract getSpecificLines(
info: MatcherErrorInfo,
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): LineGroup[];
protected abstract getMatcherName(): string;
protected renderErrorLine(
info: RenderedErrorInfo,
config: RenderConfig,
): string {
const maybeColorize = (text: string, color: keyof typeof ANSI_COLORS) =>
config.colorize ? colorize(text, color) : text;
if ("customMessage" in info && typeof info.customMessage === "string") {
return maybeColorize(info.customMessage, "white");
}
return maybeColorize(`expect(`, "darkGrey") +
maybeColorize(this.getReceivedPlaceholder(), "red") +
maybeColorize(`).`, "darkGrey") +
maybeColorize(this.getMatcherName(), "white") +
this.renderMatcherArgs(maybeColorize);
}
protected renderMatcherArgs(
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): string {
return maybeColorize(`()`, "darkGrey");
}
render(info: MatcherErrorInfo, config: RenderConfig): string {
const maybeColorize = (text: string, color: keyof typeof ANSI_COLORS) =>
config.colorize ? colorize(text, color) : text;
const lines: LineGroup[] = [
{ label: "Error", value: this.renderErrorLine(info, config), group: 1 },
{
label: "At",
value: maybeColorize(
info.executionContext.at || "unknown location",
"darkGrey",
),
group: 1,
},
...this.getSpecificLines(info, maybeColorize),
{
label: "Filename",
value: maybeColorize(info.executionContext.fileName, "darkGrey"),
group: 99,
},
{
label: "Line",
value: maybeColorize(
info.executionContext.lineNumber.toString(),
"darkGrey",
),
group: 99,
},
];
return DisplayFormatRegistry.getFormatter(config.display).renderLines(
lines,
);
}
}
/**
* Base class for matchers that only show the received value
*/
export abstract class ReceivedOnlyMatcherRenderer
extends BaseMatcherErrorRenderer {
protected getSpecificLines(
info: MatcherErrorInfo,
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): LineGroup[] {
return [
{
label: "Received",
value: maybeColorize(info.received, "red"),
group: 2,
},
];
}
}
/**
* Base class for matchers that show both expected and received values
*/
export abstract class ExpectedReceivedMatcherRenderer
extends BaseMatcherErrorRenderer {
protected getSpecificLines(
info: MatcherErrorInfo,
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): LineGroup[] {
return [
{
label: "Expected",
value: maybeColorize(info.expected, "green"),
group: 2,
},
{
label: "Received",
value: maybeColorize(info.received, "red"),
group: 2,
},
];
}
protected override renderMatcherArgs(
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): string {
return maybeColorize(`(`, "darkGrey") +
maybeColorize(this.getExpectedPlaceholder(), "green") +
maybeColorize(`)`, "darkGrey");
}
}
/**
* The default matcher error renderer.
*/
export class DefaultMatcherErrorRenderer implements MatcherErrorRenderer {
render(info: RenderedErrorInfo, config: RenderConfig): string {
const maybeColorize = (text: string, color: keyof typeof ANSI_COLORS) =>
config.colorize ? colorize(text, color) : text;
const lines: LineGroup[] = [
{ label: "Error", value: this.renderErrorLine(info, config), group: 1 },
{
label: "At",
value: maybeColorize(
info.executionContext.at || "unknown location",
"darkGrey",
),
group: 1,
},
{
label: "Expected",
value: maybeColorize(info.expected, "green"),
group: 2,
},
{
label: "Received",
value: maybeColorize(info.received, "red"),
group: 2,
},
{
label: "Filename",
value: maybeColorize(info.executionContext.fileName, "darkGrey"),
group: 3,
},
{
label: "Line",
value: maybeColorize(
info.executionContext.lineNumber.toString(),
"darkGrey",
),
group: 3,
},
];
return DisplayFormatRegistry.getFormatter(config.display).renderLines(
lines,
);
}
protected renderErrorLine(
info: RenderedErrorInfo,
config: RenderConfig,
): string {
const maybeColorize = (text: string, color: keyof typeof ANSI_COLORS) =>
config.colorize ? colorize(text, color) : text;
return maybeColorize(`expect(`, "darkGrey") +
maybeColorize(`received`, "red") +
maybeColorize(`).`, "darkGrey") +
maybeColorize(`${info.matcherName}`, "white") +
maybeColorize(`(`, "darkGrey") +
maybeColorize(`expected`, "green") +
maybeColorize(`)`, "darkGrey");
}
}
interface DisplayFormatRenderer {
renderLines(lines: LineGroup[]): string;
}
/**
* Pretty format renderer that groups and aligns output
*
* Note that any stylization of the lines, such as colorization is expected to
* be done by the caller.
*/
class PrettyFormatRenderer implements DisplayFormatRenderer {
renderLines(lines: LineGroup[]): string {
const maxLabelWidth = Math.max(
...lines
.filter((line) => !line.raw)
.map(({ label }: { label: string }) => (label + ":").length),
);
return "\n\n" + lines
.map(({ label, value, raw }, index) => {
let line: string;
if (raw) {
line = value;
} else {
const labelWithColon = label + ":";
const spaces = " ".repeat(maxLabelWidth - labelWithColon.length);
line = spaces + labelWithColon + " " + value;
}
// Add newlines before a new group of lines (except for the first group)
const nextLine = lines[index + 1];
if (nextLine && lines[index].group !== nextLine.group) {
return line + "\n";
}
return line;
})
.join("\n") +
"\n\n";
}
}
/**
* Inline format renderer that outputs in logfmt style
*/
class InlineFormatRenderer implements DisplayFormatRenderer {
renderLines(lines: LineGroup[]): string {
return lines
.map(({ label, value }) => {
// Escape any spaces or special characters in the value
const escapedValue = typeof value === "string"
? value.includes(" ") ? `"${value}"` : value
: value;
// Convert label to lowercase and replace spaces with underscores
const escapedLabel = label.toLowerCase().replace(/\s+/g, "_");
return `${escapedLabel}=${escapedValue}`;
})
.join(" ");
}
}
class DisplayFormatRegistry {
private static formatters: Map<DisplayFormat, DisplayFormatRenderer> =
new Map([
["pretty", new PrettyFormatRenderer()],
["inline", new InlineFormatRenderer()],
]);
static getFormatter(format: DisplayFormat): DisplayFormatRenderer {
const formatter = this.formatters.get(format);
if (!formatter) {
throw new Error(`Unknown display format: ${format}`);
}
return formatter;
}
}
/**
* A line with a label and a value.
*
* The label is the text before the colon, and the value is the text after the colon.
*
* The group number is used to align the lines at the same column and group them into
* newline separated sections.
*/
export interface LineGroup {
// The label of the line.
label: string;
// The value of the line.
value: string;
// The group number of the line. Lines with the same group number are aligned at the same column.
group?: number;
// If true, the line is not formatted and is output as raw text.
raw?: boolean;
}