-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
241 lines (201 loc) · 7.17 KB
/
index.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
/*
MIT License
Copyright (c) 2020 Alexandru Ciobanu ([email protected])
Parts of the code based on existing plugin: https://github.com/codeceptjs/CodeceptJS/blob/3.x/lib/plugin/screenshotOnFail.js
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const { container, recorder, event, output } = codeceptjs;
const supportedHelpers = [
'Playwright',
'Protractor',
'Puppeteer',
'TestCafe',
'WebDriver'
];
const defaultConfig = {
uniqueNames: false
};
// Find the the acting helper that supports browser logs.
const getBrowserLogsHelper = (helpers) => {
for (const helperName of supportedHelpers) {
if (Object.keys(helpers).indexOf(helperName) > -1) {
return helpers[helperName];
}
}
return null;
};
// Cleans a test name to make is FS-compatible.
const cleanString = function (str) {
if (!str) return '';
str = str
.replace(/ /g, '_')
.replace(/"/g, "'")
.replace(/\//g, '_')
.replace(/</g, '(')
.replace(/>/g, ')')
.replace(/:/g, '_')
.replace(/\\/g, '_')
.replace(/\|/g, '_')
.replace(/\?/g, '.')
.replace(/\*/g, '^')
.replace(/'/g, '');
if (str.indexOf('{') !== -1) {
str = str.substr(0, str.indexOf('{') - 3).trim();
}
return str;
};
// Gets an unique UUID for a test.
const _getUUID = (test) => {
if (test.uuid) {
return test.uuid;
}
if (test.ctx && test.ctx.test.uuid) {
return test.ctx.test.uuid;
}
return Math.floor(new Date().getTime() / 1000);
};
module.exports = function (config) {
const helpers = container.helpers();
const helper = getBrowserLogsHelper(helpers);
if (!helper) {
output.plugin('browserLogOnFail', 'Unsupported acting helper.');
return;
}
const options = Object.assign(defaultConfig, helper.options, config);
if (container.mocha()) {
options.reportDir =
container.mocha().options.reporterOptions &&
container.mocha().options.reporterOptions.reportDir;
}
event.dispatcher.on(event.test.failed, (test) => {
recorder.add(
'browser log of failed test',
async () => {
let fileName = cleanString(test.title);
const ext = 'failed.txt';
if (test.ctx && test.ctx.test && test.ctx.test.type === 'hook')
fileName = cleanString(`${test.title}_${test.ctx.test.title}`);
if (options.uniqueNames && test) {
const uuid = _getUUID(test);
fileName = `${fileName.substring(0, 10)}_${uuid}.${ext}`;
} else {
fileName += `.${ext}`;
}
output.plugin(
'browserLogOnFail',
'Saving browser log for failed test.'
);
try {
let filePath = path.join(global.output_dir, fileName);
if (options.reportDir) {
const mochaReportDir = path.resolve(
process.cwd(),
options.reportDir
);
if (!fs.existsSync(mochaReportDir)) {
fs.mkdirSync(mochaReportDir);
}
filePath = path.join(mochaReportDir, fileName);
}
const logs = await helper.grabBrowserLogs();
if (logs) {
const text = logs.map((log) => util.format('%O', log)).join('\n');
fs.writeFileSync(filePath, text);
}
if ('artifacts' in test) {
test.artifacts.browserLogs = filePath;
}
if (
container.mocha().options.reporterOptions['mocha-junit-reporter'] &&
container.mocha().options.reporterOptions['mocha-junit-reporter']
.attachments
) {
if (test.attachments) {
test.attachments.push(filePath);
} else {
test.attachments = [filePath];
}
}
const allureReporter = container.plugins('allure');
if (allureReporter) {
allureReporter.addAttachment(
'Last Seen Browser Logs',
fs.readFileSync(filePath),
'text/json'
);
}
if ('mochawesome' in container.mocha().options.reporterOptions) {
const addContext = require('mochawesome/addContext');
let contents = logs.map(function(log) {
if ('_location' in log) {
let location = "URL: " + log._location.url;
if (log._location.lineNumber) {
location.append(" - " + log._location.lineNumber)
}
if (log._location.columnNumber) {
location.append(":" + log._location.columnNumber)
}
return [
log._type + ": " + log._text,
location
];
}
/* Special case for Puppeteer message */
if (typeof log == "object" && log.constructor.name == "ConsoleMessage") {
let location = "URL: " + log.location().url;
if (log.location().lineNumber) {
location = location.concat(" - " + log.location().lineNumber)
}
if (log.location().columnNumber) {
location = location.concat(":" + log.location().columnNumber)
}
return [
log.type() + ": " + util.format('%O', log.text()),
location
]
}
return [ util.format('%O', log) ];
})
addContext(test.ctx, {
title: 'Browser Logs',
value: contents
});
}
} catch (err) {
output.plugin(err);
if (
err &&
err.type &&
err.type === 'RuntimeError' &&
err.message &&
(err.message.indexOf('was terminated due to') > -1 ||
err.message.indexOf(
'no such window: target window already closed'
) > -1)
) {
output.log(`Can't extract the browser log, ${err}`);
helper.isRunning = false;
}
}
},
true
);
});
};