Skip to content

Commit

Permalink
add configuration option to provide labels to all the tests (via #1217)
Browse files Browse the repository at this point in the history
  • Loading branch information
epszaw authored Jan 14, 2025
1 parent 2de0a93 commit a1569ff
Show file tree
Hide file tree
Showing 14 changed files with 343 additions and 17 deletions.
36 changes: 36 additions & 0 deletions packages/allure-cucumberjs/test/spec/globalLabels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, it } from "vitest";
import { runCucumberInlineTest } from "../utils.js";

it("should handle global labels", async () => {
const { tests } = await runCucumberInlineTest(
["examples"],
["examples"],
undefined,
(reporterFilePath) => `
module.exports = {
default: {
paths: ["./**/*.feature"],
format: ["summary", "${reporterFilePath}"],
formatOptions: {
globalLabels: [
{
name: "foo",
value: "bar"
}
]
}
}
}
`,
);

expect(tests).toHaveLength(2);
expect(tests[0].labels[0]).toEqual({
name: "foo",
value: "bar",
});
expect(tests[1].labels[0]).toEqual({
name: "foo",
value: "bar",
});
});
22 changes: 14 additions & 8 deletions packages/allure-cucumberjs/test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,23 @@ export const runCucumberInlineTest = async (
features: string[],
stepsDefs: string[],
{ parallel = true, testPlan, env, cwd }: CucumberRunOptions = {},
configFactory?: (reporterPath: string) => string,
): Promise<AllureResults> => {
const samplesPath = join(__dirname, "samples");
const testDir = join(__dirname, "fixtures", randomUUID());
const configFilePath = join(testDir, "config.js");
const reporterFilePath = require.resolve("allure-cucumberjs/reporter");
const reporterFilePath = pathToFileURL(require.resolve("allure-cucumberjs/reporter")).toString();
const featuresTempPath = join(testDir, "features");
const supportTempPath = join(testDir, "features/support");
const worldFilePath = join(supportTempPath, "world.js");
const configContent = `
const configContent = configFactory
? configFactory(reporterFilePath)
: `
module.exports = {
default: {
paths: ["./**/*.feature"],
${parallel ? "parallel: 4," : ""}
format: ["summary", '"${pathToFileURL(reporterFilePath).toString()}":"ignore.txt"'],
format: ["summary", '"${reporterFilePath}":"ignore.txt"'],
formatOptions: {
labels: [
{
Expand All @@ -57,11 +60,14 @@ export const runCucumberInlineTest = async (
"app version": "123.0.1",
"some other key": "some other value"
},
categories: [{
name: "first"
},{
name: "second"
}],
categories: [
{
name: "first"
},
{
name: "second"
}
],
}
}
}
Expand Down
43 changes: 43 additions & 0 deletions packages/allure-cypress/test/spec/globalLabels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect, it } from "vitest";
import { runCypressInlineTest } from "../utils.js";

it("should handle global labels", async () => {
const { tests } = await runCypressInlineTest({
"cypress/e2e/sample.cy.js": () => `
it("passed", () => {
cy.wrap(1).should("eq", 1);
});
`,
"cypress.config.js": ({ allureCypressReporterModulePath, supportFilePath, specPattern, allureDirPath }) => `
const { allureCypress } = require("${allureCypressReporterModulePath}");
module.exports = {
e2e: {
baseUrl: "https://allurereport.org",
supportFile: "${supportFilePath}",
specPattern: "${specPattern}",
viewportWidth: 1240,
setupNodeEvents: (on, config) => {
allureCypress(on, config, {
resultsDir: "${allureDirPath}",
globalLabels: [
{
name: "foo",
value: "bar"
}
]
});
return config;
},
},
};
`,
});

expect(tests).toHaveLength(1);
expect(tests[0].labels[0]).toEqual({
name: "foo",
value: "bar",
});
});
33 changes: 33 additions & 0 deletions packages/allure-jasmine/test/spec/globalLabels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect, it } from "vitest";
import { runJasmineInlineTest } from "../utils.js";

it("should handle global labels", async () => {
const { tests } = await runJasmineInlineTest({
"spec/sample.spec.js": `
it("should pass 1", () => {
expect(true).toBe(true);
});
`,
"spec/helpers/allure.js": `
const AllureJasmineReporter = require("allure-jasmine");
const reporter = new AllureJasmineReporter({
testMode: true,
globalLabels: [
{
name: "foo",
value: "bar"
}
]
});
jasmine.getEnv().addReporter(reporter);
`,
});

expect(tests).toHaveLength(1);
expect(tests[0].labels[0]).toEqual({
name: "foo",
value: "bar",
});
});
34 changes: 34 additions & 0 deletions packages/allure-jest/test/spec/globalLabels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, it } from "vitest";
import { runJestInlineTest } from "../utils.js";

