@testomatio/reporter 2.21.0 → 2.23.0

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.
@@ -890,7 +890,11 @@ class AllureReader {
890
890
  uploadedTests += chunk.length;
891
891
  debug(`Uploaded ${uploadedTests}/${totalTests} tests`);
892
892
  }
893
- if (totalChunks > 1) {
893
+ const testomatioPipe = this.pipes.find(p => p.constructor.name === 'TestomatioPipe');
894
+ if (testomatioPipe && !testomatioPipe.isEnabled) {
895
+ console.warn(constants_js_1.APP_PREFIX, `⚠️ Tests were not uploaded to Testomat.io, skipping report`);
896
+ }
897
+ else if (totalChunks > 1) {
894
898
  console.log(constants_js_1.APP_PREFIX, `✅ Successfully uploaded ${uploadedTests} tests in ${totalChunks} chunks`);
895
899
  }
896
900
  else {
package/lib/bin/cli.js CHANGED
@@ -131,7 +131,7 @@ const fetchCommand = program
131
131
  .command('fetch')
132
132
  .description('Fetch runs from Testomat.io API v2')
133
133
  .argument('[url]', 'URL of a run or of a (filtered) runs page in Testomat.io')
134
- .option('--project <slug>', 'Project slug (or set TESTOMATIO_PROJECT)')
134
+ .option('--project <slug>', 'Project slug for listing runs (or set TESTOMATIO_PROJECT)')
135
135
  .option('--run <id>', 'Fetch a single run by its id')
136
136
  .option('--title <text>', 'Filter by run title')
137
137
  .option('--tql <query>', 'Filter using Testomat Query Language')
@@ -154,31 +154,31 @@ const fetchCommand = program
154
154
  process.exit(1);
155
155
  }
156
156
  }
157
- const project = opts.project || page.project || process.env.TESTOMATIO_PROJECT;
158
- if (!project) {
159
- log_js_1.log.error(picocolors_1.default.red('⚠️ --project (or TESTOMATIO_PROJECT) is required'));
160
- process.exit(1);
161
- }
162
157
  const baseUrl = page.baseUrl || process.env.TESTOMATIO_URL || 'https://app.testomat.io';
163
158
  const runId = opts.run || page.runId;
164
- let url;
165
159
  if (runId) {
166
- url = new URL(`/api/v2/${project}/runs/${runId}`, baseUrl);
160
+ const fetcher = new testruns_js_1.RunFetcher({ baseUrl, project: page.project, runId, apiKey });
161
+ const run = await fetcher.fetchRun().catch(exitOnFetchError);
162
+ console.log((0, pipe_utils_js_1.formatFetchRunsOutput)({ data: run }, opts.format));
163
+ return;
167
164
  }
168
- else {
169
- url = new URL(`/api/v2/${project}/runs`, baseUrl);
170
- for (const [key, value] of page.params || [])
171
- url.searchParams.append(key, value);
172
- if (opts.title)
173
- url.searchParams.set('search', opts.title);
174
- if (opts.tql)
175
- url.searchParams.set('tql', opts.tql);
176
- if (opts.rungroup)
177
- url.searchParams.set('groupId', opts.rungroup);
178
- const requestedLimit = opts.latest ? 1 : parseInt(opts.limit, 10) || FETCH_RUNS_DEFAULT_LIMIT;
179
- const limit = Math.min(Math.max(requestedLimit, 1), FETCH_RUNS_MAX_LIMIT);
180
- url.searchParams.set('per_page', String(limit));
165
+ const project = opts.project || page.project || process.env.TESTOMATIO_PROJECT;
166
+ if (!project) {
167
+ log_js_1.log.error(picocolors_1.default.red('⚠️ --project (or TESTOMATIO_PROJECT) is required to list runs, unless --run or a URL is passed'));
168
+ process.exit(1);
181
169
  }
170
+ const url = new URL(`/api/v2/${project}/runs`, baseUrl);
171
+ for (const [key, value] of page.params || [])
172
+ url.searchParams.append(key, value);
173
+ if (opts.title)
174
+ url.searchParams.set('search', opts.title);
175
+ if (opts.tql)
176
+ url.searchParams.set('tql', opts.tql);
177
+ if (opts.rungroup)
178
+ url.searchParams.set('groupId', opts.rungroup);
179
+ const requestedLimit = opts.latest ? 1 : parseInt(opts.limit, 10) || FETCH_RUNS_DEFAULT_LIMIT;
180
+ const limit = Math.min(Math.max(requestedLimit, 1), FETCH_RUNS_MAX_LIMIT);
181
+ url.searchParams.set('per_page', String(limit));
182
182
  const response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
183
183
  const body = await response.json();
184
184
  if (!response.ok) {
@@ -187,23 +187,22 @@ const fetchCommand = program
187
187
  }
188
188
  console.log((0, pipe_utils_js_1.formatFetchRunsOutput)(body, opts.format));
189
189
  });
