-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathinstallLogsPrinter.js
executable file
·324 lines (280 loc) · 9.54 KB
/
installLogsPrinter.js
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
const chalk = require('chalk');
const path = require('path');
const tv4 = require('tv4');
const schema = require('./installLogsPrinter.schema.json');
const tv4ErrorTransformer = require('./tv4ErrorTransformer');
const CtrError = require('./CtrError');
const CONSTANTS = require('./constants');
const LOG_TYPES = CONSTANTS.LOG_TYPES;
const KNOWN_TYPES = Object.values(CONSTANTS.LOG_TYPES);
const CustomOutputProcessor = require('./outputProcessor/CustomOutputProcessor');
const NestedOutputProcessorDecorator = require('./outputProcessor/NestedOutputProcessorDecorator');
const OUTPUT_PROCESSOR_TYPE = {
'json': require('./outputProcessor/JsonOutputProcessor'),
'txt': require('./outputProcessor/TextOutputProcessor'),
};
const LOG_SYMBOLS = (() => {
if (process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color') {
return {
error: '✘',
warning: '❖',
success: '✔',
info: '✱',
debug: '⚈',
route: '➟'
}
} else {
return {
error: 'x',
warning: '!',
success: '+',
info: 'i',
debug: '%',
route: '~'
}
}
})();
let writeToFileMessages = {};
let outputProcessors = [];
/**
* Installs the cypress plugin for printing logs to terminal.
*
* Needs to be added to plugins file.
*
* @see ./installLogsPrinter.d.ts
*/
function installLogsPrinter(on, options = {}) {
options.printLogsToFile = options.printLogsToFile || "onFail";
options.printLogsToConsole = options.printLogsToConsole || "onFail";
const result = tv4.validateMultiple(options, schema);
if (!result.valid) {
throw new CtrError(`Invalid plugin install options: ${tv4ErrorTransformer.toReadableString(result.errors)}`);
}
on('task', {
[CONSTANTS.TASK_NAME]: function (data) {
let messages = data.messages;
const terminalMessages =
typeof options.compactLogs === 'number' && options.compactLogs >= 0
? compactLogs(messages, options.compactLogs)
: messages;
const isHookAndShouldLog = data.isHook &&
(options.includeSuccessfulHookLogs || data.state === 'failed');
if (options.outputTarget && options.printLogsToFile !== "never") {
if (
data.state === "failed" ||
options.printLogsToFile === "always" ||
isHookAndShouldLog
) {
let outputFileMessages =
typeof options.outputCompactLogs === 'number'
? compactLogs(messages, options.outputCompactLogs)
: options.outputCompactLogs === false
? messages
: terminalMessages;
writeToFileMessages[data.spec] = writeToFileMessages[data.spec] || {};
writeToFileMessages[data.spec][data.test] = outputFileMessages;
}
}
if (
(options.printLogsToConsole === "onFail" && data.state !== "passed")
|| options.printLogsToConsole === "always"
|| isHookAndShouldLog
) {
logToTerminal(terminalMessages, options, data);
}
if (options.collectTestLogs) {
options.collectTestLogs(
{spec: data.spec, test: data.test, state: data.state},
terminalMessages
);
}
return null;
},
[CONSTANTS.TASK_NAME_OUTPUT]: () => {
logToFiles(options);
return null;
}
});
if (options.outputTarget) {
installOutputProcessors(on, options);
}
if (options.logToFilesOnAfterRun) {
enableLogToFilesOnAfterRun(on, options);
}
}
function enableLogToFilesOnAfterRun(on, options) {
on('after:run', () => {
logToFiles(options);
});
}
function logToFiles(options) {
outputProcessors.forEach((processor) => {
if (Object.entries(writeToFileMessages).length !== 0){
processor.write(writeToFileMessages);
if (options.outputVerbose !== false)
logOutputTarget(processor);
}
});
writeToFileMessages = {};
}
function logOutputTarget(processor) {
let message;
let standardOutputType = Object.keys(OUTPUT_PROCESSOR_TYPE).find(
(type) => processor instanceof OUTPUT_PROCESSOR_TYPE[type]
);
if (standardOutputType) {
message = `Wrote ${standardOutputType} logs to ${processor.getTarget()}. (${processor.getSpentTime()}ms)`;
} else {
message = `Wrote custom logs to ${processor.getTarget()}. (${processor.getSpentTime()}ms)`;
}
console.log('cypress-terminal-report:', message);
}
function installOutputProcessors(on, options) {
if (!options.outputRoot) {
throw new CtrError(`Missing outputRoot configuration.`);
}
const createProcessorFromType = (file, type) => {
if (typeof type === 'string') {
return new OUTPUT_PROCESSOR_TYPE[type](path.join(options.outputRoot, file));
}
if (typeof type === 'function') {
return new CustomOutputProcessor(path.join(options.outputRoot, file), type);
}
};
Object.entries(options.outputTarget).forEach(([file, type]) => {
const requiresNested = file.match(/^[^|]+\|.*$/);
if (typeof type === 'string' && !OUTPUT_PROCESSOR_TYPE[type]) {
throw new CtrError(`Unknown output format '${type}'.`);
}
if (!['function', 'string'].includes(typeof type)) {
throw new CtrError(`Output target type can only be string or function.`);
}
if (requiresNested) {
const parts = file.split('|');
const root = parts[0];
const ext = parts[1];
outputProcessors.push(new NestedOutputProcessorDecorator(root, options.specRoot, ext, (nestedFile) => {
return createProcessorFromType(nestedFile, type);
}));
} else {
outputProcessors.push(createProcessorFromType(file, type));
}
});
outputProcessors.forEach((processor) => processor.initialize());
}
function compactLogs(logs, keepAroundCount) {
const failingIndexes = logs.filter((log) => log[2] === CONSTANTS.SEVERITY.ERROR)
.map((log) => logs.indexOf(log));
const includeIndexes = new Array(logs.length);
failingIndexes.forEach((index) => {
const from = Math.max(0, index - keepAroundCount);
const to = Math.min(logs.length - 1, index + keepAroundCount);
for (let i = from; i <= to; i++) {
includeIndexes[i] = 1;
}
});
const compactedLogs = [];
const addOmittedLog = (count) =>
compactedLogs.push([
CONSTANTS.LOG_TYPES.PLUGIN_LOG_TYPE,
`[ ... ${count} omitted logs ... ]`,
CONSTANTS.SEVERITY.SUCCESS
]);
let excludeCount = 0;
for (let i = 0; i < includeIndexes.length; i++) {
if (includeIndexes[i]) {
if (excludeCount) {
addOmittedLog(excludeCount);
excludeCount = 0;
}
compactedLogs.push(logs[i]);
} else {
++excludeCount;
}
}
if (excludeCount) {
addOmittedLog(excludeCount);
}
return compactedLogs;
}
function logToTerminal(messages, options, data) {
const tabLevel = data.level || 0;
const levelPadding = ' '.repeat(Math.max(0, tabLevel - 1));
const padding = CONSTANTS.PADDING.LOG + levelPadding;
const padType = (type) =>
new Array(Math.max(padding.length - type.length - 3, 0)).join(' ') + type + ' ';
if (data.consoleTitle) {
console.log(' '.repeat(4) + levelPadding + chalk.gray(data.consoleTitle));
}
messages.forEach(([type, message, severity]) => {
let color = 'white',
typeString = KNOWN_TYPES.includes(type) ? padType(type) : padType('[unknown]'),
processedMessage = message,
trim = options.defaultTrimLength || 800,
icon = '-';
if (type === LOG_TYPES.BROWSER_CONSOLE_WARN) {
color = 'yellow';
icon = LOG_SYMBOLS.warning;
} else if (type === LOG_TYPES.BROWSER_CONSOLE_ERROR) {
color = 'red';
icon = LOG_SYMBOLS.warning;
} else if (type === LOG_TYPES.BROWSER_CONSOLE_DEBUG) {
color = 'blue';
icon = LOG_SYMBOLS.debug;
} else if (type === LOG_TYPES.BROWSER_CONSOLE_LOG) {
color = 'white';
icon = LOG_SYMBOLS.info;
} else if (type === LOG_TYPES.BROWSER_CONSOLE_INFO) {
color = 'white';
icon = LOG_SYMBOLS.info;
} else if (type === LOG_TYPES.CYPRESS_LOG) {
color = 'green';
icon = LOG_SYMBOLS.info;
} else if (type === LOG_TYPES.CYPRESS_XHR) {
color = 'green';
icon = LOG_SYMBOLS.route;
trim = options.routeTrimLength || 5000;
} else if (type === LOG_TYPES.CYPRESS_FETCH) {
color = 'green';
icon = LOG_SYMBOLS.route;
trim = options.routeTrimLength || 5000;
} else if (type === LOG_TYPES.CYPRESS_ROUTE) {
color = 'green';
icon = LOG_SYMBOLS.route;
trim = options.routeTrimLength || 5000;
} else if (type === LOG_TYPES.CYPRESS_INTERCEPT) {
color = 'green';
icon = LOG_SYMBOLS.route;
trim = options.routeTrimLength || 5000;
} else if (type === LOG_TYPES.CYPRESS_REQUEST) {
color = 'green';
icon = LOG_SYMBOLS.success;
trim = options.routeTrimLength || 5000;
} else if (type === LOG_TYPES.CYPRESS_COMMAND) {
color = 'green';
icon = LOG_SYMBOLS.success;
trim = options.commandTrimLength || 800;
}
if (severity === CONSTANTS.SEVERITY.ERROR) {
color = 'red';
icon = LOG_SYMBOLS.error;
} else if (severity === CONSTANTS.SEVERITY.WARNING) {
color = 'yellow';
icon = LOG_SYMBOLS.warning;
}
if (message.length > trim) {
processedMessage = message.substring(0, trim) + ' ...';
}
const coloredTypeString = ['red', 'yellow'].includes(color) ?
chalk[color].bold(typeString + icon + ' ') :
chalk[color](typeString + icon + ' ');
console.log(
coloredTypeString,
processedMessage.replace(/\n/g, '\n' + padding)
);
});
if (messages.length !== 0) {
console.log('\n');
}
}
module.exports = installLogsPrinter;