@testomatio/reporter 2.0.1-beta.5-timestamp → 2.0.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 (149) hide show
  1. package/README.md +1 -0
  2. package/lib/adapter/codecept.d.ts +2 -0
  3. package/lib/adapter/codecept.js +293 -335
  4. package/lib/adapter/cucumber/current.d.ts +14 -0
  5. package/lib/adapter/cucumber/current.js +195 -203
  6. package/lib/adapter/cucumber/legacy.d.ts +0 -0
  7. package/lib/adapter/cucumber/legacy.js +130 -155
  8. package/lib/adapter/cucumber.d.ts +2 -0
  9. package/lib/adapter/cucumber.js +5 -16
  10. package/lib/adapter/cypress-plugin/index.d.ts +2 -0
  11. package/lib/adapter/cypress-plugin/index.js +91 -105
  12. package/lib/adapter/jasmine.d.ts +11 -0
  13. package/lib/adapter/jasmine.js +54 -53
  14. package/lib/adapter/jest.d.ts +13 -0
  15. package/lib/adapter/jest.js +97 -99
  16. package/lib/adapter/mocha.d.ts +2 -0
  17. package/lib/adapter/mocha.js +112 -141
  18. package/lib/adapter/nightwatch.d.ts +4 -0
  19. package/lib/adapter/nightwatch.js +80 -0
  20. package/lib/adapter/playwright.d.ts +14 -0
  21. package/lib/adapter/playwright.js +199 -231
  22. package/lib/adapter/vitest.d.ts +35 -0
  23. package/lib/adapter/vitest.js +150 -149
  24. package/lib/adapter/webdriver.d.ts +24 -0
  25. package/lib/adapter/webdriver.js +144 -121
  26. package/lib/bin/cli.d.ts +2 -0
  27. package/lib/bin/cli.js +229 -211
  28. package/lib/bin/reportXml.d.ts +2 -0
  29. package/lib/bin/reportXml.js +51 -52
  30. package/lib/bin/startTest.d.ts +2 -0
  31. package/lib/bin/startTest.js +83 -95
  32. package/lib/bin/uploadArtifacts.d.ts +2 -0
  33. package/lib/bin/uploadArtifacts.js +56 -61
  34. package/lib/client.d.ts +76 -0
  35. package/lib/client.js +429 -465
  36. package/lib/config.d.ts +1 -0
  37. package/lib/config.js +18 -23
  38. package/lib/constants.d.ts +25 -0
  39. package/lib/constants.js +50 -44
  40. package/lib/data-storage.d.ts +34 -0
  41. package/lib/data-storage.js +216 -188
  42. package/lib/junit-adapter/adapter.d.ts +9 -0
  43. package/lib/junit-adapter/adapter.js +17 -20
  44. package/lib/junit-adapter/csharp.d.ts +5 -0
  45. package/lib/junit-adapter/csharp.js +28 -14
  46. package/lib/junit-adapter/index.d.ts +3 -0
  47. package/lib/junit-adapter/index.js +27 -25
  48. package/lib/junit-adapter/java.d.ts +5 -0
  49. package/lib/junit-adapter/java.js +41 -53
  50. package/lib/junit-adapter/javascript.d.ts +4 -0
  51. package/lib/junit-adapter/javascript.js +30 -27
  52. package/lib/junit-adapter/python.d.ts +5 -0
  53. package/lib/junit-adapter/python.js +38 -37
  54. package/lib/junit-adapter/ruby.d.ts +4 -0
  55. package/lib/junit-adapter/ruby.js +11 -8
  56. package/lib/output.d.ts +11 -0
  57. package/lib/output.js +44 -52
  58. package/lib/package.json +3 -0
  59. package/lib/pipe/bitbucket.d.ts +25 -0
  60. package/lib/pipe/bitbucket.js +223 -230
  61. package/lib/pipe/csv.d.ts +47 -0
  62. package/lib/pipe/csv.js +113 -126
  63. package/lib/pipe/debug.d.ts +29 -0
  64. package/lib/pipe/debug.js +125 -99
  65. package/lib/pipe/github.d.ts +30 -0
  66. package/lib/pipe/github.js +218 -213
  67. package/lib/pipe/gitlab.d.ts +25 -0
  68. package/lib/pipe/gitlab.js +183 -206
  69. package/lib/pipe/html.d.ts +35 -0
  70. package/lib/pipe/html.js +258 -321
  71. package/lib/pipe/index.d.ts +1 -0
  72. package/lib/pipe/index.js +94 -66
  73. package/lib/pipe/testomatio.d.ts +71 -0
  74. package/lib/pipe/testomatio.js +429 -474
  75. package/lib/replay.d.ts +31 -0
  76. package/lib/replay.js +255 -0
  77. package/lib/reporter-functions.d.ts +34 -0
  78. package/lib/reporter-functions.js +28 -26
  79. package/lib/reporter.d.ts +232 -0
  80. package/lib/reporter.js +34 -29
  81. package/lib/services/artifacts.d.ts +33 -0
  82. package/lib/services/artifacts.js +55 -51
  83. package/lib/services/index.d.ts +9 -0
  84. package/lib/services/index.js +14 -12
  85. package/lib/services/key-values.d.ts +27 -0
  86. package/lib/services/key-values.js +56 -53
  87. package/lib/services/logger.d.ts +64 -0
  88. package/lib/services/logger.js +226 -245
  89. package/lib/template/testomatio.hbs +1026 -1366
  90. package/lib/uploader.d.ts +60 -0
  91. package/lib/uploader.js +295 -364
  92. package/lib/utils/pipe_utils.d.ts +41 -0
  93. package/lib/utils/pipe_utils.js +89 -85
  94. package/lib/utils/utils.d.ts +54 -0
  95. package/lib/utils/utils.js +398 -307
  96. package/lib/xmlReader.d.ts +92 -0
  97. package/lib/xmlReader.js +525 -532
  98. package/package.json +64 -21
  99. package/src/adapter/codecept.js +373 -0
  100. package/src/adapter/cucumber/current.js +228 -0
  101. package/src/adapter/cucumber/legacy.js +158 -0
  102. package/src/adapter/cucumber.js +4 -0
  103. package/src/adapter/cypress-plugin/index.js +110 -0
  104. package/src/adapter/jasmine.js +60 -0
  105. package/src/adapter/jest.js +107 -0
  106. package/src/adapter/mocha.cjs +2 -0
  107. package/src/adapter/mocha.js +156 -0
  108. package/src/adapter/nightwatch.js +88 -0
  109. package/src/adapter/playwright.js +254 -0
  110. package/src/adapter/vitest.js +183 -0
  111. package/src/adapter/webdriver.js +142 -0
  112. package/src/bin/cli.js +348 -0
  113. package/src/bin/reportXml.js +77 -0
  114. package/src/bin/startTest.js +124 -0
  115. package/src/bin/uploadArtifacts.js +91 -0
  116. package/src/client.js +515 -0
  117. package/src/config.js +30 -0
  118. package/src/constants.js +53 -0
  119. package/src/data-storage.js +204 -0
  120. package/src/junit-adapter/adapter.js +23 -0
  121. package/src/junit-adapter/csharp.js +28 -0
  122. package/src/junit-adapter/index.js +28 -0
  123. package/src/junit-adapter/java.js +58 -0
  124. package/src/junit-adapter/javascript.js +31 -0
  125. package/src/junit-adapter/python.js +42 -0
  126. package/src/junit-adapter/ruby.js +10 -0
  127. package/src/output.js +57 -0
  128. package/src/pipe/bitbucket.js +252 -0
  129. package/src/pipe/csv.js +140 -0
  130. package/src/pipe/debug.js +125 -0
  131. package/src/pipe/github.js +232 -0
  132. package/src/pipe/gitlab.js +247 -0
  133. package/src/pipe/html.js +373 -0
  134. package/src/pipe/index.js +71 -0
  135. package/src/pipe/testomatio.js +504 -0
  136. package/src/replay.js +262 -0
  137. package/src/reporter-functions.js +55 -0
  138. package/src/reporter.cjs_decprecated +21 -0
  139. package/src/reporter.js +33 -0
  140. package/src/services/artifacts.js +59 -0
  141. package/src/services/index.js +13 -0
  142. package/src/services/key-values.js +59 -0
  143. package/src/services/logger.js +315 -0
  144. package/src/template/emptyData.svg +23 -0
  145. package/src/template/testomatio.hbs +1081 -0
  146. package/src/uploader.js +376 -0
  147. package/src/utils/pipe_utils.js +119 -0
  148. package/src/utils/utils.js +416 -0
  149. package/src/xmlReader.js +614 -0
