aboutsummaryrefslogtreecommitdiff
path: root/node_modules/ava/lib/reporters/mini.js
blob: 8acfab8e7e078222cb1433c507e2a3f5bb076123 (plain)
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
'use strict';
const StringDecoder = require('string_decoder').StringDecoder;
const cliCursor = require('cli-cursor');
const lastLineTracker = require('last-line-stream/tracker');
const plur = require('plur');
const spinners = require('cli-spinners');
const chalk = require('chalk');
const cliTruncate = require('cli-truncate');
const cross = require('figures').cross;
const indentString = require('indent-string');
const ansiEscapes = require('ansi-escapes');
const trimOffNewlines = require('trim-off-newlines');
const extractStack = require('../extract-stack');
const codeExcerpt = require('../code-excerpt');
const colors = require('../colors');
const formatSerializedError = require('./format-serialized-error');
const improperUsageMessages = require('./improper-usage-messages');

class MiniReporter {
	constructor(options) {
		this.options = Object.assign({}, options);

		chalk.enabled = this.options.color;
		for (const key of Object.keys(colors)) {
			colors[key].enabled = this.options.color;
		}

		const spinnerDef = spinners[process.platform === 'win32' ? 'line' : 'dots'];
		this.spinnerFrames = spinnerDef.frames.map(c => chalk.gray.dim(c));
		this.spinnerInterval = spinnerDef.interval;

		this.reset();
		this.stream = process.stderr;
		this.stringDecoder = new StringDecoder();
	}
	start() {
		this.interval = setInterval(() => {
			this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;
			this.write(this.prefix());
		}, this.spinnerInterval);

		return this.prefix('');
	}
	reset() {
		this.clearInterval();
		this.passCount = 0;
		this.knownFailureCount = 0;
		this.failCount = 0;
		this.skipCount = 0;
		this.todoCount = 0;
		this.rejectionCount = 0;
		this.exceptionCount = 0;
		this.currentStatus = '';
		this.currentTest = '';
		this.statusLineCount = 0;
		this.spinnerIndex = 0;
		this.lastLineTracker = lastLineTracker();
	}
	spinnerChar() {
		return this.spinnerFrames[this.spinnerIndex];
	}
	clearInterval() {
		clearInterval(this.interval);
		this.interval = null;
	}
	test(test) {
		if (test.todo) {
			this.todoCount++;
		} else if (test.skip) {
			this.skipCount++;
		} else if (test.error) {
			this.failCount++;
		} else {
			this.passCount++;
			if (test.failing) {
				this.knownFailureCount++;
			}
		}

		if (test.todo || test.skip) {
			return;
		}

		return this.prefix(this._test(test));
	}
	prefix(str) {
		str = str || this.currentTest;
		this.currentTest = str;

		// The space before the newline is required for proper formatting
		// TODO(jamestalmage): Figure out why it's needed and document it here
		return ` \n ${this.spinnerChar()} ${str}`;
	}
	_test(test) {
		const SPINNER_WIDTH = 3;
		const PADDING = 1;
		let title = cliTruncate(test.title, process.stdout.columns - SPINNER_WIDTH - PADDING);

		if (test.error || test.failing) {
			title = colors.error(test.title);
		}

		return title + '\n' + this.reportCounts();
	}
	unhandledError(err) {
		if (err.type === 'exception') {
			this.exceptionCount++;
		} else {
			this.rejectionCount++;
		}
	}
	reportCounts(time) {
		const lines = [
			this.passCount > 0 ? '\n  ' + colors.pass(this.passCount, 'passed') : '',
			this.knownFailureCount > 0 ? '\n  ' + colors.error(this.knownFailureCount, plur('known failure', this.knownFailureCount)) : '',
			this.failCount > 0 ? '\n  ' + colors.error(this.failCount, 'failed') : '',
			this.skipCount > 0 ? '\n  ' + colors.skip(this.skipCount, 'skipped') : '',
			this.todoCount > 0 ? '\n  ' + colors.todo(this.todoCount, 'todo') : ''
		].filter(Boolean);

		if (time && lines.length > 0) {
			lines[0] += ' ' + time;
		}

		return lines.join('');
	}
	finish(runStatus) {
		this.clearInterval();
		let time;

		if (this.options.watching) {
			time = chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']');
		}

		let status = this.reportCounts(time) + '\n';

		if (this.rejectionCount > 0) {
			status += '  ' + colors.error(this.rejectionCount, plur('rejection', this.rejectionCount)) + '\n';
		}

		if (this.exceptionCount > 0) {
			status += '  ' + colors.error(this.exceptionCount, plur('exception', this.exceptionCount)) + '\n';
		}

		if (runStatus.previousFailCount > 0) {
			status += '  ' + colors.error(runStatus.previousFailCount, 'previous', plur('failure', runStatus.previousFailCount), 'in test files that were not rerun') + '\n';
		}

