@testomatio/reporter 2.9.3-beta.3-allure-links → 2.9.3

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.
@@ -1,840 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const debug_1 = __importDefault(require("debug"));
7
- const path_1 = __importDefault(require("path"));
8
- const picocolors_1 = __importDefault(require("picocolors"));
9
- const fs_1 = __importDefault(require("fs"));
10
- const glob_1 = require("glob");
11
- const constants_js_1 = require("./constants.js");
12
- const crypto_1 = require("crypto");
13
- const url_1 = require("url");
14
- const config_js_1 = require("./config.js");
15
- const uploader_js_1 = require("./uploader.js");
16
- const index_js_1 = require("./pipe/index.js");
17
- const pipe_utils_js_1 = require("./utils/pipe_utils.js");
18
- const utils_js_1 = require("./utils/utils.js");
19
- const index_js_2 = __importDefault(require("./junit-adapter/index.js"));
20
- // @ts-ignore
21
- const debug = (0, debug_1.default)('@testomatio/reporter:allure');
22
- const TESTOMATIO_URL = process.env.TESTOMATIO_URL || 'https://app.testomat.io';
23
- const { TESTOMATIO_RUNGROUP_TITLE, TESTOMATIO_SUITE, TESTOMATIO_TITLE, TESTOMATIO_ENV, TESTOMATIO_RUN } = process.env;
24
- class AllureReader {
25
- constructor(opts = {}) {
26
- this.requestParams = {
27
- apiKey: opts.apiKey || config_js_1.config.TESTOMATIO,
28
- url: opts.url || TESTOMATIO_URL,
29
- title: TESTOMATIO_TITLE,
30
- env: TESTOMATIO_ENV,
31
- group_title: TESTOMATIO_RUNGROUP_TITLE,
32
- // Buffer tests and flush them manually in size-limited chunks, exactly like XmlReader.
33
- // No setInterval auto-upload means each test is sent exactly once (no double-send).
34
- batchMode: constants_js_1.BATCH_MODE.MANUAL,
35
- };
36
- this.runId = opts.runId || TESTOMATIO_RUN;
37
- this.opts = opts || {};
38
- this.withPackage = opts.withPackage || false;
39
- this.store = {};
40
- this.pipesPromise = (0, index_js_1.pipesFactory)(opts, this.store);
41
- this._tests = [];
42
- this.stats = {};
43
- this.suites = {};
44
- this.uploader = new uploader_js_1.S3Uploader();
45
- // Allure results already contain steps and stack traces for all tests,
46
- // so enable passing them for passed tests by default
47
- if (!process.env.TESTOMATIO_STACK_PASSED) {
48
- process.env.TESTOMATIO_STACK_PASSED = '1';
49
- }
50
- if (!process.env.TESTOMATIO_STEPS_PASSED) {
51
- process.env.TESTOMATIO_STEPS_PASSED = '1';
52
- }
53
- const packageJsonPath = path_1.default.resolve(__dirname, '..', 'package.json');
54
- this.version = JSON.parse(fs_1.default.readFileSync(packageJsonPath).toString()).version;
55
- console.log(constants_js_1.APP_PREFIX, `Testomatio Reporter v${this.version}`);
56
- }
57
- get tests() {
58
- return this._tests;
59
- }
60
- set tests(value) {
61
- this._tests = value;
62
- }
63
- async createRun() {
64
- const runParams = {
65
- api_key: this.requestParams.apiKey,
66
- title: this.requestParams.title,
67
- env: this.requestParams.env,
68
- group_title: this.requestParams.group_title,
69
- batchMode: this.requestParams.batchMode,
70
- };
71
- debug('Run', runParams);
72
- this.pipes = this.pipes || (await this.pipesPromise);
73
- const run = await Promise.all(this.pipes.map(p => p.createRun(runParams)));
74
- this.uploader.checkEnabled();
75
- return run;
76
- }
77
- parse(resultsPattern) {
78
- this._tests = [];
79
- let pattern = resultsPattern;
80
- // Auto-append wildcard if pattern refers to a directory (like XML command does)
81
- if (!pattern.endsWith('.json') && !pattern.includes('*')) {
82
- if (pattern.endsWith('/') || (fs_1.default.existsSync(pattern) && fs_1.default.statSync(pattern).isDirectory())) {
83
- pattern = pattern.replace(/\/+$/, '') + '/*-result.json';
84
- }
85
- else {
86
- pattern += '*-result.json';
87
- }
88
- }
89
- const resultsDir = path_1.default.dirname(pattern);
90
- console.log(constants_js_1.APP_PREFIX, `Scanning for Allure results in: ${resultsDir}`);
91
- console.log(constants_js_1.APP_PREFIX, `Using pattern: ${pattern}`);
92
- const resultFiles = glob_1.glob.sync(pattern);
93
- const containerFiles = glob_1.glob.sync(pattern.replace('*-result.json', '*-container.json'));
94
- if (resultFiles.length === 0 && containerFiles.length === 0) {
95
- throw new Error(`No Allure result files found matching pattern: ${pattern}`);
96
- }
97
- console.log(constants_js_1.APP_PREFIX, `Found ${resultFiles.length} result files and ${containerFiles.length} container files`);
98
- this.parseContainerFiles(containerFiles);
99
- // Store all tests temporarily for deduplication by historyId
100
- const allTests = [];
101
- for (const file of resultFiles) {
102
- const fullPath = file;
103
- const fileDir = path_1.default.dirname(file);
104
- try {
105
- const resultData = JSON.parse(fs_1.default.readFileSync(fullPath, 'utf8'));
106
- const test = this.processAllureResult(resultData, fileDir);
107
- if (test) {
108
- test._historyId = resultData.historyId;
109
- test._stop = resultData.stop || 0;
110
- allTests.push(test);
111
- }
112
- }
113
- catch (err) {
114
- console.warn(constants_js_1.APP_PREFIX, `Failed to parse ${file}:`, err.message);
115
- debug('Parse error:', err);
116
- }
117
- }
118
- const attemptsMap = new Map();
119
- for (const test of allTests) {
120
- const historyId = test._historyId || test.rid;
121
- if (!attemptsMap.has(historyId)) {
122
- attemptsMap.set(historyId, []);
123
- }
124
- attemptsMap.get(historyId).push(test);
125
- }
126
- const uniqueTestsMap = new Map();
127
- for (const [historyId, attempts] of attemptsMap) {
128
- uniqueTestsMap.set(historyId, this.combineRetryAttempts(attempts));
129
- }
130
- // Convert map to array and clean up internal fields
131
- this._tests = Array.from(uniqueTestsMap.values()).map(t => {
132
- delete t._historyId;
133
- delete t._stop;
134
- return t;
135
- });
136
- console.log(constants_js_1.APP_PREFIX, `Processed ${this._tests.length} unique tests (from ${allTests.length} result files)`);
137
- return this.calculateStats();
138
- }
139
- parseContainerFiles(containerFiles) {
140
- for (const file of containerFiles) {
141
- try {
142
- const data = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
143
- if (data.name && data.children) {
144
- data.children.forEach(uuid => {
145
- this.suites[uuid] = data.name;
146
- });
147
- }
148
- }
149
- catch (err) {
150
- debug('Failed to parse container file:', file, err.message);
151
- }
152
- }
153
- debug('Parsed suites:', this.suites);
154
- }
155
- processAllureResult(result, resultsDir) {
156
- const test = {
157
- rid: result.uuid || (0, crypto_1.randomUUID)(),
158
- title: result.name || 'Unknown test',
159
- status: this.mapStatus(result.status),
160
- suite_title: this.extractSuiteTitle(result),
161
- file: this.extractFile(result),
162
- run_time: this.calculateRunTime(result),
163
- steps: this.convertSteps(result.steps || []),
164
- message: result.statusDetails?.message || '',
165
- stack: result.statusDetails?.trace || '',
166
- meta: this.extractMeta(result),
167
- links: this.extractLinks(result),
168
- artifacts: [],
169
- create: true,
170
- overwrite: true,
171
- };
172
- // @TmsLink references link the result to existing Testomat.io cases. Add EVERY id as
173
- // a linked case ({ test: id }) so all of them are updated from this one result, with
174
- // consistent behaviour whether the test has one or many @TmsLink. The test_id is kept
175
- // a SEPARATE concern — it is never derived from @TmsLink; it is only set from a native
176
- // Testomat.io id found in source (see fetchSourceCode / fetchIdFromCode).
177
- this.addLinkedTestIds(test, this.extractTmsIds(result));
178
- // Add description if present
179
- if (result.description) {
180
- test.description = result.description;
181
- }
182
- if (result.parameters && result.parameters.length > 0) {
183
- test.example = this.convertParameters(result.parameters);
184
- }
185
- if (result.attachments && result.attachments.length > 0) {
186
- const attachments = result.attachments
187
- .map(att => {
188
- const fullPath = path_1.default.join(resultsDir, att.source);
189
- if (fs_1.default.existsSync(fullPath)) {
190
- return fullPath;
191
- }
192
- debug('Attachment file not found:', fullPath);
193
- return null;
194
- })
195
- .filter(Boolean);
196
- if (attachments.length > 0) {
197
- test.files = attachments;
198
- }
199
- }
200
- return test;
201
- }
202
- mapStatus(status) {
203
- const statusMap = {
204
- passed: 'passed',
205
- failed: 'failed',
206
- broken: 'failed',
207
- skipped: 'skipped',
208
- pending: 'skipped',
209
- };
210
- return statusMap[status] || 'failed';
211
- }
212
- /**
213
- * Map an Allure step status to the Testomat.io Step status enum
214
- * (`passed | failed | none | custom`, see testomat-api-definition.yml).
215
- *
216
- * Allure marks a step `broken` when it threw an unexpected error — that is a
217
- * failure for reporting purposes, matching how `mapStatus` treats tests.
218
- * `skipped` and anything unknown/absent become `none` (the neutral value),
219
- * since the step enum has no `skipped`.
220
- *
221
- * @param {string} status - Allure step status
222
- * @returns {'passed'|'failed'|'none'} Testomat.io step status
223
- */
224
- mapStepStatus(status) {
225
- const statusMap = {
226
- passed: 'passed',
227
- failed: 'failed',
228
- broken: 'failed',
229
- skipped: 'none',
230
- pending: 'none',
231
- };
232
- return statusMap[status] || 'none';
233
- }
234
- extractSuiteTitle(result) {
235
- const labels = result.labels || [];
236
- // Only use suite label for suite_title
237
- // Epic and Feature are sent as separate labels in meta
238
- const suiteLabel = labels.find(l => l.name === 'suite')?.value;
239
- if (suiteLabel) {
240
- return this.stripNamespace(suiteLabel);
241
- }
242
- // Fallback to parentSuite or subSuite if no suite label
243
- const parentSuite = labels.find(l => l.name === 'parentSuite')?.value;
244
- const subSuite = labels.find(l => l.name === 'subSuite')?.value;
245
- if (parentSuite && subSuite) {
246
- return `${parentSuite} / ${subSuite}`;
247
- }
248
- if (parentSuite)
249
- return parentSuite;
250
- if (subSuite)
251
- return subSuite;
252
- return 'Default Suite';
253
- }
254
- stripNamespace(suiteName) {
255
- if (suiteName && suiteName.includes('.')) {
256
- return suiteName.split('.').pop();
257
- }
258
- return suiteName;
259
- }
260
- extractFile(result) {
261
- const labels = result.labels || [];
262
- const packageLabel = labels.find(l => l.name === 'package')?.value;
263
- const testClassLabel = labels.find(l => l.name === 'testClass')?.value;
264
- if (!packageLabel) {
265
- return null;
266
- }
267
- const ext = this.getFileExtension(result);
268
- let className;
269
- if (testClassLabel) {
270
- className = testClassLabel.split('.').pop();
271
- }
272
- else if (result.fullName) {
273
- const fullNameParts = result.fullName.split('.');
274
- className = fullNameParts[fullNameParts.length - 2] || fullNameParts[fullNameParts.length - 1];
275
- }
276
- else {
277
- return null;
278
- }
279
- if (this.withPackage) {
280
- const parts = packageLabel.split('.');
281
- return `${parts.join('/')}/${className}.${ext}`;
282
- }
283
- return `${className}.${ext}`;
284
- }
285
- getFileExtension(result) {
286
- const labels = result.labels || [];
287
- const languageLabel = labels.find(l => l.name === 'language')?.value;
288
- const extMap = {
289
- java: 'java',
290
- kotlin: 'kt',
291
- javascript: 'js',
292
- typescript: 'ts',
293
- python: 'py',
294
- ruby: 'rb',
295
- 'c#': 'cs',
296
- php: 'php',
297
- };
298
- return extMap[languageLabel?.toLowerCase()] || 'java';
299
- }
300
- extractMeta(result) {
301
- const labels = result.labels || [];
302
- const excludedLabels = [
303
- 'suite', 'package', 'parentSuite', 'subSuite',
304
- 'testClass', 'testMethod', 'epic', 'feature',
305
- ];
306
- const meta = {};
307
- labels.forEach(label => {
308
- if (!excludedLabels.includes(label.name)) {
309
- meta[label.name] = label.value;
310
- }
311
- });
312
- return meta;
313
- }
314
- extractLinks(result) {
315
- const labels = result.labels || [];
316
- const links = [];
317
- const epicLabel = labels.find(l => l.name === 'epic');
318
- const featureLabel = labels.find(l => l.name === 'feature');
319
- if (epicLabel?.value) {
320
- links.push({ label: `epic:${epicLabel.value}` });
321
- }
322
- if (featureLabel?.value) {
323
- links.push({ label: `feature:${featureLabel.value}` });
324
- }
325
- return links.length > 0 ? links : undefined;
326
- }
327
- /**
328
- * Extract all Testomat.io test ids from Allure links so reported results match
329
- * existing cases instead of creating duplicates.
330
- *
331
- * A test may carry several `@TmsLink`s (e.g. `@TmsLinks(@TmsLink("…"), @TmsLink("…"))`),
332
- * each producing a link with `type: "tms"`. Some exporters omit the type but still point
333
- * the link URL at a Testomat.io test page; both are accepted. The link `name` is used as
334
- * the id (falling back to the id segment of a Testomat.io URL). Ids are normalized and
335
- * de-duplicated, preserving order so the first one stays the primary `test_id`.
336
- *
337
- * @param {object} result - Parsed Allure result JSON
338
- * @returns {string[]} Normalized test ids (possibly empty)
339
- */
340
- extractTmsIds(result) {
341
- const links = result.links || [];
342
- if (!links.length)
343
- return [];
344
- const isTmsLink = l => typeof l?.type === 'string' && l.type.toLowerCase() === 'tms';
345
- const isTestomatioLink = l => typeof l?.url === 'string' && /testomat\.io\/[^\s]*\/test\//i.test(l.url);
346
- const ids = [];
347
- for (const link of links) {
348
- if (!isTmsLink(link) && !isTestomatioLink(link))
349
- continue;
350
- // Prefer the explicit link name; fall back to the id segment of a Testomat.io URL.
351
- let id = this.normalizeTestId(link.name);
352
- if (!id && typeof link.url === 'string') {
353
- const fromUrl = link.url.match(/\/test\/([\w\d]{8})(?=$|[/?#])/i);
354
- if (fromUrl)
355
- id = fromUrl[1];
356
- }
357
- if (id && !ids.includes(id))
358
- ids.push(id);
359
- }
360
- return ids;
361
- }
362
- /**
363
- * The primary Testomat.io test id (the first `@TmsLink`), or null when there is none.
364
- *
365
- * @param {object} result - Parsed Allure result JSON
366
- * @returns {string|null}
367
- */
368
- extractTestId(result) {
369
- return this.extractTmsIds(result)[0] || null;
370
- }
371
- /**
372
- * Attach additional linked test cases to a reported test as `{ test: id }` link entries
373
- * (the same shape `linkTest()` uses), so a single result updates every case it is linked
374
- * to — not just the primary `test_id`. Existing links are preserved; duplicates skipped.
375
- *
376
- * @param {object} test - converted test
377
- * @param {string[]} ids - additional test ids to link
378
- */
379
- addLinkedTestIds(test, ids) {
380
- if (!ids || !ids.length)
381
- return;
382
- if (!Array.isArray(test.links))
383
- test.links = [];
384
- for (const id of ids) {
385
- if (!test.links.some(l => l && l.test === id)) {
386
- test.links.push({ test: id });
387
- }
388
- }
389
- }
390
- /**
391
- * Normalize a value into a Testomat.io test id.
392
- *
393
- * Testomat.io test ids are exactly **8 word characters**. The value may arrive bare
394
- * (`1a2b3c4d`), or carrying the `T` / `@T` markers Testomat uses in code and titles
395
- * (`T1a2b3c4d`, `@T1a2b3c4d`). The markers are removed only when doing so still leaves
396
- * a valid 8-char id, so a real id that happens to start with `T` is preserved.
397
- *
398
- * Anything that does not resolve to a valid 8-char id — a numeric Allure TestOps id
399
- * like `12345`, a JIRA key, a 6-digit TMS number — is rejected (returns null) so we
400
- * never send an unmatchable id that would create duplicates.
401
- *
402
- * @param {string|number|null|undefined} value
403
- * @returns {string|null} The bare 8-char id, or null when the value is not a valid id
404
- */
405
- normalizeTestId(value) {
406
- if (value === null || value === undefined)
407
- return null;
408
- const match = value.toString().trim().match(/^@?T?([\w\d]{8})$/);
409
- return match ? match[1] : null;
410
- }
411
- /**
412
- * Recover a Testomat.io test id from the `@TmsLink("…")` annotation in test source.
413
- *
414
- * Allure does not emit link annotations for skipped (`@Ignore` / `@Disabled`) tests,
415
- * so their results carry no `tms` link and `extractTestId` returns null — which makes
416
- * the server create a duplicate case. The id still lives in the source, on the test
417
- * method, so we read it from there as a fallback.
418
- *
419
- * The lookup is method-scoped: we locate the test method declaration by name, collect
420
- * its annotation/comment block (the lines directly above it, up to the previous code
421
- * construct) and read every `@TmsLink` from it — so an unrelated method's annotation can
422
- * never be picked up. Both `@TmsLink("…")` and the container forms
423
- * `@TmsLinks(@TmsLink("…"), @TmsLink("…"))` (single- or multi-line) are supported.
424
- *
425
- * @param {string} contents - full source file
426
- * @param {object} test - converted test (uses `title`)
427
- * @returns {string[]} normalized 8-char ids in source order (possibly empty)
428
- */
429
- extractTmsIdsFromSource(contents, test) {
430
- if (!contents || !test || !test.title)
431
- return [];
432
- const lines = contents.split('\n');
433
- const title = test.title.replace(/[([].*$/, '').trim();
434
- if (!title)
435
- return [];
436
- const escaped = title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
437
- // Locate the test method declaration (Kotlin `fun name(`, then a typed declaration,
438
- // then a generic `name(` fallback for other JVM languages).
439
- let idx = lines.findIndex(l => new RegExp(`\\bfun\\s+${escaped}\\s*\\(`).test(l));
440
- if (idx === -1)
441
- idx = lines.findIndex(l => new RegExp(`\\b[\\w.<>\\[\\]]+\\s+${escaped}\\s*\\(`).test(l));
442
- if (idx === -1)
443
- idx = lines.findIndex(l => new RegExp(`\\b${escaped}\\s*\\(`).test(l));
444
- if (idx === -1)
445
- return [];
446
- // Collect the annotation/comment block above the declaration. Stop at the previous
447
- // code construct (a line ending in `{`/`}` or another method declaration) so we never
448
- // read into a sibling method. Multi-line `@TmsLinks(...)` continuation lines (e.g. a
449
- // lone `@TmsLink("…"),` or a closing `)`) are kept because they aren't boundaries.
450
- const block = [];
451
- for (let i = idx - 1, scanned = 0; i >= 0 && scanned < 60; i--, scanned++) {
452
- const trimmed = lines[i].trim();
453
- if (trimmed.endsWith('{') || trimmed.endsWith('}'))
454
- break;
455
- if (/\bfun\s+\w+\s*\(/.test(trimmed))
456
- break;
457
- block.push(lines[i]);
458
- }
459
- const ids = [];
460
- const tmsRe = /\bTmsLink\s*\(\s*["']([^"']+)["']/g;
461
- let match;
462
- // block was collected bottom-up; reverse so ids come out in source order
463
- const text = block.reverse().join('\n');
464
- while ((match = tmsRe.exec(text)) !== null) {
465
- const id = this.normalizeTestId(match[1]);
466
- if (id && !ids.includes(id))
467
- ids.push(id);
468
- }
469
- return ids;
470
- }
471
- /**
472
- * The primary `@TmsLink` id for a test method in source, or null. Convenience wrapper
473
- * around {@link extractTmsIdsFromSource}.
474
- *
475
- * @param {string} contents - full source file
476
- * @param {object} test - converted test (uses `title`)
477
- * @returns {string|null}
478
- */
479
- extractTmsIdFromSource(contents, test) {
480
- return this.extractTmsIdsFromSource(contents, test)[0] || null;
481
- }
482
- convertSteps(steps, depth = 0) {
483
- if (depth >= 10)
484
- return null;
485
- return steps
486
- .map(step => {
487
- const convertedStep = {
488
- category: 'user',
489
- title: step.name || step.title || 'Unknown step',
490
- status: this.mapStepStatus(step.status),
491
- duration: this.calculateRunTime(step),
492
- steps: this.convertSteps(step.steps || [], depth + 1),
493
- };
494
- // Attach the failure description (error message + trace with the failing
495
- // code line) straight onto the failed step. Testomat.io renders a step's
496
- // `error` inline in the step tree, so the failure shows up on the exact
497
- // step that broke instead of only at the test level.
498
- //
499
- // Allure propagates a failure's statusDetails up the whole step chain, so
500
- // every ancestor of the real failure point is also `failed` and carries
501
- // the same message. To avoid repeating it at every level, only surface the
502
- // error on the deepest failed step — skip it whenever a descendant step
503
- // already shows the error.
504
- const error = this.extractStepError(step);
505
- if (error && !this.subtreeHasError(convertedStep.steps)) {
506
- convertedStep.error = error;
507
- }
508
- if (convertedStep.steps && convertedStep.steps.length === 0) {
509
- delete convertedStep.steps;
510
- }
511
- if (convertedStep.duration === 0) {
512
- delete convertedStep.duration;
513
- }
514
- return convertedStep;
515
- })
516
- .filter(Boolean);
517
- }
518
- /**
519
- * Check whether any step in the given (already converted) subtree already
520
- * carries an `error`. Used to keep the failure message on the deepest failed
521
- * step only, instead of repeating it on every ancestor in the failure chain.
522
- *
523
- * @param {Array<object>|undefined} steps - converted child steps
524
- * @returns {boolean}
525
- */
526
- subtreeHasError(steps) {
527
- if (!steps || !steps.length)
528
- return false;
529
- return steps.some(step => step.error || this.subtreeHasError(step.steps));
530
- }
531
- /**
532
- * Build the `error` payload for a failed step from its Allure `statusDetails`.
533
- *
534
- * Allure stores the failure message and stack trace (which includes the failing
535
- * source line) in `statusDetails` on the step itself. We only surface it for
536
- * failed/broken steps — passing or skipped steps carry no error. Returns null
537
- * when there is no usable failure information so the field is omitted entirely.
538
- *
539
- * @param {object} step - Allure step
540
- * @returns {{message: string, stack: string}|null}
541
- */
542
- extractStepError(step) {
543
- if (this.mapStepStatus(step.status) !== 'failed')
544
- return null;
545
- const details = step.statusDetails || {};
546
- const message = details.message || '';
547
- const stack = details.trace || '';
548
- if (!message && !stack)
549
- return null;
550
- return { message, stack };
551
- }
552
- calculateRunTime(item) {
553
- if (item.start && item.stop) {
554
- const durationMs = item.stop - item.start;
555
- return durationMs / 1000;
556
- }
557
- return null;
558
- }
559
- convertParameters(parameters) {
560
- const example = {};
561
- parameters.forEach(param => {
562
- if (param.name) {
563
- example[param.name] = param.value;
564
- }
565
- });
566
- return example;
567
- }
568
- combineRetryAttempts(attempts) {
569
- attempts.sort((a, b) => (a._stop || 0) - (b._stop || 0));
570
- const finalTest = attempts[attempts.length - 1];
571
- const retryCount = attempts.length - 1;
572
- if (retryCount > 0) {
573
- finalTest.retries = retryCount;
574
- }
575
- const failedAttempts = attempts.filter(t => t.status === 'failed');
576
- if (failedAttempts.length === 0) {
577
- return finalTest;
578
- }
579
- const failureMessages = [];
580
- const failureStacks = [];
581
- for (const failed of failedAttempts) {
582
- const attemptNum = attempts.indexOf(failed) + 1;
583
- if (failed.message) {
584
- failureMessages.push(`[Attempt ${attemptNum}] ${failed.message}`);
585
- }
586
- if (failed.stack) {
587
- failureStacks.push(`\n--- Attempt ${attemptNum} ---\n${failed.stack}`);
588
- }
589
- }
590
- if (failureMessages.length > 0) {
591
- finalTest.message = failureMessages.join('\n');
592
- }
593
- if (failureStacks.length > 0) {
594
- finalTest.stack = failureStacks.join('\n');
595
- }
596
- // When the final attempt passed (after earlier failures) keep the test as passed —
597
- // this mirrors the server's overwrite-by-latest retry model. The aggregated failure
598
- // message/stack built above is retained so the flakiness history stays visible.
599
- if (finalTest.status === 'passed') {
600
- const retryMsg = `Test passed after ${failedAttempts.length} retries. Previous failures:\n`;
601
- finalTest.message = retryMsg + finalTest.message;
602
- }
603
- return finalTest;
604
- }
605
- calculateStats() {
606
- this.stats = {
607
- create_tests: true,
608
- tests_count: this._tests.length,
609
- passed_count: 0,
610
- failed_count: 0,
611
- skipped_count: 0,
612
- duration: 0,
613
- status: 'passed',
614
- tests: this._tests,
615
- };
616
- this._tests.forEach(t => {
617
- if (t.status === 'passed')
618
- this.stats.passed_count++;
619
- if (t.status === 'failed')
620
- this.stats.failed_count++;
621
- if (t.status === 'skipped')
622
- this.stats.skipped_count++;
623
- });
624
- this.stats.duration = this._tests.reduce((acc, t) => acc + (t.run_time || 0), 0);
625
- if (this.stats.failed_count)
626
- this.stats.status = 'failed';
627
- debug('Stats:', this.stats);
628
- return this.stats;
629
- }
630
- fetchSourceCode() {
631
- const adapter = this.adapter || (0, index_js_2.default)(this.getLanguage(), this.opts);
632
- this._tests.forEach(t => {
633
- try {
634
- let filePath = t.file;
635
- if (adapter && adapter.getFilePath) {
636
- filePath = adapter.getFilePath(t);
637
- }
638
- if (!filePath)
639
- return;
640
- if (!fs_1.default.existsSync(filePath)) {
641
- debug('Source file not found:', filePath);
642
- return;
643
- }
644
- const contents = fs_1.default.readFileSync(filePath).toString();
645
- const code = (0, utils_js_1.fetchSourceCode)(contents, { ...t, lang: this.getLanguage() });
646
- if (code) {
647
- t.code = code;
648
- debug('Fetched code for test %s', t.title);
649
- }
650
- // Don't override an id already taken from a @TmsLink — the link is the
651
- // explicit, source-independent match key the client maintains.
652
- const testId = (0, utils_js_1.fetchIdFromCode)(contents, { lang: this.getLanguage() });
653
- if (testId && !t.test_id) {
654
- t.test_id = testId;
655
- debug('Fetched test id %s for test %s', testId, t.title);
656
- }
657
- }
658
- catch (err) {
659
- debug('Failed to fetch source code:', err.message);
660
- }
661
- });
662
- }
663
- getLanguage() {
664
- if (this._tests.length === 0)
665
- return null;
666
- return this._tests[0].meta?.language || this.opts.lang;
667
- }
668
- /**
669
- * Link tests to their Testomat.io cases by reading `@TmsLink` from source for tests that
670
- * carry no `{ test: … }` link yet. This rescues skipped (`@Ignore` / `@Disabled`) tests,
671
- * whose Allure results drop the `@TmsLink` link and would otherwise create duplicate
672
- * cases. Every `@TmsLink` on the method is linked (consistent with executed tests); the
673
- * `test_id` is left untouched — links and test_id are separate concerns.
674
- *
675
- * Opt-in: only runs when `--java-tests` (a source root) is provided. The source files are
676
- * indexed once by basename; for each not-yet-linked test we read the candidate file(s)
677
- * matching its `testFile` / class name and parse the method's `@TmsLink`(s).
678
- */
679
- recoverTmsLinksFromSource() {
680
- const root = this.opts.javaTests;
681
- if (!root)
682
- return;
683
- const hasTestLink = t => Array.isArray(t.links) && t.links.some(l => l && l.test);
684
- const unlinked = this._tests.filter(t => !hasTestLink(t));
685
- if (!unlinked.length)
686
- return;
687
- if (!fs_1.default.existsSync(root)) {
688
- debug('java-tests source root not found: %s', root);
689
- return;
690
- }
691
- const index = this.indexSourceFiles(root);
692
- let recovered = 0;
693
- for (const t of unlinked) {
694
- for (const filePath of this.sourceCandidatesForTest(t, index)) {
695
- let contents;
696
- try {
697
- contents = fs_1.default.readFileSync(filePath).toString();
698
- }
699
- catch (err) {
700
- debug('Failed to read source %s: %s', filePath, err.message);
701
- continue;
702
- }
703
- const ids = this.extractTmsIdsFromSource(contents, t);
704
- if (ids.length) {
705
- this.addLinkedTestIds(t, ids);
706
- recovered++;
707
- debug('Linked %s to case(s) %s from @TmsLink in %s', t.title, ids.join(', '), filePath);
708
- break;
709
- }
710
- }
711
- }
712
- if (recovered) {
713
- console.log(constants_js_1.APP_PREFIX, `🔗 Linked ${picocolors_1.default.bold(recovered)} test(s) to cases from @TmsLink in source`);
714
- }
715
- }
716
- /**
717
- * Build (and cache) a basename -> [absolute paths] index of source files under `root`.
718
- * Walks synchronously, skipping common build/dependency directories.
719
- *
720
- * @param {string} root
721
- * @returns {Map<string, string[]>}
722
- */
723
- indexSourceFiles(root) {
724
- if (this._sourceIndex)
725
- return this._sourceIndex;
726
- const exts = new Set(['.kt', '.java', '.py', '.rb', '.cs']);
727
- const skipDirs = new Set(['node_modules', '.git', 'build', 'out', 'target', '.gradle', 'dist', 'bin']);
728
- const index = new Map();
729
- const stack = [root];
730
- while (stack.length) {
731
- const dir = stack.pop();
732
- let entries;
733
- try {
734
- entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
735
- }
736
- catch (err) {
737
- debug('Failed to read dir %s: %s', dir, err.message);
738
- continue;
739
- }
740
- for (const entry of entries) {
741
- const full = path_1.default.join(dir, entry.name);
742
- if (entry.isDirectory()) {
743
- if (!skipDirs.has(entry.name))
744
- stack.push(full);
745
- }
746
- else if (exts.has(path_1.default.extname(entry.name))) {
747
- const list = index.get(entry.name) || [];
748
- list.push(full);
749
- index.set(entry.name, list);
750
- }
751
- }
752
- }
753
- this._sourceIndex = index;
754
- return index;
755
- }
756
- /**
757
- * Candidate source file paths for a test, looked up in the basename index.
758
- * Uses the `testFile` meta label (e.g. `Foo.kt`) and the class name from `file`,
759
- * trying both `.kt` and `.java` extensions. Ambiguity (same basename in several
760
- * dirs) is harmless: only the file that actually declares the method will match.
761
- *
762
- * @param {object} t
763
- * @param {Map<string, string[]>} index
764
- * @returns {string[]}
765
- */
766
- sourceCandidatesForTest(t, index) {
767
- const names = new Set();
768
- if (t.meta?.testFile)
769
- names.add(t.meta.testFile);
770
- if (t.file) {
771
- const base = path_1.default.basename(t.file);
772
- names.add(base);
773
- const stem = base.replace(/\.[^.]+$/, '');
774
- ['kt', 'java'].forEach(ext => names.add(`${stem}.${ext}`));
775
- }
776
- const paths = [];
777
- for (const name of names) {
778
- (index.get(name) || []).forEach(p => paths.push(p));
779
- }
780
- return paths;
781
- }
782
- async uploadArtifacts() {
783
- for (const test of this._tests.filter(t => t.files && t.files.length > 0)) {
784
- const runId = this.runId || this.store.runId || Date.now().toString();
785
- const artifacts = await Promise.all(test.files.map(f => this.uploader.uploadFileByPath(f, [runId, test.rid, path_1.default.basename(f)])));
786
- test.artifacts = artifacts.filter(a => a && a.link).map(a => a.link);
787
- delete test.files;
788
- if (test.artifacts.length > 0) {
789
- console.log(constants_js_1.APP_PREFIX, `🗄️ Uploaded ${picocolors_1.default.bold(`${test.artifacts.length} artifacts`)} for test ${test.title}`);
790
- }
791
- }
792
- }
793
- async uploadData() {
794
- await this.uploadArtifacts();
795
- this.calculateStats();
796
- this.fetchSourceCode();
797
- this.recoverTmsLinksFromSource();
798
- this.pipes = this.pipes || (await this.pipesPromise);
799
- const finishData = {
800
- api_key: this.requestParams.apiKey,
801
- status: 'finished',
802
- duration: this.stats.duration,
803
- };
804
- if (!this._tests || !Array.isArray(this._tests) || this._tests.length === 0) {
805
- debug('No tests to upload, finishing run');
806
- return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
807
- }
808
- // Upload tests in size-limited chunks (max 1MB each), exactly like XmlReader.
809
- // The testomatio pipe runs in MANUAL batch mode, so addTest only buffers tests and
810
- // sync() flushes one batch request per chunk. There is no setInterval auto-upload,
811
- // so each test is sent exactly once (no double-send) and requests stay under the limit.
812
- const testChunks = (0, pipe_utils_js_1.splitTestsIntoChunks)(this._tests);
813
- const totalChunks = testChunks.length;
814
- const totalTests = this._tests.length;
815
- debug(`Split ${totalTests} tests into ${totalChunks} chunks (max 1MB per chunk)`);
816
- let uploadedTests = 0;
817
- for (let i = 0; i < testChunks.length; i++) {
818
- const chunk = testChunks[i];
819
- if (totalChunks > 1) {
820
- debug(`Uploading chunk ${i + 1}/${totalChunks} (${chunk.length} tests)`);
821
- }
822
- // Buffer each test in the chunk, then flush the whole chunk as a single batch
823
- for (const test of chunk) {
824
- await Promise.all(this.pipes.map(p => p.addTest(test)));
825
- }
826
- await Promise.all(this.pipes.map(p => p.sync()));
827
- uploadedTests += chunk.length;
828
- debug(`Uploaded ${uploadedTests}/${totalTests} tests`);
829
- }
830
- if (totalChunks > 1) {
831
- console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests in ${totalChunks} chunks`);
832
- }
833
- else {
834
- console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests`);
835
- }
836
- debug('Uploaded %d tests, finishing run', this._tests.length);
837
- return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
838
- }
839
- }
840
- module.exports = AllureReader;