-
Notifications
You must be signed in to change notification settings - Fork 110
/
fixtures.ts
167 lines (153 loc) · 5.55 KB
/
fixtures.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fork } from "child_process";
import { mkdir, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { test as base, TestInfo } from "@playwright/test";
import type { AllureResults } from "allure-js-commons";
import { parse } from "properties";
import { allure } from "allure-playwright";
export { expect } from "@playwright/test";
type RunResult = any;
type Files = { [key: string]: string | Buffer };
type Params = { [key: string]: string | number | boolean | string[] };
type Env = { [key: string]: string | number | boolean | undefined };
const writeFiles = async (testInfo: TestInfo, files: Files) => {
const baseDir = testInfo.outputPath();
const hasConfig = Object.keys(files).some((name) => name.includes(".config."));
const reporterOptions = files.reporterOptions && JSON.parse(files.reporterOptions.toString());
if (!hasConfig) {
files = {
...files,
"playwright.config.ts": `
module.exports = {
projects: [{ name: 'project' }],
grep: require("../../dist/testplan.js").testPlanFilter(),
reporter: [[require.resolve("../../dist/index.js"),
${JSON.stringify(reporterOptions || false)} || undefined], ["dot"]],
};
`,
};
}
await Promise.all(
Object.keys(files).map(async (name) => {
const fullName = join(baseDir, name);
await allure.attachment(name, Buffer.from(files[name]), "text/plain");
await mkdir(dirname(fullName), { recursive: true });
await writeFile(fullName, files[name]);
}),
);
return baseDir;
};
const runPlaywrightTest = async (
baseDir: string,
params: any,
env: Env,
): Promise<AllureResults> => {
const paramList = [];
let additionalArgs = "";
for (const key of Object.keys(params)) {
if (key === "args") {
additionalArgs = params[key];
continue;
}
for (const value of Array.isArray(params[key]) ? params[key] : [params[key]]) {
const k = key.startsWith("-") ? key : `--${key}`;
paramList.push(params[key] === true ? `${k}` : `${k}=${value}`);
}
}
const outputDir = join(baseDir, "test-results");
const args = ["test"];
args.push(`--output=${outputDir}`, "--workers=2", ...paramList);
if (additionalArgs) {
args.push(additionalArgs);
}
const modulePath = require.resolve("@playwright/test/lib/cli");
await allure.logStep(`${modulePath} ${args.join(" ")}`);
const testProcess = fork(modulePath, args, {
env: {
...process.env,
...env,
PW_ALLURE_POST_PROCESSOR_FOR_TEST: String("true"),
},
cwd: baseDir,
stdio: "pipe",
});
const results: AllureResults = { tests: [], groups: [], attachments: {} };
testProcess.on("message", (message) => {
const event: { path: string; type: string; data: string } = JSON.parse(message.toString());
switch (event.type) {
case "result": {
results.tests.push(JSON.parse(Buffer.from(event.data, "base64").toString()));
break;
}
case "container": {
results.groups.push(JSON.parse(Buffer.from(event.data, "base64").toString()));
break;
}
case "attachment": {
results.attachments[event.path] = event.data;
break;
}
case "misc": {
if (event.path === "environment.properties") {
results.envInfo = parse(Buffer.from(event.data, "base64").toString());
} else if (event.path === "categories.json") {
results.categories = JSON.parse(Buffer.from(event.data, "base64").toString());
}
}
}
});
testProcess.stdout?.on("data", (chunk) => {
process.stdout.write(String(chunk));
});
testProcess.stderr?.on("data", (chunk) => {
process.stderr.write(String(chunk));
});
await new Promise<number>((x) => testProcess.on("close", x));
return results;
};
type Fixtures = {
runInlineTest: (files: Files, params?: Params, env?: Env) => Promise<AllureResults>;
attachment: (name: string) => string;
};
export const test = base.extend<Fixtures>({
// eslint-disable-next-line no-empty-pattern
runInlineTest: async ({}, use, testInfo: TestInfo) => {
let runResult: RunResult | undefined;
await use(async (files: Files, params: Params = {}, env: Env = {}) => {
const baseDir = await base.step("write files", async () => await writeFiles(testInfo, files));
runResult = await base.step("run tests", async () => {
const allureResults = await runPlaywrightTest(baseDir, params, env);
await allure.attachment(
"allure-results",
Buffer.from(JSON.stringify(allureResults, null, 2)),
"application/json",
);
return allureResults;
});
return runResult;
});
if (testInfo.status !== testInfo.expectedStatus && runResult && !process.env.PW_RUNNER_DEBUG) {
// eslint-disable-next-line no-console
console.error(runResult.output);
}
},
// eslint-disable-next-line no-empty-pattern
attachment: async ({}, use) => {
await use((name) => join(__dirname, "assets", name));
},
});