testomatio-reporter-cli 2.9.1-beta.3-allure-steps → 2.9.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testomatio-reporter-cli",
3
- "version": "2.9.1-beta.3-allure-steps",
3
+ "version": "2.9.1",
4
4
  "description": "Yarn Berry compatible standalone CLI for @testomatio/reporter",
5
5
  "type": "module",
6
6
  "bin": {
package/src/bin/cli.js CHANGED
@@ -6,7 +6,6 @@ import { glob } from 'glob';
6
6
  import createDebugMessages from 'debug';
7
7
  import TestomatClient from '../client.js';
8
8
  import XmlReader from '../xmlReader.js';
9
- import AllureReader from '../allureReader.js';
10
9
  import { APP_PREFIX, STATUS, DEBUG_FILE, BATCH_MODE } from '../constants.js';
11
10
  import { cleanLatestRunId, getPackageVersion, applyFilter } from '../utils/utils.js';
12
11
  import { config } from '../config.js';
@@ -352,40 +351,6 @@ program
352
351
  if (timeoutTimer) clearTimeout(timeoutTimer);
353
352
  });
354
353
 
355
- program
356
- .command('allure')
357
- .description('Parse Allure result files and upload to Testomat.io')
358
- .argument('<pattern>', 'Allure result directory pattern')
359
- .option('-d, --dir <dir>', 'Project directory')
360
- .option('--timelimit <time>', 'default time limit in seconds to kill a stuck process')
361
- .option('--with-package', 'Keep full package path in file names (default: strip package prefix)')
362
- .action(async (pattern, opts) => {
363
- const runReader = new AllureReader({ withPackage: opts.withPackage });
364
-
365
- let timeoutTimer;
366
- if (opts.timelimit) {
367
- timeoutTimer = setTimeout(
368
- () => {
369
- console.log(
370
- `⚠️ Reached timeout of ${opts.timelimit}s. Exiting... (Exit code is 0 to not fail the pipeline)`,
371
- );
372
- process.exit(0);
373
- },
374
- parseInt(opts.timelimit, 10) * 1000,
375
- );
376
- }
377
-
378
- try {
379
- await runReader.parse(pattern);
380
- await runReader.createRun();
381
- await runReader.uploadData();
382
- } catch (err) {
383
- console.log(APP_PREFIX, 'Error uploading Allure results:', err);
384
- }
385
-
386
- if (timeoutTimer) clearTimeout(timeoutTimer);
387
- });
388
-
389
354
  program
390
355
  .command('upload-artifacts')
391
356
  .description('Upload artifacts to Testomat.io')
@@ -4,7 +4,6 @@ import JavaAdapter from './java.js';
4
4
  import PythonAdapter from './python.js';
5
5
  import RubyAdapter from './ruby.js';
6
6
  import CSharpAdapter from './csharp.js';
7
- import KotlinAdapter from './kotlin.js';
8
7
 