		if (this.knownFailureCount > 0) {
			for (const test of runStatus.knownFailures) {
				const title = test.title;
				status += '\n   ' + colors.title(title) + '\n';
				// TODO: Output description with link
				// status += colors.stack(description);
			}
		}

		status += '\n';
		if (this.failCount > 0) {
			runStatus.errors.forEach(test => {
				if (!test.error) {
					return;
				}

				status += '  ' + colors.title(test.title) + '\n';
				if (test.error.source) {
					status += '  ' + colors.errorSource(test.error.source.file + ':' + test.error.source.line) + '\n';

					const excerpt = codeExcerpt(test.error.source, {maxWidth: process.stdout.columns});
					if (excerpt) {
						status += '\n' + indentString(excerpt, 2) + '\n';
					}
				}

				if (test.error.avaAssertionError) {
					const result = formatSerializedError(test.error);
					if (result.printMessage) {
						status += '\n' + indentString(test.error.message, 2) + '\n';
					}

					if (result.formatted) {
						status += '\n' + indentString(result.formatted, 2) + '\n';
					}

					const message = improperUsageMessages.forError(test.error);
					if (message) {
						status += '\n' + indentString(message, 2) + '\n';
					}
				} else if (test.error.message) {
					status += '\n' + indentString(test.error.message, 2) + '\n';
				}

				if (test.error.stack) {
					const extracted = extractStack(test.error.stack);
					if (extracted.includes('\n')) {
						status += '\n' + indentString(colors.errorStack(extracted), 2) + '\n';
					}
				}

				status += '\n\n\n';
			});
		}

		if (this.rejectionCount > 0 || this.exceptionCount > 0) {
			// TODO(sindresorhus): Figure out why this causes a test failure when switched to a for-of loop
			runStatus.errors.forEach(err => {
				if (err.title) {
					return;
				}

				if (err.type === 'exception' && err.name === 'AvaError') {
					status += '  ' + colors.error(cross + ' ' + err.message) + '\n\n';
				} else {
					const title = err.type === 'rejection' ? 'Unhandled Rejection' : 'Uncaught Exception';
					let description = err.stack ? err.stack.trimRight() : JSON.stringify(err);
					description = description.split('\n');
					const errorTitle = err.name ? description[0] : 'Threw non-error: ' + description[0];
					const errorStack = description.slice(1).join('\n');

					status += '  ' + colors.title(title) + '\n';
					status += '  ' + colors.stack(errorTitle) + '\n';
					status += colors.errorStack(errorStack) + '\n\n';
				}
			});
		}

		if (runStatus.failFastEnabled === true && runStatus.remainingCount > 0 && runStatus.failCount > 0) {
			const remaining = 'At least ' + runStatus.remainingCount + ' ' + plur('test was', 'tests were', runStatus.remainingCount) + ' skipped.';
			status += '  ' + colors.information('`--fail-fast` is on. ' + remaining) + '\n\n';
		}

		if (runStatus.hasExclusive === true && runStatus.remainingCount > 0) {
			status += '  ' + colors.information('The .only() modifier is used in some tests.', runStatus.remainingCount, plur('test', runStatus.remainingCount), plur('was', 'were', runStatus.remainingCount), 'not run');
		}

		return '\n' + trimOffNewlines(status) + '\n';
	}
	section() {
		return '\n' + chalk.gray.dim('\u2500'.repeat(process.stdout.columns || 80));
	}
	clear() {
		return '';
	}
	write(str) {
		cliCursor.hide();
		this.currentStatus = str;
		this._update();
		this.statusLineCount = this.currentStatus.split('\n').length;
	}
	stdout(data) {
		this._update(data);
	}
	stderr(data) {
		this._update(data);
	}
	_update(data) {
		let str = '';
		let ct = this.statusLineCount;
		const columns = process.stdout.columns;
		let lastLine = this.lastLineTracker.lastLine();

		// Terminals automatically wrap text. We only need the last log line as seen on the screen.
		lastLine = lastLine.substring(lastLine.length - (lastLine.length % columns));

		// Don't delete the last log line if it's completely empty.
		if (lastLine.length > 0) {
			ct++;
		}

		// Erase the existing status message, plus the last log line.
		str += ansiEscapes.eraseLines(ct);

		// Rewrite the last log line.
		str += lastLine;

		if (str.length > 0) {
			this.stream.write(str);
		}

		if (data) {
			// Send new log data to the terminal, and update the last line status.
			this.lastLineTracker.update(this.stringDecoder.write(data));
			this.stream.write(data);
		}

		let currentStatus = this.currentStatus;

		if (currentStatus.length > 0) {
			lastLine = this.lastLineTracker.lastLine();
			// We need a newline at the end of the last log line, before the status message.
			// However, if the last log line is the exact width of the terminal a newline is implied,
			// and adding a second will cause problems.
			if (lastLine.length % columns) {
				currentStatus = '\n' + currentStatus;
			}
			// Rewrite the status message.
			this.stream.write(currentStatus);
		}
	}
}

module.exports = MiniReporter;