it("should handle global labels", async () => {
const { tests } = await runJestInlineTest({
"sample.spec.js": `
it("should pass", () => {
expect(true).toBe(true);
});
`,
"jest.config.js": ({ allureJestNodePath }) => `
const config = {
bail: false,
testEnvironment: "${allureJestNodePath}",
testEnvironmentOptions: {
globalLabels: [
{
name: "foo",
value: "bar"
}
]
},
};
module.exports = config;
`,
});

expect(tests).toHaveLength(1);
expect(tests[0].labels[0]).toEqual({
name: "foo",
value: "bar",
});
});
22 changes: 17 additions & 5 deletions packages/allure-jest/test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,21 @@ import { attachment, step } from "allure-js-commons";
import type { AllureResults } from "allure-js-commons/sdk";
import { MessageReader, getPosixPath } from "allure-js-commons/sdk/reporter";

type TestFileWriter = (opts: { allureJestNodePath: string }) => string;

type TestFiles = Record<string, string | TestFileWriter>;

export const runJestInlineTest = async (
testFiles: Record<string, string>,
testFiles: TestFiles,
env?: (testDir: string) => Record<string, string>,
cliArgs?: string[],
): Promise<AllureResults> => {
const testDir = join(__dirname, "fixtures", randomUUID());
const configFileName = "jest.config.js";
const configFilePath = join(testDir, configFileName);

const allureJestNode = require.resolve("allure-jest/node");
const allureJestNodePath = getPosixPath(relative(testDir, allureJestNode));
const testFilesToWrite: Record<string, string> = {
const testFilesToWrite: TestFiles = {
"jest.config.js": `
const config = {
bail: false,
Expand Down Expand Up @@ -56,10 +59,19 @@ export const runJestInlineTest = async (
for (const testFile in testFilesToWrite) {
await step(testFile, async () => {
const testFilePath = join(testDir, testFile);
let testFileContent: string;

if (typeof testFilesToWrite[testFile] === "string") {
testFileContent = testFilesToWrite[testFile] as string;
} else {
testFileContent = (testFilesToWrite[testFile] as TestFileWriter)({
allureJestNodePath,
});
}

await mkdir(dirname(testFilePath), { recursive: true });
await writeFile(join(testDir, testFile), testFilesToWrite[testFile], "utf8");
await attachment(testFile, testFilesToWrite[testFile], {
await writeFile(join(testDir, testFile), testFileContent, "utf8");
await attachment(testFile, testFileContent, {
contentType: "text/plain",
encoding: "utf-8",
fileExtension: extname(testFile),
Expand Down
24 changes: 22 additions & 2 deletions packages/allure-js-commons/src/sdk/reporter/ReporterRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type Attachment,
type AttachmentOptions,
type FixtureResult,
type Label,
Stage,
type StepResult,
type TestResult,
Expand Down Expand Up @@ -104,13 +105,15 @@ export class ReporterRuntime {
categories?: Category[];
environmentInfo?: EnvironmentInfo;
linkConfig?: LinkConfig;
globalLabels: Label[] = [];

constructor({ writer, listeners = [], environmentInfo, categories, links }: ReporterRuntimeConfig) {
constructor({ writer, listeners = [], environmentInfo, categories, links, globalLabels }: ReporterRuntimeConfig) {
this.writer = resolveWriter(writer);
this.notifier = new Notifier({ listeners });
this.categories = categories;
this.environmentInfo = environmentInfo;
this.linkConfig = links;
this.globalLabels = globalLabels ?? [];
}

startScope = (): string => {
Expand Down Expand Up @@ -238,33 +241,43 @@ export class ReporterRuntime {
const testResult = wrapped.value;

this.notifier.beforeTestResultStop(testResult);

testResult.testCaseId ??= getTestResultTestCaseId(testResult);
testResult.historyId ??= getTestResultHistoryId(testResult);

const startStop = this.#calculateTimings(testResult.start, opts?.stop, opts?.duration);

testResult.start = startStop.start;
testResult.stop = startStop.stop;

const scopeUuids = wrapped.scopeUuids;

scopeUuids.forEach((scopeUuid) => {
const scope = this.state.getScope(scopeUuid);

if (scope?.labels) {
testResult.labels = [...testResult.labels, ...scope.labels];
}

if (scope?.links) {
testResult.links = [...testResult.links, ...scope.links];
}

if (scope?.parameters) {
testResult.parameters = [...testResult.parameters, ...scope.parameters];
}

if (scope?.description) {
testResult.description = testResult.description ?? scope.description;
}

if (scope?.descriptionHtml) {
testResult.descriptionHtml = testResult.descriptionHtml ?? scope.descriptionHtml;
}
});

testResult.labels = [...this.globalLabels, ...testResult.labels];

this.notifier.afterTestResultStop(testResult);
};

Expand Down Expand Up @@ -642,7 +655,14 @@ export class ReporterRuntime {
});
};

#calculateTimings = (start?: number, stop?: number, duration?: number): { start?: number; stop?: number } => {
#calculateTimings = (
start?: number,
stop?: number,
duration?: number,
): {
start?: number;
stop?: number;
} => {
const result: { start?: number; stop?: number } = { start, stop };
if (duration) {
const normalisedDuration = Math.max(0, duration);
Expand Down
1 change: 1 addition & 0 deletions packages/allure-js-commons/src/sdk/reporter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export type WriterDescriptor = [cls: string, ...args: readonly unknown[]] | stri
export interface ReporterConfig {
readonly resultsDir?: string;
readonly links?: LinkConfig;
readonly globalLabels?: Label[];
readonly listeners?: LifecycleListener[];
readonly environmentInfo?: EnvironmentInfo;
readonly categories?: Category[];
Expand Down
2 changes: 1 addition & 1 deletion packages/allure-mocha/test/samples/reporter.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class ProcessMessageAllureReporter extends AllureMochaReporter {
if (opts.reporterOptions?.emitFiles !== "true") {
(opts.reporterOptions ??= {}).writer = "MessageWriter";
}
for (const key of ["environmentInfo", "categories", "extraReporters"]) {
for (const key of ["environmentInfo", "categories", "extraReporters", "globalLabels"]) {
if (typeof opts.reporterOptions?.[key] === "string") {
opts.reporterOptions[key] = JSON.parse(Buffer.from(opts.reporterOptions[key], "base64Url").toString());
}
Expand Down
3 changes: 3 additions & 0 deletions packages/allure-mocha/test/samples/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ for (let i = 0; i < args.length; i++) {
case "--extra-reporters":
reporterOptions.extraReporters = JSON.parse(Buffer.from(args[++i], "base64url").toString());
break;
case "--global-labels":
reporterOptions.globalLabels = JSON.parse(Buffer.from(args[++i], "base64url").toString());
break;
}
}

Expand Down
29 changes: 29 additions & 0 deletions packages/allure-mocha/test/spec/framework/globalLabels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { beforeAll, describe, expect, it } from "vitest";
import type { AllureResults } from "allure-js-commons/sdk";
import { runMochaInlineTest } from "../../utils.js";

describe("global labels", () => {
let results: AllureResults;

beforeAll(async () => {
results = await runMochaInlineTest(
{
globalLabels: [
{
name: "foo",
value: "bar",
},
],
},
["plain-mocha", "testInSuite"],
);
});

it("should handle global labels", () => {
expect(results.tests).toHaveLength(1);
expect(results.tests[0].labels[0]).toEqual({
name: "foo",
value: "bar",
});
});
});
Loading

0 comments on commit a1569ff

Please sign in to comment.