reporting-labs 0.6.15 → 0.6.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -5
- package/dist/cypress/index.d.ts +134 -0
- package/dist/cypress/index.js +504 -0
- package/dist/cypress/support.d.ts +19 -0
- package/dist/cypress/support.js +231 -0
- package/dist/explain.js +105 -0
- package/dist/template.html +6 -3
- package/dist/template.js +6 -3
- package/dist/wdio/finalize.d.ts +2 -39
- package/dist/wdio/finalize.js +3 -102
- package/dist/write-report.d.ts +51 -0
- package/dist/write-report.js +149 -0
- package/package.json +11 -1
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.CypressCollector = void 0;
|
|
37
|
+
exports.reportingLabs = reportingLabs;
|
|
38
|
+
/**
|
|
39
|
+
* reportingLabs for Cypress.
|
|
40
|
+
*
|
|
41
|
+
* // cypress.config.js
|
|
42
|
+
* const { defineConfig } = require('cypress');
|
|
43
|
+
* const { reportingLabs } = require('reporting-labs/cypress');
|
|
44
|
+
*
|
|
45
|
+
* module.exports = defineConfig({
|
|
46
|
+
* e2e: {
|
|
47
|
+
* setupNodeEvents(on, config) {
|
|
48
|
+
* reportingLabs(on, config, { title: 'Checkout regression' });
|
|
49
|
+
* return config;
|
|
50
|
+
* },
|
|
51
|
+
* },
|
|
52
|
+
* });
|
|
53
|
+
*
|
|
54
|
+
* `cypress run` then writes reporting-labs/index.html, report.json and report.pdf: the same report the Playwright
|
|
55
|
+
* reporter makes. It is built from what Cypress hands the Node process after every spec (`after:spec`): each test's
|
|
56
|
+
* title path, state, retries, duration and error, the screenshots and the spec video. Line numbers and comment meta
|
|
57
|
+
* come from the spec file itself. Cypress allows one handler per event, so if your config already listens to
|
|
58
|
+
* before:run / after:spec / after:run, call the handlers this returns from your own (see README).
|
|
59
|
+
*
|
|
60
|
+
* Nothing here touches the Playwright or WebdriverIO reporters; it only reuses the shared helpers.
|
|
61
|
+
*/
|
|
62
|
+
const fs = __importStar(require("fs"));
|
|
63
|
+
const path = __importStar(require("path"));
|
|
64
|
+
const crypto = __importStar(require("crypto"));
|
|
65
|
+
const write_report_1 = require("../write-report");
|
|
66
|
+
const mask_1 = require("../mask");
|
|
67
|
+
const explain_1 = require("../explain");
|
|
68
|
+
const comments_1 = require("../comments");
|
|
69
|
+
const reporter_1 = require("../wdio/reporter");
|
|
70
|
+
const reporter_2 = require("../reporter");
|
|
71
|
+
const DEFAULT_EMBED_LIMIT = 2 * 1024 * 1024;
|
|
72
|
+
const ATTEMPT_TASK = 'reportingLabs:attempt';
|
|
73
|
+
const ENABLED_FLAG = 'reportingLabsEnabled';
|
|
74
|
+
function reportingLabs(on, config = {}, options = {}) {
|
|
75
|
+
const opts = withRuntimeOverrides(options);
|
|
76
|
+
// tells the support file the task is registered; without it, cy.task would fail every test
|
|
77
|
+
// Cypress 16 reads it with Cypress.expose() (config.expose); 12 to 15 with Cypress.env() (config.env)
|
|
78
|
+
try {
|
|
79
|
+
if (config && typeof config === 'object') {
|
|
80
|
+
const major = parseInt(String(config.version ?? ''), 10);
|
|
81
|
+
if ('expose' in config || major >= 16)
|
|
82
|
+
config.expose = { ...(config.expose ?? {}), [ENABLED_FLAG]: true };
|
|
83
|
+
else
|
|
84
|
+
config.env = { ...(config.env ?? {}), [ENABLED_FLAG]: true };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch { /* fine */ }
|
|
88
|
+
const collector = new CypressCollector(opts, config);
|
|
89
|
+
const handlers = {
|
|
90
|
+
beforeRun: d => safe(() => collector.beforeRun(d)),
|
|
91
|
+
afterSpec: (spec, results) => safe(() => collector.afterSpec(spec, results)),
|
|
92
|
+
afterRun: async (results) => { try {
|
|
93
|
+
return await collector.afterRun(results);
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
console.warn('reporting-labs: report not written:', e?.message ?? e);
|
|
97
|
+
return undefined;
|
|
98
|
+
} },
|
|
99
|
+
};
|
|
100
|
+
if (typeof on === 'function') {
|
|
101
|
+
// what the support file collects in the browser; Cypress merges this with the project's own tasks
|
|
102
|
+
on('task', { [ATTEMPT_TASK]: (payload) => { safe(() => collector.addAttempt(payload)); return null; } });
|
|
103
|
+
on('before:run', handlers.beforeRun);
|
|
104
|
+
on('after:spec', handlers.afterSpec);
|
|
105
|
+
on('after:run', handlers.afterRun);
|
|
106
|
+
}
|
|
107
|
+
return handlers;
|
|
108
|
+
}
|
|
109
|
+
exports.default = reportingLabs;
|
|
110
|
+
function safe(fn) { try {
|
|
111
|
+
fn();
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
console.warn('reporting-labs:', e?.message ?? e);
|
|
115
|
+
} }
|
|
116
|
+
/** REPORTING_LABS_* variables beat the options, the same contract as the Playwright, Java and Python reporters. */
|
|
117
|
+
function withRuntimeOverrides(options) {
|
|
118
|
+
const metadata = { ...(options.metadata ?? {}) };
|
|
119
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
120
|
+
const m = /^REPORTING_LABS_METADATA_([A-Z0-9_]+)$/.exec(k);
|
|
121
|
+
if (m && v && v.trim())
|
|
122
|
+
metadata[m[1].toLowerCase()] = v.trim();
|
|
123
|
+
}
|
|
124
|
+
if (!process.env.REPORTING_LABS_METADATA_ENV) {
|
|
125
|
+
const detected = (0, reporter_2.detectEnvName)(process.env, options.envVar);
|
|
126
|
+
if (detected)
|
|
127
|
+
metadata.env = detected;
|
|
128
|
+
}
|
|
129
|
+
const scalar = (name, current) => { const v = process.env['REPORTING_LABS_' + name]; return v && v.trim() ? v.trim() : current; };
|
|
130
|
+
return { ...options, metadata,
|
|
131
|
+
title: scalar('TITLE', options.title), theme: scalar('THEME', options.theme),
|
|
132
|
+
palette: scalar('PALETTE', options.palette), accent: scalar('ACCENT', options.accent),
|
|
133
|
+
logo: scalar('LOGO', options.logo), outputFolder: scalar('OUTPUT_FOLDER', options.outputFolder) };
|
|
134
|
+
}
|
|
135
|
+
class CypressCollector {
|
|
136
|
+
constructor(options, config = {}) {
|
|
137
|
+
this.options = options;
|
|
138
|
+
this.config = config;
|
|
139
|
+
this.tests = [];
|
|
140
|
+
this.startTime = 0;
|
|
141
|
+
this.endTime = 0;
|
|
142
|
+
this.browser = '';
|
|
143
|
+
this.cypressVersion = '';
|
|
144
|
+
this.assetCounter = 0;
|
|
145
|
+
this.assetsReady = false;
|
|
146
|
+
this.attempts = new Map();
|
|
147
|
+
this.masker = (0, mask_1.makeMasker)(options.maskKeys ?? [], { knownValues: options.maskValues ?? [], fromEnv: options.maskFromEnv !== false });
|
|
148
|
+
this.base = typeof config.projectRoot === 'string' && config.projectRoot ? config.projectRoot : process.cwd();
|
|
149
|
+
this.outDir = path.resolve(this.base, options.outputFolder || 'reporting-labs');
|
|
150
|
+
this.assetsDir = path.join(this.outDir, 'assets');
|
|
151
|
+
}
|
|
152
|
+
addAttempt(p) {
|
|
153
|
+
if (!p || !Array.isArray(p.titlePath))
|
|
154
|
+
return;
|
|
155
|
+
const key = attemptKey(p.spec, p.titlePath);
|
|
156
|
+
const list = this.attempts.get(key) ?? [];
|
|
157
|
+
list[Math.max(0, Number(p.retry) || 0)] = p;
|
|
158
|
+
this.attempts.set(key, list);
|
|
159
|
+
}
|
|
160
|
+
beforeRun(d = {}) {
|
|
161
|
+
this.startTime = Date.now();
|
|
162
|
+
this.browser = browserLabel(d.browser);
|
|
163
|
+
this.cypressVersion = d.cypressVersion || '';
|
|
164
|
+
this.prepareAssets();
|
|
165
|
+
}
|
|
166
|
+
/** assets/ holds this run's copied files only: emptied once per run, before the first file lands. */
|
|
167
|
+
prepareAssets() {
|
|
168
|
+
if (this.assetsReady)
|
|
169
|
+
return;
|
|
170
|
+
this.assetsReady = true;
|
|
171
|
+
try {
|
|
172
|
+
fs.rmSync(this.assetsDir, { recursive: true, force: true });
|
|
173
|
+
}
|
|
174
|
+
catch { /* fine */ }
|
|
175
|
+
}
|
|
176
|
+
afterSpec(spec = {}, results = {}) {
|
|
177
|
+
this.prepareAssets();
|
|
178
|
+
const s = results.spec ?? spec ?? {};
|
|
179
|
+
const abs = s.absolute || spec.absolute || '';
|
|
180
|
+
const file = this.rel(abs || s.relative || spec.relative || s.name || '');
|
|
181
|
+
const startedAt = Date.parse(results.stats?.startedAt ?? '') || Date.now();
|
|
182
|
+
const endedAt = Date.parse(results.stats?.endedAt ?? '') || startedAt + (results.stats?.duration ?? 0);
|
|
183
|
+
if (!this.startTime || startedAt < this.startTime)
|
|
184
|
+
this.startTime = startedAt;
|
|
185
|
+
if (endedAt > this.endTime)
|
|
186
|
+
this.endTime = endedAt;
|
|
187
|
+
const cyTests = results.tests ?? [];
|
|
188
|
+
const out = [];
|
|
189
|
+
let cursor = startedAt;
|
|
190
|
+
const specRel = (s.relative || spec.relative || '').split(path.sep).join('/');
|
|
191
|
+
for (const ct of cyTests) {
|
|
192
|
+
const t = this.toTest(ct, abs, file, cursor);
|
|
193
|
+
this.enrich(t, this.attempts.get(attemptKey(specRel, ct.title ?? [])), abs);
|
|
194
|
+
cursor = Math.max(cursor + t.duration, ...t.results.map(r => r.startTime + r.duration));
|
|
195
|
+
out.push(t);
|
|
196
|
+
}
|
|
197
|
+
// The spec could not run at all (syntax error, failed import, uncaught error before the first test)
|
|
198
|
+
if (!out.length && results.error) {
|
|
199
|
+
const t = this.toTest({ title: [s.name || path.basename(file) || 'spec'], state: 'failed', duration: 0, displayError: results.error, attempts: [{ state: 'failed' }] }, abs, file, startedAt);
|
|
200
|
+
t.note = 'The spec failed before any test ran.';
|
|
201
|
+
out.push(t);
|
|
202
|
+
}
|
|
203
|
+
this.attachScreenshots(out, cyTests, results.screenshots ?? [], startedAt);
|
|
204
|
+
this.attachVideo(out, results.video, file);
|
|
205
|
+
this.tests.push(...out);
|
|
206
|
+
}
|
|
207
|
+
async afterRun(results = {}) {
|
|
208
|
+
if (!this.tests.length) {
|
|
209
|
+
if ((results.totalTests ?? 0) > 0)
|
|
210
|
+
console.warn('\n reporting-labs: no report: no spec results reached it. Cypress keeps one handler per event, so an after:spec\n' +
|
|
211
|
+
' registered after reportingLabs() replaced ours. Call it from yours: const rl = reportingLabs(on, config, {…});\n' +
|
|
212
|
+
" on('after:spec', (spec, results) => { rl.afterSpec(spec, results); /* your code */ });\n");
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
if (!this.attempts.size && this.options.announce !== false) {
|
|
216
|
+
console.log("\n reporting-labs: no steps or API calls came from the browser. For them, add import 'reporting-labs/cypress/support';\n" +
|
|
217
|
+
" to cypress/support/e2e.js and make sure setupNodeEvents ends with return config;");
|
|
218
|
+
}
|
|
219
|
+
const project = this.browser || results.browserName || '';
|
|
220
|
+
for (const t of this.tests) {
|
|
221
|
+
t.project = project;
|
|
222
|
+
t.key = `${project}::${t.file}::${[...t.path, t.title].join(' › ')}`;
|
|
223
|
+
}
|
|
224
|
+
const start = Date.parse(results.startedTestsAt ?? '') || this.startTime || Date.now();
|
|
225
|
+
const end = Date.parse(results.endedTestsAt ?? '') || this.endTime || Date.now();
|
|
226
|
+
const failed = this.tests.some(t => t.outcome === 'failed' || t.outcome === 'timedOut');
|
|
227
|
+
const version = this.cypressVersion || results.cypressVersion || '';
|
|
228
|
+
const bver = results.browserVersion ? ` ${results.browserVersion}` : '';
|
|
229
|
+
const envRows = version ? [{ k: 'Cypress', v: version + (project ? ` · ${project}${bver}` : '') }] : [];
|
|
230
|
+
return (0, write_report_1.writeReport)(this.tests, { startTime: start, endTime: Math.max(end, start), runStatus: failed ? 'failed' : 'passed', workers: 1, envRows }, { ...this.options, outputFolder: this.outDir, logo: this.resolveLogo(this.options.logo), bdd: this.options.bdd });
|
|
231
|
+
}
|
|
232
|
+
/** One Cypress test → one report row. Cypress gives the attempts' states but one duration and one error (the last). */
|
|
233
|
+
toTest(ct, abs, file, startTime) {
|
|
234
|
+
const titles = (ct.title ?? []).map(x => String(x));
|
|
235
|
+
const title = titles[titles.length - 1] ?? '';
|
|
236
|
+
const suites = titles.slice(0, -1);
|
|
237
|
+
const attempts = ct.attempts && ct.attempts.length ? ct.attempts : [{ state: ct.state }];
|
|
238
|
+
const total = Math.max(0, Math.round(ct.duration ?? 0));
|
|
239
|
+
const each = attempts.length > 1 ? Math.round(total / attempts.length) : total;
|
|
240
|
+
// Line numbers and comment meta from the spec file: each describe is looked up after the one around it
|
|
241
|
+
const at = [];
|
|
242
|
+
let from = 0;
|
|
243
|
+
for (const st of suites) {
|
|
244
|
+
const ln = abs ? (0, comments_1.lineOfTitle)(abs, st, 'describe|context|suite', from) : 0;
|
|
245
|
+
if (ln) {
|
|
246
|
+
at.push(ln);
|
|
247
|
+
from = ln;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const line = abs ? (0, comments_1.lineOfTitle)(abs, title, 'it|test|specify', from) : 0;
|
|
251
|
+
const tags = [...titles.join(' ').matchAll(/@[A-Za-z][\w:.=-]*/g)].map(m => m[0]);
|
|
252
|
+
const fromComments = {};
|
|
253
|
+
if (abs && this.options.commentMeta !== false) {
|
|
254
|
+
try {
|
|
255
|
+
for (const ln of [...at, line].filter(Boolean)) {
|
|
256
|
+
const c = (0, comments_1.commentMetaAt)(abs, ln);
|
|
257
|
+
Object.assign(fromComments, c.meta);
|
|
258
|
+
for (const g of c.tags)
|
|
259
|
+
if (!tags.includes(g) && !reporter_1.META_KEYS.includes(g.slice(1).toLowerCase()))
|
|
260
|
+
tags.push(g);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
catch { /* comments are a convenience: never fail the run over them */ }
|
|
264
|
+
}
|
|
265
|
+
const { meta, clean } = (0, reporter_1.metaFromTags)(tags, reporter_1.META_KEYS);
|
|
266
|
+
for (const [k, v] of Object.entries(fromComments))
|
|
267
|
+
meta[k] = this.masker.maskStr(v);
|
|
268
|
+
const results = attempts.map((a, i) => {
|
|
269
|
+
const status = cyStatus(a.state);
|
|
270
|
+
const last = i === attempts.length - 1;
|
|
271
|
+
const r = {
|
|
272
|
+
retry: i, status, duration: last ? total - each * (attempts.length - 1) : each, startTime: startTime + each * i, workerIndex: 0,
|
|
273
|
+
errors: [], steps: [], attachments: [], stdout: [], stderr: [], logs: [], data: [], api: [],
|
|
274
|
+
};
|
|
275
|
+
if (status === 'failed' && last && ct.displayError)
|
|
276
|
+
r.errors.push(this.toError(ct.displayError, abs));
|
|
277
|
+
return r;
|
|
278
|
+
});
|
|
279
|
+
const finalState = cyStatus(ct.state ?? attempts[attempts.length - 1].state);
|
|
280
|
+
let outcome = finalState === 'passed' ? 'passed' : finalState === 'skipped' ? 'skipped' : 'failed';
|
|
281
|
+
if (outcome === 'passed' && results.some(r => r.status === 'failed'))
|
|
282
|
+
outcome = 'flaky';
|
|
283
|
+
// a failing final state whose last attempt Cypress reports otherwise: keep the error on the last result
|
|
284
|
+
if (outcome === 'failed' && ct.displayError && !results[results.length - 1].errors.length)
|
|
285
|
+
results[results.length - 1].errors.push(this.toError(ct.displayError, abs));
|
|
286
|
+
const t = {
|
|
287
|
+
id: crypto.createHash('sha1').update(file + '\u0000' + titles.join('\u0000')).digest('hex').slice(0, 20),
|
|
288
|
+
key: '', title: this.masker.maskStr(title), path: suites.map(x => this.masker.maskStr(x)),
|
|
289
|
+
file, line, project: '', tags: clean, annotations: [], meta,
|
|
290
|
+
outcome, duration: total, results, retries: attempts.length - 1,
|
|
291
|
+
};
|
|
292
|
+
if (ct.state === 'skipped')
|
|
293
|
+
t.note = 'Not run: a before / beforeEach hook failed earlier in this spec.';
|
|
294
|
+
const hook = /during a `(before all|before each|after each|after all)` hook/.exec(ct.displayError ?? '');
|
|
295
|
+
if (hook)
|
|
296
|
+
t.note = `Failed in the ${hook[1]} hook${/before all|after all/.test(hook[1]) ? ', so Cypress skipped the other tests of this describe and did not retry' : ''}.`;
|
|
297
|
+
if (ct.state === 'pending')
|
|
298
|
+
t.annotations.push({ type: 'skip' });
|
|
299
|
+
return t;
|
|
300
|
+
}
|
|
301
|
+
/** What the support file sent for this test: real per-attempt times, steps, API calls, each attempt's error, meta(). */
|
|
302
|
+
enrich(t, attempts, abs) {
|
|
303
|
+
if (!attempts || !attempts.length)
|
|
304
|
+
return;
|
|
305
|
+
t.results.forEach((r, i) => {
|
|
306
|
+
const a = attempts[i];
|
|
307
|
+
if (!a)
|
|
308
|
+
return;
|
|
309
|
+
if (typeof a.start === 'number' && a.start > 0)
|
|
310
|
+
r.startTime = a.start;
|
|
311
|
+
if (typeof a.duration === 'number')
|
|
312
|
+
r.duration = Math.max(0, Math.round(a.duration));
|
|
313
|
+
// API calls first: masking them teaches the masker the secrets they carry (a password in a body), so the
|
|
314
|
+
// same value typed in a step is blanked too
|
|
315
|
+
r.api = (a.api ?? []).map(c => this.masker.mask(trimApi(c, this.options)));
|
|
316
|
+
r.steps = (a.steps ?? []).map(st => this.maskStep(st));
|
|
317
|
+
if (r.status === 'failed' && !r.errors.length && a.err?.message)
|
|
318
|
+
r.errors.push(this.toError([a.err.message, a.err.stack ? a.err.stack.replace(/^[^\n]*\n?/, '') : ''].filter(Boolean).join('\n'), abs));
|
|
319
|
+
const cf = a.err?.codeFrame;
|
|
320
|
+
const e = r.errors[0];
|
|
321
|
+
if (e && cf?.line && !e.location && abs) {
|
|
322
|
+
e.location = { file: this.rel(abs), line: cf.line, column: cf.column ?? 0 };
|
|
323
|
+
const snip = codeFrame(abs, cf.line, cf.column ?? 0);
|
|
324
|
+
if (snip)
|
|
325
|
+
e.snippet = snip;
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
t.duration = t.results.reduce((n, r) => n + r.duration, 0);
|
|
329
|
+
// meta() in the test wins over comments and tags, as in Playwright
|
|
330
|
+
const m = attempts[attempts.length - 1]?.meta ?? {};
|
|
331
|
+
for (const [k, v] of Object.entries(m)) {
|
|
332
|
+
if (v === undefined || v === null || typeof v === 'object' && !Array.isArray(v))
|
|
333
|
+
continue;
|
|
334
|
+
t.meta[k.toLowerCase()] = this.masker.maskStr(Array.isArray(v) ? v.join(', ') : String(v));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
maskStep(st) {
|
|
338
|
+
return { title: this.masker.maskStr(String(st.title ?? '')), category: String(st.category ?? 'cy'), duration: Math.max(0, Math.round(Number(st.duration) || 0)),
|
|
339
|
+
...(st.error ? { error: this.masker.maskStr(stripAnsi(String(st.error))) } : {}), steps: (st.steps ?? []).map(c => this.maskStep(c)) };
|
|
340
|
+
}
|
|
341
|
+
/** displayError is the message plus a stack (" at …"); the first frame in the spec file gives the location. */
|
|
342
|
+
toError(display, abs) {
|
|
343
|
+
const clean = stripAnsi(display);
|
|
344
|
+
const idx = clean.search(/\n\s+at /);
|
|
345
|
+
const message = this.masker.maskStr((idx >= 0 ? clean.slice(0, idx) : clean).trim());
|
|
346
|
+
const stack = idx >= 0 ? this.masker.maskStr(clean.slice(idx + 1)) : undefined;
|
|
347
|
+
const d = { message };
|
|
348
|
+
if (stack)
|
|
349
|
+
d.stack = stack;
|
|
350
|
+
const ex = (0, explain_1.explainError)(message);
|
|
351
|
+
if (ex)
|
|
352
|
+
d.explain = ex;
|
|
353
|
+
if (abs) {
|
|
354
|
+
const base = path.basename(abs).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
355
|
+
const m = new RegExp(`${base}:(\\d+):(\\d+)`).exec(stack ?? clean);
|
|
356
|
+
if (m) {
|
|
357
|
+
const line = Number(m[1]), column = Number(m[2]);
|
|
358
|
+
d.location = { file: this.rel(abs), line, column };
|
|
359
|
+
const snip = codeFrame(abs, line, column);
|
|
360
|
+
if (snip)
|
|
361
|
+
d.snippet = snip;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return d;
|
|
365
|
+
}
|
|
366
|
+
/** Cypress names a failure screenshot "<describe> -- <it> (failed) (attempt 2).png"; a custom cy.screenshot('name')
|
|
367
|
+
* is matched to the test that was running when it was taken. */
|
|
368
|
+
attachScreenshots(tests, cyTests, shots, specStart) {
|
|
369
|
+
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '');
|
|
370
|
+
const byName = new Map();
|
|
371
|
+
cyTests.forEach((ct, i) => byName.set(norm((ct.title ?? []).join(' -- ')), i));
|
|
372
|
+
for (const sh of shots) {
|
|
373
|
+
if (!sh.path)
|
|
374
|
+
continue;
|
|
375
|
+
const base = path.basename(sh.path).replace(/\.\w+$/, '');
|
|
376
|
+
const attemptM = /\(attempt (\d+)\)\s*$/.exec(base);
|
|
377
|
+
const stem = base.replace(/\s*\(attempt \d+\)\s*$/, '').replace(/\s*\(failed\)\s*$/, '');
|
|
378
|
+
let ti = byName.get(norm(stem));
|
|
379
|
+
if (ti === undefined) {
|
|
380
|
+
// custom name: the test whose time window holds takenAt, else the spec's only test
|
|
381
|
+
const at = Date.parse(sh.takenAt ?? '');
|
|
382
|
+
tests.forEach((t, i) => { if (ti === undefined && at && t.results.some(r => at >= r.startTime && at <= r.startTime + r.duration + 1000))
|
|
383
|
+
ti = i; });
|
|
384
|
+
if (ti === undefined && tests.length === 1)
|
|
385
|
+
ti = 0;
|
|
386
|
+
}
|
|
387
|
+
if (ti === undefined || !tests[ti])
|
|
388
|
+
continue;
|
|
389
|
+
const t = tests[ti];
|
|
390
|
+
const at = Date.parse(sh.takenAt ?? '');
|
|
391
|
+
const byTime = at ? t.results.findIndex(r => at >= r.startTime && at <= r.startTime + r.duration + 1000) : -1;
|
|
392
|
+
const ri = attemptM ? Math.min(Number(attemptM[1]) - 1, t.results.length - 1) : (/\(failed\)/.test(base) ? firstFailed(t) : byTime >= 0 ? byTime : t.results.length - 1);
|
|
393
|
+
const a = this.attachment(sh.path, /\(failed\)/.test(base) ? 'screenshot' : (sh.name || stem), t.title);
|
|
394
|
+
if (a)
|
|
395
|
+
t.results[Math.max(0, ri)].attachments.push(a);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
attachVideo(tests, video, file) {
|
|
399
|
+
if (!video || !fs.existsSync(video))
|
|
400
|
+
return;
|
|
401
|
+
const who = this.options.video === 'all' ? tests : tests.filter(t => t.outcome === 'failed' || t.outcome === 'flaky');
|
|
402
|
+
if (!who.length)
|
|
403
|
+
return;
|
|
404
|
+
const a = this.attachment(video, 'video', path.basename(file) || 'spec', true);
|
|
405
|
+
if (!a)
|
|
406
|
+
return;
|
|
407
|
+
for (const t of who)
|
|
408
|
+
t.results[t.results.length - 1].attachments.push({ ...a });
|
|
409
|
+
}
|
|
410
|
+
attachment(p, name, owner, isVideoFile = false) {
|
|
411
|
+
try {
|
|
412
|
+
if (!fs.existsSync(p))
|
|
413
|
+
return null;
|
|
414
|
+
const ext = path.extname(p).toLowerCase();
|
|
415
|
+
const contentType = ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.mp4' ? 'video/mp4' : ext === '.webm' ? 'video/webm' : 'application/octet-stream';
|
|
416
|
+
const size = fs.statSync(p).size;
|
|
417
|
+
const out = { name, contentType, size };
|
|
418
|
+
const isVideo = isVideoFile || contentType.startsWith('video/');
|
|
419
|
+
const embed = (this.options.embedAttachments ?? true) && (!isVideo || this.options.embedVideos === true);
|
|
420
|
+
if (embed && size <= (this.options.embedLimit ?? DEFAULT_EMBED_LIMIT)) {
|
|
421
|
+
out.src = `data:${contentType};base64,${fs.readFileSync(p).toString('base64')}`;
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
fs.mkdirSync(this.assetsDir, { recursive: true });
|
|
425
|
+
const fname = `${sanitize(owner)}-${sanitize(name)}-${this.assetCounter++}${ext}`;
|
|
426
|
+
fs.copyFileSync(p, path.join(this.assetsDir, fname));
|
|
427
|
+
out.src = `assets/${fname}`;
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
resolveLogo(logo) {
|
|
435
|
+
if (!logo || /^(https?:|data:)/i.test(logo))
|
|
436
|
+
return logo;
|
|
437
|
+
const file = path.resolve(this.base, logo);
|
|
438
|
+
const mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon' };
|
|
439
|
+
const type = mime[path.extname(file).toLowerCase()];
|
|
440
|
+
if (!fs.existsSync(file) || !type) {
|
|
441
|
+
console.warn(`reporting-labs: logo ${logo} not found or not an image`);
|
|
442
|
+
return undefined;
|
|
443
|
+
}
|
|
444
|
+
return `data:${type};base64,${fs.readFileSync(file).toString('base64')}`;
|
|
445
|
+
}
|
|
446
|
+
rel(file) {
|
|
447
|
+
if (!file)
|
|
448
|
+
return file;
|
|
449
|
+
if (!path.isAbsolute(file))
|
|
450
|
+
return file.split(path.sep).join('/');
|
|
451
|
+
try {
|
|
452
|
+
return path.relative(this.base, file).split(path.sep).join('/');
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
return file;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
exports.CypressCollector = CypressCollector;
|
|
460
|
+
function attemptKey(spec, titlePath) {
|
|
461
|
+
return String(spec ?? '').split('\\').join('/') + '\u0000' + titlePath.map(String).join('\u0000');
|
|
462
|
+
}
|
|
463
|
+
/** Bodies are kept up to apiMaxBody characters (default 64 KB), as for Playwright. */
|
|
464
|
+
function trimApi(c, options) {
|
|
465
|
+
const max = options.apiMaxBody ?? 64 * 1024;
|
|
466
|
+
const cut = (v) => { if (v === undefined || v === null)
|
|
467
|
+
return v; const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > max ? s.slice(0, max) + '…' : v; };
|
|
468
|
+
return { ...c, requestBody: cut(c.requestBody), responseBody: cut(c.responseBody) };
|
|
469
|
+
}
|
|
470
|
+
function cyStatus(state) {
|
|
471
|
+
return state === 'passed' ? 'passed' : state === 'failed' ? 'failed' : 'skipped';
|
|
472
|
+
}
|
|
473
|
+
function firstFailed(t) {
|
|
474
|
+
const i = t.results.findIndex(r => r.status === 'failed');
|
|
475
|
+
return i >= 0 ? i : t.results.length - 1;
|
|
476
|
+
}
|
|
477
|
+
function browserLabel(b) {
|
|
478
|
+
if (!b)
|
|
479
|
+
return '';
|
|
480
|
+
return String(b.name || b.displayName || '').toLowerCase();
|
|
481
|
+
}
|
|
482
|
+
function stripAnsi(s) { return s.replace(/\x1b\[[0-9;]*m/g, ''); }
|
|
483
|
+
function sanitize(s) { return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'file'; }
|
|
484
|
+
/** The lines around `line` with a marker, like Playwright's error snippet. */
|
|
485
|
+
function codeFrame(file, line, column) {
|
|
486
|
+
let src;
|
|
487
|
+
try {
|
|
488
|
+
src = fs.readFileSync(file, 'utf8').split(/\r?\n/);
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
return undefined;
|
|
492
|
+
}
|
|
493
|
+
if (line < 1 || line > src.length)
|
|
494
|
+
return undefined;
|
|
495
|
+
const lo = Math.max(1, line - 2), hi = Math.min(src.length, line + 2);
|
|
496
|
+
const w = String(hi).length;
|
|
497
|
+
const rows = [];
|
|
498
|
+
for (let n = lo; n <= hi; n++) {
|
|
499
|
+
rows.push(`${n === line ? '>' : ' '} ${String(n).padStart(w)} | ${src[n - 1]}`);
|
|
500
|
+
if (n === line && column > 0)
|
|
501
|
+
rows.push(` ${' '.repeat(w)} | ${' '.repeat(column - 1)}^`);
|
|
502
|
+
}
|
|
503
|
+
return rows.join('\n');
|
|
504
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reportingLabs support file for Cypress: runs in the browser, next to your tests.
|
|
3
|
+
*
|
|
4
|
+
* // cypress/support/e2e.js
|
|
5
|
+
* import 'reporting-labs/cypress/support';
|
|
6
|
+
*
|
|
7
|
+
* For every attempt of every test it collects what the Node-side plugin cannot see, and hands it over in an
|
|
8
|
+
* afterEach hook (cy.task, not logged):
|
|
9
|
+
* - the Cypress commands as steps (cy.get → type / click, assertions), hooks grouped, timings, the failing step
|
|
10
|
+
* - cy.request calls with their request and response, and the app's own fetch / XHR calls, for the API tab
|
|
11
|
+
* - the error of every attempt with Cypress's code frame (the Node side only gets the last one)
|
|
12
|
+
* - meta({ owner, priority, … }) called in the test
|
|
13
|
+
* A value typed into a password field is masked here; everything else is masked by the plugin with the report's
|
|
14
|
+
* masking rules. Nothing in this file may ever fail a test: every handler is guarded.
|
|
15
|
+
*
|
|
16
|
+
* In a spec: import { meta } from 'reporting-labs/cypress/support'; … meta({ owner: 'asha', priority: 'P1' });
|
|
17
|
+
*/
|
|
18
|
+
/** Meta for the running test: priority, severity, owner, feature, story, issue… The same keys as meta() in Playwright. */
|
|
19
|
+
export declare function meta(values: Record<string, unknown>): void;
|