@testomatio/reporter 1.4.1-beta-1 → 1.4.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.
Files changed (45) hide show
  1. package/README.md +60 -57
  2. package/lib/adapter/codecept.js +86 -27
  3. package/lib/adapter/cucumber/current.js +17 -10
  4. package/lib/adapter/cucumber/legacy.js +5 -4
  5. package/lib/adapter/cucumber.js +2 -2
  6. package/lib/adapter/cypress-plugin/index.js +53 -26
  7. package/lib/adapter/jasmine.js +2 -2
  8. package/lib/adapter/jest.js +48 -10
  9. package/lib/adapter/mocha.js +90 -10
  10. package/lib/adapter/playwright.js +68 -18
  11. package/lib/adapter/webdriver.js +47 -2
  12. package/lib/bin/reportXml.js +21 -16
  13. package/lib/bin/startTest.js +12 -12
  14. package/lib/client.js +112 -52
  15. package/lib/config.js +34 -0
  16. package/lib/constants.js +28 -1
  17. package/lib/data-storage.js +203 -0
  18. package/lib/fileUploader.js +66 -53
  19. package/lib/junit-adapter/adapter.js +0 -2
  20. package/lib/junit-adapter/csharp.js +3 -4
  21. package/lib/junit-adapter/index.js +3 -3
  22. package/lib/junit-adapter/java.js +11 -11
  23. package/lib/junit-adapter/javascript.js +1 -2
  24. package/lib/junit-adapter/python.js +12 -14
  25. package/lib/junit-adapter/ruby.js +1 -2
  26. package/lib/pipe/csv.js +35 -32
  27. package/lib/pipe/github.js +4 -3
  28. package/lib/pipe/gitlab.js +17 -10
  29. package/lib/pipe/html.js +361 -0
  30. package/lib/pipe/index.js +3 -1
  31. package/lib/pipe/testomatio.js +230 -51
  32. package/lib/reporter-functions.js +12 -9
  33. package/lib/reporter.js +8 -12
  34. package/lib/services/artifacts.js +57 -0
  35. package/lib/services/index.js +13 -0
  36. package/lib/{storages/key-value-storage.js → services/key-values.js} +19 -19
  37. package/lib/{storages → services}/logger.js +58 -37
  38. package/lib/template/emptyData.svg +23 -0
  39. package/lib/template/testomatio.hbs +1421 -0
  40. package/lib/utils/pipe_utils.js +73 -79
  41. package/lib/utils/utils.js +53 -40
  42. package/lib/xmlReader.js +113 -105
  43. package/package.json +13 -7
  44. package/lib/storages/artifact-storage.js +0 -70
  45. package/lib/storages/data-storage.js +0 -307
