-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
429 lines (379 loc) · 12.3 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
const { event } = require('codeceptjs');
const { deepMerge, clearString } = require('codeceptjs/lib/utils');
const Container = require('codeceptjs').container;
const helpers = Container.helpers();
const output = require('./lib/output');
const TestRail = require('./lib/testrail');
const supportedHelpers = [
'WebDriver',
'Appium',
'Nightmare',
'Puppeteer',
'Playwright',
'TestCafe'
];
const defaultConfig = {
host: '',
user: '',
password: '',
enabled: false,
testCase: {
passed: { status_id: 1 },
failed: { status_id: 5 },
},
runId: undefined,
closeTestRun: true,
version: '1', // this is the build version - OPTIONAL,
resultProcessor: undefined
};
let helper;
for (const helperName of supportedHelpers) {
if (Object.keys(helpers).indexOf(helperName) > -1) {
helper = helpers[helperName];
}
}
module.exports = (config) => {
config = deepMerge (defaultConfig, config);
output.showDebugLog(config.debugLog);
if (!config.host) throw new Error('Please provide proper Testrail host');
if (!config.user) throw new Error('Please provide proper Testrail user');
if (!config.password) throw new Error('Please provide proper Testrail password');
if (!config.projectId) throw new Error('Please provide project id in config file');
if (config.resultProcessor && typeof config.resultProcessor !== 'function') {
throw new Error('Result processor (`resultProcessor` config option) has to be function');
}
const testrail = new TestRail(config);
let runName;
let runId;
let failedTests = [];
let passedTests = [];
let skippedTest = [];
let errors = {};
let attachments = {};
let prefixTag;
let defaultElapsedTime = '1s';
runName = config.runName ? config.runName : `New test run on ${_getToday()}`;
prefixTag = config.prefixTag || '@C';
const prefixRegExp = new RegExp(`${prefixTag}\\d+`);
async function _updateTestRun(runId, ids) {
try {
await testrail.updateRun(runId, { case_ids: ids });
} catch (error) {
output.error(`Cannot update run due to ${error}`);
}
}
async function _getTestRun(runId) {
try {
return testrail.getRun(runId);
} catch (error) {
output.error(`Cannot get run due to ${error}`);
}
}
async function _addTestRun(projectId, suiteId, runName) {
try {
return testrail.addRun(projectId, { suite_id: suiteId, name: runName, include_all: false });
} catch (error) {
output.error(`Cannot create new test run due to ${JSON.stringify(error)}`);
}
}
async function _addTestPlan(projectId, planName, data) {
const planData = Object.assign({ name: planName }, data);
return testrail.addPlan(projectId, planData);
}
event.dispatcher.on(event.test.started, async (test) => {
if (test.body) {
if (test.body.includes('addExampleInTable')) {
const testRailTagRegExp = new RegExp(`"testRailTag":"(${prefixTag}\\d+)"`);
const testRailTag = testRailTagRegExp.exec(test.title);
if (testRailTag) {
test.tags.push(testRailTag[1]);
}
}
}
test.startTime = Date.now();
});
const failedTestCaseIds = new Set();
event.dispatcher.on(event.test.skipped, async (test) => {
test.endTime = Date.now();
test.elapsed = Math.round((test.endTime - test.startTime) / 1000);
test.tags.forEach(tag => {
if (prefixRegExp.test(tag)) {
const caseId = tag.split(prefixTag)[1];
const elapsed = !test.elapsed ? defaultElapsedTime : `${test.elapsed}s`;
if (!failedTestCaseIds.has(caseId)) {
// else it also failed on retry, so we shouldn't add in a duplicate
skippedTest.push({ case_id: caseId, elapsed: elapsed });
}
}
});
});
event.dispatcher.on(event.test.failed, async (test, err) => {
test.endTime = Date.now();
test.elapsed = test.duration ? test.duration / 1000 : Math.round((test.endTime - test.startTime) / 1000);
for (const tag of test.tags) {
const uuid = Math.floor(new Date().getTime() / 1000);
const fileName = `${uuid}.failed.png`;
try {
if (helper) {
output.log('Saving the screenshot...');
await helper.saveScreenshot(fileName);
}
} catch (error) {
output.log(`Cannot save screenshot due to ${error}`);
}
if (prefixRegExp.test(tag)) {
const caseId = tag.split(prefixTag)[1];
const elapsed = test.elapsed === 0 ? defaultElapsedTime : `${test.elapsed}s`;
if (!failedTestCaseIds.has(caseId)) {
// else it also failed on retry so we shouldnt add in a duplicate
failedTestCaseIds.add(caseId);
failedTests.push({ case_id: caseId, elapsed: elapsed });
}
errors[tag.split(prefixTag)[1]] = err || test.err;
attachments[tag.split(prefixTag)[1]] = fileName;
}
}
});
event.dispatcher.on(event.test.passed, (test) => {
test.endTime = Date.now();
test.elapsed = test.startTime ? Math.round((test.endTime - test.startTime) / 1000) : 0;
test.tags.forEach(tag => {
if (prefixRegExp.test(tag)) {
const caseId = tag.split(prefixTag)[1];
const elapsed = test.elapsed === 0 ? defaultElapsedTime : `${test.elapsed}s`;
// remove duplicates caused by retries
if (failedTestCaseIds.has(caseId)) {
failedTests = failedTests.filter(({ case_id }) => case_id !== caseId);
}
passedTests.push({ case_id: caseId, elapsed: elapsed });
}
});
});
event.dispatcher.on(event.workers.result, async (result) => {
for (const test of result.tests.passed) {
test.tags.forEach(tag => {
if (prefixRegExp.test(tag)) {
const caseId = tag.split(prefixTag)[1];
const elapsed = !test.duration ? defaultElapsedTime : `${test.duration / 1000}s`;
passedTests.push({ case_id: caseId , elapsed });
}
});
}
for (const test of result.tests.failed) {
test.tags.forEach(tag => {
if (prefixRegExp.test(tag)) {
const caseId = tag.split(prefixTag)[1];
const elapsed = !test.duration ? defaultElapsedTime : `${test.duration / 1000}s`;
failedTests.push({ case_id: caseId, elapsed });
errors[caseId] = test.err;
attachments[caseId] = clearString(test.title) + '.failed.png';
}
});
}
await _publishResultsToTestrail();
});
event.dispatcher.on(event.all.result, async () => {
if (!process.env.RUNS_WITH_WORKERS) {
await _publishResultsToTestrail();
}
});
async function _publishResultsToTestrail() {
const mergedTests = [...failedTests, ...passedTests, ...skippedTest];
let ids = [];
let config_ids = [];
mergedTests.forEach(test => {
for (const [key, value] of Object.entries(test)) {
if (key === 'case_id') {
ids.push(value);
}
}
});
if (ids.length > 0) {
let suiteId;
if (config.suiteId === undefined || config.suiteId === null) {
let res = await testrail.getSuites(config.projectId);
suiteId = res[0].id;
} else {
suiteId = config.suiteId;
}
if (config.configuration) {
const res = await testrail.getConfigs(config.projectId);
for (let i = 0; i < res.length; i++) {
if (res[i].name === config.configuration.groupName) {
for (let j = 0; j < res[i].configs.length; j++) {
if (res[i].configs[j].name === config.configuration.configName) {
config_ids.push(res[i].configs[j].id);
}
}
}
}
}
if (config.plan) {
if (config.plan.existingPlanId) {
let data = {
suite_id: suiteId,
name: runName,
include_all: !config.plan.onlyCaseIds,
config_ids,
runs: [{
include_all: false,
case_ids: ids,
config_ids
}]
};
if (config.plan.onlyCaseIds) {
data = { ...data, case_ids: ids };
}
const res = await testrail.addPlanEntry(config.plan.existingPlanId, data);
runId = config.runId ? config.runId : res.runs[0].id;
} else {
const data = {
description: config.plan.description || '',
entries: [{
suite_id: suiteId,
name: runName,
include_all: true,
config_ids,
runs: [{
include_all: false,
case_ids: ids,
config_ids
}]
}]
};
const res = await _addTestPlan(config.projectId, config.plan.name, data);
runId = res.entries[0].runs[0].id;
}
} else {
try {
if (config.runId) {
runId = config.runId;
} else {
const res = await _addTestRun(config.projectId, suiteId, runName);
process.env.TESTRAIL_RUN_URL = res.url;
runId = res.id;
}
// Do not update the run if it is part of a plan, but this has not been specified in the config
const runData = await _getTestRun(runId);
if (runData && !runData.plan_id) {
await _updateTestRun(runId, ids);
}
} catch (error) {
output.error(error);
}
}
// Assign extra/missing params for each PASSED test case
passedTests.forEach(test => {
const testCase = {
passed: {
comment: config.testCase.passed.comment || `Test case ${prefixTag}${test.case_id} is *PASSED*.`,
status_id: config.testCase.passed.status_id,
version: config.version
}
};
Object.assign(test, testCase.passed);
});
// Assign extra/missing params for each FAILED test case
failedTests.forEach(test => {
let errorString = '';
if (errors[test.case_id] && errors[test.case_id]['message']) {
errorString = errors[test.case_id]['message'].replace(/\u001b\[.*?m/g, '');
} else {
errorString = errors[test.case_id];
}
const testCase = {
failed: {
comment: config.testCase.failed.comment || `Test case C${test.case_id} is *FAILED* due to **${JSON.stringify(errorString)}**`,
status_id: config.testCase.failed.status_id,
version: config.version
}
};
Object.assign(test, testCase.failed);
});
skippedTest.forEach(test => {
const testCase = {
failed: {
comment: `SKIPPED - ${config.skipInfo.message}`,
status_id: config.testCase.skipped.status_id,
version: config.version
}
};
Object.assign(test, testCase.failed);
});
const allResults = passedTests.concat(failedTests.concat(skippedTest));
testrail.getCases(config.projectId, config.suiteId).then(testCases => {
if (testCases.length) {
// Before POST-ing the results, filter the array for any non-existing tags in TR test bucket assigned to this test run
// This is to avoid any failure to POST results due to labels in the results array not part of the test run
const { validResults, missingLabels } = allResults.reduce(
(acc, testResult) => {
const testCase = testCases.find(it => it.id == testResult.case_id);
// If there is `resultProcessor` callback in config, then we need to process test result
const processedResult = config.resultProcessor
? config.resultProcessor(testResult, { testCase, allResults, allTestCases: testCases })
: testResult;
if (processedResult) {
if (testCase) {
acc.validResults.push(processedResult);
} else {
acc.missingLabels.push(processedResult);
}
}
return acc;
},
{ validResults: [], missingLabels: [] }
);
if (missingLabels.length) {
output.error(`Error: some labels are missing from the test run and the results were not send through: ${JSON.stringify(missingLabels.map(l => l.case_id))}`);
}
return { validResults };
}
return { validResults: [] };
}).then(({ validResults }) => {
if (validResults.length) {
testrail.addResultsForCases(runId, {results: validResults}).then(res => {
output.log(`The run ${runId} is updated with ${JSON.stringify(res)}`);
for (const test of failedTests) {
testrail.getResultsForCase(runId, test.case_id).then(async res => {
try {
helper && await testrail.addAttachmentToResult(res[0].id, attachments[test.case_id]);
} catch (err) {
output.error(`Cannot add attachment due to error: ${err}`);
}
});
}
});
_closeTestRun();
}
});
} else {
output.log('There is no TC, hence no test run is created');
}
}
function _closeTestRun() {
if (config.closeTestRun === true) {
testrail.closeTestRun(runId).then(res => {
output.log(`The run ${runId} is updated with ${JSON.stringify(res)}`);
});
}
}
return this;
};
function _getToday() {
const today = new Date();
let dd = today.getDate();
let mm = today.getMonth() + 1; // January is 0!
const yyyy = today.getFullYear();
let hour = today.getHours();
let minute = today.getMinutes();
if (dd < 10) {
dd = `0${dd}`;
}
if (mm < 10) {
mm = `0${mm}`;
}
if (minute < 10) {
minute = `0${minute}`;
}
return `${dd}/${mm}/${yyyy} ${hour}:${minute}`;
}