190
- // fetch parses the options it shares with its subcommands (--project, --format, --limit) wherever they are placed,
190
+ // fetch parses the options it shares with its subcommands (--format, --limit) wherever they are placed,
191
191
  // so subcommands declare them only for help and read them with optsWithGlobals()
192
192
  /**
193
193
  * Build a RunFetcher for the run argument of fetch status|count|report, or exit with an error.
194
194
  *
195
195
  * @param {string} runArg
196
- * @param {{project?: string}} opts
197
196
  * @returns {RunFetcher}
198
197
  */
199
- function createRunFetcher(runArg, opts) {
198
+ function createRunFetcher(runArg) {
200
199
  const apiKey = process.env['INPUT_TESTOMATIO-KEY'] || config_js_1.config.TESTOMATIO;
201
200
  if (!apiKey) {
202
201
  log_js_1.log.error(picocolors_1.default.red('⚠️ TESTOMATIO API key required'));
203
202
  process.exit(1);
204
203
  }
205
204
  try {
206
- return new testruns_js_1.RunFetcher({ ...(0, testruns_js_1.resolveRunTarget)(runArg, opts), apiKey });
205
+ return new testruns_js_1.RunFetcher({ ...(0, testruns_js_1.resolveRunTarget)(runArg), apiKey });
207
206
  }
208
207
  catch (err) {
209
208
  log_js_1.log.error(picocolors_1.default.red(`⚠️ ${err.message}`));
@@ -237,11 +236,10 @@ fetchCommand
237
236
  .command('status')
238
237
  .description('Show a run with the number of its testruns by status')
239
238
  .argument('<run>', RUN_ARGUMENT_DESCRIPTION)
240
- .option('--project <slug>', 'Project slug (or set TESTOMATIO_PROJECT)')
241
239
  .option('--format <format>', 'Machine-readable output: run status and counts as JSON (--format json)')
242
240
  .action(async (runArg, _opts, command) => {
243
241
  const opts = command.optsWithGlobals();
244
- const fetcher = createRunFetcher(runArg, opts);
242
+ const fetcher = createRunFetcher(runArg);
245
243
  const [run, summary] = await Promise.all([fetcher.fetchRun(), fetcher.countTestrunsByStatus()]).catch(exitOnFetchError);
246
244
  const counts = Object.fromEntries(testruns_js_1.TESTRUN_STATUSES.map(status => [status, summary.byStatus[status] || 0]));
247
245
  if (opts.format === 'json') {
@@ -258,12 +256,11 @@ fetchCommand
258
256
  .command('count')
259
257
  .description('Print the number of testruns of a run, to pick --limit and filters for fetch report')
260
258
  .argument('<run>', RUN_ARGUMENT_DESCRIPTION)
261
- .option('--project <slug>', 'Project slug (or set TESTOMATIO_PROJECT)')
262
259
  .option('--only <statuses>', STATUS_FILTER_DESCRIPTION)
263
260
  .option('--only-failed', 'Only failed testruns (shorthand for --only failed)')
264
261
  .action(async (runArg, _opts, command) => {
265
262
  const opts = command.optsWithGlobals();
266
- const fetcher = createRunFetcher(runArg, opts);
263
+ const fetcher = createRunFetcher(runArg);
267
264
  const statuses = getStatusFilter(opts);
268
265
  const total = await fetcher.countTestruns(statuses).catch(exitOnFetchError);
269
266
  console.log(total);
@@ -272,20 +269,19 @@ fetchCommand
272
269
  .command('report')
273
270
  .description('Print a run with its testruns as a Markdown report')
274
271
  .argument('<run>', RUN_ARGUMENT_DESCRIPTION)
275
- .option('--project <slug>', 'Project slug (or set TESTOMATIO_PROJECT)')
276
272
  .option('--only <statuses>', STATUS_FILTER_DESCRIPTION)
277
273
  .option('--only-failed', 'Only failed testruns (shorthand for --only failed)')
278
274
  .option('--stack', 'Include stack traces')
279
275
  .option('--artifacts', 'Download artifacts to --out and link them from the report')
280
276
  .option('--out <dir>', 'Directory for downloaded artifacts (default: ./<run-title>-<run-id>)')
281
- .option('--limit <number>', `Max number of testruns, failed first (default ${testruns_js_1.TESTRUNS_DEFAULT_LIMIT}, max ${testruns_js_1.TESTRUNS_MAX_LIMIT})`)
277
+ .option('--limit <number>', `Max number of testruns, failed first (default ${testruns_js_1.TESTRUNS_DEFAULT_LIMIT})`)
278
+ .option('--all', 'All matching testruns, fetched in chunks of 100 (overrides --limit)')
279
+ .option('--no-defects', 'Skip defects of the run and of its tests')
282
280
  .action(async (runArg, _opts, command) => {
283
281
  const opts = command.optsWithGlobals();
284
- const fetcher = createRunFetcher(runArg, opts);
282
+ const fetcher = createRunFetcher(runArg);
285
283
  const statuses = getStatusFilter(opts);
286
- const { limit, capped } = (0, testruns_js_1.parseTestrunsLimit)(opts.limit);
287
- if (capped)
288
- log_js_1.log.warn(picocolors_1.default.yellow(`⚠️ --limit is capped at ${testruns_js_1.TESTRUNS_MAX_LIMIT}`));
284
+ const limit = (0, testruns_js_1.parseTestrunsLimit)(opts);
289
285
  const run = await fetcher.fetchRun().catch(exitOnFetchError);
290
286
  if (opts.artifacts) {
291
287
  const hasSharedCredentials = await fetcher.applySharedS3Credentials(run);
@@ -294,13 +290,21 @@ fetchCommand
294
290
  process.exit(1);
295
291
  }
296
292
  }
297
- const [summary, list] = await Promise.all([
293
+ let runDefectsRequest;
294
+ if (opts.defects) {
295
+ runDefectsRequest = fetcher.listRunDefects().catch(err => {
296
+ log_js_1.log.warn(picocolors_1.default.yellow(`⚠️ Failed to fetch defects of the run: ${err.message}`));
297
+ return null;
298
+ });
299
+ }
300
+ const [summary, list, runDefects] = await Promise.all([
298
301
  fetcher.countTestrunsByStatus(),
299
302
  fetcher.listTestruns({ statuses, limit }),
303
+ runDefectsRequest,
300
304
  ]).catch(exitOnFetchError);
301
305
  let { testruns } = list;
302
306
  if (list.total > testruns.length) {
303
- log_js_1.log.warn(picocolors_1.default.yellow(`⚠️ Showing ${testruns.length} of ${list.total} testruns. Use --limit or --only-failed to narrow it.`));
307
+ log_js_1.log.warn(picocolors_1.default.yellow(`⚠️ Showing ${testruns.length} of ${list.total} testruns. Use --all, --limit or --only-failed.`));
304
308
  }
305
309
  if (opts.stack || opts.artifacts) {
306
310
  testruns = await fetcher.addTestrunDetails(testruns, (testrun, err) => {
@@ -309,6 +313,14 @@ fetchCommand
309
313
  if (!opts.stack)
310
314
  testruns = testruns.map(({ stack, ...testrun }) => testrun);
311
315
  }
316
+ if (opts.defects) {
317
+ testruns = await fetcher.addTestDefects(testruns, (testId, err) => {
318
+ log_js_1.log.warn(picocolors_1.default.yellow(`⚠️ Failed to fetch defects of test ${testId}: ${err.message}`));
319
+ });
320
+ }
321
+ else {
322
+ testruns = testruns.map(({ defects, ...testrun }) => testrun);
323
+ }
312
324
  if (opts.artifacts) {
313
325
  const outDir = opts.out || (0, testruns_js_1.defaultArtifactsDir)(run, fetcher.runId);
314
326
  const artifactsCount = testruns.reduce((sum, testrun) => sum + (testrun.artifacts?.length || 0), 0);
@@ -320,7 +332,7 @@ fetchCommand
320
332
  else {
321
333
  testruns = testruns.map(({ artifacts, ...testrun }) => testrun);
322
334
  }
323
- process.stdout.write((0, report_js_1.renderRunReport)({ run, runUrl: fetcher.runUrl, summary, testruns, matched: list.total, statuses }));
335
+ process.stdout.write((0, report_js_1.renderRunReport)({ run, runUrl: fetcher.runUrl, summary, testruns, matched: list.total, statuses, runDefects }));
324
336
  });
325
337
  program
326
338
  .command('run')
@@ -8,9 +8,10 @@
8
8
  * @param {object[]} params.testruns
9
9
  * @param {number} params.matched - Number of testruns matching the filter
10
10
  * @param {string[]} params.statuses - Status filter, empty for all testruns
11
+ * @param {{defects: object[], total: number} | null} [params.runDefects] - Defects of the run
11
12
  * @returns {string}
12
13
  */
13
- export function renderRunReport({ run, runUrl, summary, testruns, matched, statuses }: {
14
+ export function renderRunReport({ run, runUrl, summary, testruns, matched, statuses, runDefects }: {
14
15
  run: object;
15
16
  runUrl: string;
16
17
  summary: {
@@ -20,6 +21,10 @@ export function renderRunReport({ run, runUrl, summary, testruns, matched, statu
20
21
  testruns: object[];
21
22
  matched: number;
22
23
  statuses: string[];
24
+ runDefects?: {
25
+ defects: object[];
26
+ total: number;
27
+ } | null;
23
28
  }): string;
24
29
  /**
25
30
  * Map a testrun of API v2 to the test shape of the Markdown pipe.
@@ -28,8 +28,24 @@ function toReportTest(testrun) {
28
28
  message: testrun.message,
29
29
  stack: testrun.stack,
30
30
  artifacts: testrun.artifacts,
31
+ defects: testrun.defects,
31
32
  };
32
33
  }
34
+ /**
35
+ * @param {{defects: object[], total: number}} runDefects - Defects of GET /api/v2/:project/defects?run_id=
36
+ * @returns {string}
37
+ */
38
+ function renderRunDefects({ defects, total }) {
39
+ const lines = ['## Defects', ''];
40
+ if (total > defects.length)
41
+ lines.push(`${defects.length} of ${total} shown`, '');
42
+ lines.push('| Defect | Title | Status | Severity |', '| ------ | ----- | ------ | -------- |');
43
+ for (const defect of defects) {
44
+ const cells = [(0, markdown_js_1.defectLink)(defect), defect.title, defect.status, defect.severity].map(cell => String(cell || '').replace(/\|/g, '\\|'));
45
+ lines.push(`| ${cells.join(' | ')} |`);
46
+ }
47
+ return lines.join('\n');
48
+ }
33
49
  /**
34
50
  * Render a fetched run with its testruns as a Markdown report.
35
51
  *
@@ -40,9 +56,10 @@ function toReportTest(testrun) {
40
56
  * @param {object[]} params.testruns
41
57
  * @param {number} params.matched - Number of testruns matching the filter
42
58
  * @param {string[]} params.statuses - Status filter, empty for all testruns
59
+ * @param {{defects: object[], total: number} | null} [params.runDefects] - Defects of the run
43
60
  * @returns {string}
44
61
  */
45
- function renderRunReport({ run, runUrl, summary, testruns, matched, statuses }) {
62
+ function renderRunReport({ run, runUrl, summary, testruns, matched, statuses, runDefects }) {
46
63
  const status = String(run.status || 'unknown');
47
64
  const sections = [`# ${run.title || run.id} — ${status.toUpperCase()}`];
48
65
  const rows = [
@@ -72,6 +89,8 @@ function renderRunReport({ run, runUrl, summary, testruns, matched, statuses })
72
89
  ...counts.map(([name, count]) => `| ${name} | ${count} |`),
73
90
  `| total | ${summary.total} |`,
74
91
  ].join('\n'));
92
+ if (runDefects?.defects.length)
93
+ sections.push(renderRunDefects(runDefects));
75
94
  sections.push((0, markdown_js_1.renderTests)(testruns.map(toReportTest)));
76
95
  return `${sections.join('\n\n')}\n`;
77
96
  }
@@ -1,16 +1,16 @@
1
1
  export const TESTRUNS_DEFAULT_LIMIT: 50;
2
- export const TESTRUNS_MAX_LIMIT: 100;
2
+ export const TESTRUNS_PAGE_SIZE: 100;
3
3
  export const TESTRUN_STATUSES: string[];
4
4
  /**
5
5
  * Read-only client for a single run and its testruns in API v2.
6
6
  */
7
7
  export class RunFetcher {
8
8
  /**
9
- * @param {{baseUrl: string, project: string, runId: string, apiKey: string}} params
9
+ * @param {{baseUrl: string, project?: string, runId: string, apiKey: string}} params
10
10
  */
11
11
  constructor({ baseUrl, project, runId, apiKey }: {
12
12
  baseUrl: string;
13
- project: string;
13
+ project?: string;
14
14
  runId: string;
15
15
  apiKey: string;
16
16
  });
@@ -18,6 +18,20 @@ export class RunFetcher {
18
18
  project: string;
19
19
  runId: string;
20
20
  apiKey: string;
21
+ /** @type {Promise<any>|null} */
22
+ reporterRun: Promise<any> | null;
23
+ /**
24
+ * Empty update of the run in the reporter API: it returns the project of the token and shared S3 credentials.
25
+ *
26
+ * @returns {Promise<{project?: {id: string}, artifacts?: object}>}
27
+ */
28
+ updateReporterRun(): Promise<{
29
+ project?: {
30
+ id: string;
31
+ };
32
+ artifacts?: object;
33
+ }>;
34
+ resolveProject(): Promise<string>;
21
35
  get runUrl(): string;
22
36
  get(apiPath: any, params?: any[]): Promise<any>;
23
37
  fetchRun(): Promise<any>;
@@ -39,9 +53,9 @@ export class RunFetcher {
39
53
  byStatus: Record<string, number>;
40
54
  }>;
41
55
  /**
42
- * Testruns with failures first; the list has no stack and no artifacts.
56
+ * Testruns with failures first, read in pages of TESTRUNS_PAGE_SIZE; the list has no stack and no artifacts.
43
57
  *
44
- * @param {{statuses?: string[], limit: number}} params
58
+ * @param {{statuses?: string[], limit: number}} params - limit is Infinity to read all testruns
45
59
  * @returns {Promise<{testruns: object[], total: number}>}
46
60
  */
47
61
  listTestruns({ statuses, limit }: {
@@ -58,9 +72,27 @@ export class RunFetcher {
58
72
  * @param {(testrun: object, err: Error) => void} onError
59
73
  */
60
74
  addTestrunDetails(testruns: object[], onError: (testrun: object, err: Error) => void): Promise<any[]>;
75
+ /**
76
+ * Defects linked to the testruns of the run; one page of TESTRUNS_PAGE_SIZE.
77
+ *
78
+ * @returns {Promise<{defects: object[], total: number}>}
79
+ */
80
+ listRunDefects(): Promise<{
81
+ defects: object[];
82
+ total: number;
83
+ }>;
84
+ /**
85
+ * Add the defects linked to the test case of each testrun to the testrun's own defects.
86
+ * A test that fails to load keeps only the testrun defects.
87
+ *
88
+ * @param {object[]} testruns
89
+ * @param {(testId: string, err: Error) => void} onError
90
+ */
91
+ addTestDefects(testruns: object[], onError: (testId: string, err: Error) => void): Promise<any[]>;
61
92
  /**
62
93
  * Shared S3 credentials of the project, returned by an empty update of the run.
63
- * Skipped for scheduled runs (the update launches them) and mixed runs (it marks automated tests as started).
94
+ * Unless the run was already updated to resolve its project, skipped for scheduled runs (the update launches them)
95
+ * and unfinished mixed runs (it marks automated tests as started).
64
96
  *
65
97
  * @param {{status?: string, kind?: string}} run
66
98
  * @returns {Promise<boolean>} whether credentials were applied
@@ -72,17 +104,14 @@ export class RunFetcher {
72
104
  }
73
105
  /**
74
106
  * Resolve the run argument of `fetch status|count|report`: a run id or a run URL.
75
- * A URL also sets the server and the project.
107
+ * A URL also sets the server and the project; for a run id the project is resolved from the run by RunFetcher.
76
108
  *
77
109
  * @param {string} runArg
78
- * @param {{project?: string}} opts
79
- * @returns {{baseUrl: string, project: string, runId: string}}
110
+ * @returns {{baseUrl: string, project?: string, runId: string}}
80
111
  */
81
- export function resolveRunTarget(runArg: string, opts: {
82
- project?: string;
83
- }): {
112
+ export function resolveRunTarget(runArg: string): {
84
113
  baseUrl: string;
85
- project: string;
114
+ project?: string;
86
115
  runId: string;
87
116
  };
88
117
  /**
@@ -96,13 +125,13 @@ export function parseStatuses(opts: {
96
125
  onlyFailed?: boolean;
97
126
  }): string[];
98
127
  /**
99
- * @param {string} [value] - Value of the CLI --limit option.
100
- * @returns {{limit: number, capped: boolean}}
128
+ * @param {{limit?: string, all?: boolean}} opts - Values of the CLI --limit and --all options.
129
+ * @returns {number} Infinity for --all
101
130
  */
102
- export function parseTestrunsLimit(value?: string): {
103
- limit: number;
104
- capped: boolean;
105
- };
131
+ export function parseTestrunsLimit(opts: {
132
+ limit?: string;
133
+ all?: boolean;
134
+ }): number;
106
135
  /**
107
136
  * Run `fn` over `items` with at most `limit` calls in flight; results keep the order of `items`.
108
137
  *
@@ -3,13 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RunFetcher = exports.TESTRUN_STATUSES = exports.TESTRUNS_MAX_LIMIT = exports.TESTRUNS_DEFAULT_LIMIT = void 0;
6
+ exports.RunFetcher = exports.TESTRUN_STATUSES = exports.TESTRUNS_PAGE_SIZE = exports.TESTRUNS_DEFAULT_LIMIT = void 0;
7
7
  exports.resolveRunTarget = resolveRunTarget;
8
8
  exports.parseStatuses = parseStatuses;
9
9
  exports.parseTestrunsLimit = parseTestrunsLimit;
10
10
  exports.mapWithLimit = mapWithLimit;
11
11
  exports.downloadArtifacts = downloadArtifacts;
12
- module.exportsArtifactsDir = defaultArtifactsDir;
12
+ exports.defaultArtifactsDir = defaultArtifactsDir;
13
13
  const debug_1 = __importDefault(require("debug"));
14
14
  const path_1 = __importDefault(require("path"));
15
15
  const pipe_utils_js_1 = require("../utils/pipe_utils.js");
@@ -17,30 +17,27 @@ const uploader_js_1 = require("../uploader.js");
17
17
  const debug = (0, debug_1.default)('@testomatio/reporter:fetch');
18
18
  const TESTRUNS_DEFAULT_LIMIT = 50;
19
19
  exports.TESTRUNS_DEFAULT_LIMIT = TESTRUNS_DEFAULT_LIMIT;
20
- const TESTRUNS_MAX_LIMIT = 100;
21
- exports.TESTRUNS_MAX_LIMIT = TESTRUNS_MAX_LIMIT;
20
+ const TESTRUNS_PAGE_SIZE = 100;
21
+ exports.TESTRUNS_PAGE_SIZE = TESTRUNS_PAGE_SIZE;
22
22
  const TESTRUN_STATUSES = ['passed', 'failed', 'skipped', 'pending'];
23
23
  exports.TESTRUN_STATUSES = TESTRUN_STATUSES;
24
24
  const PARALLEL_REQUESTS = 5;
25
+ const FINISHED_RUN_STATUSES = ['passed', 'failed', 'terminated', 'finished'];
25
26
  /**
26
27
  * Resolve the run argument of `fetch status|count|report`: a run id or a run URL.
27
- * A URL also sets the server and the project.
28
+ * A URL also sets the server and the project; for a run id the project is resolved from the run by RunFetcher.
28
29
  *
29
30
  * @param {string} runArg
30
- * @param {{project?: string}} opts
31
- * @returns {{baseUrl: string, project: string, runId: string}}
31
+ * @returns {{baseUrl: string, project?: string, runId: string}}
32
32
  */
33
- function resolveRunTarget(runArg, opts) {
33
+ function resolveRunTarget(runArg) {
34
34
  if (/^https?:\/\//i.test(runArg)) {
35
35
  const page = (0, pipe_utils_js_1.parseRunsUrl)(runArg);
36
36
  if (!page?.runId)
37
37
  throw new Error(`Not a Testomat.io run URL: ${runArg}`);
38
- return { baseUrl: page.baseUrl, project: opts.project || page.project, runId: page.runId };
38
+ return { baseUrl: page.baseUrl, project: page.project, runId: page.runId };
39
39
  }
40
- const project = opts.project || process.env.TESTOMATIO_PROJECT;
41
- if (!project)
42
- throw new Error('--project (or TESTOMATIO_PROJECT) is required');
43
- return { baseUrl: process.env.TESTOMATIO_URL || 'https://app.testomat.io', project, runId: runArg };
40
+ return { baseUrl: process.env.TESTOMATIO_URL || 'https://app.testomat.io', runId: runArg };
44
41
  }
45
42
  /**
46
43
  * Collect the statuses passed with --only and --only-failed.
@@ -62,12 +59,13 @@ function parseStatuses(opts) {
62
59
  return [...new Set(statuses)];
63
60
  }
64
61
  /**
65
- * @param {string} [value] - Value of the CLI --limit option.
66
- * @returns {{limit: number, capped: boolean}}
62
+ * @param {{limit?: string, all?: boolean}} opts - Values of the CLI --limit and --all options.
63
+ * @returns {number} Infinity for --all
67
64
  */
68
- function parseTestrunsLimit(value) {
69
- const requested = Math.max(parseInt(value, 10) || TESTRUNS_DEFAULT_LIMIT, 1);
70
- return { limit: Math.min(requested, TESTRUNS_MAX_LIMIT), capped: requested > TESTRUNS_MAX_LIMIT };
65
+ function parseTestrunsLimit(opts) {
66
+ if (opts.all)
67
+ return Infinity;
68
+ return Math.max(parseInt(opts.limit, 10) || TESTRUNS_DEFAULT_LIMIT, 1);
71
69
  }
72
70
  /**
73
71
  * Run `fn` over `items` with at most `limit` calls in flight; results keep the order of `items`.
@@ -95,18 +93,53 @@ async function mapWithLimit(items, limit, fn) {
95
93
  */
96
94
  class RunFetcher {
97
95
  /**
98
- * @param {{baseUrl: string, project: string, runId: string, apiKey: string}} params
96
+ * @param {{baseUrl: string, project?: string, runId: string, apiKey: string}} params
99
97
  */
100
98
  constructor({ baseUrl, project, runId, apiKey }) {
101
99
  this.baseUrl = baseUrl;
102
100
  this.project = project;
103
101
  this.runId = runId;
104
102
  this.apiKey = apiKey;
103
+ /** @type {Promise<any>|null} */
104
+ this.reporterRun = null;
105
+ }
106
+ /**
107
+ * Empty update of the run in the reporter API: it returns the project of the token and shared S3 credentials.
108
+ *
109
+ * @returns {Promise<{project?: {id: string}, artifacts?: object}>}
110
+ */
111
+ updateReporterRun() {
112
+ this.reporterRun ||= (async () => {
113
+ const url = new URL(`/api/reporter/${this.runId}`, this.baseUrl);
114
+ debug('PUT', url.toString());
115
+ const response = await fetch(url, {
116
+ method: 'PUT',
117
+ headers: { 'Content-Type': 'application/json' },
118
+ body: JSON.stringify({ api_key: this.apiKey }),
119
+ });
120
+ const body = await response.json().catch(() => ({}));
121
+ if (response.status === 404)
122
+ throw new Error(`Run ${this.runId} not found`);
123
+ if (!response.ok)
124
+ throw new Error(`${response.status} ${body.message || body.error || response.statusText}`);
125
+ return body;
126
+ })();
127
+ return this.reporterRun;
128
+ }
129
+ async resolveProject() {
130
+ if (this.project)
131
+ return this.project;
132
+ const body = await this.updateReporterRun();
133
+ if (!body.project?.id)
134
+ throw new Error(`Project of run ${this.runId} is unknown`);
135
+ this.project = body.project.id;
136
+ return this.project;
105
137
  }
106
138
  get runUrl() {
107
139
  return new URL(`/projects/${this.project}/runs/${this.runId}`, this.baseUrl).toString();
108
140
  }
109
141
  async get(apiPath, params = []) {
142
+ await this.resolveProject();
110
143
  const url = new URL(`/api/v2/${this.project}${apiPath}`, this.baseUrl);
111
144
  for (const [key, value] of params)
112
145
  url.searchParams.append(key, value);
@@ -150,19 +183,29 @@ class RunFetcher {
150
183
  return { total: body.meta?.total || 0, byStatus: body.meta?.group_by || {} };
151
184
  }
152
185
  /**
153
- * Testruns with failures first; the list has no stack and no artifacts.
186
+ * Testruns with failures first, read in pages of TESTRUNS_PAGE_SIZE; the list has no stack and no artifacts.
154
187
  *
155
- * @param {{statuses?: string[], limit: number}} params
188
+ * @param {{statuses?: string[], limit: number}} params - limit is Infinity to read all testruns
156
189
  * @returns {Promise<{testruns: object[], total: number}>}
157
190
  */
158
191
  async listTestruns({ statuses = [], limit }) {
159
- const body = await this.get('/testruns', [
160
- ...this.testrunParams(statuses),
161
- ['sort', 'failure'],
162
- ['order', 'desc'],
163
- ['per_page', String(limit)],
164
- ]);
165
- return { testruns: body.data || [], total: body.meta?.total || 0 };
192
+ const perPage = Math.min(limit, TESTRUNS_PAGE_SIZE);
193
+ const getPage = async (page) => {
194
+ const body = await this.get('/testruns', [
195
+ ...this.testrunParams(statuses),
196
+ ['sort', 'failure'],
197
+ ['order', 'desc'],
198
+ ['per_page', String(perPage)],
199
+ ['page', String(page)],
200
+ ]);
201
+ return { testruns: body.data || [], total: body.meta?.total || 0 };
202
+ };
203
+ const first = await getPage(1);
204
+ const pagesCount = Math.ceil(Math.min(limit, first.total) / perPage);
205
+ const nextPages = Array.from({ length: Math.max(pagesCount - 1, 0) }, (_, index) => index + 2);
206
+ const rest = await mapWithLimit(nextPages, PARALLEL_REQUESTS, getPage);
207
+ const testruns = [first, ...rest].flatMap(page => page.testruns).slice(0, limit);
208
+ return { testruns, total: first.total };
166
209
  }
167
210
  /**
168
211
  * Add `stack` and `artifacts` to each testrun; a testrun that fails to load is kept as is.
@@ -182,29 +225,66 @@ class RunFetcher {
182
225
  }
183
226
  });
184
227
  }
228
+ /**
229
+ * Defects linked to the testruns of the run; one page of TESTRUNS_PAGE_SIZE.
230
+ *
231
+ * @returns {Promise<{defects: object[], total: number}>}
232
+ */
233
+ async listRunDefects() {
234
+ const body = await this.get('/defects', [
235
+ ['run_id', this.runId],
236
+ ['per_page', String(TESTRUNS_PAGE_SIZE)],
237
+ ]);
238
+ return { defects: body.data || [], total: body.meta?.total || 0 };
239
+ }
240
+ /**
241
+ * Add the defects linked to the test case of each testrun to the testrun's own defects.
242
+ * A test that fails to load keeps only the testrun defects.
243
+ *
244
+ * @param {object[]} testruns
245
+ * @param {(testId: string, err: Error) => void} onError
246
+ */
247
+ async addTestDefects(testruns, onError) {
248
+ const testIds = [...new Set(testruns.map(testrun => testrun.testId).filter(Boolean))];
249
+ const testDefects = await mapWithLimit(testIds, PARALLEL_REQUESTS, async (testId) => {
250
+ try {
251
+ const body = await this.get('/defects', [
252
+ ['test_id', testId],
253
+ ['per_page', String(TESTRUNS_PAGE_SIZE)],
254
+ ]);
255
+ return body.data || [];
256
+ }
257
+ catch (err) {
258
+ onError(testId, err);
259
+ return [];
260
+ }
261
+ });
262
+ const defectsByTest = new Map(testIds.map((testId, index) => [testId, testDefects[index]]));
263
+ return testruns.map(testrun => {
264
+ const defects = [...(testrun.defects || []), ...(defectsByTest.get(testrun.testId) || [])];
265
+ const unique = [...new Map(defects.map(defect => [defect.id, defect])).values()];
266
+ return { ...testrun, defects: unique };
267
+ });
268
+ }
185
269
  /**
186
270
  * Shared S3 credentials of the project, returned by an empty update of the run.
187
- * Skipped for scheduled runs (the update launches them) and mixed runs (it marks automated tests as started).
271
+ * Unless the run was already updated to resolve its project, skipped for scheduled runs (the update launches them)
272
+ * and unfinished mixed runs (it marks automated tests as started).
188
273
  *
189
274
  * @param {{status?: string, kind?: string}} run
190
275
  * @returns {Promise<boolean>} whether credentials were applied
191
276
  */
192
277
  async applySharedS3Credentials(run) {
193
- if (run.status === 'scheduled' || run.kind === 'mixed') {
278
+ const isUnfinishedMixed = run.kind === 'mixed' && !FINISHED_RUN_STATUSES.includes(run.status);
279
+ if (!this.reporterRun && (run.status === 'scheduled' || isUnfinishedMixed)) {
194
280
  debug(`Shared S3 credentials are not requested for a ${run.status} ${run.kind} run`);
195
281
  return false;
196
282
  }
197
- const url = new URL(`/api/reporter/${this.runId}`, this.baseUrl);
198
- const response = await fetch(url, {
199
- method: 'PUT',
200
- headers: { 'Content-Type': 'application/json' },
201
- body: JSON.stringify({ api_key: this.apiKey }),
283
+ const body = await this.updateReporterRun().catch(err => {
284
+ debug('Failed to get shared S3 credentials:', err.message);
285
+ return { artifacts: null };
202
286
  });
203
- if (!response.ok) {
204
- debug('Failed to get shared S3 credentials:', response.status);
205
- return false;
206
- }
207
- const { artifacts } = await response.json();
287
+ const { artifacts } = body;
208
288
  if (!artifacts || !Object.keys(artifacts).length)
209
289
  return false;
210
290
  (0, pipe_utils_js_1.setS3Credentials)(artifacts);
@@ -277,9 +357,11 @@ module.exports.mapWithLimit = mapWithLimit;
277
357
 
278
358
  module.exports.downloadArtifacts = downloadArtifacts;
279
359
 
360
+ module.exports.defaultArtifactsDir = defaultArtifactsDir;
361
+
280
362
  module.exports.TESTRUNS_DEFAULT_LIMIT = TESTRUNS_DEFAULT_LIMIT;
281
363
 
282
- module.exports.TESTRUNS_MAX_LIMIT = TESTRUNS_MAX_LIMIT;
364
+ module.exports.TESTRUNS_PAGE_SIZE = TESTRUNS_PAGE_SIZE;
283
365
 
284
366
  module.exports.TESTRUN_STATUSES = TESTRUN_STATUSES;
285
367
 
@@ -1,5 +1,6 @@
1
1
  export default MarkdownPipe;
2
2
  export function renderTests(tests: any): string;
3
+ export function defectLink(defect: any): string;
3
4
  declare class MarkdownPipe {
4
5
  constructor(params: any, store?: {});
5
6
  store: {};