@testomatio/reporter 2.7.2 → 2.7.3-beta.3.allure

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.
@@ -18,7 +18,7 @@ exports.stripColors = stripColors;
18
18
  * Returns the formatted stack including the stack trace, steps, and logs.
19
19
  * @param {Object} params - Parameters for formatting logs
20
20
  * @param {string} params.error - Error message
21
- * @param {Array|any} params.steps - Test steps (array or other types)
21
+ * @param {Array|any} [params.steps] - Test steps (array or other types)
22
22
  * @param {string} params.logs - Test logs
23
23
  * @returns {string}
24
24
  */
@@ -324,6 +324,15 @@ const fetchSourceCode = (contents, opts = {}) => {
324
324
  if (lineIndex === -1)
325
325
  lineIndex = lines.findIndex(l => l.includes(`${title}(`));
326
326
  }
327
+ else if (opts.lang === 'kotlin') {
328
+ lineIndex = lines.findIndex(l => l.includes(`fun test${title}`));
329
+ if (lineIndex === -1)
330
+ lineIndex = lines.findIndex(l => l.includes(`@DisplayName("${title}`));
331
+ if (lineIndex === -1)
332
+ lineIndex = lines.findIndex(l => l.includes(`fun ${title}`));
333
+ if (lineIndex === -1)
334
+ lineIndex = lines.findIndex(l => l.includes(`${title}(`));
335
+ }
327
336
  else if (opts.lang === 'csharp') {
328
337
  // Find the method declaration line
329
338
  let methodLineIndex = lines.findIndex(l => l.includes(`public void ${title}(`));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testomatio/reporter",
3
- "version": "2.7.2",
3
+ "version": "2.7.3-beta.3.allure",
4
4
  "description": "Testomatio Reporter Client",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -0,0 +1,532 @@
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 } 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 {
13
+ fetchSourceCode,
14
+ fetchIdFromCode,
15
+ } from './utils/utils.js';
16
+ import adapterFactory from './junit-adapter/index.js';
17
+
18
+ // @ts-ignore
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+
21
+ const debug = createDebugMessages('@testomatio/reporter:allure');
22
+
23
+ const TESTOMATIO_URL = process.env.TESTOMATIO_URL || 'https://app.testomat.io';
24
+ const { TESTOMATIO_RUNGROUP_TITLE, TESTOMATIO_SUITE, TESTOMATIO_TITLE, TESTOMATIO_ENV, TESTOMATIO_RUN } = process.env;
25
+
26
+ class AllureReader {
27
+ constructor(opts = {}) {
28
+ this.requestParams = {
29
+ apiKey: opts.apiKey || config.TESTOMATIO,
30
+ url: opts.url || TESTOMATIO_URL,
31
+ title: TESTOMATIO_TITLE,
32
+ env: TESTOMATIO_ENV,
33
+ group_title: TESTOMATIO_RUNGROUP_TITLE,
34
+ isBatchEnabled: true,
35
+ };
36
+ this.runId = opts.runId || TESTOMATIO_RUN;
37
+ this.opts = opts || {};
38
+ this.withPackage = opts.withPackage || false;
39
+ this.store = {};
40
+ this.pipesPromise = pipesFactory(opts, this.store);
41
+ this._tests = [];
42
+ this.stats = {};
43
+ this.suites = {};
44
+ this.uploader = new S3Uploader();
45
+
46
+ // Allure results already contain steps and stack traces for all tests,
47
+ // so enable passing them for passed tests by default
48
+ if (!process.env.TESTOMATIO_STACK_PASSED) {
49
+ process.env.TESTOMATIO_STACK_PASSED = '1';
50
+ }
51
+ if (!process.env.TESTOMATIO_STEPS_PASSED) {
52
+ process.env.TESTOMATIO_STEPS_PASSED = '1';
53
+ }
54
+
55
+ const packageJsonPath = path.resolve(__dirname, '..', 'package.json');
56
+ this.version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version;
57
+ console.log(APP_PREFIX, `Testomatio Reporter v${this.version}`);
58
+ }
59
+
60
+ get tests() {
61
+ return this._tests;
62
+ }
63
+
64
+ set tests(value) {
65
+ this._tests = value;
66
+ }
67
+
68
+ async createRun() {
69
+ const runParams = {
70
+ api_key: this.requestParams.apiKey,
71
+ title: this.requestParams.title,
72
+ env: this.requestParams.env,
73
+ group_title: this.requestParams.group_title,
74
+ isBatchEnabled: this.requestParams.isBatchEnabled,
75
+ };
76
+
77
+ debug('Run', runParams);
78
+ this.pipes = this.pipes || (await this.pipesPromise);
79
+
80
+ const run = await Promise.all(this.pipes.map(p => p.createRun(runParams)));
81
+ this.uploader.checkEnabled();
82
+ return run;
83
+ }
84
+
85
+ parse(resultsPattern) {
86
+ this._tests = [];
87
+ let pattern = resultsPattern;
88
+
89
+ // Auto-append wildcard if pattern refers to a directory (like XML command does)
90
+ if (!pattern.endsWith('.json') && !pattern.includes('*')) {
91
+ if (pattern.endsWith('/') || (fs.existsSync(pattern) && fs.statSync(pattern).isDirectory())) {
92
+ pattern = pattern.replace(/\/+$/, '') + '/*-result.json';
93
+ } else {
94
+ pattern += '*-result.json';
95
+ }
96
+ }
97
+
98
+ const resultsDir = path.dirname(pattern);
99
+
100
+ console.log(APP_PREFIX, `Scanning for Allure results in: ${resultsDir}`);
101
+ console.log(APP_PREFIX, `Using pattern: ${pattern}`);
102
+
103
+ const resultFiles = glob.sync(pattern);
104
+ const containerFiles = glob.sync(pattern.replace('*-result.json', '*-container.json'));
105
+
106
+ if (resultFiles.length === 0 && containerFiles.length === 0) {
107
+ throw new Error(`No Allure result files found matching pattern: ${pattern}`);
108
+ }
109
+
110
+ console.log(APP_PREFIX, `Found ${resultFiles.length} result files and ${containerFiles.length} container files`);
111
+
112
+ this.parseContainerFiles(containerFiles);
113
+
114
+ // Store all tests temporarily for deduplication by historyId
115
+ const allTests = [];
116
+ for (const file of resultFiles) {
117
+ const fullPath = file;
118
+ const fileDir = path.dirname(file);
119
+ try {
120
+ const resultData = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
121
+ const test = this.processAllureResult(resultData, fileDir);
122
+ if (test) {
123
+ test._historyId = resultData.historyId;
124
+ test._stop = resultData.stop || 0;
125
+ allTests.push(test);
126
+ }
127
+ } catch (err) {
128
+ console.warn(APP_PREFIX, `Failed to parse ${file}:`, err.message);
129
+ debug('Parse error:', err);
130
+ }
131
+ }
132
+
133
+ const attemptsMap = new Map();
134
+ for (const test of allTests) {
135
+ const historyId = test._historyId || test.rid;
136
+ if (!attemptsMap.has(historyId)) {
137
+ attemptsMap.set(historyId, []);
138
+ }
139
+ attemptsMap.get(historyId).push(test);
140
+ }
141
+
142
+ const uniqueTestsMap = new Map();
143
+ for (const [historyId, attempts] of attemptsMap) {
144
+ uniqueTestsMap.set(historyId, this.combineRetryAttempts(attempts));
145
+ }
146
+
147
+ // Convert map to array and clean up internal fields
148
+ this._tests = Array.from(uniqueTestsMap.values()).map(t => {
149
+ delete t._historyId;
150
+ delete t._stop;
151
+ return t;
152
+ });
153
+
154
+ console.log(APP_PREFIX, `Processed ${this._tests.length} unique tests (from ${allTests.length} result files)`);
155
+
156
+ return this.calculateStats();
157
+ }
158
+
159
+ parseContainerFiles(containerFiles) {
160
+ for (const file of containerFiles) {
161
+ try {
162
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
163
+ if (data.name && data.children) {
164
+ data.children.forEach(uuid => {
165
+ this.suites[uuid] = data.name;
166
+ });
167
+ }
168
+ } catch (err) {
169
+ debug('Failed to parse container file:', file, err.message);
170
+ }
171
+ }
172
+ debug('Parsed suites:', this.suites);
173
+ }
174
+
175
+ processAllureResult(result, resultsDir) {
176
+ const test = {
177
+ rid: result.uuid || randomUUID(),
178
+ title: result.name || 'Unknown test',
179
+ status: this.mapStatus(result.status),
180
+ suite_title: this.extractSuiteTitle(result),
181
+ file: this.extractFile(result),
182
+ run_time: this.calculateRunTime(result),
183
+ steps: this.convertSteps(result.steps || []),
184
+ message: result.statusDetails?.message || '',
185
+ stack: result.statusDetails?.trace || '',
186
+ meta: this.extractMeta(result),
187
+ links: this.extractLinks(result),
188
+ artifacts: [],
189
+ create: true,
190
+ overwrite: true,
191
+ };
192
+
193
+ // Add description if present
194
+ if (result.description) {
195
+ test.description = result.description;
196
+ }
197
+
198
+ if (result.parameters && result.parameters.length > 0) {
199
+ test.example = this.convertParameters(result.parameters);
200
+ }
201
+
202
+ if (result.attachments && result.attachments.length > 0) {
203
+ const attachments = result.attachments
204
+ .map(att => {
205
+ const fullPath = path.join(resultsDir, att.source);
206
+ if (fs.existsSync(fullPath)) {
207
+ return fullPath;
208
+ }
209
+ debug('Attachment file not found:', fullPath);
210
+ return null;
211
+ })
212
+ .filter(Boolean);
213
+
214
+ if (attachments.length > 0) {
215
+ test.files = attachments;
216
+ }
217
+ }
218
+
219
+ return test;
220
+ }
221
+
222
+ mapStatus(status) {
223
+ const statusMap = {
224
+ passed: 'passed',
225
+ failed: 'failed',
226
+ broken: 'failed',
227
+ skipped: 'skipped',
228
+ pending: 'skipped',
229
+ };
230
+ return statusMap[status] || 'failed';
231
+ }
232
+
233
+ extractSuiteTitle(result) {
234
+ const labels = result.labels || [];
235
+
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
+
240
+ if (suiteLabel) {
241
+ return this.stripNamespace(suiteLabel);
242
+ }
243
+
244
+ // Fallback to parentSuite or subSuite if no suite label
245
+ const parentSuite = labels.find(l => l.name === 'parentSuite')?.value;
246
+ const subSuite = labels.find(l => l.name === 'subSuite')?.value;
247
+
248
+ if (parentSuite && subSuite) {
249
+ return `${parentSuite} / ${subSuite}`;
250
+ }
251
+ if (parentSuite) return parentSuite;
252
+ if (subSuite) return subSuite;
253
+
254
+ return 'Default Suite';
255
+ }
256
+
257
+ stripNamespace(suiteName) {
258
+ if (suiteName && suiteName.includes('.')) {
259
+ return suiteName.split('.').pop();
260
+ }
261
+ return suiteName;
262
+ }
263
+
264
+ extractFile(result) {
265
+ const labels = result.labels || [];
266
+ const packageLabel = labels.find(l => l.name === 'package')?.value;
267
+ const testClassLabel = labels.find(l => l.name === 'testClass')?.value;
268
+
269
+ if (!packageLabel) {
270
+ return null;
271
+ }
272
+
273
+ const ext = this.getFileExtension(result);
274
+ let className;
275
+
276
+ if (testClassLabel) {
277
+ className = testClassLabel.split('.').pop();
278
+ } else if (result.fullName) {
279
+ const fullNameParts = result.fullName.split('.');
280
+ className = fullNameParts[fullNameParts.length - 2] || fullNameParts[fullNameParts.length - 1];
281
+ } else {
282
+ return null;
283
+ }
284
+
285
+ if (this.withPackage) {
286
+ const parts = packageLabel.split('.');
287
+ return `${parts.join('/')}/${className}.${ext}`;
288
+ }
289
+
290
+ return `${className}.${ext}`;
291
+ }
292
+
293
+ getFileExtension(result) {
294
+ const labels = result.labels || [];
295
+ const languageLabel = labels.find(l => l.name === 'language')?.value;
296
+
297
+ const extMap = {
298
+ java: 'java',
299
+ kotlin: 'kt',
300
+ javascript: 'js',
301
+ typescript: 'ts',
302
+ python: 'py',
303
+ ruby: 'rb',
304
+ 'c#': 'cs',
305
+ php: 'php',
306
+ };
307
+
308
+ return extMap[languageLabel?.toLowerCase()] || 'java';
309
+ }
310
+
311
+ extractMeta(result) {
312
+ const labels = result.labels || [];
313
+ const excludedLabels = [
314
+ 'suite', 'package', 'parentSuite', 'subSuite',
315
+ 'testClass', 'testMethod', 'epic', 'feature',
316
+ ];
317
+
318
+ const meta = {};
319
+ labels.forEach(label => {
320
+ if (!excludedLabels.includes(label.name)) {
321
+ meta[label.name] = label.value;
322
+ }
323
+ });
324
+
325
+ return meta;
326
+ }
327
+
328
+ extractLinks(result) {
329
+ const labels = result.labels || [];
330
+ const links = [];
331
+
332
+ const epicLabel = labels.find(l => l.name === 'epic');
333
+ const featureLabel = labels.find(l => l.name === 'feature');
334
+
335
+ if (epicLabel?.value) {
336
+ links.push({ label: `epic:${epicLabel.value}` });
337
+ }
338
+
339
+ if (featureLabel?.value) {
340
+ links.push({ label: `feature:${featureLabel.value}` });
341
+ }
342
+
343
+ return links.length > 0 ? links : undefined;
344
+ }
345
+
346
+ convertSteps(steps, depth = 0) {
347
+ if (depth >= 10) return null;
348
+
349
+ return steps
350
+ .map(step => {
351
+ const convertedStep = {
352
+ category: 'user',
353
+ title: step.name || step.title || 'Unknown step',
354
+ duration: this.calculateRunTime(step),
355
+ steps: this.convertSteps(step.steps || [], depth + 1),
356
+ };
357
+
358
+ if (convertedStep.steps && convertedStep.steps.length === 0) {
359
+ delete convertedStep.steps;
360
+ }
361
+
362
+ if (convertedStep.duration === 0) {
363
+ delete convertedStep.duration;
364
+ }
365
+
366
+ return convertedStep;
367
+ })
368
+ .filter(Boolean);
369
+ }
370
+
371
+ calculateRunTime(item) {
372
+ if (item.start && item.stop) {
373
+ const durationMs = item.stop - item.start;
374
+ return durationMs / 1000;
375
+ }
376
+ return null;
377
+ }
378
+
379
+ convertParameters(parameters) {
380
+ const example = {};
381
+ parameters.forEach(param => {
382
+ if (param.name) {
383
+ example[param.name] = param.value;
384
+ }
385
+ });
386
+ return example;
387
+ }
388
+
389
+ combineRetryAttempts(attempts) {
390
+ attempts.sort((a, b) => (a._stop || 0) - (b._stop || 0));
391
+
392
+ const finalTest = attempts[attempts.length - 1];
393
+ const retryCount = attempts.length - 1;
394
+
395
+ if (retryCount > 0) {
396
+ finalTest.retries = retryCount;
397
+ }
398
+
399
+ const failedAttempts = attempts.filter(t => t.status === 'failed');
400
+
401
+ if (failedAttempts.length === 0) {
402
+ return finalTest;
403
+ }
404
+
405
+ const failureMessages = [];
406
+ const failureStacks = [];
407
+
408
+ for (const failed of failedAttempts) {
409
+ const attemptNum = attempts.indexOf(failed) + 1;
410
+ if (failed.message) {
411
+ failureMessages.push(`[Attempt ${attemptNum}] ${failed.message}`);
412
+ }
413
+ if (failed.stack) {
414
+ failureStacks.push(`\n--- Attempt ${attemptNum} ---\n${failed.stack}`);
415
+ }
416
+ }
417
+
418
+ if (failureMessages.length > 0) {
419
+ finalTest.message = failureMessages.join('\n');
420
+ }
421
+ if (failureStacks.length > 0) {
422
+ finalTest.stack = failureStacks.join('\n');
423
+ }
424
+
425
+ if (finalTest.status === 'passed') {
426
+ finalTest.status = 'failed';
427
+ const retryMsg = `Test passed after ${failedAttempts.length} retries. Previous failures:\n`;
428
+ finalTest.message = retryMsg + finalTest.message;
429
+ }
430
+
431
+ return finalTest;
432
+ }
433
+
434
+ calculateStats() {
435
+ this.stats = {
436
+ create_tests: true,
437
+ tests_count: this._tests.length,
438
+ passed_count: 0,
439
+ failed_count: 0,
440
+ skipped_count: 0,
441
+ duration: 0,
442
+ status: 'passed',
443
+ tests: this._tests,
444
+ };
445
+ this._tests.forEach(t => {
446
+ if (t.status === 'passed') this.stats.passed_count++;
447
+ if (t.status === 'failed') this.stats.failed_count++;
448
+ if (t.status === 'skipped') this.stats.skipped_count++;
449
+ });
450
+ this.stats.duration = this._tests.reduce((acc, t) => acc + (t.run_time || 0), 0);
451
+ if (this.stats.failed_count) this.stats.status = 'failed';
452
+
453
+ debug('Stats:', this.stats);
454
+ return this.stats;
455
+ }
456
+
457
+ fetchSourceCode() {
458
+ const adapter = this.adapter || adapterFactory(this.getLanguage(), this.opts);
459
+
460
+ this._tests.forEach(t => {
461
+ try {
462
+ let filePath = t.file;
463
+
464
+ if (adapter && adapter.getFilePath) {
465
+ filePath = adapter.getFilePath(t);
466
+ }
467
+
468
+ if (!filePath) return;
469
+
470
+ if (!fs.existsSync(filePath)) {
471
+ debug('Source file not found:', filePath);
472
+ return;
473
+ }
474
+
475
+ const contents = fs.readFileSync(filePath).toString();
476
+ const code = fetchSourceCode(contents, { ...t, lang: this.getLanguage() });
477
+ if (code) {
478
+ t.code = code;
479
+ debug('Fetched code for test %s', t.title);
480
+ }
481
+
482
+ const testId = fetchIdFromCode(contents, { lang: this.getLanguage() });
483
+ if (testId) {
484
+ t.test_id = testId;
485
+ debug('Fetched test id %s for test %s', testId, t.title);
486
+ }
487
+ } catch (err) {
488
+ debug('Failed to fetch source code:', err.message);
489
+ }
490
+ });
491
+ }
492
+
493
+ getLanguage() {
494
+ if (this._tests.length === 0) return null;
495
+ return this._tests[0].meta?.language || this.opts.lang;
496
+ }
497
+
498
+ async uploadArtifacts() {
499
+ for (const test of this._tests.filter(t => t.files && t.files.length > 0)) {
500
+ const runId = this.runId || this.store.runId || Date.now().toString();
501
+ const artifacts = await Promise.all(
502
+ test.files.map(f => this.uploader.uploadFileByPath(f, [runId, test.rid, path.basename(f)])),
503
+ );
504
+ test.artifacts = artifacts.filter(a => a && a.link).map(a => a.link);
505
+ delete test.files;
506
+ if (test.artifacts.length > 0) {
507
+ console.log(APP_PREFIX, `🗄️ Uploaded ${pc.bold(`${test.artifacts.length} artifacts`)} for test ${test.title}`);
508
+ }
509
+ }
510
+ }
511
+
512
+ async uploadData() {
513
+ await this.uploadArtifacts();
514
+ this.calculateStats();
515
+ this.fetchSourceCode();
516
+
517
+ const dataString = {
518
+ ...this.stats,
519
+ api_key: this.requestParams.apiKey,
520
+ status: 'finished',
521
+ duration: this.stats.duration,
522
+ tests: this._tests,
523
+ };
524
+
525
+ debug('Uploading data', dataString);
526
+
527
+ this.pipes = this.pipes || (await this.pipesPromise);
528
+ return Promise.all(this.pipes.map(p => p.finishRun(dataString)));
529
+ }
530
+ }
531
+
532
+ export default AllureReader;
package/src/bin/cli.js CHANGED
@@ -6,6 +6,7 @@ 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';
9
10
  import { APP_PREFIX, STATUS } from '../constants.js';
