@testomatio/reporter 2.9.1 → 2.9.2-beta.1-allure-retries

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.
@@ -0,0 +1,601 @@
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
+ // Use the @TmsLink / Testomat.io link as the test id so reported tests MATCH
173
+ // existing cases instead of creating duplicates on every run.
174
+ const testId = this.extractTestId(result);
175
+ if (testId) {
176
+ test.test_id = testId;
177
+ }
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 a Testomat.io test id from Allure links so reported tests match
329
+ * existing cases instead of creating duplicates.
330
+ *
331
+ * Allure's `@TmsLink("T1a2b3c4d")` produces a link with `type: "tms"`. Some exporters
332
+ * omit the type but still point the link URL at a Testomat.io test page; both are
333
+ * accepted. The link `name` is used as the id (falling back to the last URL segment).
334
+ *
335
+ * @param {object} result - Parsed Allure result JSON
336
+ * @returns {string|null} Normalized test id, or null when no usable link exists
337
+ */
338
+ extractTestId(result) {
339
+ const links = result.links || [];
340
+ if (!links.length)
341
+ return null;
342
+ const isTmsLink = l => typeof l?.type === 'string' && l.type.toLowerCase() === 'tms';
343
+ const isTestomatioLink = l => typeof l?.url === 'string' && /testomat\.io\/[^\s]*\/test\//i.test(l.url);
344
+ const link = links.find(isTmsLink) || links.find(isTestomatioLink);
345
+ if (!link)
346
+ return null;
347
+ // Prefer the explicit link name; fall back to the id segment of a Testomat.io URL.
348
+ let id = this.normalizeTestId(link.name);
349
+ if (!id && typeof link.url === 'string') {
350
+ const fromUrl = link.url.match(/\/test\/([\w\d]{8})(?=$|[/?#])/i);
351
+ if (fromUrl)
352
+ id = fromUrl[1];
353
+ }
354
+ return id;
355
+ }
356
+ /**
357
+ * Normalize a value into a Testomat.io test id.
358
+ *
359
+ * Testomat.io test ids are exactly **8 word characters**. The value may arrive bare
360
+ * (`1a2b3c4d`), or carrying the `T` / `@T` markers Testomat uses in code and titles
361
+ * (`T1a2b3c4d`, `@T1a2b3c4d`). The markers are removed only when doing so still leaves
362
+ * a valid 8-char id, so a real id that happens to start with `T` is preserved.
363
+ *
364
+ * Anything that does not resolve to a valid 8-char id — a numeric Allure TestOps id
365
+ * like `12345`, a JIRA key, a 6-digit TMS number — is rejected (returns null) so we
366
+ * never send an unmatchable id that would create duplicates.
367
+ *
368
+ * @param {string|number|null|undefined} value
369
+ * @returns {string|null} The bare 8-char id, or null when the value is not a valid id
370
+ */
371
+ normalizeTestId(value) {
372
+ if (value === null || value === undefined)
373
+ return null;
374
+ const match = value.toString().trim().match(/^@?T?([\w\d]{8})$/);
375
+ return match ? match[1] : null;
376
+ }
377
+ convertSteps(steps, depth = 0) {
378
+ if (depth >= 10)
379
+ return null;
380
+ return steps
381
+ .map(step => {
382
+ const convertedStep = {
383
+ category: 'user',
384
+ title: step.name || step.title || 'Unknown step',
385
+ status: this.mapStepStatus(step.status),
386
+ duration: this.calculateRunTime(step),
387
+ steps: this.convertSteps(step.steps || [], depth + 1),
388
+ };
389
+ // Attach the failure description (error message + trace with the failing
390
+ // code line) straight onto the failed step. Testomat.io renders a step's
391
+ // `error` inline in the step tree, so the failure shows up on the exact
392
+ // step that broke instead of only at the test level.
393
+ const error = this.extractStepError(step);
394
+ if (error) {
395
+ convertedStep.error = error;
396
+ }
397
+ if (convertedStep.steps && convertedStep.steps.length === 0) {
398
+ delete convertedStep.steps;
399
+ }
400
+ if (convertedStep.duration === 0) {
401
+ delete convertedStep.duration;
402
+ }
403
+ return convertedStep;
404
+ })
405
+ .filter(Boolean);
406
+ }
407
+ /**
408
+ * Build the `error` payload for a failed step from its Allure `statusDetails`.
409
+ *
410
+ * Allure stores the failure message and stack trace (which includes the failing
411
+ * source line) in `statusDetails` on the step itself. We only surface it for
412
+ * failed/broken steps — passing or skipped steps carry no error. Returns null
413
+ * when there is no usable failure information so the field is omitted entirely.
414
+ *
415
+ * @param {object} step - Allure step
416
+ * @returns {{message: string, stack: string}|null}
417
+ */
418
+ extractStepError(step) {
419
+ if (this.mapStepStatus(step.status) !== 'failed')
420
+ return null;
421
+ const details = step.statusDetails || {};
422
+ const message = details.message || '';
423
+ const stack = details.trace || '';
424
+ if (!message && !stack)
425
+ return null;
426
+ return { message, stack };
427
+ }
428
+ calculateRunTime(item) {
429
+ if (item.start && item.stop) {
430
+ const durationMs = item.stop - item.start;
431
+ return durationMs / 1000;
432
+ }
433
+ return null;
434
+ }
435
+ convertParameters(parameters) {
436
+ const example = {};
437
+ parameters.forEach(param => {
438
+ if (param.name) {
439
+ example[param.name] = param.value;
440
+ }
441
+ });
442
+ return example;
443
+ }
444
+ combineRetryAttempts(attempts) {
445
+ attempts.sort((a, b) => (a._stop || 0) - (b._stop || 0));
446
+ const finalTest = attempts[attempts.length - 1];
447
+ const retryCount = attempts.length - 1;
448
+ if (retryCount > 0) {
449
+ finalTest.retries = retryCount;
450
+ }
451
+ const failedAttempts = attempts.filter(t => t.status === 'failed');
452
+ if (failedAttempts.length === 0) {
453
+ return finalTest;
454
+ }
455
+ const failureMessages = [];
456
+ const failureStacks = [];
457
+ for (const failed of failedAttempts) {
458
+ const attemptNum = attempts.indexOf(failed) + 1;
459
+ if (failed.message) {
460
+ failureMessages.push(`[Attempt ${attemptNum}] ${failed.message}`);
461
+ }
462
+ if (failed.stack) {
463
+ failureStacks.push(`\n--- Attempt ${attemptNum} ---\n${failed.stack}`);
464
+ }
465
+ }
466
+ if (failureMessages.length > 0) {
467
+ finalTest.message = failureMessages.join('\n');
468
+ }
469
+ if (failureStacks.length > 0) {
470
+ finalTest.stack = failureStacks.join('\n');
471
+ }
472
+ // When the final attempt passed (after earlier failures) keep the test as passed —
473
+ // this mirrors the server's overwrite-by-latest retry model. The aggregated failure
474
+ // message/stack built above is retained so the flakiness history stays visible.
475
+ if (finalTest.status === 'passed') {
476
+ const retryMsg = `Test passed after ${failedAttempts.length} retries. Previous failures:\n`;
477
+ finalTest.message = retryMsg + finalTest.message;
478
+ }
479
+ return finalTest;
480
+ }
481
+ calculateStats() {
482
+ this.stats = {
483
+ create_tests: true,
484
+ tests_count: this._tests.length,
485
+ passed_count: 0,
486
+ failed_count: 0,
487
+ skipped_count: 0,
488
+ duration: 0,
489
+ status: 'passed',
490
+ tests: this._tests,
491
+ };
492
+ this._tests.forEach(t => {
493
+ if (t.status === 'passed')
494
+ this.stats.passed_count++;
495
+ if (t.status === 'failed')
496
+ this.stats.failed_count++;
497
+ if (t.status === 'skipped')
498
+ this.stats.skipped_count++;
499
+ });
500
+ this.stats.duration = this._tests.reduce((acc, t) => acc + (t.run_time || 0), 0);
501
+ if (this.stats.failed_count)
502
+ this.stats.status = 'failed';
503
+ debug('Stats:', this.stats);
504
+ return this.stats;
505
+ }
506
+ fetchSourceCode() {
507
+ const adapter = this.adapter || (0, index_js_2.default)(this.getLanguage(), this.opts);
508
+ this._tests.forEach(t => {
509
+ try {
510
+ let filePath = t.file;
511
+ if (adapter && adapter.getFilePath) {
512
+ filePath = adapter.getFilePath(t);
513
+ }
514
+ if (!filePath)
515
+ return;
516
+ if (!fs_1.default.existsSync(filePath)) {
517
+ debug('Source file not found:', filePath);
518
+ return;
519
+ }
520
+ const contents = fs_1.default.readFileSync(filePath).toString();
521
+ const code = (0, utils_js_1.fetchSourceCode)(contents, { ...t, lang: this.getLanguage() });
522
+ if (code) {
523
+ t.code = code;
524
+ debug('Fetched code for test %s', t.title);
525
+ }
526
+ // Don't override an id already taken from a @TmsLink — the link is the
527
+ // explicit, source-independent match key the client maintains.
528
+ const testId = (0, utils_js_1.fetchIdFromCode)(contents, { lang: this.getLanguage() });
529
+ if (testId && !t.test_id) {
530
+ t.test_id = testId;
531
+ debug('Fetched test id %s for test %s', testId, t.title);
532
+ }
533
+ }
534
+ catch (err) {
535
+ debug('Failed to fetch source code:', err.message);
536
+ }
537
+ });
538
+ }
539
+ getLanguage() {
540
+ if (this._tests.length === 0)
541
+ return null;
542
+ return this._tests[0].meta?.language || this.opts.lang;
543
+ }
544
+ async uploadArtifacts() {
545
+ for (const test of this._tests.filter(t => t.files && t.files.length > 0)) {
546
+ const runId = this.runId || this.store.runId || Date.now().toString();
547
+ const artifacts = await Promise.all(test.files.map(f => this.uploader.uploadFileByPath(f, [runId, test.rid, path_1.default.basename(f)])));
548
+ test.artifacts = artifacts.filter(a => a && a.link).map(a => a.link);
549
+ delete test.files;
550
+ if (test.artifacts.length > 0) {
551
+ console.log(constants_js_1.APP_PREFIX, `🗄️ Uploaded ${picocolors_1.default.bold(`${test.artifacts.length} artifacts`)} for test ${test.title}`);
552
+ }
553
+ }
554
+ }
555
+ async uploadData() {
556
+ await this.uploadArtifacts();
557
+ this.calculateStats();
558
+ this.fetchSourceCode();
559
+ this.pipes = this.pipes || (await this.pipesPromise);
560
+ const finishData = {
561
+ api_key: this.requestParams.apiKey,
562
+ status: 'finished',
563
+ duration: this.stats.duration,
564
+ };
565
+ if (!this._tests || !Array.isArray(this._tests) || this._tests.length === 0) {
566
+ debug('No tests to upload, finishing run');
567
+ return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
568
+ }
569
+ // Upload tests in size-limited chunks (max 1MB each), exactly like XmlReader.
570
+ // The testomatio pipe runs in MANUAL batch mode, so addTest only buffers tests and
571
+ // sync() flushes one batch request per chunk. There is no setInterval auto-upload,
572
+ // so each test is sent exactly once (no double-send) and requests stay under the limit.
573
+ const testChunks = (0, pipe_utils_js_1.splitTestsIntoChunks)(this._tests);
574
+ const totalChunks = testChunks.length;
575
+ const totalTests = this._tests.length;
576
+ debug(`Split ${totalTests} tests into ${totalChunks} chunks (max 1MB per chunk)`);
577
+ let uploadedTests = 0;
578
+ for (let i = 0; i < testChunks.length; i++) {
579
+ const chunk = testChunks[i];
580
+ if (totalChunks > 1) {
581
+ debug(`Uploading chunk ${i + 1}/${totalChunks} (${chunk.length} tests)`);
582
+ }
583
+ // Buffer each test in the chunk, then flush the whole chunk as a single batch
584
+ for (const test of chunk) {
585
+ await Promise.all(this.pipes.map(p => p.addTest(test)));
586
+ }
587
+ await Promise.all(this.pipes.map(p => p.sync()));
588
+ uploadedTests += chunk.length;
589
+ debug(`Uploaded ${uploadedTests}/${totalTests} tests`);
590
+ }
591
+ if (totalChunks > 1) {
592
+ console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests in ${totalChunks} chunks`);
593
+ }
594
+ else {
595
+ console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests`);
596
+ }
597
+ debug('Uploaded %d tests, finishing run', this._tests.length);
598
+ return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
599
+ }
600
+ }
601
+ module.exports = AllureReader;
package/lib/bin/cli.js CHANGED
@@ -10,6 +10,7 @@ const glob_1 = require("glob");
10
10
  const debug_1 = __importDefault(require("debug"));
11
11
  const client_js_1 = __importDefault(require("../client.js"));
12
12
  const xmlReader_js_1 = __importDefault(require("../xmlReader.js"));
13
+ const allureReader_js_1 = __importDefault(require("../allureReader.js"));
13
14
  const constants_js_1 = require("../constants.js");
14
15
  const utils_js_1 = require("../utils/utils.js");
15
16
  const config_js_1 = require("../config.js");
@@ -318,6 +319,33 @@ program
318
319
  if (timeoutTimer)
319
320
  clearTimeout(timeoutTimer);
320
321
  });
