@azimuth-sh/playwright 0.0.0-alpha.0 → 0.2.0-alpha.4

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 (3) hide show
  1. package/README.md +21 -4
  2. package/index.js +204 -0
  3. package/package.json +20 -8
package/README.md CHANGED
@@ -1,6 +1,23 @@
1
- # @azimuth-sh/playwright
1
+ # Azimuth's Playwright adapter
2
2
 
3
- This version reserves the package name and holds no code. Do not install it.
3
+ This adapter lists marked Playwright tests, runs the requested Checks and reports
4
+ their first attempts to Azimuth. It uses the application's own `@playwright/test`.
5
+ This version supports Playwright `>=1.61.1 <1.66.0`, verified with the adapter's
6
+ real-runner suite at 1.61.1 and 1.65.1. The resolved-config loader uses an
7
+ undocumented interface because the public reporter configuration does not expose
8
+ the entries of a `webServer` array.
4
9
 
5
- The Azimuth adapter for Playwright is published under this name by the release workflow of
6
- [azimuth-sh/azimuth](https://github.com/azimuth-sh/azimuth). See <https://azimuth.sh>.
10
+ Install it as a development dependency of the application:
11
+
12
+ ```sh
13
+ npm install --save-dev --save-exact @azimuth-sh/playwright@<version>
14
+ ```
15
+
16
+ `azimuth init` prints that line with the CLI's version filled in. The suite's
17
+ adapter command is `npx --no @azimuth-sh/playwright`.
18
+
19
+ Put a Playwright config in each suite's folder. Its `webServer` must start the
20
+ application, with `reuseExistingServer` false. Mark a test or a `describe` group
21
+ with a tag such as `@Check:loan-is-refused`; several tags may mark one test.
22
+ An annotation is not a marker. A suite with another `marker_key` uses that key
23
+ in place of `Check`.
package/index.js ADDED
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawn, execFileSync } = require('node:child_process');
8
+ const { createRequire } = require('node:module');
9
+ const manifest = require('./package.json');
10
+
11
+ // Standard output belongs exclusively to the adapter report, including when a config logs.
12
+ const writeReport = process.stdout.write.bind(process.stdout);
13
+ process.stdout.write = process.stderr.write.bind(process.stderr);
14
+ let temporary;
15
+ process.on('exit', () => {
16
+ if (temporary) fs.rmSync(temporary, { recursive: true, force: true });
17
+ });
18
+ // Every process in the launch group already receives the interrupt from the core.
19
+ process.on('SIGINT', () => process.exit(1));
20
+
21
+ function installedIn(folder) {
22
+ const ownFolder = fs.realpathSync(__dirname);
23
+ for (let current = fs.realpathSync(folder); ; current = path.dirname(current)) {
24
+ const installation = path.join(current, 'node_modules', '@azimuth-sh', 'playwright');
25
+ if (fs.existsSync(installation) && ownFolder === fs.realpathSync(installation)) return;
26
+ if (path.dirname(current) === current) break;
27
+ }
28
+ throw new Error('the package is not installed in this application');
29
+ }
30
+
31
+ function discover(folder, root) {
32
+ const projects = [];
33
+ function visit(current) {
34
+ const entries = fs.readdirSync(current, { withFileTypes: true });
35
+ if (entries.some(entry => entry.isFile() && /^playwright\.config\.(?:[cm]?[jt]s)$/.test(entry.name))) {
36
+ projects.push({ path: path.relative(root, current).split(path.sep).join('/') || '.' });
37
+ }
38
+ for (const entry of entries) {
39
+ if (entry.isDirectory() && entry.name !== '.git' && entry.name !== 'node_modules') {
40
+ visit(path.join(current, entry.name));
41
+ }
42
+ }
43
+ }
44
+ visit(folder);
45
+ projects.sort((a, b) => a.path.localeCompare(b.path));
46
+ return { projects };
47
+ }
48
+
49
+ function specs(document) {
50
+ if (!document || !Array.isArray(document.suites) || !Array.isArray(document.errors)) {
51
+ throw new Error('the runner wrote a report without suites and errors');
52
+ }
53
+ const entries = new Map();
54
+ function visit(suite, parents) {
55
+ if (typeof suite.title !== 'string' || !Array.isArray(suite.specs)) throw new Error('the runner wrote an invalid suite');
56
+ const titles = [...parents, suite.title];
57
+ for (const spec of suite.specs) {
58
+ if (typeof spec.title !== 'string' || typeof spec.file !== 'string' || !Number.isInteger(spec.line) || !Number.isInteger(spec.column) || !Array.isArray(spec.tags)
59
+ || !spec.tags.every(tag => typeof tag === 'string') || !Array.isArray(spec.tests) || !spec.tests.length) {
60
+ throw new Error('the runner wrote an invalid test listing');
61
+ }
62
+ for (const test of spec.tests) {
63
+ if (!Array.isArray(test.results) || typeof test.expectedStatus !== 'string') throw new Error('the runner wrote an invalid test result');
64
+ for (const result of test.results) {
65
+ if (!['passed', 'failed', 'timedOut', 'skipped', 'interrupted'].includes(result.status)
66
+ || !Number.isInteger(result.duration) || result.duration < 0) throw new Error('the runner wrote an invalid attempt');
67
+ }
68
+ }
69
+ const name = [...titles, spec.title].join(' › ');
70
+ const identity = JSON.stringify([spec.file, spec.line, spec.column, name]);
71
+ entries.set(identity, { ...spec, name });
72
+ }
73
+ for (const child of suite.suites || []) visit(child, titles);
74
+ }
75
+ for (const suite of document.suites) visit(suite, []);
76
+ return entries;
77
+ }
78
+
79
+ function outcome(rows, expectedCount) {
80
+ const verdicts = rows.map(row => {
81
+ const result = row.results[0];
82
+ if (!result || result.status === 'interrupted') return 'not_run';
83
+ if (result.status === 'skipped') return 'skipped';
84
+ return result.status === row.expectedStatus ? 'passed' : 'failed';
85
+ });
86
+ if (verdicts.includes('failed')) return 'failed';
87
+ if (rows.length !== expectedCount || verdicts.includes('not_run')) return 'not_run';
88
+ return verdicts.every(verdict => verdict === 'passed') ? 'passed' : 'skipped';
89
+ }
90
+
91
+ function escapeRegex(text) {
92
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
93
+ }
94
+
95
+ function applicationRunner() {
96
+ const application = createRequire(path.join(process.cwd(), 'package.json'));
97
+ const version = application('@playwright/test/package.json').version;
98
+ const supported = manifest.peerDependencies['@playwright/test'];
99
+ const bounds = /^>=(\d+)\.(\d+)\.(\d+) <(\d+)\.(\d+)\.(\d+)$/.exec(supported);
100
+ const installed = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
101
+ const compare = (left, right) => {
102
+ for (let index = 0; index < 3; index++) {
103
+ const difference = Number(left[index]) - Number(right[index]);
104
+ if (difference) return difference;
105
+ }
106
+ return 0;
107
+ };
108
+ if (!bounds || !installed || compare(installed.slice(1), bounds.slice(1, 4)) < 0 || compare(installed.slice(1), bounds.slice(4)) >= 0) {
109
+ throw new Error(`installed Playwright ${version} is outside the supported range ${supported}`);
110
+ }
111
+ return application;
112
+ }
113
+
114
+ async function run(request, application) {
115
+ const runner = createRequire(application.resolve('@playwright/test/package.json'));
116
+ // The public FullConfig loses the individual entries when webServer is an array.
117
+ const { configLoader } = runner('playwright/lib/common');
118
+ const args = process.argv.slice(2);
119
+ const configIndex = args.findIndex(arg => arg === '--config' || arg === '-c');
120
+ const configPath = configIndex >= 0 ? args[configIndex + 1] : args.find(arg => arg.startsWith('--config='))?.slice(9);
121
+ let config;
122
+ try {
123
+ config = await configLoader.loadConfigFromFile(configPath, { retries: 0 });
124
+ } catch (error) {
125
+ console.error(error);
126
+ return { build: 'failed', tests: [] };
127
+ }
128
+ if (!config.webServers.length) throw new Error('the resolved config has no webServer entry');
129
+ if (config.webServers.some(server => server.reuseExistingServer)) {
130
+ throw new Error('the resolved config sets reuseExistingServer to true');
131
+ }
132
+
133
+ temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'azimuth-playwright-'));
134
+ const output = path.join(temporary, 'report.json');
135
+ const cli = application.resolve('@playwright/test/cli');
136
+ async function launch(extra) {
137
+ fs.rmSync(output, { force: true });
138
+ const status = await new Promise((resolve, reject) => {
139
+ const child = spawn(process.execPath, [cli, 'test', ...args, ...extra, '--retries=0', '--reporter=line,json'], {
140
+ stdio: ['ignore', 2, 2],
141
+ env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_FILE: output, PLAYWRIGHT_JSON_OUTPUT_NAME: output, PLAYWRIGHT_JSON_ONLY_FAILURES: '0' },
142
+ });
143
+ child.on('error', reject);
144
+ child.on('exit', (code, signal) => signal ? reject(new Error(`the runner ended with ${signal}`)) : resolve(code));
145
+ });
146
+ const report = fs.existsSync(output) ? JSON.parse(fs.readFileSync(output, 'utf8')) : null;
147
+ return { status, report };
148
+ }
149
+
150
+ const listed = await launch(['--list']);
151
+ const listing = specs(listed.report);
152
+ if (listed.status !== 0) return { build: 'failed', tests: [] };
153
+ const marked = [...listing].map(([identity, spec]) => {
154
+ const prefix = `${request.marker_key}:`;
155
+ const checks = [...new Set(spec.tags.filter(tag => tag.startsWith(prefix) && /^[A-Za-z0-9-]+$/.test(tag.slice(prefix.length))).map(tag => tag.slice(prefix.length)))];
156
+ return { identity, spec, checks };
157
+ }).filter(test => test.checks.length);
158
+ const asked = new Set(request.checks);
159
+ const selected = [...new Set(marked.flatMap(test => test.checks).filter(check => asked.has(check)))];
160
+ let ran = new Map();
161
+ if (selected.length) {
162
+ const filter = `(?:^|\\s)@${escapeRegex(request.marker_key)}:(?:${selected.map(escapeRegex).join('|')})(?=\\s|$)`;
163
+ const executed = await launch(['--grep', filter]);
164
+ ran = specs(executed.report);
165
+ if (executed.report.errors.length || (executed.status !== 0 && ![...ran.values()].some(spec => outcome(spec.tests, spec.tests.length) === 'failed'))) {
166
+ throw new Error('the runner failed outside a test');
167
+ }
168
+ }
169
+ return {
170
+ build: 'ok',
171
+ tests: marked.map(({ identity, spec, checks }) => {
172
+ const rows = ran.get(identity)?.tests || [];
173
+ return {
174
+ name: spec.name,
175
+ checks,
176
+ outcome: rows.length ? outcome(rows, spec.tests.length) : 'not_run',
177
+ duration_ms: rows.reduce((sum, row) => sum + (row.results[0]?.duration || 0), 0),
178
+ };
179
+ }),
180
+ };
181
+ }
182
+
183
+ async function main() {
184
+ let input = '';
185
+ process.stdin.setEncoding('utf8');
186
+ for await (const chunk of process.stdin) input += chunk;
187
+ const request = JSON.parse(input);
188
+ if (request.format !== 'adapter-request-1') throw new Error('the request is not an adapter-request-1');
189
+ const root = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim();
190
+ const folder = path.resolve(root, request.verb === 'discover' ? request.folder : request.suite);
191
+ if (fs.realpathSync(folder) !== fs.realpathSync(process.cwd())) throw new Error('the request folder is not the folder where the adapter was started');
192
+ installedIn(folder);
193
+ const application = applicationRunner();
194
+ let report;
195
+ if (request.verb === 'discover') report = discover(folder, root);
196
+ else if (request.verb === 'run') report = await run(request, application);
197
+ else throw new Error(`the verb ${request.verb} is not known; this adapter knows discover and run`);
198
+ writeReport(JSON.stringify({ format: 'adapter-report-1', adapter: { name: manifest.name, version: manifest.version }, ...report }));
199
+ }
200
+
201
+ main().catch(error => {
202
+ console.error(`azimuth-playwright: ${error.message}`);
203
+ process.exitCode = 1;
204
+ });
package/package.json CHANGED
@@ -1,19 +1,31 @@
1
1
  {
2
2
  "name": "@azimuth-sh/playwright",
3
- "version": "0.0.0-alpha.0",
4
- "description": "Reserves the name of the Azimuth adapter for Playwright. This version holds no code.",
3
+ "version": "0.2.0-alpha.4",
4
+ "description": "The Azimuth test adapter for Playwright",
5
+ "bin": {
6
+ "azimuth-playwright": "index.js"
7
+ },
8
+ "files": [
9
+ "index.js",
10
+ "README.md"
11
+ ],
5
12
  "license": "Apache-2.0",
6
13
  "homepage": "https://azimuth.sh",
7
14
  "repository": {
8
15
  "type": "git",
9
- "url": "git+https://github.com/azimuth-sh/azimuth.git",
16
+ "url": "https://github.com/azimuth-sh/azimuth.git",
10
17
  "directory": "adapters/playwright"
11
18
  },
12
19
  "author": "Azimuth",
13
- "files": [
14
- "README.md"
15
- ],
16
- "publishConfig": {
17
- "access": "public"
20
+ "peerDependencies": {
21
+ "@playwright/test": ">=1.61.1 <1.66.0"
22
+ },
23
+ "peerDependenciesMeta": {
24
+ "@playwright/test": {
25
+ "optional": true
26
+ }
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
18
30
  }
19
31
  }