10
11
  import { cleanLatestRunId, getPackageVersion, applyFilter } from '../utils/utils.js';
11
12
  import { config } from '../config.js';
@@ -264,6 +265,40 @@ program
264
265
  if (timeoutTimer) clearTimeout(timeoutTimer);
265
266
  });
266
267
 
268
+ program
269
+ .command('allure')
270
+ .description('Parse Allure result files and upload to Testomat.io')
271
+ .argument('<pattern>', 'Allure result directory pattern')
272
+ .option('-d, --dir <dir>', 'Project directory')
273
+ .option('--timelimit <time>', 'default time limit in seconds to kill a stuck process')
274
+ .option('--with-package', 'Keep full package path in file names (default: strip package prefix)')
275
+ .action(async (pattern, opts) => {
276
+ const runReader = new AllureReader({ withPackage: opts.withPackage });
277
+
278
+ let timeoutTimer;
279
+ if (opts.timelimit) {
280
+ timeoutTimer = setTimeout(
281
+ () => {
282
+ console.log(
283
+ `⚠️ Reached timeout of ${opts.timelimit}s. Exiting... (Exit code is 0 to not fail the pipeline)`,
284
+ );
285
+ process.exit(0);
286
+ },
287
+ parseInt(opts.timelimit, 10) * 1000,
288
+ );
289
+ }
290
+
291
+ try {
292
+ await runReader.parse(pattern);
293
+ await runReader.createRun();
294
+ await runReader.uploadData();
295
+ } catch (err) {
296
+ console.log(APP_PREFIX, 'Error uploading Allure results:', err);
297
+ }
298
+
299
+ if (timeoutTimer) clearTimeout(timeoutTimer);
300
+ });
301
+
267
302
  program
