@testomatio/reporter 1.6.13 → 2.0.1-beta-esm

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 (142) hide show
  1. package/lib/adapter/codecept.d.ts +2 -0
  2. package/lib/adapter/codecept.js +295 -335
  3. package/lib/adapter/cucumber/current.d.ts +14 -0
  4. package/lib/adapter/cucumber/current.js +195 -203
  5. package/lib/adapter/cucumber/legacy.d.ts +0 -0
  6. package/lib/adapter/cucumber/legacy.js +130 -155
  7. package/lib/adapter/cucumber.d.ts +2 -0
  8. package/lib/adapter/cucumber.js +5 -16
  9. package/lib/adapter/cypress-plugin/index.d.ts +2 -0
  10. package/lib/adapter/cypress-plugin/index.js +93 -105
  11. package/lib/adapter/jasmine.d.ts +11 -0
  12. package/lib/adapter/jasmine.js +54 -53
  13. package/lib/adapter/jest.d.ts +13 -0
  14. package/lib/adapter/jest.js +97 -99
  15. package/lib/adapter/mocha.d.ts +2 -0
  16. package/lib/adapter/mocha.js +112 -140
  17. package/lib/adapter/playwright.d.ts +14 -0
  18. package/lib/adapter/playwright.js +195 -231
  19. package/lib/adapter/vitest.d.ts +35 -0
  20. package/lib/adapter/vitest.js +150 -149
  21. package/lib/adapter/webdriver.d.ts +24 -0
  22. package/lib/adapter/webdriver.js +134 -119
  23. package/lib/bin/cli.d.ts +2 -0
  24. package/lib/bin/cli.js +164 -211
  25. package/lib/bin/reportXml.d.ts +2 -0
  26. package/lib/bin/reportXml.js +49 -52
  27. package/lib/bin/startTest.d.ts +2 -0
  28. package/lib/bin/startTest.js +82 -95
  29. package/lib/bin/uploadArtifacts.d.ts +2 -0
  30. package/lib/bin/uploadArtifacts.js +55 -61
  31. package/lib/client.d.ts +76 -0
  32. package/lib/client.js +411 -465
  33. package/lib/config.d.ts +1 -0
  34. package/lib/config.js +16 -21
  35. package/lib/constants.d.ts +25 -0
  36. package/lib/constants.js +50 -44
  37. package/lib/data-storage.d.ts +34 -0
  38. package/lib/data-storage.js +206 -188
  39. package/lib/junit-adapter/adapter.d.ts +9 -0
  40. package/lib/junit-adapter/adapter.js +17 -20
  41. package/lib/junit-adapter/csharp.d.ts +4 -0
  42. package/lib/junit-adapter/csharp.js +18 -14
  43. package/lib/junit-adapter/index.d.ts +3 -0
  44. package/lib/junit-adapter/index.js +27 -25
  45. package/lib/junit-adapter/java.d.ts +5 -0
  46. package/lib/junit-adapter/java.js +41 -53
  47. package/lib/junit-adapter/javascript.d.ts +4 -0
  48. package/lib/junit-adapter/javascript.js +30 -27
  49. package/lib/junit-adapter/python.d.ts +5 -0
  50. package/lib/junit-adapter/python.js +38 -37
  51. package/lib/junit-adapter/ruby.d.ts +4 -0
  52. package/lib/junit-adapter/ruby.js +11 -8
  53. package/lib/output.d.ts +11 -0
  54. package/lib/output.js +44 -52
  55. package/lib/package.json +3 -0
  56. package/lib/pipe/bitbucket.d.ts +23 -0
  57. package/lib/pipe/bitbucket.js +210 -229
  58. package/lib/pipe/csv.d.ts +47 -0
  59. package/lib/pipe/csv.js +113 -126
  60. package/lib/pipe/debug.d.ts +29 -0
  61. package/lib/pipe/debug.js +104 -99
  62. package/lib/pipe/github.d.ts +30 -0
  63. package/lib/pipe/github.js +186 -213
  64. package/lib/pipe/gitlab.d.ts +23 -0
  65. package/lib/pipe/gitlab.js +166 -207
  66. package/lib/pipe/html.d.ts +34 -0
  67. package/lib/pipe/html.js +260 -319
  68. package/lib/pipe/index.d.ts +1 -0
  69. package/lib/pipe/index.js +84 -66
  70. package/lib/pipe/testomatio.d.ts +70 -0
  71. package/lib/pipe/testomatio.js +413 -462
  72. package/lib/reporter-functions.d.ts +34 -0
  73. package/lib/reporter-functions.js +28 -26
  74. package/lib/reporter.d.ts +232 -0
  75. package/lib/reporter.js +34 -29
  76. package/lib/services/artifacts.d.ts +33 -0
  77. package/lib/services/artifacts.js +55 -51
  78. package/lib/services/index.d.ts +9 -0
  79. package/lib/services/index.js +14 -12
  80. package/lib/services/key-values.d.ts +27 -0
  81. package/lib/services/key-values.js +56 -53
  82. package/lib/services/logger.d.ts +64 -0
  83. package/lib/services/logger.js +227 -245
  84. package/lib/template/testomatio.hbs +651 -1366
  85. package/lib/uploader.d.ts +60 -0
  86. package/lib/uploader.js +291 -360
  87. package/lib/utils/pipe_utils.d.ts +41 -0
  88. package/lib/utils/pipe_utils.js +89 -85
  89. package/lib/utils/utils.d.ts +45 -0
  90. package/lib/utils/utils.js +347 -307
  91. package/lib/xmlReader.d.ts +92 -0
  92. package/lib/xmlReader.js +490 -529
  93. package/package.json +57 -15
  94. package/src/adapter/codecept.js +375 -0
  95. package/src/adapter/cucumber/current.js +228 -0
  96. package/src/adapter/cucumber/legacy.js +158 -0
  97. package/src/adapter/cucumber.js +4 -0
  98. package/src/adapter/cypress-plugin/index.js +112 -0
  99. package/src/adapter/jasmine.js +60 -0
  100. package/src/adapter/jest.js +107 -0
  101. package/src/adapter/mocha.cjs +2 -0
  102. package/src/adapter/mocha.js +157 -0
  103. package/src/adapter/playwright.js +250 -0
  104. package/src/adapter/vitest.js +183 -0
  105. package/src/adapter/webdriver.js +142 -0
  106. package/src/bin/cli.js +280 -0
  107. package/src/bin/reportXml.js +74 -0
  108. package/src/bin/startTest.js +123 -0
  109. package/src/bin/uploadArtifacts.js +90 -0
  110. package/src/client.js +504 -0
  111. package/src/config.js +30 -0
  112. package/src/constants.js +53 -0
  113. package/src/data-storage.js +204 -0
  114. package/src/junit-adapter/adapter.js +23 -0
  115. package/src/junit-adapter/csharp.js +16 -0
  116. package/src/junit-adapter/index.js +28 -0
  117. package/src/junit-adapter/java.js +58 -0
  118. package/src/junit-adapter/javascript.js +31 -0
  119. package/src/junit-adapter/python.js +42 -0
  120. package/src/junit-adapter/ruby.js +10 -0
  121. package/src/output.js +57 -0
  122. package/src/pipe/bitbucket.js +254 -0
  123. package/src/pipe/csv.js +140 -0
  124. package/src/pipe/debug.js +104 -0
  125. package/src/pipe/github.js +233 -0
  126. package/src/pipe/gitlab.js +229 -0
  127. package/src/pipe/html.js +374 -0
  128. package/src/pipe/index.js +71 -0
  129. package/src/pipe/testomatio.js +503 -0
  130. package/src/reporter-functions.js +55 -0
  131. package/src/reporter.cjs_decprecated +21 -0
  132. package/src/reporter.js +33 -0
  133. package/src/services/artifacts.js +59 -0
  134. package/src/services/index.js +13 -0
  135. package/src/services/key-values.js +59 -0
  136. package/src/services/logger.js +316 -0
  137. package/src/template/emptyData.svg +23 -0
  138. package/src/template/testomatio.hbs +706 -0
  139. package/src/uploader.js +371 -0
  140. package/src/utils/pipe_utils.js +119 -0
  141. package/src/utils/utils.js +383 -0
  142. package/src/xmlReader.js +562 -0
