@testomatio/reporter 2.9.0 → 2.9.1-beta.1-allure-chunking

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 CHANGED
@@ -76,6 +76,7 @@ npx testomatio-reporter <command> [options]
76
76
  | [TestCafe](./docs/frameworks.md#testcafe) | [Detox](./docs/frameworks.md#detox) | [Codeception](https://github.com/testomatio/php-reporter) |
77
77
  | [Newman (Postman)](./docs/frameworks.md#newman) | [JUnit](./docs/junit.md#junit) | [NUnit](./docs/junit.md#nunit) |
78
78
  | [PyTest](./docs/junit.md#pytest) | [PHPUnit](./docs/junit.md#phpunit) | [Protractor](./docs/frameworks.md#protractor) |
79
+ | [Allure](./docs/allure.md) | | |
79
80
 
80
81
  or **any [other via JUnit](./docs/junit.md)** report....
81
82
 
@@ -137,9 +138,10 @@ Bring this reporter on CI and never lose test results again!
137
138
  - [HTML report](./docs/pipes/html.md)
138
139
  - [Markdown report](./docs/pipes/markdown.md)
139
140
  - [Bitbucket](./docs/pipes/bitbucket.md)
140
- - 🔗 [Linking Tests](./docs/linking-tests.md)
141
- - 📓 [JUnit](./docs/junit.md)
141
+ - 📓 [JUnit Reports](./docs/junit.md)
142
142
  - 🗄️ [Artifacts](./docs/artifacts.md)
143
+ - 🔬 [Allure Reports](./docs/allure.md)
144
+ - 🔗 [Linking Tests](./docs/linking-tests.md)
143
145
  - 🔂 [Workflows](./docs/workflows.md)
144
146
  - 🖊️ [Logger](./docs/logger.md)
145
147
  - 🪲 [Debug File Format](./docs/debug-file-format.md)
@@ -0,0 +1,65 @@
1
+ export default AllureReader;
2
+ declare class AllureReader {
3
+ constructor(opts?: {});
4
+ requestParams: {
5
+ apiKey: any;
6
+ url: any;
7
+ title: string;
8
+ env: string;
9
+ group_title: string;
10
+ batchMode: "manual";
11
+ };
12
+ runId: any;
13
+ opts: {};
14
+ withPackage: any;
15
+ store: {};
16
+ pipesPromise: Promise<any[]>;
17
+ _tests: any[];
18
+ stats: {};
19
+ suites: {};
20
+ uploader: S3Uploader;
21
+ version: any;
22
+ set tests(value: any[]);
23
+ get tests(): any[];
24
+ createRun(): Promise<any[]>;
25
+ pipes: any;
26
+ parse(resultsPattern: any): {};
27
+ parseContainerFiles(containerFiles: any): void;
28
+ processAllureResult(result: any, resultsDir: any): {
29
+ rid: any;
30
+ title: any;
31
+ status: any;
32
+ suite_title: any;
33
+ file: string;
34
+ run_time: number;
35
+ steps: any;
36
+ message: any;
37
+ stack: any;
38
+ meta: {};
39
+ links: {
40
+ label: string;
41
+ }[];
42
+ artifacts: any[];
43
+ create: boolean;
44
+ overwrite: boolean;
45
+ };
46
+ mapStatus(status: any): any;
47
+ extractSuiteTitle(result: any): any;
48
+ stripNamespace(suiteName: any): any;
49
+ extractFile(result: any): string;
50
+ getFileExtension(result: any): any;
51
+ extractMeta(result: any): {};
52
+ extractLinks(result: any): {
53
+ label: string;
54
+ }[];
55
+ convertSteps(steps: any, depth?: number): any;
56
+ calculateRunTime(item: any): number;
57
+ convertParameters(parameters: any): {};
58
+ combineRetryAttempts(attempts: any): any;
59
+ calculateStats(): {};
60
+ fetchSourceCode(): void;
61
+ getLanguage(): any;
62
+ uploadArtifacts(): Promise<void>;
63
+ uploadData(): Promise<any[]>;
64
+ }
65
+ import { S3Uploader } from './uploader.js';
@@ -0,0 +1,489 @@
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
+ // Add description if present
173
+ if (result.description) {
174
+ test.description = result.description;
175
+ }
176
+ if (result.parameters && result.parameters.length > 0) {
177
+ test.example = this.convertParameters(result.parameters);
178
+ }
179
+ if (result.attachments && result.attachments.length > 0) {
180
+ const attachments = result.attachments
181
+ .map(att => {
182
+ const fullPath = path_1.default.join(resultsDir, att.source);
183
+ if (fs_1.default.existsSync(fullPath)) {
184
+ return fullPath;
185
+ }
186
+ debug('Attachment file not found:', fullPath);
187
+ return null;
188
+ })
189
+ .filter(Boolean);
190
+ if (attachments.length > 0) {
191
+ test.files = attachments;
192
+ }
193
+ }
194
+ return test;
195
+ }
196
+ mapStatus(status) {
197
+ const statusMap = {
198
+ passed: 'passed',
199
+ failed: 'failed',
200
+ broken: 'failed',
201
+ skipped: 'skipped',
202
+ pending: 'skipped',
203
+ };
204
+ return statusMap[status] || 'failed';
205
+ }
206
+ extractSuiteTitle(result) {
207
+ const labels = result.labels || [];
208
+ // Only use suite label for suite_title
209
+ // Epic and Feature are sent as separate labels in meta
210
+ const suiteLabel = labels.find(l => l.name === 'suite')?.value;
211
+ if (suiteLabel) {
212
+ return this.stripNamespace(suiteLabel);
213
+ }
214
+ // Fallback to parentSuite or subSuite if no suite label
215
+ const parentSuite = labels.find(l => l.name === 'parentSuite')?.value;
216
+ const subSuite = labels.find(l => l.name === 'subSuite')?.value;
217
+ if (parentSuite && subSuite) {
218
+ return `${parentSuite} / ${subSuite}`;
219
+ }
220
+ if (parentSuite)
221
+ return parentSuite;
222
+ if (subSuite)
223
+ return subSuite;
224
+ return 'Default Suite';
225
+ }
226
+ stripNamespace(suiteName) {
227
+ if (suiteName && suiteName.includes('.')) {
228
+ return suiteName.split('.').pop();
229
+ }
230
+ return suiteName;
231
+ }
232
+ extractFile(result) {
233
+ const labels = result.labels || [];
234
+ const packageLabel = labels.find(l => l.name === 'package')?.value;
235
+ const testClassLabel = labels.find(l => l.name === 'testClass')?.value;
236
+ if (!packageLabel) {
237
+ return null;
238
+ }
239
+ const ext = this.getFileExtension(result);
240
+ let className;
241
+ if (testClassLabel) {
242
+ className = testClassLabel.split('.').pop();
243
+ }
244
+ else if (result.fullName) {
245
+ const fullNameParts = result.fullName.split('.');
246
+ className = fullNameParts[fullNameParts.length - 2] || fullNameParts[fullNameParts.length - 1];
247
+ }
248
+ else {
249
+ return null;
250
+ }
251
+ if (this.withPackage) {
252
+ const parts = packageLabel.split('.');
253
+ return `${parts.join('/')}/${className}.${ext}`;
254
+ }
255
+ return `${className}.${ext}`;
256
+ }
257
+ getFileExtension(result) {
258
+ const labels = result.labels || [];
259
+ const languageLabel = labels.find(l => l.name === 'language')?.value;
260
+ const extMap = {
261
+ java: 'java',
262
+ kotlin: 'kt',
263
+ javascript: 'js',
264
+ typescript: 'ts',
265
+ python: 'py',
266
+ ruby: 'rb',
267
+ 'c#': 'cs',
268
+ php: 'php',
269
+ };
270
+ return extMap[languageLabel?.toLowerCase()] || 'java';
271
+ }
272
+ extractMeta(result) {
273
+ const labels = result.labels || [];
274
+ const excludedLabels = [
275
+ 'suite', 'package', 'parentSuite', 'subSuite',
276
+ 'testClass', 'testMethod', 'epic', 'feature',
277
+ ];
278
+ const meta = {};
279
+ labels.forEach(label => {
280
+ if (!excludedLabels.includes(label.name)) {
281
+ meta[label.name] = label.value;
282
+ }
283
+ });
284
+ return meta;
285
+ }
286
+ extractLinks(result) {
287
+ const labels = result.labels || [];
288
+ const links = [];
289
+ const epicLabel = labels.find(l => l.name === 'epic');
290
+ const featureLabel = labels.find(l => l.name === 'feature');
291
+ if (epicLabel?.value) {
292
+ links.push({ label: `epic:${epicLabel.value}` });
293
+ }
294
+ if (featureLabel?.value) {
295
+ links.push({ label: `feature:${featureLabel.value}` });
296
+ }
297
+ return links.length > 0 ? links : undefined;
298
+ }
299
+ convertSteps(steps, depth = 0) {
300
+ if (depth >= 10)
301
+ return null;
302
+ return steps
303
+ .map(step => {
304
+ const convertedStep = {
305
+ category: 'user',
306
+ title: step.name || step.title || 'Unknown step',
307
+ duration: this.calculateRunTime(step),
308
+ steps: this.convertSteps(step.steps || [], depth + 1),
309
+ };
310
+ if (convertedStep.steps && convertedStep.steps.length === 0) {
311
+ delete convertedStep.steps;
312
+ }
313
+ if (convertedStep.duration === 0) {
314
+ delete convertedStep.duration;
315
+ }
316
+ return convertedStep;
317
+ })
318
+ .filter(Boolean);
319
+ }
320
+ calculateRunTime(item) {
321
+ if (item.start && item.stop) {
322
+ const durationMs = item.stop - item.start;
323
+ return durationMs / 1000;
324
+ }
325
+ return null;
326
+ }
327
+ convertParameters(parameters) {
328
+ const example = {};
329
+ parameters.forEach(param => {
330
+ if (param.name) {
331
+ example[param.name] = param.value;
332
+ }
333
+ });
334
+ return example;
335
+ }
336
+ combineRetryAttempts(attempts) {
337
+ attempts.sort((a, b) => (a._stop || 0) - (b._stop || 0));
338
+ const finalTest = attempts[attempts.length - 1];
339
+ const retryCount = attempts.length - 1;
340
+ if (retryCount > 0) {
341
+ finalTest.retries = retryCount;
342
+ }
343
+ const failedAttempts = attempts.filter(t => t.status === 'failed');
344
+ if (failedAttempts.length === 0) {
345
+ return finalTest;
346
+ }
347
+ const failureMessages = [];
348
+ const failureStacks = [];
349
+ for (const failed of failedAttempts) {
350
+ const attemptNum = attempts.indexOf(failed) + 1;
351
+ if (failed.message) {
352
+ failureMessages.push(`[Attempt ${attemptNum}] ${failed.message}`);
353
+ }
354
+ if (failed.stack) {
355
+ failureStacks.push(`\n--- Attempt ${attemptNum} ---\n${failed.stack}`);
356
+ }
357
+ }
358
+ if (failureMessages.length > 0) {
359
+ finalTest.message = failureMessages.join('\n');
360
+ }
361
+ if (failureStacks.length > 0) {
362
+ finalTest.stack = failureStacks.join('\n');
363
+ }
364
+ if (finalTest.status === 'passed') {
365
+ finalTest.status = 'failed';
366
+ const retryMsg = `Test passed after ${failedAttempts.length} retries. Previous failures:\n`;
367
+ finalTest.message = retryMsg + finalTest.message;
368
+ }
369
+ return finalTest;
370
+ }
371
+ calculateStats() {
372
+ this.stats = {
373
+ create_tests: true,
374
+ tests_count: this._tests.length,
375
+ passed_count: 0,
376
+ failed_count: 0,
377
+ skipped_count: 0,
378
+ duration: 0,
379
+ status: 'passed',
380
+ tests: this._tests,
381
+ };
382
+ this._tests.forEach(t => {
383
+ if (t.status === 'passed')
384
+ this.stats.passed_count++;
385
+ if (t.status === 'failed')
386
+ this.stats.failed_count++;
387
+ if (t.status === 'skipped')
388
+ this.stats.skipped_count++;
389
+ });
390
+ this.stats.duration = this._tests.reduce((acc, t) => acc + (t.run_time || 0), 0);
391
+ if (this.stats.failed_count)
392
+ this.stats.status = 'failed';
393
+ debug('Stats:', this.stats);
394
+ return this.stats;
395
+ }
396
+ fetchSourceCode() {
397
+ const adapter = this.adapter || (0, index_js_2.default)(this.getLanguage(), this.opts);
398
+ this._tests.forEach(t => {
399
+ try {
400
+ let filePath = t.file;
401
+ if (adapter && adapter.getFilePath) {
402
+ filePath = adapter.getFilePath(t);
403
+ }
404
+ if (!filePath)
405
+ return;
406
+ if (!fs_1.default.existsSync(filePath)) {
407
+ debug('Source file not found:', filePath);
408
+ return;
409
+ }
410
+ const contents = fs_1.default.readFileSync(filePath).toString();
411
+ const code = (0, utils_js_1.fetchSourceCode)(contents, { ...t, lang: this.getLanguage() });
412
+ if (code) {
413
+ t.code = code;
414
+ debug('Fetched code for test %s', t.title);
415
+ }
416
+ const testId = (0, utils_js_1.fetchIdFromCode)(contents, { lang: this.getLanguage() });
417
+ if (testId) {
418
+ t.test_id = testId;
419
+ debug('Fetched test id %s for test %s', testId, t.title);
420
+ }
421
+ }
422
+ catch (err) {
423
+ debug('Failed to fetch source code:', err.message);
424
+ }
425
+ });
426
+ }
427
+ getLanguage() {
428
+ if (this._tests.length === 0)
429
+ return null;
430
+ return this._tests[0].meta?.language || this.opts.lang;
431
+ }
432
+ async uploadArtifacts() {
433
+ for (const test of this._tests.filter(t => t.files && t.files.length > 0)) {
434
+ const runId = this.runId || this.store.runId || Date.now().toString();
435
+ const artifacts = await Promise.all(test.files.map(f => this.uploader.uploadFileByPath(f, [runId, test.rid, path_1.default.basename(f)])));
436
+ test.artifacts = artifacts.filter(a => a && a.link).map(a => a.link);
437
+ delete test.files;
438
+ if (test.artifacts.length > 0) {
439
+ console.log(constants_js_1.APP_PREFIX, `🗄️ Uploaded ${picocolors_1.default.bold(`${test.artifacts.length} artifacts`)} for test ${test.title}`);
440
+ }
441
+ }
442
+ }
443
+ async uploadData() {
444
+ await this.uploadArtifacts();
445
+ this.calculateStats();
446
+ this.fetchSourceCode();
447
+ this.pipes = this.pipes || (await this.pipesPromise);
448
+ const finishData = {
449
+ api_key: this.requestParams.apiKey,
450
+ status: 'finished',
451
+ duration: this.stats.duration,
452
+ };
453
+ if (!this._tests || !Array.isArray(this._tests) || this._tests.length === 0) {
454
+ debug('No tests to upload, finishing run');
455
+ return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
456
+ }
457
+ // Upload tests in size-limited chunks (max 1MB each), exactly like XmlReader.
458
+ // The testomatio pipe runs in MANUAL batch mode, so addTest only buffers tests and
459
+ // sync() flushes one batch request per chunk. There is no setInterval auto-upload,
460
+ // so each test is sent exactly once (no double-send) and requests stay under the limit.
461
+ const testChunks = (0, pipe_utils_js_1.splitTestsIntoChunks)(this._tests);
462
+ const totalChunks = testChunks.length;
463
+ const totalTests = this._tests.length;
464
+ debug(`Split ${totalTests} tests into ${totalChunks} chunks (max 1MB per chunk)`);
465
+ let uploadedTests = 0;
466
+ for (let i = 0; i < testChunks.length; i++) {
467
+ const chunk = testChunks[i];
468
+ if (totalChunks > 1) {
469
+ debug(`Uploading chunk ${i + 1}/${totalChunks} (${chunk.length} tests)`);
470
+ }
471
+ // Buffer each test in the chunk, then flush the whole chunk as a single batch
472
+ for (const test of chunk) {
473
+ await Promise.all(this.pipes.map(p => p.addTest(test)));
474
+ }
475
+ await Promise.all(this.pipes.map(p => p.sync()));
476
+ uploadedTests += chunk.length;
477
+ debug(`Uploaded ${uploadedTests}/${totalTests} tests`);
478
+ }
479
+ if (totalChunks > 1) {
480
+ console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests in ${totalChunks} chunks`);
481
+ }
482
+ else {
483
+ console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests`);
484
+ }
485
+ debug('Uploaded %d tests, finishing run', this._tests.length);
486
+ return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
487
+ }
488
+ }
489
+ 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';
@@ -0,0 +1,46 @@
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 path_1 = __importDefault(require("path"));
7
+ const adapter_js_1 = __importDefault(require("./adapter.js"));
8
+ class KotlinAdapter extends adapter_js_1.default {
9
+ getFilePath(t) {
10
+ const fileName = namespaceToFileName(t.suite_title);
11
+ return this.opts.javaTests + path_1.default.sep + fileName;
12
+ }
13
+ formatTest(t) {
14
+ const fileParts = t.suite_title.split('.');
15
+ t.file = namespaceToFileName(t.suite_title);
16
+ t.title = t.title.split('(')[0];
17
+ // detect params
18
+ const paramMatches = t.title.match(/\[(.*?)\]/g);
19
+ if (paramMatches) {
20
+ const params = paramMatches.map((_match, index) => `param${index + 1}`);
21
+ if (params.length === 1)
22
+ params[0] = 'param';
23
+ let paramIndex = 0;
24
+ t.title = t.title.replace(/: \[(.*?)\]/g, () => {
25
+ if (params.length < 2)
26
+ return `\${param}`;
27
+ const paramName = params[paramIndex] || `param${paramIndex + 1}`;
28
+ paramIndex++;
29
+ return `\${${paramName}}`;
30
+ });
31
+ const example = {};
32
+ paramMatches.forEach((match, index) => {
33
+ example[params[index]] = match.replace(/[[\]]/g, '');
34
+ });
35
+ t.example = example;
36
+ }
37
+ t.suite_title = fileParts[fileParts.length - 1].replace(/\$/g, ' | ');
38
+ return t;
39
+ }
40
+ }
41
+ function namespaceToFileName(fileName) {
42
+ const fileParts = fileName.split('.');
43
+ fileParts[fileParts.length - 1] = fileParts[fileParts.length - 1]?.replace(/\$.*/, '');
44
+ return `${fileParts.join(path_1.default.sep)}.kt`;
45
+ }
46
+ module.exports = KotlinAdapter;