@@ -0,0 +1,361 @@
1
+ const debug = require('debug')('@testomatio/reporter:pipe:html');
2
+ const merge = require('lodash.merge');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const chalk = require('chalk');
6
+ const handlebars = require('handlebars');
7
+ const fileUrl = require('file-url');
8
+
9
+ const { fileSystem, isSameTest, ansiRegExp } = require('../utils/utils');
10
+ const { HTML_REPORT } = require('../constants');
11
+
12
+ class HtmlPipe {
13
+ constructor(params, store = {}) {
14
+ this.store = store || {};
15
+ this.title = params.title || process.env.TESTOMATIO_TITLE;
16
+ this.apiKey = params.apiKey || process.env.TESTOMATIO;
17
+ this.isHtml = process.env.TESTOMATIO_HTML_REPORT_SAVE;
18
+
19
+ debug('HTML Pipe: ', this.apiKey ? 'API KEY' : '*no api key provided*');
20
+
21
+ this.isEnabled = false;
22
+ this.htmlOutputPath = '';
23
+ this.fullHtmlOutputPath = '';
24
+ this.filenameMsg = '';
25
+ this.tests = [];
26
+
27
+ if (this.isHtml) {
28
+ this.isEnabled = true;
29
+ this.htmlReportDir = process.env.TESTOMATIO_HTML_REPORT_FOLDER || HTML_REPORT.FOLDER;
30
+
31
+ if (process.env.TESTOMATIO_HTML_FILENAME && process.env.TESTOMATIO_HTML_FILENAME.endsWith('.html')) {
32
+ this.htmlReportName = process.env.TESTOMATIO_HTML_FILENAME;
33
+ }
34
+
35
+ if (process.env.TESTOMATIO_HTML_FILENAME && !process.env.TESTOMATIO_HTML_FILENAME.endsWith('.html')) {
36
+ this.htmlReportName = HTML_REPORT.REPORT_DEFAULT_NAME;
37
+ this.filenameMsg =
38
+ 'HTML filename must include the extension ".html".' +
39
+ ` The default report name "${this.htmlReportDir}/${HTML_REPORT.REPORT_DEFAULT_NAME}" is used!`;
40
+ }
41
+
42
+ if (!process.env.TESTOMATIO_HTML_FILENAME) {
43
+ this.htmlReportName = HTML_REPORT.REPORT_DEFAULT_NAME;
44
+ }
45
+
46
+ this.templateFolderPath = path.resolve(__dirname, '..', 'template');
47
+ this.templateHtmlPath = path.resolve(this.templateFolderPath, HTML_REPORT.TEMPLATE_NAME);
48
+ this.htmlOutputPath = path.join(this.htmlReportDir, this.htmlReportName);
49
+ // create a new folder for the HTML reports
50
+ fileSystem.createDir(this.htmlReportDir);
51
+
52
+ debug(
53
+ chalk.yellow('HTML Pipe:'),
54
+ `Save HTML report: ${this.isEnabled}`,
55
+ `HTML report folder: ${this.htmlReportDir}, report name: ${this.htmlReportName}`,
56
+ );
57
+ }
58
+ }
59
+
60
+ async createRun() {
61
+ // empty
62
+ }
63
+
64
+ updateRun() {
65
+ // empty
66
+ }
67
+
68
+ /**
69
+ * Add test data to the result array for saving. As a result of this function, we get a result object to save.
70
+ * @param {import('../../types').RunData} test - object which includes each test entry.
71
+ */
72
+ addTest(test) {
73
+ if (!this.isEnabled) return;
74
+
75
+ if (!test.status) return;
76
+
77
+ const index = this.tests.findIndex(t => isSameTest(t, test));
78
+ // update if they were already added
79
+ if (index >= 0) {
80
+ this.tests[index] = merge(this.tests[index], test);
81
+ return;
82
+ }
83
+
84
+ this.tests.push(test);
85
+ }
86
+
87
+ async finishRun(runParams) {
88
+ if (!this.isEnabled) return;
89
+
90
+ if (this.isHtml) {
91
+ // GENERATE HTML reports based on the results data
92
+ this.buildReport({
93
+ runParams,
94
+ // TODO: this.tests=[] in case of Mocha, need retest by Vitalii
95
+ tests: this.tests,
96
+ outputPath: this.htmlOutputPath,
97
+ templatePath: this.templateHtmlPath,
98
+ warningMsg: this.filenameMsg,
99
+ });
100
+ }
101
+ }
102
+ /**
103
+ * Generates an HTML report based on provided test data and a template.
104
+ * @param {object} opts - Test options used to generate the HTML report:
105
+ * runParams, tests, outputPath, templatePath
106
+ * @returns {void} - This function does not return anything.
107
+ */
108
+
109
+ buildReport(opts) {
110
+ const { runParams, tests, outputPath, templatePath, warningMsg: msg } = opts;
111
+
112
+ debug('HTML tests data:', tests);
113
+
114
+ if (!outputPath) {
115
+ console.log(chalk.yellow(`🚨 HTML export path is not set, ignoring...`));
116
+ return;
117
+ }
118
+
119
+ console.log(chalk.yellow(`⏳ The test results will be added to the HTML report. It will take some time...`));
120
+
121
+ if (msg) {
122
+ console.log(chalk.blue(msg));
123
+ }
124
+
125
+ tests.forEach(test => {
126
+ if (!test.message?.trim()) {
127
+ test.message = "This test has no 'message' code";
128
+ }
129
+
130
+ if (!test.suite_title?.trim()) {
131
+ test.suite_title = 'Unknown suite';
132
+ }
133
+
134
+ if (!test.title?.trim()) {
135
+ test.title = 'Unknown test title';
136
+ }
137
+
138
+ if (!test.files?.length) {
139
+ test.files = 'This test has no files';
140
+ }
141
+
142
+ if (!test.steps?.trim()) {
143
+ test.steps = "This test has no 'steps' code";
144
+ } else {
145
+ test.steps = removeAnsiColorCodes(test.steps);
146
+ }
147
+
148
+ // TODO: future-proof: currently there is no need to display Artifacts and Metadata in HTML
149
+ test.artifacts = test.artifacts || [];
150
+ test.meta = test.meta || {};
151
+ // TODO: u can added an additional test values to this checks in the future
152
+ });
153
+
154
+ const data = {
155
+ runId: this.store.runId || '',
156
+ status: runParams.status || 'No status info',
157
+ parallel: runParams.isParallel || 'No parallel info',
158
+ runUrl: this.store.runUrl || '',
159
+ executionTime: testExecutionSumTime(tests),
160
+ executionDate: getCurrentDateTimeFormatted(),
161
+ tests,
162
+ };
163
+ // generate output HTML based on the template
164
+ const html = this.#generateHTMLReport(data, templatePath);
165
+
166
+ if (!html) return;
167
+
168
+ fs.writeFileSync(outputPath, html, 'utf-8');
169
+ // Check if the file exists
170
+ if (fs.existsSync(outputPath)) {
171
+ // Get the absolute path of the file
172
+ const absolutePath = path.resolve(outputPath);
173
+ // Convert the file path to a file URL
174
+ const fileUrlPath = fileUrl(absolutePath, { resolve: true });
175
+
176
+ debug('HTML tests data:', fileUrlPath);
177
+
178
+ console.log(chalk.green(`📊 The HTML report was successfully generated. Full filepath: ${fileUrlPath}`));
179
+ } else {
180
+ console.log(chalk.red(`🚨 Failed to generate the HTML report.`));
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Generates an HTML report based on provided test data and a template path.
186
+ * @param {any} data - Test data used to generate the HTML report.
187
+ * @param {string} [templatePath=""] - The path to the HTML template used for generating the report.
188
+ * @returns {string | void} - The generated HTML report as a string or void if templatePath is not provided.
189
+ */
190
+ #generateHTMLReport(data, templatePath = '') {
191
+ if (!templatePath) {
192
+ console.log(chalk.red(`🚨 HTML template not found. Report generation is impossible!`));
193
+ return;
194
+ }
195
+
196
+ const templateSource = fs.readFileSync(templatePath, 'utf8');
197
+ this.#loadReportHelpers();
198
+ try {
199
+ const template = handlebars.compile(templateSource);
200
+
201
+ return template(data);
202
+ } catch (e) {
203
+ console.log(chalk.red('❌ Oops! An unknown error occurred when generating an HTML report'));
204
+ console.log(chalk.red(e));
205
+ }
206
+ }
207
+
208
+ #loadReportHelpers() {
209
+ handlebars.registerHelper(
210
+ 'getTestsByStatus',
211
+ (tests, status) => tests.filter(test => test.status.toLowerCase() === status.toLowerCase()).length,
212
+ );
213
+
214
+ handlebars.registerHelper(
215
+ 'selectComponent',
216
+ () =>
217
+ new handlebars.SafeString(
218
+ `<select style="width: 70px;height: 38px;" class="form-select" aria-label="Tests counter on page">
219
+ <option value="0">10</option>
220
+ <option value="1">25</option>
221
+ <option value="2">50</option>
222
+ </select>`,
223
+ ),
224
+ );
225
+ /* eslint-disable */
226
+ handlebars.registerHelper('emptyDataComponent', () => {
227
+ const svgFilePath = path.join(__dirname, '..', 'template', 'emptyData.svg');
228
+ const svgContent = fs.readFileSync(svgFilePath, 'utf8');
229
+
230
+ return new handlebars.SafeString(
231
+ `
232
+ <div class="noData">
233
+ <div class="noDataSvg">
234
+ ${svgContent}
235
+ </div>
236
+ <div class="noDataText">
237
+ NO MATCHING TESTS
238
+ </div>
239
+ <div>`,
240
+ );
241
+ });
242
+ /* eslint-enable */
243
+ handlebars.registerHelper('pageDispleyElements', tests => {
244
+ // We wrapp the lines to the HTML format we need
245
+ const totalTests = JSON.parse(
246
+ JSON.stringify(tests)
247
+ .replace(/<script>/g, '&lt;script&gt;')
248
+ .replace(/<\/script>/g, '&lt;/script&gt;'), // eslint-disable-line
249
+ );
250
+
251
+ const paginationOptions = {
252
+ 0: 10,
253
+ 1: 25,
254
+ 2: 50,
255
+ };
256
+ const statuses = ['all', 'passed', 'failed', 'skipped'];
257
+ const pageItemGroups = {
258
+ all: {},
259
+ passed: {},
260
+ failed: {},
261
+ skipped: {},
262
+ totalTests,
263
+ };
264
+
265
+ function paginateItems(items, pageSize) {
266
+ const paginatedItems = [];
267
+ for (let i = 0; i < items.length; i += pageSize) {
268
+ paginatedItems.push(items.slice(i, i + pageSize));
269
+ }
270
+ return paginatedItems;
271
+ }
272
+
273
+ statuses.forEach(status => {
274
+ for (const option in paginationOptions) {
275
+ // eslint-disable-next-line no-prototype-builtins
276
+ if (paginationOptions.hasOwnProperty(option)) {
277
+ const pageSize = paginationOptions[option];
278
+ let filteredItems = totalTests;
279
+
280
+ if (status !== 'all') {
281
+ filteredItems = totalTests.filter(item => item.status === status);
282
+ }
283
+
284
+ pageItemGroups[status][option] = paginateItems(filteredItems, pageSize);
285
+ }
286
+ }
287
+ });
288
+
289
+ pageItemGroups.totalTests = totalTests;
290
+
291
+ return JSON.stringify(pageItemGroups);
292
+ });
293
+ }
294
+
295
+ toString() {
296
+ return 'HTML Reporter';
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Calculates the total execution time for an array of tests.
302
+ * @param {Object[]} tests - An array of test objects.
303
+ * @param {number} tests[].run_time - The execution time of each test in milliseconds.
304
+ * @returns {string} - The total execution time in a formatted duration string.
305
+ */
306
+ function testExecutionSumTime(tests) {
307
+ const totalMilliseconds = tests.reduce((sum, test) => {
308
+ if (typeof test.run_time === 'number' && !Number.isNaN(test.run_time)) {
309
+ return sum + test.run_time;
310
+ }
311
+ return sum;
312
+ }, 0);
313
+
314
+ return formatDuration(totalMilliseconds);
315
+ }
316
+
317
+ /**
318
+ * Removes ANSI color codes and converts newline characters to HTML line breaks in a given string.
319
+ * @param {string} str - The input string containing ANSI color codes.
320
+ * @returns {string} - The updated string with removed ANSI color codes and replaced newline characters.
321
+ */
322
+ function removeAnsiColorCodes(str) {
323
+ let updatedStr = str.replace(ansiRegExp(), '');
324
+ updatedStr = updatedStr.replace(/\n/g, '<br>');
325
+
326
+ return updatedStr;
327
+ }
328
+
329
+ /**
330
+ * Formats duration in milliseconds into a human-readable string representation.
331
+ * @param {number} duration - The duration in milliseconds.
332
+ * @returns {string} - The formatted duration string (e.g., "2h 30m 15s 500ms").
333
+ */
334
+ function formatDuration(duration) {
335
+ const milliseconds = duration % 1000;
336
+ duration = (duration - milliseconds) / 1000;
337
+ const seconds = duration % 60;
338
+ duration = (duration - seconds) / 60;
339
+ const minutes = duration % 60;
340
+ const hours = (duration - minutes) / 60;
341
+
342
+ return `${hours}h ${minutes}m ${seconds}s ${milliseconds}ms`;
343
+ }
344
+
345
+ /**
346
+ * Retrieves the current date and time in a formatted string.
347
+ * @returns {string} - The formatted date and time string (e.g., "(01/01/2023 12:00:00)").
348
+ */
349
+ function getCurrentDateTimeFormatted() {
350
+ const currentDate = new Date();
351
+ const day = currentDate.getDate().toString().padStart(2, '0');
352
+ const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
353
+ const year = currentDate.getFullYear();
354
+ const hours = currentDate.getHours().toString().padStart(2, '0');
355
+ const minutes = currentDate.getMinutes().toString().padStart(2, '0');
356
+ const seconds = currentDate.getSeconds().toString().padStart(2, '0');
357
+
358
+ return `(${day}/${month}/${year} ${hours}:${minutes}:${seconds})`;
359
+ }
360
+
361
+ module.exports = HtmlPipe;
package/lib/pipe/index.js CHANGED
@@ -6,6 +6,7 @@ const TestomatioPipe = require('./testomatio');
6
6
  const GitHubPipe = require('./github');
7
7
  const GitLabPipe = require('./gitlab');
8
8
  const CsvPipe = require('./csv');
9
+ const HtmlPipe = require('./html');
9
10
 
10
11
  function PipeFactory(params, opts) {
11
12
  const extraPipes = [];
@@ -43,6 +44,7 @@ function PipeFactory(params, opts) {
43
44
  new GitHubPipe(params, opts),
44
45
  new GitLabPipe(params, opts),
45
46
  new CsvPipe(params, opts),
47
+ new HtmlPipe(params, opts),
46
48
  ...extraPipes,
47
49
  ];
48
50
 
@@ -60,4 +62,4 @@ function PipeFactory(params, opts) {
60
62
  return pipes;
61
63
  }
62
64
 
63
- module.exports = PipeFactory;
65
+ module.exports = PipeFactory;