268
303
  .command('upload-artifacts')
269
304
  .description('Upload artifacts to Testomat.io')
package/src/client.js CHANGED
@@ -257,7 +257,7 @@ class Client {
257
257
  message = error?.message;
258
258
  }
259
259
 
260
- let fullLogs = formatLogs({ error: errorFormatted, steps, logs: testData.logs });
260
+ let fullLogs = formatLogs({ error: errorFormatted, logs: testData.logs });
261
261
 
262
262
  if (stackArtifactsEnabled && fullLogs?.trim()?.length > 0) {
263
263
  uploadedFiles.push(
@@ -4,6 +4,7 @@ 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';
7
8
 
8
9
  function AdapterFactory(lang, opts) {
9
10
  if (lang === 'java') {
@@ -21,6 +22,9 @@ function AdapterFactory(lang, opts) {
21
22
  if (lang === 'c#' || lang === 'csharp') {
22
23
  return new CSharpAdapter(opts);
23
24
  }
25
+ if (lang === 'kotlin') {
26
+ return new KotlinAdapter(opts);
27
+ }
24
28
 
25
29
  return new Adapter(opts);
26
30
  }
@@ -0,0 +1,48 @@
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;
@@ -11,7 +11,7 @@ const stripColors = stripVTControlCharacters || (str => str?.replace(/\x1b\[[0-9
11
11
  * Returns the formatted stack including the stack trace, steps, and logs.
12
12
  * @param {Object} params - Parameters for formatting logs
13
13
  * @param {string} params.error - Error message
14
- * @param {Array|any} params.steps - Test steps (array or other types)
14
+ * @param {Array|any} [params.steps] - Test steps (array or other types)
15
15
  * @param {string} params.logs - Test logs
16
16
  * @returns {string}
17
17
  */