322
+ program
323
+ .command('allure')
324
+ .description('Parse Allure result files and upload to Testomat.io')
325
+ .argument('<pattern>', 'Allure result directory pattern')
326
+ .option('-d, --dir <dir>', 'Project directory')
327
+ .option('--timelimit <time>', 'default time limit in seconds to kill a stuck process')
328
+ .option('--with-package', 'Keep full package path in file names (default: strip package prefix)')
329
+ .action(async (pattern, opts) => {
330
+ const runReader = new allureReader_js_1.default({ withPackage: opts.withPackage });
331
+ let timeoutTimer;
332
+ if (opts.timelimit) {
333
+ timeoutTimer = setTimeout(() => {
334
+ console.log(`⚠️ Reached timeout of ${opts.timelimit}s. Exiting... (Exit code is 0 to not fail the pipeline)`);
335
+ process.exit(0);
336
+ }, parseInt(opts.timelimit, 10) * 1000);
337
+ }
338
+ try {
339
+ await runReader.parse(pattern);
340
+ await runReader.createRun();
341
+ await runReader.uploadData();
342
+ }
343
+ catch (err) {
344
+ console.log(constants_js_1.APP_PREFIX, 'Error uploading Allure results:', err);
345
+ }
346
+ if (timeoutTimer)
347
+ clearTimeout(timeoutTimer);
348
+ });
321
349
  program
