allure 3.0.0-beta.17 → 3.0.0-beta.18

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.
@@ -2,7 +2,7 @@ import { Command } from "clipanion";
2
2
  export declare class GenerateCommand extends Command {
3
3
  static paths: string[][];
4
4
  static usage: import("clipanion").Usage;
5
- resultsDir: string;
5
+ resultsDir: string | undefined;
6
6
  config: string | undefined;
7
7
  output: string | undefined;
8
8
  cwd: string | undefined;
@@ -1,13 +1,19 @@
1
1
  import { AllureReport, readConfig } from "@allurereport/core";
2
+ import { findMatching } from "@allurereport/directory-watcher";
2
3
  import { KnownError } from "@allurereport/service";
3
4
  import { Command, Option } from "clipanion";
5
+ import { join } from "node:path";
4
6
  import process from "node:process";
7
+ import pm from "picomatch";
5
8
  import { red } from "yoctocolors";
6
9
  import { logError } from "../utils/logs.js";
7
10
  export class GenerateCommand extends Command {
8
11
  constructor() {
9
12
  super(...arguments);
10
- this.resultsDir = Option.String({ required: true, name: "The directory with Allure results" });
13
+ this.resultsDir = Option.String({
14
+ required: false,
15
+ name: "Pattern to match test results directories in the current working directory (default: ./**/allure-results)",
16
+ });
11
17
  this.config = Option.String("--config,-c", {
12
18
  description: "The path Allure config file",
13
19
  });
@@ -22,14 +28,34 @@ export class GenerateCommand extends Command {
22
28
  });
23
29
  }
24
30
  async execute() {
25
- const config = await readConfig(this.cwd, this.config, {
31
+ const cwd = this.cwd ?? process.cwd();
32
+ const resultsDir = (this.resultsDir ?? "./**/allure-results").replace(/[\\/]$/, "");
33
+ const config = await readConfig(cwd, this.config, {
26
34
  name: this.reportName,
27
35
  output: this.output ?? "allure-report",
28
36
  });
37
+ const matcher = pm(resultsDir, {
38
+ dot: true,
39
+ contains: true,
40
+ });
41
+ const resultsDirectories = new Set();
42
+ await findMatching(cwd, resultsDirectories, (dirent) => {
43
+ if (dirent.isDirectory()) {
44
+ const fullPath = join(dirent?.parentPath ?? dirent?.path, dirent.name);
45
+ return matcher(fullPath);
46
+ }
47
+ return false;
48
+ });
49
+ if (resultsDirectories.size === 0) {
50
+ console.log(red(`No test results directories found matching pattern: ${resultsDir}`));
51
+ return;
52
+ }
29
53
  try {
30
54
  const allureReport = new AllureReport(config);
31
55
  await allureReport.start();
32
- await allureReport.readDirectory(this.resultsDir);
56
+ for (const dir of resultsDirectories) {
57
+ await allureReport.readDirectory(dir);
58
+ }
33
59
  await allureReport.done();
34
60
  }
35
61
  catch (error) {
@@ -19,3 +19,4 @@ export * from "./login.js";
19
19
  export * from "./logout.js";
20
20
  export * from "./whoami.js";
21
21
  export * from "./projects/index.js";
22
+ export * from "./results/index.js";
@@ -19,3 +19,4 @@ export * from "./login.js";
19
19
  export * from "./logout.js";
20
20
  export * from "./whoami.js";
21
21
  export * from "./projects/index.js";
22
+ export * from "./results/index.js";
@@ -77,7 +77,7 @@ ProjectsCreateCommand.usage = Command.Usage({
77
77
  description: "Creates a new project",
78
78
  details: "This command creates a new project in the Allure Service.",
79
79
  examples: [
80
- ["project-create my-project", "Create a new project named 'my-project'"],
81
- ["project-create", "Create a new project with a name from git repo or prompt for a name"],
80
+ ["project create my-project", "Create a new project named 'my-project'"],
81
+ ["project create", "Create a new project with a name from git repo or prompt for a name"],
82
82
  ],
83
83
  });
@@ -62,7 +62,7 @@ ProjectsDeleteCommand.usage = Command.Usage({
62
62
  description: "Deletes a project",
63
63
  details: "This command deletes a project from the Allure Service.",
64
64
  examples: [
65
- ["project-delete my-project", "Delete the project named 'my-project' (with confirmation)"],
66
- ["project-delete my-project --force", "Delete the project named 'my-project' without confirmation"],
65
+ ["project delete my-project", "Delete the project named 'my-project' (with confirmation)"],
66
+ ["project delete my-project --force", "Delete the project named 'my-project' without confirmation"],
67
67
  ],
68
68
  });
@@ -71,5 +71,5 @@ ProjectsListCommand.usage = Command.Usage({
71
71
  category: "Allure Service Projects",
72
72
  description: "Shows list of all available projects for current user",
73
73
  details: "This command lists all available projects for the current user and allows selecting one to get configuration information.",
74
- examples: [["projects", "List all available projects"]],
74
+ examples: [["projects list", "List all available projects"]],
75
75
  });
@@ -2,8 +2,13 @@ import { Command } from "clipanion";
2
2
  export declare class QualityGateCommand extends Command {
3
3
  static paths: string[][];
4
4
  static usage: import("clipanion").Usage;
5
- resultsDir: string;
5
+ resultsDir: string | undefined;
6
6
  config: string | undefined;
7
+ fastFail: boolean | undefined;
8
+ maxFailures: number | undefined;
9
+ minTestsCount: number | undefined;
10
+ successRate: number | undefined;
11
+ knownIssues: string | undefined;
7
12
  cwd: string | undefined;
8
13
  execute(): Promise<void>;
9
14
  }
@@ -1,45 +1,127 @@
1
- import { AllureReport, readConfig } from "@allurereport/core";
1
+ import { AllureReport, QualityGateState, readConfig, stringifyQualityGateResults } from "@allurereport/core";
2
+ import { findMatching } from "@allurereport/directory-watcher";
2
3
  import { Command, Option } from "clipanion";
3
4
  import * as console from "node:console";
4
- import { exit } from "node:process";
5
- import { bold, red } from "yoctocolors";
5
+ import { realpath } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { exit, cwd as processCwd } from "node:process";
8
+ import pm from "picomatch";
9
+ import * as typanion from "typanion";
10
+ import { red } from "yoctocolors";
6
11
  export class QualityGateCommand extends Command {
7
12
  constructor() {
8
13
  super(...arguments);
9
- this.resultsDir = Option.String({ required: true, name: "The directory with Allure results" });
14
+ this.resultsDir = Option.String({
15
+ required: false,
16
+ name: "Pattern to match test results directories in the current working directory (default: ./**/allure-results)",
17
+ });
10
18
  this.config = Option.String("--config,-c", {
11
19
  description: "The path Allure config file",
12
20
  });
21
+ this.fastFail = Option.Boolean("--fast-fail", {
22
+ description: "Force the command to fail if there are any rule failures",
23
+ });
24
+ this.maxFailures = Option.String("--max-failures", {
25
+ description: "The maximum number of rule failures to allow before failing the command",
26
+ validator: typanion.isNumber(),
27
+ });
28
+ this.minTestsCount = Option.String("--min-tests-count", {
29
+ description: "The minimum number of tests to run before validating the quality gate",
30
+ validator: typanion.isNumber(),
31
+ });
32
+ this.successRate = Option.String("--success-rate", {
33
+ description: "The minimum success rate to allow before failing the command",
34
+ validator: typanion.isNumber(),
35
+ });
36
+ this.knownIssues = Option.String("--known-issues", {
37
+ description: "Path to the known issues file. Updates the file and quarantines failed tests when specified",
38
+ });
13
39
  this.cwd = Option.String("--cwd", {
14
40
  description: "The working directory for the command to run (default: current working directory)",
15
41
  });
16
42
  }
17
43
  async execute() {
18
- const fullConfig = await readConfig(this.cwd, this.config);
19
- const allureReport = new AllureReport(fullConfig);
20
- await allureReport.start();
21
- await allureReport.readDirectory(this.resultsDir);
22
- await allureReport.done();
23
- await allureReport.validate();
24
- if (allureReport.exitCode === 0) {
44
+ const cwd = await realpath(this.cwd ?? processCwd());
45
+ const resultsDir = (this.resultsDir ?? "./**/allure-results").replace(/[\\/]$/, "");
46
+ const { maxFailures, minTestsCount, successRate, fastFail, knownIssues: knownIssuesPath } = this;
47
+ const config = await readConfig(cwd, this.config, {
48
+ knownIssuesPath,
49
+ });
50
+ const rules = {};
51
+ const resultsDirectories = new Set();
52
+ const matcher = pm(resultsDir, {
53
+ dot: true,
54
+ contains: true,
55
+ });
56
+ if (maxFailures !== undefined) {
57
+ rules.maxFailures = maxFailures;
58
+ }
59
+ if (minTestsCount !== undefined) {
60
+ rules.minTestsCount = minTestsCount;
61
+ }
62
+ if (successRate !== undefined) {
63
+ rules.successRate = successRate;
64
+ }
65
+ if (fastFail) {
66
+ rules.fastFail = fastFail;
67
+ }
68
+ config.plugins = [];
69
+ if (Object.keys(rules).length > 0) {
70
+ config.qualityGate = {
71
+ rules: [rules],
72
+ };
73
+ }
74
+ const allureReport = new AllureReport(config);
75
+ if (!allureReport.hasQualityGate) {
76
+ console.error(red("Quality gate is not configured!"));
77
+ console.error(red("Add qualityGate to the config or consult help to know, how to use the command with command-line arguments"));
78
+ exit(-1);
79
+ return;
80
+ }
81
+ await findMatching(cwd, resultsDirectories, (dirent) => {
82
+ if (dirent.isDirectory()) {
83
+ const fullPath = join(dirent?.parentPath ?? dirent?.path, dirent.name);
84
+ return matcher(fullPath);
85
+ }
86
+ return false;
87
+ });
88
+ if (resultsDirectories.size === 0) {
89
+ console.error("No Allure results directories found");
90
+ exit(0);
25
91
  return;
26
92
  }
27
- const failedResults = allureReport.validationResults.filter((result) => !result.success);
28
- console.error(red(`Quality gate has failed with ${bold(failedResults.length.toString())} errors:\n`));
29
- for (const result of failedResults) {
30
- let scope = "";
31
- switch (result.meta?.type) {
32
- case "label":
33
- scope = `(label[${result.meta.name}="${result.meta.value}"])`;
34
- break;
35
- case "parameter":
36
- scope = `(parameter[${result.meta.name}="${result.meta.value}"])`;
37
- break;
93
+ const knownIssues = await allureReport.store.allKnownIssues();
94
+ const state = new QualityGateState();
95
+ allureReport.realtimeSubscriber.onTestResults(async (trsIds) => {
96
+ const trs = await Promise.all(trsIds.map((id) => allureReport.store.testResultById(id)));
97
+ const notHiddenTrs = trs.filter((tr) => !tr.hidden);
98
+ const { results, fastFailed } = await allureReport.validate({
99
+ trs: notHiddenTrs,
100
+ knownIssues,
101
+ state,
102
+ });
103
+ if (!fastFailed) {
104
+ return;
38
105
  }
39
- console.error(red(`⨯ ${bold(`${result.rule}${scope}`)}: expected ${result.expected}, actual ${result.actual}`));
106
+ console.error(stringifyQualityGateResults(results));
107
+ exit(1);
108
+ });
109
+ await allureReport.start();
110
+ for (const dir of resultsDirectories) {
111
+ await allureReport.readDirectory(dir);
112
+ }
113
+ await allureReport.done();
114
+ const allTrs = await allureReport.store.allTestResults({ includeHidden: false });
115
+ const validationResults = await allureReport.validate({
116
+ trs: allTrs,
117
+ knownIssues,
118
+ });
119
+ if (validationResults.results.length === 0) {
120
+ exit(0);
121
+ return;
40
122
  }
41
- console.error(red("\nThe process has been exited with code 1"));
42
- exit(allureReport.exitCode);
123
+ console.error(stringifyQualityGateResults(validationResults.results));
124
+ exit(1);
43
125
  }
44
126
  }
45
127
  QualityGateCommand.paths = [["quality-gate"]];
@@ -0,0 +1,2 @@
1
+ export * from "./pack.js";
2
+ export * from "./unpack.js";
@@ -0,0 +1,2 @@
1
+ export * from "./pack.js";
2
+ export * from "./unpack.js";
@@ -0,0 +1,10 @@
1
+ import { Command } from "clipanion";
2
+ export declare class ResultsPackCommand extends Command {
3
+ #private;
4
+ static paths: string[][];
5
+ static usage: import("clipanion").Usage;
6
+ resultsDir: string | undefined;
7
+ name: string | undefined;
8
+ cwd: string | undefined;
9
+ execute(): Promise<void>;
10
+ }
@@ -0,0 +1,111 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _ResultsPackCommand_instances, _ResultsPackCommand_formatSize;
7
+ import { findMatching } from "@allurereport/directory-watcher";
8
+ import AdmZip from "adm-zip";
9
+ import { Command, Option } from "clipanion";
10
+ import * as console from "node:console";
11
+ import * as fs from "node:fs/promises";
12
+ import { realpath } from "node:fs/promises";
13
+ import { basename, join, resolve } from "node:path";
14
+ import pm from "picomatch";
15
+ import { green, red } from "yoctocolors";
16
+ export class ResultsPackCommand extends Command {
17
+ constructor() {
18
+ super(...arguments);
19
+ _ResultsPackCommand_instances.add(this);
20
+ this.resultsDir = Option.String({
21
+ required: false,
22
+ name: "Pattern to match test results directories in the current working directory (default: ./**/allure-results)",
23
+ });
24
+ this.name = Option.String("--name", {
25
+ description: "The archive name (default: allure-results.zip)",
26
+ });
27
+ this.cwd = Option.String("--cwd", {
28
+ description: "The working directory for the command to run (default: current working directory)",
29
+ });
30
+ }
31
+ async execute() {
32
+ const cwd = await realpath(this.cwd ?? process.cwd());
33
+ const resultsDir = (this.resultsDir ?? "./**/allure-results").replace(/[\\/]$/, "");
34
+ const archiveName = this.name ?? "allure-results.zip";
35
+ const resultsDirectories = new Set();
36
+ const resultsFiles = new Set();
37
+ const matcher = pm(resultsDir, {
38
+ dot: true,
39
+ contains: true,
40
+ });
41
+ await findMatching(cwd, resultsDirectories, (dirent) => {
42
+ if (dirent.isDirectory()) {
43
+ const fullPath = join(dirent?.parentPath ?? dirent?.path, dirent.name);
44
+ return matcher(fullPath);
45
+ }
46
+ return false;
47
+ });
48
+ if (resultsDirectories.size === 0) {
49
+ console.log(red(`No test results directories found matching pattern: ${resultsDir}`));
50
+ return;
51
+ }
52
+ for (const dir of resultsDirectories) {
53
+ const files = await fs.readdir(dir);
54
+ if (files.length === 0) {
55
+ continue;
56
+ }
57
+ for (const file of files) {
58
+ resultsFiles.add(resolve(dir, file));
59
+ }
60
+ }
61
+ const outputPath = join(cwd, archiveName);
62
+ const zip = new AdmZip();
63
+ for (const file of resultsFiles) {
64
+ try {
65
+ const stats = await fs.stat(file);
66
+ if (stats.isFile()) {
67
+ zip.addLocalFile(file, "", basename(file));
68
+ }
69
+ }
70
+ catch (error) {
71
+ console.log(red(`Error adding file ${file} to archive: ${error.message}`));
72
+ }
73
+ }
74
+ try {
75
+ zip.writeZip(outputPath);
76
+ const stats = await fs.stat(outputPath);
77
+ console.log(green(`Archive created successfully: ${outputPath}`));
78
+ console.log(green(`Total size: ${__classPrivateFieldGet(this, _ResultsPackCommand_instances, "m", _ResultsPackCommand_formatSize).call(this, stats.size)}. ${resultsFiles.size} results files have been collected`));
79
+ }
80
+ catch (err) {
81
+ console.log(red(`Error creating archive: ${err.message}`));
82
+ throw err;
83
+ }
84
+ }
85
+ }
86
+ _ResultsPackCommand_instances = new WeakSet(), _ResultsPackCommand_formatSize = function _ResultsPackCommand_formatSize(bytes) {
87
+ const units = ["bytes", "KB", "MB", "GB"];
88
+ let size = bytes;
89
+ let unitIndex = 0;
90
+ while (size >= 1024 && unitIndex < units.length - 1) {
91
+ size /= 1024;
92
+ unitIndex++;
93
+ }
94
+ if (bytes === 0) {
95
+ return "0 bytes";
96
+ }
97
+ return unitIndex === 0 ? `${Math.round(size)} ${units[unitIndex]}` : `${size.toFixed(2)} ${units[unitIndex]}`;
98
+ };
99
+ ResultsPackCommand.paths = [["results", "pack"]];
100
+ ResultsPackCommand.usage = Command.Usage({
101
+ description: "Creates .zip archive with test results",
102
+ category: "Allure Test Results",
103
+ details: "This command creates .zip archive with all test results which can be collected in the project",
104
+ examples: [
105
+ ["results pack", "Creates .zip archive with test results in directories matched to ./**/allure-results pattern"],
106
+ [
107
+ "results pack ./**/foo/**/my-results --name results.zip",
108
+ "Creates results.zip archive with test results in directories matched to ./**/foo/**/my-results pattern",
109
+ ],
110
+ ],
111
+ });
@@ -0,0 +1,9 @@
1
+ import { Command } from "clipanion";
2
+ export declare class ResultsUnpackCommand extends Command {
3
+ static paths: string[][];
4
+ static usage: import("clipanion").Usage;
5
+ output: string;
6
+ archives: string[];
7
+ cwd: string | undefined;
8
+ execute(): Promise<void>;
9
+ }
@@ -0,0 +1,79 @@
1
+ import AdmZip from "adm-zip";
2
+ import { Command, Option } from "clipanion";
3
+ import * as console from "node:console";
4
+ import * as fs from "node:fs/promises";
5
+ import { realpath } from "node:fs/promises";
6
+ import { basename, resolve } from "node:path";
7
+ import { green, red } from "yoctocolors";
8
+ export class ResultsUnpackCommand extends Command {
9
+ constructor() {
10
+ super(...arguments);
11
+ this.output = Option.String("--output", "./allure-results", {
12
+ description: "Output directory where the archives should be unarchived to (default: ./allure-results)",
13
+ });
14
+ this.archives = Option.Rest({
15
+ name: "List of test results archives to extract separated by spaces. If no archives are provided, the command will extract allure-results.zip archive",
16
+ });
17
+ this.cwd = Option.String("--cwd", {
18
+ description: "The working directory for the command to run (default: current working directory)",
19
+ });
20
+ }
21
+ async execute() {
22
+ const cwd = await realpath(this.cwd ?? process.cwd());
23
+ const outputDir = resolve(cwd, this.output);
24
+ const archives = this.archives.length > 0 ? this.archives : ["allure-results.zip"];
25
+ try {
26
+ await fs.mkdir(outputDir, { recursive: true });
27
+ }
28
+ catch (ignored) { }
29
+ let successCount = 0;
30
+ let failCount = 0;
31
+ for (const archivePath of archives) {
32
+ const resolvedPath = resolve(cwd, archivePath);
33
+ try {
34
+ await fs.access(resolvedPath);
35
+ console.log(`Extracting ${resolvedPath} to ${outputDir}`);
36
+ try {
37
+ const zip = new AdmZip(resolvedPath);
38
+ zip.extractAllTo(outputDir, true);
39
+ console.log(green(`Successfully extracted ${basename(resolvedPath)}`));
40
+ successCount++;
41
+ }
42
+ catch (err) {
43
+ console.log(red(`Error extracting ${basename(resolvedPath)}: ${err.message}`));
44
+ failCount++;
45
+ }
46
+ }
47
+ catch (error) {
48
+ console.log(red(`Error accessing archive ${resolvedPath}: ${error.message}`));
49
+ failCount++;
50
+ }
51
+ }
52
+ console.log(green(`Extraction complete. Successfully extracted ${successCount} archive(s).`));
53
+ if (failCount > 0) {
54
+ console.log(red(`Failed to extract ${failCount} archive(s).`));
55
+ return;
56
+ }
57
+ }
58
+ }
59
+ ResultsUnpackCommand.paths = [["results", "unpack"]];
60
+ ResultsUnpackCommand.usage = Command.Usage({
61
+ description: "Extracts test results from .zip archives",
62
+ category: "Allure Test Results",
63
+ details: "This command extracts test results from .zip archives to the specified output directory",
64
+ examples: [
65
+ ["results unpack", "Extract test results from allure-results.zip to the default directory (./allure-results)"],
66
+ [
67
+ "results unpack results.zip",
68
+ "Extract test results from results.zip to the default directory (./allure-results)",
69
+ ],
70
+ [
71
+ "results unpack results1.zip results2.zip results3.zip",
72
+ "Extract test results from multiple archives to the default directory",
73
+ ],
74
+ [
75
+ "results unpack --output ./mydir results1.zip results2.zip results3.zip",
76
+ "Extract test results from multiple archives to the specified directory (./mydir)",
77
+ ],
78
+ ],
79
+ });
@@ -1,4 +1,11 @@
1
+ import type { QualityGateValidationResult } from "@allurereport/plugin-api";
1
2
  import { Command } from "clipanion";
3
+ export type TestProcessResult = {
4
+ code: number | null;
5
+ stdout: string;
6
+ stderr: string;
7
+ qualityGateResults: QualityGateValidationResult[];
8
+ };
2
9
  export declare class RunCommand extends Command {
3
10
  static paths: string[][];
4
11
  static usage: import("clipanion").Usage;
@@ -8,6 +15,8 @@ export declare class RunCommand extends Command {
8
15
  reportName: string | undefined;
9
16
  rerun: string | undefined;
10
17
  silent: boolean | undefined;
18
+ ignoreLogs: boolean | undefined;
11
19
  commandToRun: string[];
20
+ get logs(): "pipe" | "ignore" | "inherit";
12
21
  execute(): Promise<void>;
13
22
  }
@@ -1,19 +1,21 @@
1
- import { AllureReport, isFileNotFoundError, readConfig } from "@allurereport/core";
1
+ import { AllureReport, QualityGateState, isFileNotFoundError, readConfig, stringifyQualityGateResults, } from "@allurereport/core";
2
2
  import { createTestPlan } from "@allurereport/core-api";
3
3
  import { allureResultsDirectoriesWatcher, delayedFileProcessingWatcher, newFilesInDirectoryWatcher, } from "@allurereport/directory-watcher";
4
4
  import Awesome from "@allurereport/plugin-awesome";
5
- import { PathResultFile } from "@allurereport/reader-api";
5
+ import { BufferResultFile, PathResultFile } from "@allurereport/reader-api";
6
6
  import { KnownError } from "@allurereport/service";
7
7
  import { Command, Option } from "clipanion";
8
8
  import * as console from "node:console";
9
9
  import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
10
10
  import { tmpdir } from "node:os";
11
11
  import { join, resolve } from "node:path";
12
- import process from "node:process";
12
+ import process, { exit } from "node:process";
13
+ import terminate from "terminate/promise";
13
14
  import { red } from "yoctocolors";
14
15
  import { logTests, runProcess, terminationOf } from "../utils/index.js";
15
16
  import { logError } from "../utils/logs.js";
16
- const runTests = async (allureReport, cwd, command, commandArgs, environment, silent) => {
17
+ const runTests = async (params) => {
18
+ const { allureReport, knownIssues, cwd, command, commandArgs, logs, environment, withQualityGate, silent } = params;
17
19
  let testProcessStarted = false;
18
20
  const allureResultsWatchers = new Map();
19
21
  const processWatcher = delayedFileProcessingWatcher(async (path) => {
@@ -47,17 +49,83 @@ const runTests = async (allureReport, cwd, command, commandArgs, environment, si
47
49
  await allureResultsWatch.initialScan();
48
50
  testProcessStarted = true;
49
51
  const beforeProcess = Date.now();
50
- const testProcess = runProcess(command, commandArgs, cwd, environment, silent);
52
+ const testProcess = runProcess({
53
+ command,
54
+ commandArgs,
55
+ cwd,
56
+ environment,
57
+ logs,
58
+ });
59
+ const qualityGateState = new QualityGateState();
60
+ let qualityGateUnsub;
61
+ let qualityGateResults = [];
62
+ let testProcessStdout = "";
63
+ let testProcessStderr = "";
64
+ if (withQualityGate) {
65
+ qualityGateUnsub = allureReport.realtimeSubscriber.onTestResults(async (testResults) => {
66
+ const trs = await Promise.all(testResults.map((tr) => allureReport.store.testResultById(tr)));
67
+ const filteredTrs = trs.filter((tr) => tr !== undefined);
68
+ if (!filteredTrs.length) {
69
+ return;
70
+ }
71
+ const { results, fastFailed } = await allureReport.validate({
72
+ trs: filteredTrs,
73
+ state: qualityGateState,
74
+ knownIssues,
75
+ });
76
+ if (!fastFailed) {
77
+ return;
78
+ }
79
+ allureReport.realtimeDispatcher.sendQualityGateResults(results);
80
+ qualityGateResults = results;
81
+ try {
82
+ await terminate(testProcess.pid, "SIGTERM");
83
+ }
84
+ catch (err) {
85
+ if (err.message.includes("kill ESRCH")) {
86
+ return;
87
+ }
88
+ throw err;
89
+ }
90
+ });
91
+ }
92
+ if (logs === "pipe") {
93
+ testProcess.stdout?.setEncoding("utf8").on?.("data", (data) => {
94
+ testProcessStdout += data;
95
+ if (silent) {
96
+ return;
97
+ }
98
+ process.stdout.write(data);
99
+ });
100
+ testProcess.stderr?.setEncoding("utf8").on?.("data", async (data) => {
101
+ testProcessStderr += data;
102
+ if (silent) {
103
+ return;
104
+ }
105
+ process.stderr.write(data);
106
+ });
107
+ }
51
108
  const code = await terminationOf(testProcess);
52
109
  const afterProcess = Date.now();
53
- console.log(`process finished with code ${code ?? 0} (${afterProcess - beforeProcess})ms`);
110
+ if (code !== null) {
111
+ console.log(`process finished with code ${code} (${afterProcess - beforeProcess}ms)`);
112
+ }
113
+ else {
114
+ console.log(`process terminated (${afterProcess - beforeProcess}ms)`);
115
+ }
54
116
  await allureResultsWatch.abort();
55
117
  for (const [ar, watcher] of allureResultsWatchers) {
56
118
  await watcher.abort();
57
119
  allureResultsWatchers.delete(ar);
58
120
  }
59
121
  await processWatcher.abort();
60
- return code;
122
+ qualityGateUnsub?.();
123
+ return {
124
+ code,
125
+ stdout: testProcessStdout,
126
+ stderr: testProcessStderr,
127
+ qualityGateResults,
128
+ };
61
129
  };
62
130
  export class RunCommand extends Command {
63
131
  constructor() {
@@ -80,7 +148,16 @@ export class RunCommand extends Command {
80
148
  this.silent = Option.Boolean("--silent", {
81
149
  description: "Don't pipe the process output logs to console (default: 0)",
82
150
  });
83
- this.commandToRun = Option.Proxy();
151
+ this.ignoreLogs = Option.Boolean("--ignore-logs", {
152
+ description: "Prevent logs attaching to the report (default: false)",
153
+ });
154
+ this.commandToRun = Option.Rest();
155
+ }
156
+ get logs() {
157
+ if (this.silent) {
158
+ return this.ignoreLogs ? "ignore" : "pipe";
159
+ }
160
+ return this.ignoreLogs ? "inherit" : "pipe";
84
161
  }
85
162
  async execute() {
86
163
  const args = this.commandToRun.filter((arg) => arg !== "--");
@@ -97,8 +174,14 @@ export class RunCommand extends Command {
97
174
  const cwd = await realpath(this.cwd ?? process.cwd());
98
175
  console.log(`${command} ${commandArgs.join(" ")}`);
99
176
  const maxRerun = this.rerun ? parseInt(this.rerun, 10) : 0;
100
- const silent = this.silent ?? false;
101
177
  const config = await readConfig(cwd, this.config, { output: this.output, name: this.reportName });
178
+ const withQualityGate = !!config.qualityGate;
179
+ const withRerun = !!this.rerun;
180
+ if (withQualityGate && withRerun) {
181
+ console.error(red("At this moment, quality gate and rerun can't be used at the same time!"));
182
+ console.error(red("Consider using --rerun=0 or disable quality gate in the config to run tests"));
183
+ exit(-1);
184
+ }
102
185
  try {
103
186
  await rm(config.output, { recursive: true });
104
187
  }
@@ -107,27 +190,44 @@ export class RunCommand extends Command {
107
190
  console.error("could not clean output directory", e);
108
191
  }
109
192
  }
193
+ const allureReport = new AllureReport({
194
+ ...config,
195
+ realTime: false,
196
+ plugins: [
197
+ ...(config.plugins?.length
198
+ ? config.plugins
199
+ : [
200
+ {
201
+ id: "awesome",
202
+ enabled: true,
203
+ options: {},
204
+ plugin: new Awesome({
205
+ reportName: config.name,
206
+ }),
207
+ },
208
+ ]),
209
+ ],
210
+ });
211
+ const knownIssues = await allureReport.store.allKnownIssues();
212
+ await allureReport.start();
213
+ const globalExitCode = {
214
+ original: 0,
215
+ actual: undefined,
216
+ };
217
+ let qualityGateResults;
218
+ let testProcessResult = null;
110
219
  try {
111
- const allureReport = new AllureReport({
112
- ...config,
113
- realTime: false,
114
- plugins: [
115
- ...(config.plugins?.length
116
- ? config.plugins
117
- : [
118
- {
119
- id: "awesome",
120
- enabled: true,
121
- options: {},
122
- plugin: new Awesome({
123
- reportName: config.name,
124
- }),
125
- },
126
- ]),
127
- ],
220
+ testProcessResult = await runTests({
221
+ logs: this.logs,
222
+ silent: this.silent,
223
+ allureReport,
224
+ knownIssues,
225
+ cwd,
226
+ command,
227
+ commandArgs,
228
+ environment: {},
229
+ withQualityGate,
128
230
  });
129
- await allureReport.start();
130
- let code = await runTests(allureReport, cwd, command, commandArgs, {}, silent);
131
231
  for (let rerun = 0; rerun < maxRerun; rerun++) {
132
232
  const failed = await allureReport.store.failedTestResults();
133
233
  if (failed.length === 0) {
@@ -140,26 +240,78 @@ export class RunCommand extends Command {
140
240
  const tmpDir = await mkdtemp(join(tmpdir(), "allure-run-"));
141
241
  const testPlanPath = resolve(tmpDir, `${rerun}-testplan.json`);
142
242
  await writeFile(testPlanPath, JSON.stringify(testPlan));
143
- code = await runTests(allureReport, cwd, command, commandArgs, {
144
- ALLURE_TESTPLAN_PATH: testPlanPath,
145
- ALLURE_RERUN: `${rerun}`,
146
- }, silent);
243
+ testProcessResult = await runTests({
244
+ silent: this.silent,
245
+ logs: this.logs,
246
+ allureReport,
247
+ knownIssues,
248
+ cwd,
249
+ command,
250
+ commandArgs,
251
+ environment: {
252
+ ALLURE_TESTPLAN_PATH: testPlanPath,
253
+ ALLURE_RERUN: `${rerun}`,
254
+ },
255
+ withQualityGate,
256
+ });
147
257
  await rm(tmpDir, { recursive: true });
148
258
  logTests(await allureReport.store.allTestResults());
149
259
  }
150
- await allureReport.done();
151
- await allureReport.validate();
152
- process.exit(code ?? allureReport.exitCode);
260
+ const trs = await allureReport.store.allTestResults({ includeHidden: false });
261
+ qualityGateResults = testProcessResult?.qualityGateResults ?? [];
262
+ if (withQualityGate && !qualityGateResults?.length) {
263
+ const { results } = await allureReport.validate({
264
+ trs,
265
+ knownIssues,
266
+ });
267
+ qualityGateResults = results;
268
+ }
269
+ if (qualityGateResults?.length) {
270
+ const qualityGateMessage = stringifyQualityGateResults(qualityGateResults);
271
+ console.error(qualityGateMessage);
272
+ allureReport.realtimeDispatcher.sendQualityGateResults(qualityGateResults);
273
+ }
274
+ globalExitCode.original = testProcessResult?.code ?? -1;
275
+ if (withQualityGate) {
276
+ globalExitCode.actual = qualityGateResults.length > 0 ? 1 : 0;
277
+ }
153
278
  }
154
279
  catch (error) {
280
+ globalExitCode.actual = 1;
155
281
  if (error instanceof KnownError) {
156
282
  console.error(red(error.message));
157
- process.exit(1);
158
- return;
283
+ allureReport.realtimeDispatcher.sendGlobalError({
284
+ message: error.message,
285
+ });
286
+ }
287
+ else {
288
+ await logError("Failed to run tests using Allure due to unexpected error", error);
289
+ allureReport.realtimeDispatcher.sendGlobalError({
290
+ message: error.message,
291
+ trace: error.stack,
292
+ });
293
+ }
294
+ }
295
+ const processFailed = Math.abs(globalExitCode.actual ?? globalExitCode.original) !== 0;
296
+ if (!this.ignoreLogs && testProcessResult?.stdout) {
297
+ const stdoutResultFile = new BufferResultFile(Buffer.from(testProcessResult.stdout, "utf8"), "stdout.txt");
298
+ stdoutResultFile.contentType = "text/plain";
299
+ allureReport.realtimeDispatcher.sendGlobalAttachment(stdoutResultFile);
300
+ }
301
+ if (!this.ignoreLogs && testProcessResult?.stderr) {
302
+ const stderrResultFile = new BufferResultFile(Buffer.from(testProcessResult.stderr, "utf8"), "stderr.txt");
303
+ stderrResultFile.contentType = "text/plain";
304
+ allureReport.realtimeDispatcher.sendGlobalAttachment(stderrResultFile);
305
+ if (processFailed) {
306
+ allureReport.realtimeDispatcher.sendGlobalError({
307
+ message: "Test process has failed",
308
+ trace: testProcessResult.stderr,
309
+ });
159
310
  }
160
- await logError("Failed to run tests using Allure due to unexpected error", error);
161
- process.exit(1);
162
311
  }
312
+ allureReport.realtimeDispatcher.sendGlobalExitCode(globalExitCode);
313
+ await allureReport.done();
314
+ exit(globalExitCode.actual ?? globalExitCode.original);
163
315
  }
164
316
  }
165
317
  RunCommand.paths = [["run"]];
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { Builtins, Cli } from "clipanion";
2
2
  import console from "node:console";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { argv, cwd } from "node:process";
5
- import { Allure2Command, AwesomeCommand, ClassicCommand, CsvCommand, DashboardCommand, GenerateCommand, HistoryCommand, KnownIssueCommand, LogCommand, LoginCommand, LogoutCommand, OpenCommand, ProjectsCreateCommand, ProjectsDeleteCommand, ProjectsListCommand, QualityGateCommand, RunCommand, SlackCommand, TestPlanCommand, WatchCommand, WhoamiCommand, } from "./commands/index.js";
5
+ import { Allure2Command, AwesomeCommand, ClassicCommand, CsvCommand, DashboardCommand, GenerateCommand, HistoryCommand, KnownIssueCommand, LogCommand, LoginCommand, LogoutCommand, OpenCommand, ProjectsCreateCommand, ProjectsDeleteCommand, ProjectsListCommand, QualityGateCommand, ResultsPackCommand, ResultsUnpackCommand, RunCommand, SlackCommand, TestPlanCommand, WatchCommand, WhoamiCommand, } from "./commands/index.js";
6
6
  const [node, app, ...args] = argv;
7
7
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
8
8
  const cli = new Cli({
@@ -31,6 +31,8 @@ cli.register(WhoamiCommand);
31
31
  cli.register(ProjectsCreateCommand);
32
32
  cli.register(ProjectsDeleteCommand);
33
33
  cli.register(ProjectsListCommand);
34
+ cli.register(ResultsPackCommand);
35
+ cli.register(ResultsUnpackCommand);
34
36
  cli.register(Builtins.HelpCommand);
35
37
  cli.runExit(args);
36
38
  console.log(cwd());
@@ -1,3 +1,9 @@
1
1
  import type { ChildProcess } from "node:child_process";
2
- export declare const runProcess: (command: string, commandArgs: string[], cwd: string | undefined, environment: Record<string, string>, silent?: boolean) => ChildProcess;
2
+ export declare const runProcess: (params: {
3
+ command: string;
4
+ commandArgs: string[];
5
+ cwd: string | undefined;
6
+ environment?: Record<string, string>;
7
+ logs?: "pipe" | "inherit" | "ignore";
8
+ }) => ChildProcess;
3
9
  export declare const terminationOf: (testProcess: ChildProcess) => Promise<number | null>;
@@ -1,12 +1,23 @@
1
1
  import { spawn } from "node:child_process";
2
- export const runProcess = (command, commandArgs, cwd, environment, silent) => {
2
+ export const runProcess = (params) => {
3
+ const { command, commandArgs, cwd, environment = {}, logs = "inherit" } = params;
4
+ const env = {
5
+ ...process.env,
6
+ ...environment,
7
+ };
8
+ if (logs === "pipe") {
9
+ Object.assign(env, {
10
+ FORCE_COLOR: "1",
11
+ CLICOLOR_FORCE: "1",
12
+ COLOR: "1",
13
+ COLORTERM: "truecolor",
14
+ TERM: "xterm-256color",
15
+ });
16
+ }
3
17
  return spawn(command, commandArgs, {
4
- env: {
5
- ...process.env,
6
- ...environment,
7
- },
18
+ env,
8
19
  cwd,
9
- stdio: silent ? "ignore" : "inherit",
20
+ stdio: logs,
10
21
  shell: true,
11
22
  });
12
23
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "allure",
3
- "version": "3.0.0-beta.17",
3
+ "version": "3.0.0-beta.18",
4
4
  "description": "Allure Commandline Tool",
5
5
  "keywords": [
6
6
  "allure",
@@ -12,7 +12,8 @@
12
12
  "author": "Qameta Software",
13
13
  "type": "module",
14
14
  "exports": {
15
- ".": "./dist/index.js"
15
+ ".": "./dist/index.js",
16
+ "./qualityGate": "./dist/qualityGate.js"
16
17
  },
17
18
  "main": "./dist/index.js",
18
19
  "module": "./dist/index.js",
@@ -30,38 +31,44 @@
30
31
  "test": "vitest run"
31
32
  },
32
33
  "dependencies": {
33
- "@allurereport/core": "3.0.0-beta.17",
34
- "@allurereport/core-api": "3.0.0-beta.17",
35
- "@allurereport/directory-watcher": "3.0.0-beta.17",
36
- "@allurereport/plugin-allure2": "3.0.0-beta.17",
37
- "@allurereport/plugin-api": "3.0.0-beta.17",
38
- "@allurereport/plugin-awesome": "3.0.0-beta.17",
39
- "@allurereport/plugin-classic": "3.0.0-beta.17",
40
- "@allurereport/plugin-csv": "3.0.0-beta.17",
41
- "@allurereport/plugin-dashboard": "3.0.0-beta.17",
42
- "@allurereport/plugin-log": "3.0.0-beta.17",
43
- "@allurereport/plugin-progress": "3.0.0-beta.17",
44
- "@allurereport/plugin-server-reload": "3.0.0-beta.17",
45
- "@allurereport/plugin-slack": "3.0.0-beta.17",
46
- "@allurereport/reader-api": "3.0.0-beta.17",
47
- "@allurereport/service": "3.0.0-beta.17",
48
- "@allurereport/static-server": "3.0.0-beta.17",
34
+ "@allurereport/core": "3.0.0-beta.18",
35
+ "@allurereport/core-api": "3.0.0-beta.18",
36
+ "@allurereport/directory-watcher": "3.0.0-beta.18",
37
+ "@allurereport/plugin-allure2": "3.0.0-beta.18",
38
+ "@allurereport/plugin-api": "3.0.0-beta.18",
39
+ "@allurereport/plugin-awesome": "3.0.0-beta.18",
40
+ "@allurereport/plugin-classic": "3.0.0-beta.18",
41
+ "@allurereport/plugin-csv": "3.0.0-beta.18",
42
+ "@allurereport/plugin-dashboard": "3.0.0-beta.18",
43
+ "@allurereport/plugin-log": "3.0.0-beta.18",
44
+ "@allurereport/plugin-progress": "3.0.0-beta.18",
45
+ "@allurereport/plugin-server-reload": "3.0.0-beta.18",
46
+ "@allurereport/plugin-slack": "3.0.0-beta.18",
47
+ "@allurereport/reader-api": "3.0.0-beta.18",
48
+ "@allurereport/service": "3.0.0-beta.18",
49
+ "@allurereport/static-server": "3.0.0-beta.18",
50
+ "adm-zip": "^0.5.16",
49
51
  "clipanion": "^4.0.0-rc.4",
50
52
  "lodash.omit": "^4.5.0",
53
+ "picomatch": "^4.0.3",
51
54
  "prompts": "^2.4.2",
55
+ "terminate": "^2.8.0",
56
+ "typanion": "^3.14.0",
52
57
  "yoctocolors": "^2.1.1"
53
58
  },
54
59
  "devDependencies": {
55
60
  "@stylistic/eslint-plugin": "^2.6.1",
61
+ "@types/adm-zip": "^0",
56
62
  "@types/eslint": "^8.56.11",
57
63
  "@types/lodash.omit": "^4.5.9",
58
64
  "@types/node": "^20.17.9",
65
+ "@types/picomatch": "^4",
59
66
  "@types/prompts": "^2",
60
67
  "@typescript-eslint/eslint-plugin": "^8.0.0",
61
68
  "@typescript-eslint/parser": "^8.0.0",
62
69
  "@vitest/runner": "^2.1.9",
63
70
  "@vitest/snapshot": "^2.1.9",
64
- "allure-vitest": "^3.3.0",
71
+ "allure-vitest": "^3.3.3",
65
72
  "eslint": "^8.57.0",
66
73
  "eslint-config-prettier": "^9.1.0",
67
74
  "eslint-plugin-import": "^2.29.1",