@@ -0,0 +1,232 @@
1
+ import createDebugMessages from 'debug';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import humanizeDuration from 'humanize-duration';
5
+ import merge from 'lodash.merge';
6
+ import { APP_PREFIX, testomatLogoURL } from '../constants.js';
7
+ import { ansiRegExp, isSameTest } from '../utils/utils.js';
8
+ import { statusEmoji, fullName } from '../utils/pipe_utils.js';
9
+
10
+ const debug = createDebugMessages('@testomatio/reporter:pipe:github');
11
+
12
+ /**
13
+ * @typedef {import('../../types/types.js').Pipe} Pipe
14
+ * @typedef {import('../../types/types.js').TestData} TestData
15
+ * @class GitHubPipe
16
+ * @implements {Pipe}
17
+ */
18
+ class GitHubPipe {
19
+ constructor(params, store = {}) {
20
+ this.isEnabled = false;
21
+ this.store = store;
22
+ this.tests = [];
23
+ this.token = params.GH_PAT || process.env.GH_PAT;
24
+ this.ref = process.env.GITHUB_REF;
25
+ this.repo = process.env.GITHUB_REPOSITORY;
26
+ this.jobKey = `${process.env.GITHUB_WORKFLOW || ''} / ${process.env.GITHUB_JOB || ''}`;
27
+ this.hiddenCommentData = `<!--- testomat.io report ${this.jobKey} -->`;
28
+
29
+ debug('GitHub Pipe: ', this.token ? 'TOKEN' : '*no token*', 'Ref:', this.ref, 'Repo:', this.repo);
30
+
31
+ if (!this.token || !this.ref || !this.repo) return;
32
+ this.isEnabled = true;
33
+ const matchedIssue = this.ref.match(/refs\/pull\/(\d+)\/merge/);
34
+ if (!matchedIssue) return;
35
+ this.issue = parseInt(matchedIssue[1], 10);
36
+
37
+ this.start = new Date();
38
+
39
+ debug('GitHub Pipe: Enabled');
40
+ }
41
+
42
+ // TODO: to using SET opts as argument => prepareRun(opts)
43
+ async prepareRun() {}
44
+
45
+ async createRun() {}
46
+
47
+ addTest(test) {
48
+ if (!this.isEnabled) return;
49
+ debug('Adding test:', test);
50
+
51
+ const index = this.tests.findIndex(t => isSameTest(t, test));
52
+ // update if they were already added
53
+ if (index >= 0) {
54
+ this.tests[index] = merge(this.tests[index], test);
55
+ return;
56
+ }
57
+
58
+ this.tests.push(test);
59
+ }
60
+
61
+ async finishRun(runParams) {
62
+ if (!this.isEnabled) return;
63
+ if (!this.issue) return;
64
+
65
+ if (runParams.tests) runParams.tests.forEach(t => this.addTest(t));
66
+ const { Octokit } = await import('@octokit/rest');
67
+
68
+ this.octokit = new Octokit({
69
+ auth: this.token,
70
+ });
71
+
72
+ const [owner, repo] = (this.repo || '').split('/');
73
+ if (!(owner || repo)) return;
74
+
75
+ // ... create a comment on GitHub
76
+ const passedCount = this.tests.filter(t => t.status === 'passed').length;
77
+ const failedCount = this.tests.filter(t => t.status === 'failed').length;
78
+ const skippedCount = this.tests.filter(t => t.status === 'skipped').length;
79
+
80
+ let summary = `${this.hiddenCommentData}
81
+
82
+ | [![Testomat.io Report](${testomatLogoURL})](https://testomat.io) | ${statusEmoji(
83
+ runParams.status,
84
+ )} ${`${process.env.GITHUB_JOB} ${runParams.status}`.toUpperCase()} |
85
+ | --- | --- |
86
+ | Tests | ✔️ **${this.tests.length}** tests run |
87
+ | Summary | ${failedCount ? `${statusEmoji('failed')} **${failedCount}** failed; ` : ''} ${statusEmoji(
88
+ 'passed',
89
+ )} **${passedCount}** passed; **${statusEmoji('skipped')}** ${skippedCount} skipped |
90
+ | Duration | 🕐 **${humanizeDuration(
91
+ parseInt(
92
+ this.tests.reduce((a, t) => a + (t.run_time || 0), 0),
93
+ 10,
94
+ ),
95
+ {
96
+ maxDecimalPoints: 0,
97
+ },
98
+ )}** |`;
99
+
100
+ if (this.store.runUrl) {
101
+ summary += `\n| Testomat.io Report | 📊 [Run #${this.store.runId}](${this.store.runUrl}) | `;
102
+ }
103
+ if (process.env.GITHUB_WORKFLOW) {
104
+ summary += `\n| Job | 🗂️ [${this.jobKey}](${process.env.GITHUB_SERVER_URL || 'https://github.com'}/${
105
+ this.repo
106
+ }/actions/runs/${process.env.GITHUB_RUN_ID}) | `;
107
+ }
108
+ if (process.env.RUNNER_OS) {
109
+ summary += `\n| Operating System | 🖥️ \`${process.env.RUNNER_OS}\` ${process.env.RUNNER_ARCH || ''} | `;
110
+ }
111
+
112
+ const failures = this.tests
113
+ .filter(t => t.status === 'failed')
114
+ .slice(0, 20)
115
+ .map(t => {
116
+ let text = `#### ${statusEmoji('failed')} ${fullName(t)} `;
117
+ text += '\n\n';
118
+ if (t.message)
119
+ text += `> ${t.message
120
+ .replace(/[^\x20-\x7E]/g, '')
121
+ .replace(ansiRegExp(), '')
122
+ .trim()}\n`;
123
+ if (t.stack) text += `\`\`\`diff\n${t.stack.replace(ansiRegExp(), '').trim()}\n\`\`\`\n`;
124
+
125
+ if (t.artifacts && t.artifacts.length && !process.env.TESTOMATIO_PRIVATE_ARTIFACTS) {
126
+ t.artifacts
127
+ .filter(f => !!f)
128
+ .filter(f => f.endsWith('.png'))
129
+ .forEach(f => {
130
+ if (f.endsWith('.png')) {
131
+ text += `![](${f})\n`;
132
+ return text;
133
+ }
134
+ text += `[📄 ${path.basename(f)}](${f})\n`;
135
+ return text;
136
+ });
137
+ }
138
+
139
+ text += '\n---\n';
140
+
141
+ return text;
142
+ });
143
+
144
+ let body = summary;
145
+
146
+ if (failures.length) {
147
+ body += `\n<details>\n<summary><h3>🟥 Failures (${failures.length})</h4></summary>\n\n${failures.join('\n')}\n`;
148
+ if (failures.length > 20) {
149
+ body += '\n> Notice\n> Only first 20 failures shown*';
150
+ }
151
+ body += '\n\n</details>';
152
+ }
153
+
154
+ if (this.tests.length > 0) {
155
+ body += '\n<details>\n<summary><h3>🐢 Slowest Tests</h3></summary>\n\n';
156
+ body += this.tests
157
+ .sort((a, b) => b?.run_time - a?.run_time)
158
+ .slice(0, 5)
159
+ .map(t => `* ${fullName(t)} (${humanizeDuration(parseFloat(t.run_time))})`)
160
+ .join('\n');
161
+ body += '\n</details>';
162
+ }
163
+
164
+ await deletePreviousReport(this.octokit, owner, repo, this.issue, this.hiddenCommentData);
165
+
166
+ // add report as comment
167
+ try {
168
+ debug('Adding comment\n', body);
169
+ const resp = await this.octokit.rest.issues.createComment({
170
+ owner,
171
+ repo,
172
+ issue_number: this.issue,
173
+ body,
174
+ });
175
+
176
+ const url = resp.data?.html_url;
177
+ debug('Comment URL:', url);
178
+ this.store.githubUrl = url;
179
+
180
+ console.log(APP_PREFIX, pc.yellow('GitHub'), `Report created: ${pc.magenta(url)}`);
181
+ } catch (err) {
182
+ console.log(APP_PREFIX, pc.yellow('GitHub'), `Couldn't create GitHub report ${err}`);
183
+ }
184
+ }
185
+
186
+ toString() {
187
+ return 'GitHub Reporter';
188
+ }
189
+ }
190
+
191
+ async function deletePreviousReport(octokit, owner, repo, issue, hiddenCommentData) {
192
+ if (process.env.GH_KEEP_OUTDATED_REPORTS) return;
193
+
194
+ // get comments
195
+ let comments = [];
196
+ try {
197
+ const response = await octokit.rest.issues.listComments({
198
+ owner,
199
+ repo,
200
+ issue_number: issue,
201
+ });
202
+ comments = response.data;
203
+ } catch (e) {
204
+ console.error('Error while attempt to retrieve comments on GitHub Pull Request:\n', e);
205
+ }
206
+
207
+ if (!comments.length) return;
208
+
209
+ for (const comment of comments) {
210
+ // if comment was left by the same workflow
211
+ if (comment.body.includes(hiddenCommentData)) {
212
+ try {
213
+ // delete previous comment
214
+ await octokit.rest.issues.deleteComment({
215
+ owner,
216
+ repo,
217
+ issue_number: issue,
218
+ comment_id: comment.id,
219
+ });
220
+ } catch (e) {
221
+ console.warn(`Can't delete previously added comment with testomat.io report. Ignore.`);
222
+ }
223
+
224
+ // pass next env var if need to clear all previous reports;
225
+ // only the last one is removed by default
226
+ if (!process.env.GITHUB_REMOVE_ALL_OUTDATED_REPORTS) break;
227
+ // TODO: in case of many reports should implement pagination
228
+ }
229
+ }
230
+ }
231
+
232
+ export default GitHubPipe;
@@ -0,0 +1,247 @@
1
+ import createDebugMessages from 'debug';
2
+ import { Gaxios } from 'gaxios';
3
+ import pc from 'picocolors';
4
+ import humanizeDuration from 'humanize-duration';
5
+ import merge from 'lodash.merge';
6
+ import path from 'path';
7
+ import { APP_PREFIX, testomatLogoURL } from '../constants.js';
8
+ import { ansiRegExp, isSameTest } from '../utils/utils.js';
9
+ import { statusEmoji, fullName } from '../utils/pipe_utils.js';
10
+
11
+ const debug = createDebugMessages('@testomatio/reporter:pipe:gitlab');
12
+
13
+ //! GITLAB_PAT environment variable is required for this functionality to work
14
+ //! and your pipeline trigger should be merge_request
15
+
16
+ /**
17
+ * @class GitLabPipe
18
+ * @typedef {import('../../types/types.js').Pipe} Pipe
19
+ * @typedef {import('../../types/types.js').TestData} TestData
20
+ */
21
+ class GitLabPipe {
22
+ constructor(params, store = {}) {
23
+ this.isEnabled = false;
24
+ this.ENV = process.env;
25
+ this.store = store;
26
+ this.tests = [];
27
+ // GitLab PAT looks like glpat-nKGdja3jsG4850sGksh7
28
+ this.token = params.GITLAB_PAT || process.env.GITLAB_PAT || this.ENV.GITLAB_PAT;
29
+ this.hiddenCommentData = `<!--- testomat.io report ${process.env.CI_JOB_NAME || ''} -->`;
30
+
31
+ debug(
32
+ pc.yellow('GitLab Pipe:'),
33
+ this.token ? 'TOKEN passed' : '*no token*',
34
+ `Project id: ${this.ENV.CI_PROJECT_ID}, MR id: ${this.ENV.CI_MERGE_REQUEST_IID}`,
35
+ );
36
+
37
+ if (!this.ENV.CI_PROJECT_ID || !this.ENV.CI_MERGE_REQUEST_IID) {
38
+ debug(`CI pipeline should be run in Merge Request to have ability to add the report comment.`);
39
+ return;
40
+ }
41
+
42
+ if (!this.token) {
43
+ debug(`Hint: GitLab CI variables are unavailable for unprotected branches by default.`);
44
+ return;
45
+ }
46
+
47
+ this.isEnabled = true;
48
+ this.client = new Gaxios({
49
+ baseURL: 'https://gitlab.com/api/v4',
50
+ headers: {
51
+ 'Content-Type': 'application/json',
52
+ }
53
+ });
54
+
55
+ debug('GitLab Pipe: Enabled');
56
+ }
57
+
58
+ // TODO: to using SET opts as argument => prepareRun(opts)
59
+ async prepareRun() {}
60
+
61
+ async createRun() {}
62
+
63
+ addTest(test) {
64
+ if (!this.isEnabled) return;
65
+
66
+ const index = this.tests.findIndex(t => isSameTest(t, test));
67
+ // update if they were already added
68
+ if (index >= 0) {
69
+ this.tests[index] = merge(this.tests[index], test);
70
+ return;
71
+ }
72
+
73
+ this.tests.push(test);
74
+ }
75
+
76
+ async finishRun(runParams) {
77
+ if (!this.isEnabled) return;
78
+
79
+ if (runParams.tests) runParams.tests.forEach(t => this.addTest(t));
80
+
81
+ // ... create a comment on GitLab
82
+ const passedCount = this.tests.filter(t => t.status === 'passed').length;
83
+ const failedCount = this.tests.filter(t => t.status === 'failed').length;
84
+ const skippedCount = this.tests.filter(t => t.status === 'skipped').length;
85
+
86
+ // constructing the table
87
+ let summary = `${this.hiddenCommentData}
88
+
89
+ | [![Testomat.io Report](${testomatLogoURL})](https://testomat.io) | ${statusEmoji(
90
+ runParams.status,
91
+ )} ${runParams.status.toUpperCase()} ${statusEmoji(runParams.status)} |
92
+ | --- | --- |
93
+ | Tests | ✔️ **${this.tests.length}** tests run |
94
+ | Summary | ${statusEmoji('failed')} **${failedCount}** failed; ${statusEmoji(
95
+ 'passed',
96
+ )} **${passedCount}** passed; **${statusEmoji('skipped')}** ${skippedCount} skipped |
97
+ | Duration | 🕐 **${humanizeDuration(
98
+ parseInt(
99
+ this.tests.reduce((a, t) => a + (t.run_time || 0), 0),
100
+ 10,
101
+ ),
102
+ {
103
+ maxDecimalPoints: 0,
104
+ },
105
+ )}** |
106
+ `;
107
+
108
+ if (this.ENV.CI_JOB_NAME && this.ENV.CI_JOB_ID) {
109
+ // eslint-disable-next-line max-len
110
+ summary += `| Job | 👷 [${this.ENV.CI_JOB_ID}](${this.ENV.CI_JOB_URL})<br>Name: **${this.ENV.CI_JOB_NAME}**<br>Stage: **${this.ENV.CI_JOB_STAGE}** | `;
111
+ }
112
+
113
+ const failures = this.tests
114
+ .filter(t => t.status === 'failed')
115
+ .slice(0, 20)
116
+ .map(t => {
117
+ let text = `#### ${statusEmoji('failed')} ${fullName(t)} `;
118
+ text += '\n\n';
119
+ if (t.message)
120
+ text += `> ${t.message
121
+ .replace(/[^\x20-\x7E]/g, '')
122
+ .replace(ansiRegExp(), '')
123
+ .trim()}\n`;
124
+ if (t.stack) text += `\`\`\`diff\n${t.stack.replace(ansiRegExp(), '').trim()}\n\`\`\`\n`;
125
+
126
+ if (t.artifacts && t.artifacts.length && !this.ENV.TESTOMATIO_PRIVATE_ARTIFACTS) {
127
+ t.artifacts
128
+ .filter(f => !!f)
129
+ .filter(f => f.endsWith('.png'))
130
+ .forEach(f => {
131
+ if (f.endsWith('.png')) {
132
+ text += `![](${f})\n`;
133
+ return text;
134
+ }
135
+ text += `[📄 ${path.basename(f)}](${f})\n`;
136
+ return text;
137
+ });
138
+ }
139
+
140
+ text += '\n---\n';
141
+
142
+ return text;
143
+ });
144
+
145
+ let body = summary;
146
+
147
+ if (failures.length) {
148
+ body += `\n<details>\n<summary><h3>🟥 Failures (${failures.length})</h4></summary>\n\n${failures.join('\n')}\n`;
149
+ if (failures.length > 20) {
150
+ body += '\n> Notice\n> Only first 20 failures shown*';
151
+ }
152
+ body += '\n\n</details>';
153
+ }
154
+
155
+ if (this.tests.length > 0) {
156
+ body += '\n<details>\n<summary><h3>🐢 Slowest Tests</h3></summary>\n\n';
157
+ body += this.tests
158
+ .sort((a, b) => b?.run_time - a?.run_time)
159
+ .slice(0, 5)
160
+ .map(t => `* ${fullName(t)} (${humanizeDuration(parseFloat(t.run_time))})`)
161
+ .join('\n');
162
+ body += '\n</details>';
163
+ }
164
+
165
+ // eslint-disable-next-line max-len
166
+ const commentsRequestURL = `/projects/${this.ENV.CI_PROJECT_ID}/merge_requests/${this.ENV.CI_MERGE_REQUEST_IID}/notes`;
167
+
168
+ // delete previous report
169
+ await deletePreviousReport(this.client, commentsRequestURL, this.hiddenCommentData, this.token);
170
+
171
+ // add current report
172
+ debug(`Adding comment via url: ${commentsRequestURL}`);
173
+
174
+ try {
175
+ const addCommentResponse = await this.client.request({
176
+ method: 'POST',
177
+ url: commentsRequestURL,
178
+ params: { access_token: this.token },
179
+ data: { body }
180
+ });
181
+
182
+ const commentID = addCommentResponse.data.id;
183
+ // eslint-disable-next-line max-len
184
+ const commentURL = `${this.ENV.CI_PROJECT_URL}/-/merge_requests/${this.ENV.CI_MERGE_REQUEST_IID}#note_${commentID}`;
185
+
186
+ console.log(APP_PREFIX, pc.yellow('GitLab'), `Report created: ${pc.magenta(commentURL)}`);
187
+ } catch (err) {
188
+ console.error(
189
+ APP_PREFIX,
190
+ pc.yellow('GitLab'),
191
+ `Couldn't create GitLab report\n${err}.
192
+ Request url: ${commentsRequestURL}
193
+ Request data: ${body}`,
194
+ );
195
+ }
196
+ }
197
+
198
+ toString() {
199
+ return 'GitLab Reporter';
200
+ }
201
+
202
+ updateRun() {}
203
+ }
204
+
205
+ async function deletePreviousReport(client, commentsRequestURL, hiddenCommentData, token) {
206
+ if (process.env.GITLAB_KEEP_OUTDATED_REPORTS) return;
207
+
208
+ // get comments
209
+ let comments = [];
210
+
211
+ try {
212
+ const response = await client.request({
213
+ method: 'GET',
214
+ url: commentsRequestURL,
215
+ params: { access_token: token }
216
+ });
217
+ comments = response.data;
218
+ } catch (e) {
219
+ console.error('Error while attempt to retrieve comments on GitLab Merge Request:\n', e);
220
+ }
221
+
222
+ if (!comments.length) return;
223
+
224
+ for (const comment of comments) {
225
+ // if comment was left by the same workflow
226
+ if (comment.body.includes(hiddenCommentData)) {
227
+ try {
228
+ // delete previous comment
229
+ const deleteCommentURL = `${commentsRequestURL}/${comment.id}`;
230
+ await client.request({
231
+ method: 'DELETE',
232
+ url: deleteCommentURL,
233
+ params: { access_token: token }
234
+ });
235
+ } catch (e) {
236
+ console.warn(`Can't delete previously added comment with testomat.io report. Ignore.`);
237
+ }
238
+
239
+ // pass next env var if need to clear all previous reports;
240
+ // only the last one is removed by default
241
+ if (!process.env.GITLAB_REMOVE_ALL_OUTDATED_REPORTS) break;
242
+ // TODO: in case of many reports should implement pagination
243
+ }
244
+ }
245
+ }
246
+
247
+ export default GitLabPipe;