@@ -0,0 +1,254 @@
1
+ import { APP_PREFIX, testomatLogoURL } from '../constants.js';
2
+ import { ansiRegExp, isSameTest } from '../utils/utils.js';
3
+ import { statusEmoji, fullName } from '../utils/pipe_utils.js';
4
+ import axios from 'axios';
5
+ import pc from 'picocolors';
6
+ import humanizeDuration from 'humanize-duration';
7
+ import merge from 'lodash.merge';
8
+ import path from 'path';
9
+ import createDebugMessages from 'debug';
10
+
11
+ const debug = createDebugMessages('@testomatio/reporter:pipe:bitbucket');
12
+
13
+ //! BITBUCKET_ACCESS_TOKEN environment variable is required for this functionality to work
14
+ //! and your pipeline trigger should be a pull request
15
+
16
+ /**
17
+ * @class BitbucketPipe
18
+ * @typedef {import('../../types/types.js').Pipe} Pipe
19
+ * @typedef {import('../../types/types.js').TestData} TestData
20
+ */
21
+ export class BitbucketPipe {
22
+ constructor(params, store = {}) {
23
+ this.isEnabled = false;
24
+ this.ENV = process.env;
25
+ this.store = store;
26
+ this.tests = [];
27
+ // Bitbucket PAT looks like bbpat-*****
28
+ this.token = params.BITBUCKET_ACCESS_TOKEN || process.env.BITBUCKET_ACCESS_TOKEN || this.ENV.BITBUCKET_ACCESS_TOKEN;
29
+ this.hiddenCommentData = `Testomat.io report: ${process.env.BITBUCKET_BRANCH || ''}`;
30
+
31
+ debug(
32
+ pc.yellow('Bitbucket Pipe:'),
33
+ this.token ? 'TOKEN passed' : '*no token*',
34
+ `Project key: ${this.ENV.BITBUCKET_PROJECT_KEY}, Pull request ID: ${this.ENV.BITBUCKET_PR_ID}`,
35
+ );
36
+
37
+ if (!this.token) {
38
+ debug(`Hint: Bitbucket CI variables are unavailable for unprotected branches by default.`);
39
+ return;
40
+ }
41
+
42
+ this.isEnabled = true;
43
+
44
+ debug('Bitbucket Pipe: Enabled');
45
+ }
46
+
47
+ async cleanLog(log) {
48
+ const stripAnsi = (await import('strip-ansi')).default;
49
+ return stripAnsi(log);
50
+ }
51
+
52
+ // Prepare the run (if needed)
53
+ async prepareRun() {}
54
+
55
+ // Create a new run (if needed)
56
+ async createRun() {}
57
+
58
+ addTest(test) {
59
+ if (!this.isEnabled) return;
60
+
61
+ const index = this.tests.findIndex(t => isSameTest(t, test));
62
+ // Update if they were already added
63
+ if (index >= 0) {
64
+ this.tests[index] = merge(this.tests[index], test);
65
+ return;
66
+ }
67
+
68
+ this.tests.push(test);
69
+ }
70
+
71
+ async finishRun(runParams) {
72
+ if (!this.isEnabled) return;
73
+
74
+ if (runParams.tests) runParams.tests.forEach(t => this.addTest(t));
75
+
76
+ // Clean up the logs from ANSI codes
77
+ for (let i = 0; i < this.tests.length; i++) {
78
+ this.tests[i].message = await this.cleanLog(this.tests[i].message || '');
79
+ this.tests[i].stack = await this.cleanLog(this.tests[i].stack || '');
80
+ }
81
+
82
+ // Create a comment on Bitbucket
83
+ const passedCount = this.tests.filter(t => t.status === 'passed').length;
84
+ const failedCount = this.tests.filter(t => t.status === 'failed').length;
85
+ const skippedCount = this.tests.filter(t => t.status === 'skipped').length;
86
+
87
+ // Constructing the table
88
+ let summary = `${this.hiddenCommentData}
89
+
90
+ | ![Testomat.io Report](${testomatLogoURL}) | ${statusEmoji(
91
+ runParams.status,
92
+ )} ${runParams.status.toUpperCase()} ${statusEmoji(runParams.status)} |
93
+ | --- | --- |
94
+ | **Tests** | ✔️ **${this.tests.length}** tests run |
95
+ | **Summary** | ${statusEmoji('failed')} **${failedCount}** failed; ${statusEmoji(
96
+ 'passed',
97
+ )} **${passedCount}** passed; **${statusEmoji('skipped')}** ${skippedCount} skipped |
98
+ | **Duration** | 🕐 **${humanizeDuration(
99
+ parseInt(
100
+ this.tests.reduce((a, t) => a + (t.run_time || 0), 0),
101
+ 10,
102
+ ),
103
+ {
104
+ maxDecimalPoints: 0,
105
+ },
106
+ )}** |
107
+ `;
108
+
109
+ if (this.ENV.BITBUCKET_BRANCH && this.ENV.BITBUCKET_COMMIT) {
110
+ // eslint-disable-next-line max-len
111
+ summary += `| **Job** | 👷 [#${this.ENV.BITBUCKET_BUILD_NUMBER}](https://bitbucket.org/${this.ENV.BITBUCKET_REPO_FULL_NAME}/pipelines/results/${this.ENV.BITBUCKET_BUILD_NUMBER}") by commit: **${this.ENV.BITBUCKET_COMMIT}** |`;
112
+ }
113
+
114
+ const failures = this.tests
115
+ .filter(t => t.status === 'failed')
116
+ .slice(0, 20)
117
+ .map(t => {
118
+ let text = `${statusEmoji('failed')} ${fullName(t)}\n`;
119
+ if (t.message) {
120
+ text += `> ${t.message
121
+ .replace(/[^\x20-\x7E]/g, '')
122
+ .replace(ansiRegExp(), '')
123
+ .trim()}\n`;
124
+ }
125
+ if (t.stack) {
126
+ text += `\n\`\`\`diff\n${t.stack
127
+ .replace(ansiRegExp(), '')
128
+ .replace(
129
+ /^[\s\S]*################\[ Failure \]################/g,
130
+ '################[ Failure ]################',
131
+ )
132
+ .trim()}\n\`\`\`\n`;
133
+ }
134
+ if (t.artifacts && t.artifacts.length && !this.ENV.TESTOMATIO_PRIVATE_ARTIFACTS) {
135
+ t.artifacts
136
+ .filter(f => !!f)
137
+ .forEach(f => {
138
+ if (f.endsWith('.png')) {
139
+ text += `![Image](${f})\n`;
140
+ } else {
141
+ text += `[📄 ${path.basename(f)}](${f})\n`;
142
+ }
143
+ });
144
+ }
145
+ text += `\n---\n`;
146
+ return text;
147
+ });
148
+
149
+ let body = summary;
150
+
151
+ if (failures.length) {
152
+ body += `\n🟥 **Failures (${failures.length})**\n\n* ${failures.join('\n* ')}\n`;
153
+ if (failures.length > 10) {
154
+ body += `\n> Notice: Only the first 10 failures are shown.`;
155
+ }
156
+ }
157
+
158
+ if (this.tests.length > 0) {
159
+ body += `\n\n**🐢 Slowest Tests**\n\n`;
160
+ body += this.tests
161
+ .sort((a, b) => b.run_time - a.run_time)
162
+ .slice(0, 5)
163
+ .map(t => `* **${fullName(t)}** (${humanizeDuration(parseFloat(t.run_time))})`)
164
+ .join('\n');
165
+ }
166
+
167
+ // Construct Bitbucket API URL for comments
168
+ // eslint-disable-next-line max-len
169
+ const commentsRequestURL = `https://api.bitbucket.org/2.0/repositories/${this.ENV.BITBUCKET_WORKSPACE}/${this.ENV.BITBUCKET_REPO_SLUG}/pullrequests/${this.ENV.BITBUCKET_PR_ID}/comments`;
170
+
171
+ // Delete previous report
172
+ await deletePreviousReport(axios, commentsRequestURL, this.hiddenCommentData, this.token);
173
+
174
+ // Add current report
175
+ debug(`Adding comment via URL: ${commentsRequestURL}`);
176
+ debug(`Final Bitbucket API call body: ${body}`);
177
+
178
+ try {
179
+ const addCommentResponse = await axios.post(
180
+ commentsRequestURL,
181
+ { content: { raw: body } },
182
+ {
183
+ headers: {
184
+ Authorization: `Bearer ${this.token}`,
185
+ 'Content-Type': 'application/json',
186
+ },
187
+ },
188
+ );
189
+
190
+ const commentID = addCommentResponse.data.id;
191
+ // eslint-disable-next-line max-len
192
+ const commentURL = `https://bitbucket.org/${this.ENV.BITBUCKET_WORKSPACE}/${this.ENV.BITBUCKET_REPO_SLUG}/pull-requests/${this.ENV.BITBUCKET_PR_ID}#comment-${commentID}`;
193
+
194
+ console.log(APP_PREFIX, pc.yellow('Bitbucket'), `Report created: ${pc.magenta(commentURL)}`);
195
+ } catch (err) {
196
+ console.error(
197
+ APP_PREFIX,
198
+ pc.yellow('Bitbucket'),
199
+ `Couldn't create Bitbucket report\n${err}.
200
+ Request URL: ${commentsRequestURL}
201
+ Request data: ${body}`,
202
+ );
203
+ }
204
+ }
205
+
206
+ toString() {
207
+ return 'Bitbucket Reporter';
208
+ }
209
+
210
+ updateRun() {}
211
+ }
212
+
213
+ async function deletePreviousReport(axiosInstance, commentsRequestURL, hiddenCommentData, token) {
214
+ if (process.env.BITBUCKET_KEEP_OUTDATED_REPORTS) return;
215
+
216
+ // Get comments
217
+ let comments = [];
218
+
219
+ try {
220
+ const response = await axiosInstance.get(commentsRequestURL, {
221
+ headers: {
222
+ Authorization: `Bearer ${token}`,
223
+ 'Content-Type': 'application/json',
224
+ },
225
+ });
226
+ comments = response.data.values;
227
+ } catch (e) {
228
+ console.error('Error while attempting to retrieve comments on Bitbucket Pull Request:\n', e);
229
+ }
230
+
231
+ if (!comments.length) return;
232
+
233
+ for (const comment of comments) {
234
+ // If comment was left by the same workflow
235
+ if (comment.content.raw.includes(hiddenCommentData)) {
236
+ try {
237
+ // Delete previous comment
238
+ const deleteCommentURL = `${commentsRequestURL}/${comment.id}`;
239
+ await axiosInstance.delete(deleteCommentURL, {
240
+ headers: {
241
+ Authorization: `Bearer ${token}`,
242
+ 'Content-Type': 'application/json',
243
+ },
244
+ });
245
+ } catch (e) {
246
+ console.warn(`Can't delete previously added comment with testomat.io report. Ignored.`);
247
+ }
248
+ // Pass next env var if need to clear all previous reports;
249
+ // only the last one is removed by default
250
+ if (!process.env.BITBUCKET_REMOVE_ALL_OUTDATED_REPORTS) break;
251
+ // TODO: in case of many reports should implement pagination
252
+ }
253
+ }
254
+ }
@@ -0,0 +1,140 @@
1
+ import createDebugMessages from 'debug';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import { createObjectCsvWriter } from 'csv-writer';
5
+ import pc from 'picocolors';
6
+ import merge from 'lodash.merge';
7
+ import { isSameTest, getCurrentDateTime, ansiRegExp } from '../utils/utils.js';
8
+ import { CSV_HEADERS } from '../constants.js';
9
+
10
+ const debug = createDebugMessages('@testomatio/reporter:pipe:csv');
11
+ /**
12
+ * @typedef {import('../../types/types.js').Pipe} Pipe
13
+ * @typedef {import('../../types/types.js').TestData} TestData
14
+ * @class CsvPipe
15
+ * @implements {Pipe}
16
+ */
17
+ class CsvPipe {
18
+ constructor(params, store) {
19
+ this.store = store || {};
20
+ this.title = params.title || process.env.TESTOMATIO_TITLE;
21
+ this.results = [];
22
+
23
+ this.outputDir = 'export';
24
+ this.defaultReportName = 'report.csv';
25
+ this.csvFilename = process.env.TESTOMATIO_CSV_FILENAME;
26
+ this.isEnabled = false;
27
+
28
+ if (this.csvFilename) {
29
+ const filenameParts = this.csvFilename.split('.');
30
+
31
+ if (filenameParts.length > 0) {
32
+ this.isEnabled = true;
33
+ const baseFilename = filenameParts[0];
34
+ const defaultOutputFile = path.resolve(process.cwd(), this.outputDir, this.defaultReportName);
35
+
36
+ const outputFile =
37
+ baseFilename === this.defaultReportName.split('.')[0] // = 'report'
38
+ ? defaultOutputFile
39
+ : path.resolve(process.cwd(), this.outputDir, `${getCurrentDateTime()}_${baseFilename}.csv`);
40
+
41
+ this.outputFile = outputFile;
42
+ }
43
+ }
44
+ }
45
+
46
+ // TODO: to using SET opts as argument => prepareRun(opts)
47
+ async prepareRun() {}
48
+
49
+ async createRun() {
50
+ // empty
51
+ }
52
+
53
+ updateRun() {}
54
+
55
+ /**
56
+ * Create a folder that will contain the exported files
57
+ */
58
+ checkExportDir() {
59
+ if (!fs.existsSync(this.outputDir)) {
60
+ return fs.mkdirSync(this.outputDir);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Save data to the csv file.
66
+ * @param {Object} data - data that will be added to the CSV file.
67
+ * Example: [{suite_title: "Suite #1", test: "Test-case-1", message: "Test msg"}]
68
+ * @param {Object} headers - csv file headers. Example: [{ id: 'suite_title', title: 'Suite_title' }]
69
+ */
70
+ async saveToCsv(data, headers) {
71
+ debug('Data', data);
72
+ // First, we check whether the export directory exists: if yes - OK, no - create it.
73
+ this.checkExportDir();
74
+
75
+ if (!this.outputFile) {
76
+ console.log(pc.yellow(`⚠️ CSV file is not set, ignoring`));
77
+ return;
78
+ }
79
+
80
+ console.log(pc.yellow(`⏳ The test results will be added to the csv. It will take some time...`));
81
+
82
+ try {
83
+ // Create csv writer object
84
+ const writer = createObjectCsvWriter({
85
+ path: this.outputFile,
86
+ header: headers,
87
+ });
88
+ // Save csv file based on the current data
89
+ return await writer.writeRecords(data);
90
+ } catch (e) {
91
+ console.log('Unknown csv error: ', e);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Add test data to the result array for saving. As a result of this function, we get a result object to save.
97
+ * @param {Object} test - object which includes each test entry.
98
+ */
99
+ addTest(test) {
100
+ if (!this.isEnabled) return;
101
+
102
+ const index = this.results.findIndex(t => isSameTest(t, test));
103
+ // update if they were already added
104
+ if (index >= 0) {
105
+ this.results[index] = merge(this.results[index], test);
106
+ return;
107
+ }
108
+
109
+ const { suite_title, title, status, message, stack } = test;
110
+
111
+ this.results.push({
112
+ suite_title,
113
+ title,
114
+ status,
115
+ message: message.replace(ansiRegExp(), ''),
116
+ stack: stack.replace(ansiRegExp(), ''),
117
+ });
118
+ }
119
+
120
+ /**
121
+ * @param {{ tests?: TestData[] }} runParams
122
+ * @returns {Promise<void>}
123
+ */
124
+ async finishRun(runParams) {
125
+ if (!this.isEnabled) return;
126
+
127
+ if (runParams.tests) runParams.tests.forEach(t => this.addTest(t));
128
+ // Save results based on the default headers
129
+ if (this.isEnabled) {
130
+ await this.saveToCsv(this.results, CSV_HEADERS);
131
+ console.log(pc.green(`🗃️ Recording completed! You can check the result in file = ${this.outputFile}`));
132
+ }
133
+ }
134
+
135
+ toString() {
136
+ return 'csv exporter';
137
+ }
138
+ }
139
+
140
+ export default CsvPipe;
@@ -0,0 +1,104 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import createDebugMessages from 'debug';
5
+ import { APP_PREFIX } from '../constants.js';
6
+ import prettyMs from 'pretty-ms';
7
+
8
+ const debug = createDebugMessages('@testomatio/reporter:pipe:debug');
9
+
10
+ export class DebugPipe {
11
+ constructor(params, store) {
12
+ this.params = params || {};
13
+ this.store = store || {};
14
+
15
+ this.isEnabled = !!process.env.TESTOMATIO_DEBUG || !!process.env.DEBUG;
16
+ if (this.isEnabled) {
17
+ this.batch = {
18
+ isEnabled: this.params.isBatchEnabled ?? !process.env.TESTOMATIO_DISABLE_BATCH_UPLOAD ?? true,
19
+ intervalFunction: null,
20
+ intervalTime: 5000,
21
+ tests: [],
22
+ batchIndex: 0,
23
+ };
24
+ this.logFilePath = path.join(os.tmpdir(), `testomatio.debug.${Date.now()}.json`);
25
+
26
+ debug('Creating debug file:', this.logFilePath);
27
+ fs.writeFileSync(this.logFilePath, '');
28
+ console.log(APP_PREFIX, '🪲. Debug created:');
29
+ this.testomatioEnvVars = Object.keys(process.env)
30
+ .filter(key => key.startsWith('TESTOMATIO_'))
31
+ .reduce((acc, key) => {
32
+ acc[key] = process.env[key];
33
+ return acc;
34
+ }, {});
35
+ this.logToFile({ datetime: new Date().toISOString(), timestamp: Date.now() });
36
+ this.logToFile({ data: 'variables', testomatioEnvVars: this.testomatioEnvVars });
37
+ this.logToFile({ data: 'store', store: this.store || {} });
38
+ // Bind batchUpload to the instance
39
+ this.batchUpload = this.batchUpload.bind(this);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Logs data to a file if logging is enabled.
45
+ *
46
+ * @param {Object} logData - The data to be logged.
47
+ * @returns {Promise<void>} A promise that resolves when the log data has been appended to the file.
48
+ */
49
+ logToFile(logData) {
50
+ if (!this.isEnabled) return;
51
+ const timePassedFromLastAction = Date.now() - (this.lastActionTimestamp || Date.now());
52
+ this.lastActionTimestamp = Date.now();
53
+
54
+ const logLine = JSON.stringify({ t: `+${prettyMs(timePassedFromLastAction)}`, ...logData });
55
+ fs.appendFileSync(this.logFilePath, `${logLine}\n`);
56
+ }
57
+
58
+ async prepareRun(opts) {
59
+ if (!this.isEnabled) return [];
60
+
61
+ this.logToFile({ action: 'prepareRun', data: opts });
62
+ }
63
+
64
+ async createRun(params = {}) {
65
+ if (!this.isEnabled) return;
66
+ if (params.isBatchEnabled === true || params.isBatchEnabled === false) this.batch.isEnabled = params.isBatchEnabled;
67
+
68
+ if (!this.isEnabled) return {};
69
+ if (this.batch.isEnabled) this.batch.intervalFunction = setInterval(this.batchUpload, this.batch.intervalTime);
70
+
71
+ this.logToFile({ action: 'createRun', params });
72
+ }
73
+
74
+ async addTest(data) {
75
+ if (!this.isEnabled) return;
76
+
77
+ if (!this.batch.isEnabled) this.logToFile({ action: 'addTest', testId: data });
78
+ else this.batch.tests.push(data);
79
+
80
+ if (!this.batch.intervalFunction) await this.batchUpload();
81
+ }
82
+
83
+ async batchUpload() {
84
+ this.batch.batchIndex++;
85
+ if (!this.batch.isEnabled) return;
86
+ if (!this.batch.tests.length) return;
87
+
88
+ const testsToSend = this.batch.tests.splice(0);
89
+
90
+ this.logToFile({ action: 'addTestsBatch', tests: testsToSend });
91
+ }
92
+
93
+ async finishRun(params) {
94
+ if (!this.isEnabled) return;
95
+ this.logToFile({ actions: 'finishRun', params });
96
+ await this.batchUpload();
97
+ if (this.batch.intervalFunction) clearInterval(this.batch.intervalFunction);
98
+ console.log(APP_PREFIX, '🪲. Debug Saved to', this.logFilePath);
99
+ }
100
+
101
+ toString() {
102
+ return 'Debug Reporter';
103
+ }
104
+ }