9
8
  function AdapterFactory(lang, opts) {
10
9
  if (lang === 'java') {
@@ -22,9 +21,6 @@ function AdapterFactory(lang, opts) {
22
21
  if (lang === 'c#' || lang === 'csharp') {
23
22
  return new CSharpAdapter(opts);
24
23
  }
25
- if (lang === 'kotlin') {
26
- return new KotlinAdapter(opts);
27
- }
28
24
 
29
25
  return new Adapter(opts);
30
26
  }
@@ -161,53 +161,6 @@ function parsePipeOptions(optionsStr) {
161
161
  return options;
162
162
  }
163
163
 
164
- /**
165
- * Calculate the approximate size of data in bytes (JSON stringified, UTF-8 encoded length).
166
- * @param {Object} data - Data to measure
167
- * @returns {number} Size in bytes
168
- */
169
- function getObjectSize(data) {
170
- const body = JSON.stringify(data);
171
- return new TextEncoder().encode(body).length;
172
- }
173
-
174
- /**
175
- * Split a tests array into chunks bounded by serialized size.
176
- * Used by the XML and Allure readers so both upload tests with identical batching:
177
- * each chunk becomes a single batch request (manual batch mode), which keeps requests
178
- * under the size limit and guarantees every test is sent exactly once.
179
- *
180
- * @param {Array} tests - Array of tests to split
181
- * @param {number} [maxSizeBytes=1048576] - Maximum serialized size per chunk (default 1MB)
182
- * @returns {Array<Array>} Array of test chunks
183
- */
184
- function splitTestsIntoChunks(tests, maxSizeBytes = 1 * 1024 * 1024) {
185
- const chunks = [];
186
- let currentChunk = [];
187
- let currentChunkSize = 0;
188
-
189
- for (const test of tests) {
190
- const testSize = getObjectSize(test);
191
-
192
- const wouldExceedSize = currentChunkSize + testSize > maxSizeBytes;
193
-
194
- if (wouldExceedSize && currentChunk.length > 0) {
195
- chunks.push(currentChunk);
196
- currentChunk = [];
197
- currentChunkSize = 0;
198
- }
199
-
200
- currentChunk.push(test);
201
- currentChunkSize += testSize;
202
- }
203
-
204
- if (currentChunk.length > 0) {
205
- chunks.push(currentChunk);
206
- }
207
-
208
- return chunks;
209
- }
210
-
211
164
  /**
212
165
  * Format a list of test IDs for `--filter-list` machine-readable output.
213
166
  * Used when the CLI `--format` option is passed,
@@ -237,6 +190,4 @@ export {
237
190
  fullName,
238
191
  parsePipeOptions,
239
192
  formatFilterListIds,
240
- getObjectSize,
241
- splitTestsIntoChunks,
242
193
  };
@@ -289,11 +289,6 @@ const fetchSourceCode = (contents, opts = {}) => {
289
289
  if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`@DisplayName("${title}`));
290
290
  if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`public void ${title}`));
291
291
  if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`${title}(`));
292
- } else if (opts.lang === 'kotlin') {
293
- lineIndex = lines.findIndex(l => l.includes(`fun test${title}`));
294
- if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`@DisplayName("${title}`));
295
- if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`fun ${title}`));
296
- if (lineIndex === -1) lineIndex = lines.findIndex(l => l.includes(`${title}(`));
297
292
  } else if (opts.lang === 'csharp') {
298
293
  // Find the method declaration line
299
294
  let methodLineIndex = lines.findIndex(l => l.includes(`public void ${title}(`));
package/src/xmlReader.js CHANGED
@@ -18,7 +18,6 @@ import {
18
18
  transformEnvVarToBoolean,
19
19
  } from './utils/utils.js';
20
20
  import { pipesFactory } from './pipe/index.js';
21
- import { splitTestsIntoChunks } from './utils/pipe_utils.js';
22
21
  import adapterFactory from './junit-adapter/index.js';
23
22
  import { config } from './config.js';
24
23
  import { S3Uploader } from './uploader.js';
@@ -554,6 +553,52 @@ class XmlReader {
554
553
  return run;
555
554
  }
556
555
 
556
+ /**
557
+ * Calculate the approximate size of data in bytes (JSON stringified length)
558
+ * @param {Object} data - Data to measure
559
+ * @returns {number} Size in bytes
560
+ */
561
+ #getObjectSize(data) {
562
+ const body = JSON.stringify(data);
563
+ return new TextEncoder().encode(body).length;
564
+ }
565
+
566
+ /**
567
+ * Split tests array into chunks based on data size
568
+ * @param {Array} tests - Array of tests to split
569
+ * @returns {Array<Array>} Array of test chunks
570
+ */
571
+ #splitTestsIntoChunks(tests) {
572
+ const maxSizeBytes = 1 * 1024 * 1024;
573
+
574
+ const chunks = [];
575
+ let currentChunk = [];
576
+ let currentChunkSize = 0;
577
+
578
+ for (const test of tests) {
579
+ const testSize = this.#getObjectSize(test);
580
+
581
+ const wouldExceedSize = currentChunkSize + testSize > maxSizeBytes;
582
+
583
+ if (wouldExceedSize) {
584
+ if (currentChunk.length > 0) {
585
+ chunks.push(currentChunk);
586
+ }
587
+ currentChunk = [];
588
+ currentChunkSize = 0;
589
+ }
590
+
591
+ currentChunk.push(test);
592
+ currentChunkSize += testSize;
593
+ }
594
+
595
+ if (currentChunk.length > 0) {
596
+ chunks.push(currentChunk);
597
+ }
598
+
599
+ return chunks;
600
+ }
601
+
557
602
  async uploadData() {
558
603
  await this.uploadArtifacts();
559
604
  this.calculateStats();
@@ -578,7 +623,7 @@ class XmlReader {
578
623
  return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
579
624
  }
580
625
 
581
- const testChunks = splitTestsIntoChunks(this.tests);
626
+ const testChunks = this.#splitTestsIntoChunks(this.tests);
582
627
 
583
628
  const totalChunks = testChunks.length;
584
629
  const totalTests = this.tests.length;
@@ -1,659 +0,0 @@
1
- import createDebugMessages from 'debug';
2
- import path from 'path';
3
- import pc from 'picocolors';
4
- import fs from 'fs';
5
- import { glob } from 'glob';
6
- import { APP_PREFIX, STATUS, BATCH_MODE } from './constants.js';
7
- import { randomUUID } from 'crypto';
8
- import { fileURLToPath } from 'url';
9
- import { config } from './config.js';
10
- import { S3Uploader } from './uploader.js';
11
- import { pipesFactory } from './pipe/index.js';
12
- import { splitTestsIntoChunks } from './utils/pipe_utils.js';
13
- import {
14
- fetchSourceCode,
15
- fetchIdFromCode,
16
- } from './utils/utils.js';
17
- import adapterFactory from './junit-adapter/index.js';
18
-
19
- // @ts-ignore
20
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
-
22
- const debug = createDebugMessages('@testomatio/reporter:allure');
23
-
24
- const TESTOMATIO_URL = process.env.TESTOMATIO_URL || 'https://app.testomat.io';
25
- const { TESTOMATIO_RUNGROUP_TITLE, TESTOMATIO_SUITE, TESTOMATIO_TITLE, TESTOMATIO_ENV, TESTOMATIO_RUN } = process.env;
26
-
27
- class AllureReader {
28
- constructor(opts = {}) {
29
- this.requestParams = {
30
- apiKey: opts.apiKey || config.TESTOMATIO,
31
- url: opts.url || TESTOMATIO_URL,
32
- title: TESTOMATIO_TITLE,
33
- env: TESTOMATIO_ENV,
34
- group_title: TESTOMATIO_RUNGROUP_TITLE,
35
- // Buffer tests and flush them manually in size-limited chunks, exactly like XmlReader.
36
- // No setInterval auto-upload means each test is sent exactly once (no double-send).
37
- batchMode: BATCH_MODE.MANUAL,
38
- };
39
- this.runId = opts.runId || TESTOMATIO_RUN;
40
- this.opts = opts || {};
41
- this.withPackage = opts.withPackage || false;
42
- this.store = {};
43
- this.pipesPromise = pipesFactory(opts, this.store);
44
- this._tests = [];
45
- this.stats = {};
46
- this.suites = {};
47
- this.uploader = new S3Uploader();
48
-
49
- // Allure results already contain steps and stack traces for all tests,
50
- // so enable passing them for passed tests by default
51
- if (!process.env.TESTOMATIO_STACK_PASSED) {
52
- process.env.TESTOMATIO_STACK_PASSED = '1';
53
- }
54
- if (!process.env.TESTOMATIO_STEPS_PASSED) {
55
- process.env.TESTOMATIO_STEPS_PASSED = '1';
56
- }
57
-
58
- const packageJsonPath = path.resolve(__dirname, '..', 'package.json');
59
- this.version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version;
60
- console.log(APP_PREFIX, `Testomatio Reporter v${this.version}`);
61
- }
62
-
63
- get tests() {
64
- return this._tests;
65
- }
66
-
67
- set tests(value) {
68
- this._tests = value;
69
- }
70
-
71
- async createRun() {
72
- const runParams = {
73
- api_key: this.requestParams.apiKey,
74
- title: this.requestParams.title,
75
- env: this.requestParams.env,
76
- group_title: this.requestParams.group_title,
77
- batchMode: this.requestParams.batchMode,
78
- };
79
-
80
- debug('Run', runParams);
81
- this.pipes = this.pipes || (await this.pipesPromise);
82
-
83
- const run = await Promise.all(this.pipes.map(p => p.createRun(runParams)));
84
- this.uploader.checkEnabled();
85
- return run;
86
- }
87
-
88
- parse(resultsPattern) {
89
- this._tests = [];
90
- let pattern = resultsPattern;
91
-
92
- // Auto-append wildcard if pattern refers to a directory (like XML command does)
93
- if (!pattern.endsWith('.json') && !pattern.includes('*')) {
94
- if (pattern.endsWith('/') || (fs.existsSync(pattern) && fs.statSync(pattern).isDirectory())) {
95
- pattern = pattern.replace(/\/+$/, '') + '/*-result.json';
96
- } else {
97
- pattern += '*-result.json';
98
- }
99
- }
100
-
101
- const resultsDir = path.dirname(pattern);
102
-
103
- console.log(APP_PREFIX, `Scanning for Allure results in: ${resultsDir}`);
104
- console.log(APP_PREFIX, `Using pattern: ${pattern}`);
105
-
106
- const resultFiles = glob.sync(pattern);
107
- const containerFiles = glob.sync(pattern.replace('*-result.json', '*-container.json'));
108
-
109
- if (resultFiles.length === 0 && containerFiles.length === 0) {
110
- throw new Error(`No Allure result files found matching pattern: ${pattern}`);
111
- }
112
-
113
- console.log(APP_PREFIX, `Found ${resultFiles.length} result files and ${containerFiles.length} container files`);
114
-
115
- this.parseContainerFiles(containerFiles);
116
-
117
- // Store all tests temporarily for deduplication by historyId
118
- const allTests = [];
119
- for (const file of resultFiles) {
120
- const fullPath = file;
121
- const fileDir = path.dirname(file);
122
- try {
123
- const resultData = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
124
- const test = this.processAllureResult(resultData, fileDir);
125
- if (test) {
126
- test._historyId = resultData.historyId;
127
- test._stop = resultData.stop || 0;
128
- allTests.push(test);
129
- }
130
- } catch (err) {
131
- console.warn(APP_PREFIX, `Failed to parse ${file}:`, err.message);
132
- debug('Parse error:', err);
133
- }
134
- }
135
-
136
- const attemptsMap = new Map();
137
- for (const test of allTests) {
138
- const historyId = test._historyId || test.rid;
139
- if (!attemptsMap.has(historyId)) {
140
- attemptsMap.set(historyId, []);
141
- }
142
- attemptsMap.get(historyId).push(test);
143
- }
144
-
145
- const uniqueTestsMap = new Map();
146
- for (const [historyId, attempts] of attemptsMap) {
147
- uniqueTestsMap.set(historyId, this.combineRetryAttempts(attempts));
148
- }
149
-
150
- // Convert map to array and clean up internal fields
151
- this._tests = Array.from(uniqueTestsMap.values()).map(t => {
152
- delete t._historyId;
153
- delete t._stop;
154
- return t;
155
- });
156
-
157
- console.log(APP_PREFIX, `Processed ${this._tests.length} unique tests (from ${allTests.length} result files)`);
158
-
159
- return this.calculateStats();
160
- }
161
-
162
- parseContainerFiles(containerFiles) {
163
- for (const file of containerFiles) {
164
- try {
165
- const data = JSON.parse(fs.readFileSync(file, 'utf8'));
166
- if (data.name && data.children) {
167
- data.children.forEach(uuid => {
168
- this.suites[uuid] = data.name;
169
- });
170
- }
171
- } catch (err) {
172
- debug('Failed to parse container file:', file, err.message);
173
- }
174
- }
175
- debug('Parsed suites:', this.suites);
176
- }
177
-
178
- processAllureResult(result, resultsDir) {
179
- const test = {
180
- rid: result.uuid || randomUUID(),
181
- title: result.name || 'Unknown test',
182
- status: this.mapStatus(result.status),
183
- suite_title: this.extractSuiteTitle(result),
184
- file: this.extractFile(result),
185
- run_time: this.calculateRunTime(result),
186
- steps: this.convertSteps(result.steps || []),
187
- message: result.statusDetails?.message || '',
188
- stack: result.statusDetails?.trace || '',
189
- meta: this.extractMeta(result),
190
- links: this.extractLinks(result),
191
- artifacts: [],
192
- create: true,
193
- overwrite: true,
194
- };
195
-
196
- // Use the @TmsLink / Testomat.io link as the test id so reported tests MATCH
197
- // existing cases instead of creating duplicates on every run.
198
- const testId = this.extractTestId(result);
199
- if (testId) {
200
- test.test_id = testId;
201
- }
202
-
203
- // Add description if present
204
- if (result.description) {
205
- test.description = result.description;
206
- }
207
-
208
- if (result.parameters && result.parameters.length > 0) {
209
- test.example = this.convertParameters(result.parameters);
210
- }
211
-
212
- if (result.attachments && result.attachments.length > 0) {
213
- const attachments = result.attachments
214
- .map(att => {
215
- const fullPath = path.join(resultsDir, att.source);
216
- if (fs.existsSync(fullPath)) {
217
- return fullPath;
218
- }
219
- debug('Attachment file not found:', fullPath);
220
- return null;
221
- })
222
- .filter(Boolean);
223
-
224
- if (attachments.length > 0) {
225
- test.files = attachments;
226
- }
227
- }
228
-
229
- return test;
230
- }
231
-
232
- mapStatus(status) {
233
- const statusMap = {
234
- passed: 'passed',
235
- failed: 'failed',
236
- broken: 'failed',
237
- skipped: 'skipped',
238
- pending: 'skipped',
239
- };
240
- return statusMap[status] || 'failed';
241
- }
242
-
243
- /**
244
- * Map an Allure step status to the Testomat.io Step status enum
245
- * (`passed | failed | none | custom`, see testomat-api-definition.yml).
246
- *
247
- * Allure marks a step `broken` when it threw an unexpected error — that is a
248
- * failure for reporting purposes, matching how `mapStatus` treats tests.
249
- * `skipped` and anything unknown/absent become `none` (the neutral value),
250
- * since the step enum has no `skipped`.
251
- *
252
- * @param {string} status - Allure step status
253
- * @returns {'passed'|'failed'|'none'} Testomat.io step status
254
- */
255
- mapStepStatus(status) {
256
- const statusMap = {
257
- passed: 'passed',
258
- failed: 'failed',
259
- broken: 'failed',
260
- skipped: 'none',
261
- pending: 'none',
262
- };
263
- return statusMap[status] || 'none';
264
- }
265
-
266
- extractSuiteTitle(result) {
267
- const labels = result.labels || [];
268
-
269
- // Only use suite label for suite_title
270
- // Epic and Feature are sent as separate labels in meta
271
- const suiteLabel = labels.find(l => l.name === 'suite')?.value;
272
-
273
- if (suiteLabel) {
274
- return this.stripNamespace(suiteLabel);
275
- }
276
-
277
- // Fallback to parentSuite or subSuite if no suite label
278
- const parentSuite = labels.find(l => l.name === 'parentSuite')?.value;
279
- const subSuite = labels.find(l => l.name === 'subSuite')?.value;
280
-
281
- if (parentSuite && subSuite) {
282
- return `${parentSuite} / ${subSuite}`;
283
- }
284
- if (parentSuite) return parentSuite;
285
- if (subSuite) return subSuite;
286
-
287
- return 'Default Suite';
288
- }
289
-
290
- stripNamespace(suiteName) {
291
- if (suiteName && suiteName.includes('.')) {
292
- return suiteName.split('.').pop();
293
- }
294
- return suiteName;
295
- }
296
-
297
- extractFile(result) {
298
- const labels = result.labels || [];
299
- const packageLabel = labels.find(l => l.name === 'package')?.value;
300
- const testClassLabel = labels.find(l => l.name === 'testClass')?.value;
301
-
302
- if (!packageLabel) {
303
- return null;
304
- }
305
-
306
- const ext = this.getFileExtension(result);
307
- let className;
308
-
309
- if (testClassLabel) {
310
- className = testClassLabel.split('.').pop();
311
- } else if (result.fullName) {
312
- const fullNameParts = result.fullName.split('.');
313
- className = fullNameParts[fullNameParts.length - 2] || fullNameParts[fullNameParts.length - 1];
314
- } else {
315
- return null;
316
- }
317
-
318
- if (this.withPackage) {
319
- const parts = packageLabel.split('.');
320
- return `${parts.join('/')}/${className}.${ext}`;
321
- }
322
-
323
- return `${className}.${ext}`;
324
- }
325
-
326
- getFileExtension(result) {
327
- const labels = result.labels || [];
328
- const languageLabel = labels.find(l => l.name === 'language')?.value;
329
-
330
- const extMap = {
331
- java: 'java',
332
- kotlin: 'kt',
333
- javascript: 'js',
334
- typescript: 'ts',
335
- python: 'py',
336
- ruby: 'rb',
337
- 'c#': 'cs',
338
- php: 'php',
339
- };
340
-
341
- return extMap[languageLabel?.toLowerCase()] || 'java';
342
- }
343
-
344
- extractMeta(result) {
345
- const labels = result.labels || [];
346
- const excludedLabels = [
347
- 'suite', 'package', 'parentSuite', 'subSuite',
348
- 'testClass', 'testMethod', 'epic', 'feature',
349
- ];
350
-
351
- const meta = {};
352
- labels.forEach(label => {
353
- if (!excludedLabels.includes(label.name)) {
354
- meta[label.name] = label.value;
355
- }
356
- });
357
-
358
- return meta;
359
- }
360
-
361
- extractLinks(result) {
362
- const labels = result.labels || [];
363
- const links = [];
364
-
365
- const epicLabel = labels.find(l => l.name === 'epic');
366
- const featureLabel = labels.find(l => l.name === 'feature');
367
-
368
- if (epicLabel?.value) {
369
- links.push({ label: `epic:${epicLabel.value}` });
370
- }
371
-
372
- if (featureLabel?.value) {
373
- links.push({ label: `feature:${featureLabel.value}` });
374
- }
375
-
376
- return links.length > 0 ? links : undefined;
377
- }
378
-
379
- /**
380
- * Extract a Testomat.io test id from Allure links so reported tests match
381
- * existing cases instead of creating duplicates.
382
- *
383
- * Allure's `@TmsLink("T1a2b3c4d")` produces a link with `type: "tms"`. Some exporters
384
- * omit the type but still point the link URL at a Testomat.io test page; both are
385
- * accepted. The link `name` is used as the id (falling back to the last URL segment).
386
- *
387
- * @param {object} result - Parsed Allure result JSON
388
- * @returns {string|null} Normalized test id, or null when no usable link exists
389
- */
390
- extractTestId(result) {
391
- const links = result.links || [];
392
- if (!links.length) return null;
393
-
394
- const isTmsLink = l => typeof l?.type === 'string' && l.type.toLowerCase() === 'tms';
395
- const isTestomatioLink = l => typeof l?.url === 'string' && /testomat\.io\/[^\s]*\/test\//i.test(l.url);
396
-
397
- const link = links.find(isTmsLink) || links.find(isTestomatioLink);
398
- if (!link) return null;
399
-
400
- // Prefer the explicit link name; fall back to the id segment of a Testomat.io URL.
401
- let id = this.normalizeTestId(link.name);
402
- if (!id && typeof link.url === 'string') {
403
- const fromUrl = link.url.match(/\/test\/([\w\d]{8})(?=$|[/?#])/i);
404
- if (fromUrl) id = fromUrl[1];
405
- }
406
-
407
- return id;
408
- }
409
-
410
- /**
411
- * Normalize a value into a Testomat.io test id.
412
- *
413
- * Testomat.io test ids are exactly **8 word characters**. The value may arrive bare
414
- * (`1a2b3c4d`), or carrying the `T` / `@T` markers Testomat uses in code and titles
415
- * (`T1a2b3c4d`, `@T1a2b3c4d`). The markers are removed only when doing so still leaves
416
- * a valid 8-char id, so a real id that happens to start with `T` is preserved.
417
- *
418
- * Anything that does not resolve to a valid 8-char id — a numeric Allure TestOps id
419
- * like `12345`, a JIRA key, a 6-digit TMS number — is rejected (returns null) so we
420
- * never send an unmatchable id that would create duplicates.
421
- *
422
- * @param {string|number|null|undefined} value
423
- * @returns {string|null} The bare 8-char id, or null when the value is not a valid id
424
- */
425
- normalizeTestId(value) {
426
- if (value === null || value === undefined) return null;
427
- const match = value.toString().trim().match(/^@?T?([\w\d]{8})$/);
428
- return match ? match[1] : null;
429
- }
430
-
431
- convertSteps(steps, depth = 0) {
432
- if (depth >= 10) return null;
433
-
434
- return steps
435
- .map(step => {
436
- const convertedStep = {
437
- category: 'user',
438
- title: step.name || step.title || 'Unknown step',
439
- status: this.mapStepStatus(step.status),
440
- duration: this.calculateRunTime(step),
441
- steps: this.convertSteps(step.steps || [], depth + 1),
442
- };
443
-
444
- if (convertedStep.steps && convertedStep.steps.length === 0) {
445
- delete convertedStep.steps;
446
- }
447
-
448
- if (convertedStep.duration === 0) {
449
- delete convertedStep.duration;
450
- }
451
-
452
- return convertedStep;
453
- })
454
- .filter(Boolean);
455
- }
456
-
457
- calculateRunTime(item) {
458
- if (item.start && item.stop) {
459
- const durationMs = item.stop - item.start;
460
- return durationMs / 1000;
461
- }
462
- return null;
463
- }
464
-
465
- convertParameters(parameters) {
466
- const example = {};
467
- parameters.forEach(param => {
468
- if (param.name) {
469
- example[param.name] = param.value;
470
- }
471
- });
472
- return example;
473
- }
474
-
475
- combineRetryAttempts(attempts) {
476
- attempts.sort((a, b) => (a._stop || 0) - (b._stop || 0));
477
-
478
- const finalTest = attempts[attempts.length - 1];
479
- const retryCount = attempts.length - 1;
480
-
481
- if (retryCount > 0) {
482
- finalTest.retries = retryCount;
483
- }
484
-
485
- const failedAttempts = attempts.filter(t => t.status === 'failed');
486
-
487
- if (failedAttempts.length === 0) {
488
- return finalTest;
489
- }
490
-
491
- const failureMessages = [];
492
- const failureStacks = [];
493
-
494
- for (const failed of failedAttempts) {
495
- const attemptNum = attempts.indexOf(failed) + 1;
496
- if (failed.message) {
497
- failureMessages.push(`[Attempt ${attemptNum}] ${failed.message}`);
498
- }
499
- if (failed.stack) {
500
- failureStacks.push(`\n--- Attempt ${attemptNum} ---\n${failed.stack}`);
501
- }
502
- }
503
-
504
- if (failureMessages.length > 0) {
505
- finalTest.message = failureMessages.join('\n');
506
- }
507
- if (failureStacks.length > 0) {
508
- finalTest.stack = failureStacks.join('\n');
509
- }
510
-
511
- if (finalTest.status === 'passed') {
512
- finalTest.status = 'failed';
513
- const retryMsg = `Test passed after ${failedAttempts.length} retries. Previous failures:\n`;
514
- finalTest.message = retryMsg + finalTest.message;
515
- }
516
-
517
- return finalTest;
518
- }
519
-
520
- calculateStats() {
521
- this.stats = {
522
- create_tests: true,
523
- tests_count: this._tests.length,
524
- passed_count: 0,
525
- failed_count: 0,
526
- skipped_count: 0,
527
- duration: 0,
528
- status: 'passed',
529
- tests: this._tests,
530
- };
531
- this._tests.forEach(t => {
532
- if (t.status === 'passed') this.stats.passed_count++;
533
- if (t.status === 'failed') this.stats.failed_count++;
534
- if (t.status === 'skipped') this.stats.skipped_count++;
535
- });
536
- this.stats.duration = this._tests.reduce((acc, t) => acc + (t.run_time || 0), 0);
537
- if (this.stats.failed_count) this.stats.status = 'failed';
538
-
539
- debug('Stats:', this.stats);
540
- return this.stats;
541
- }
542
-
543
- fetchSourceCode() {
544
- const adapter = this.adapter || adapterFactory(this.getLanguage(), this.opts);
545
-
546
- this._tests.forEach(t => {
547
- try {
548
- let filePath = t.file;
549
-
550
- if (adapter && adapter.getFilePath) {
551
- filePath = adapter.getFilePath(t);
552
- }
553
-
554
- if (!filePath) return;
555
-
556
- if (!fs.existsSync(filePath)) {
557
- debug('Source file not found:', filePath);
558
- return;
559
- }
560
-
561
- const contents = fs.readFileSync(filePath).toString();
562
- const code = fetchSourceCode(contents, { ...t, lang: this.getLanguage() });
563
- if (code) {
564
- t.code = code;
565
- debug('Fetched code for test %s', t.title);
566
- }
567
-
568
- // Don't override an id already taken from a @TmsLink — the link is the
569
- // explicit, source-independent match key the client maintains.
570
- const testId = fetchIdFromCode(contents, { lang: this.getLanguage() });
571
- if (testId && !t.test_id) {
572
- t.test_id = testId;
573
- debug('Fetched test id %s for test %s', testId, t.title);
574
- }
575
- } catch (err) {
576
- debug('Failed to fetch source code:', err.message);
577
- }
578
- });
579
- }
580
-
581
- getLanguage() {
582
- if (this._tests.length === 0) return null;
583
- return this._tests[0].meta?.language || this.opts.lang;
584
- }
585
-
586
- async uploadArtifacts() {
587
- for (const test of this._tests.filter(t => t.files && t.files.length > 0)) {
588
- const runId = this.runId || this.store.runId || Date.now().toString();
589
- const artifacts = await Promise.all(
590
- test.files.map(f => this.uploader.uploadFileByPath(f, [runId, test.rid, path.basename(f)])),
591
- );
592
- test.artifacts = artifacts.filter(a => a && a.link).map(a => a.link);
593
- delete test.files;
594
- if (test.artifacts.length > 0) {
595
- console.log(APP_PREFIX, `🗄️ Uploaded ${pc.bold(`${test.artifacts.length} artifacts`)} for test ${test.title}`);
596
- }
597
- }
598
- }
599
-
600
- async uploadData() {
601
- await this.uploadArtifacts();
602
- this.calculateStats();
603
- this.fetchSourceCode();
604
-
605
- this.pipes = this.pipes || (await this.pipesPromise);
606
-
607
- const finishData = {
608
- api_key: this.requestParams.apiKey,
609
- status: 'finished',
610
- duration: this.stats.duration,
611
- };
612
-
613
- if (!this._tests || !Array.isArray(this._tests) || this._tests.length === 0) {
614
- debug('No tests to upload, finishing run');
615
- return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
616
- }
617
-
618
- // Upload tests in size-limited chunks (max 1MB each), exactly like XmlReader.
619
- // The testomatio pipe runs in MANUAL batch mode, so addTest only buffers tests and
620
- // sync() flushes one batch request per chunk. There is no setInterval auto-upload,
621
- // so each test is sent exactly once (no double-send) and requests stay under the limit.
622
- const testChunks = splitTestsIntoChunks(this._tests);
623
-
624
- const totalChunks = testChunks.length;
625
- const totalTests = this._tests.length;
626
-
627
- debug(`Split ${totalTests} tests into ${totalChunks} chunks (max 1MB per chunk)`);
628
-
629
- let uploadedTests = 0;
630
- for (let i = 0; i < testChunks.length; i++) {
631
- const chunk = testChunks[i];
632
-
633
- if (totalChunks > 1) {
634
- debug(`Uploading chunk ${i + 1}/${totalChunks} (${chunk.length} tests)`);
635
- }
636
-
637
- // Buffer each test in the chunk, then flush the whole chunk as a single batch
638
- for (const test of chunk) {
639
- await Promise.all(this.pipes.map(p => p.addTest(test)));
640
- }
641
- await Promise.all(this.pipes.map(p => p.sync()));
642
-
643
- uploadedTests += chunk.length;
644
- debug(`Uploaded ${uploadedTests}/${totalTests} tests`);
645
- }
646
-
647
- if (totalChunks > 1) {
648
- console.log(APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests in ${totalChunks} chunks`);
649
- } else {
650
- console.log(APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests`);
651
- }
652
-
653
- debug('Uploaded %d tests, finishing run', this._tests.length);
654
-
655
- return Promise.all(this.pipes.map(p => p.finishRun(finishData)));
656
- }
657
- }
658
-
659
- export default AllureReader;
@@ -1,48 +0,0 @@
1
- import path from 'path';
2
- import Adapter from './adapter.js';
3
-
4
- class KotlinAdapter extends Adapter {
5
- getFilePath(t) {
6
- const fileName = namespaceToFileName(t.suite_title);
7
- return this.opts.javaTests + path.sep + fileName;
8
- }
9
-
10
- formatTest(t) {
11
- const fileParts = t.suite_title.split('.');
12
-
13
- t.file = namespaceToFileName(t.suite_title);
14
- t.title = t.title.split('(')[0];
15
-
16
- // detect params
17
- const paramMatches = t.title.match(/\[(.*?)\]/g);
18
-
19
- if (paramMatches) {
20
- const params = paramMatches.map((_match, index) => `param${index + 1}`);
21
- if (params.length === 1) params[0] = 'param';
22
- let paramIndex = 0;
23
-
24
- t.title = t.title.replace(/: \[(.*?)\]/g, () => {
25
- if (params.length < 2) return `\${param}`;
26
- const paramName = params[paramIndex] || `param${paramIndex + 1}`;
27
- paramIndex++;
28
- return `\${${paramName}}`;
29
- });
30
- const example = {};
31
- paramMatches.forEach((match, index) => {
32
- example[params[index]] = match.replace(/[[\]]/g, '');
33
- });
34
- t.example = example;
35
- }
36
-
37
- t.suite_title = fileParts[fileParts.length - 1].replace(/\$/g, ' | ');
38
- return t;
39
- }
40
- }
41
-
42
- function namespaceToFileName(fileName) {
43
- const fileParts = fileName.split('.');
44
- fileParts[fileParts.length - 1] = fileParts[fileParts.length - 1]?.replace(/\$.*/, '');
45
- return `${fileParts.join(path.sep)}.kt`;
46
- }
47
-
48
- export default KotlinAdapter;