322
350
  .command('upload-artifacts')
323
351
  .description('Upload artifacts to Testomat.io')
@@ -9,6 +9,7 @@ const java_js_1 = __importDefault(require("./java.js"));
9
9
  const python_js_1 = __importDefault(require("./python.js"));
10
10
  const ruby_js_1 = __importDefault(require("./ruby.js"));
11
11
  const csharp_js_1 = __importDefault(require("./csharp.js"));
12
+ const kotlin_js_1 = __importDefault(require("./kotlin.js"));
12
13
  function AdapterFactory(lang, opts) {
13
14
  if (lang === 'java') {
14
15
  return new java_js_1.default(opts);
@@ -25,6 +26,9 @@ function AdapterFactory(lang, opts) {
25
26
  if (lang === 'c#' || lang === 'csharp') {
26
27
  return new csharp_js_1.default(opts);
27
28
  }
29
+ if (lang === 'kotlin') {
30
+ return new kotlin_js_1.default(opts);
31
+ }
28
32
  return new adapter_js_1.default(opts);
29
33
  }
30
34
  module.exports = AdapterFactory;
@@ -0,0 +1,5 @@
1
+ export default KotlinAdapter;
2
+ declare class KotlinAdapter extends Adapter {
3
+ getFilePath(t: any): string;
4
+ }
5
+ import Adapter from './adapter.js';