@azimuth-sh/playwright 0.2.0-alpha.6 → 0.2.0-alpha.9

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.
package/components.js ADDED
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const http = require('node:http');
5
+ const https = require('node:https');
6
+ const net = require('node:net');
7
+ const path = require('node:path');
8
+
9
+ const READ_LIMIT_MS = 10000;
10
+ const LOOK_LIMIT_MS = 3000;
11
+ const PLAN = Symbol.for('azimuth-playwright.plan');
12
+
13
+ // The address of an entry is its origin, so a path or a query in `url` never reaches a read.
14
+ function addressOf(entry) {
15
+ if (entry.url) return new URL(entry.url).origin;
16
+ if (entry.port) return `http://localhost:${entry.port}`;
17
+ return undefined;
18
+ }
19
+
20
+ function acceptsConnection(host, port) {
21
+ return new Promise(resolve => {
22
+ const socket = net.connect({ host, port });
23
+ const finish = answered => {
24
+ socket.destroy();
25
+ resolve(answered);
26
+ };
27
+ socket.setTimeout(LOOK_LIMIT_MS, () => finish(false));
28
+ socket.on('connect', () => finish(true));
29
+ socket.on('error', () => finish(false));
30
+ });
31
+ }
32
+
33
+ // `localhost` names two addresses, and a server may hold only one of them.
34
+ async function answers(address) {
35
+ const url = new URL(address);
36
+ const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80);
37
+ const host = url.hostname.replace(/^\[|\]$/g, '');
38
+ const hosts = host === 'localhost' ? ['127.0.0.1', '::1'] : [host];
39
+ const results = await Promise.all(hosts.map(candidate => acceptsConnection(candidate, port)));
40
+ return results.includes(true);
41
+ }
42
+
43
+ function read(address, report, phase) {
44
+ return new Promise(resolve => {
45
+ const failed = error => resolve({ phase, error });
46
+ const client = address.startsWith('https:') ? https : http;
47
+ const request = client.get(address + report, { agent: false }, response => {
48
+ if (response.statusCode !== 200) {
49
+ response.resume();
50
+ failed(`the response status was ${response.statusCode}`);
51
+ return;
52
+ }
53
+ const chunks = [];
54
+ response.on('data', chunk => chunks.push(chunk));
55
+ response.on('error', error => failed(`the connection failed: ${error.message}`));
56
+ response.on('end', () => {
57
+ try {
58
+ resolve({ phase, report: JSON.parse(Buffer.concat(chunks).toString('utf8')) });
59
+ } catch {
60
+ failed('the body is not JSON');
61
+ }
62
+ });
63
+ });
64
+ // The limit covers the whole read, so a body that never ends is as much a failure as no answer.
65
+ const timer = setTimeout(() => {
66
+ request.destroy();
67
+ failed('no response within 10 seconds');
68
+ }, READ_LIMIT_MS);
69
+ request.on('error', error => failed(`the connection failed: ${error.message}`));
70
+ request.on('close', () => clearTimeout(timer));
71
+ });
72
+ }
73
+
74
+ // Runs inside the runner, as the first global setup and the last global teardown.
75
+ async function record(phase) {
76
+ const plan = globalThis[PLAN];
77
+ const reads = await Promise.all(plan.components.map(async component => ({
78
+ name: component.name,
79
+ read: await read(component.address, component.report, phase),
80
+ })));
81
+ fs.writeFileSync(path.join(plan.folder, `${phase}.json`), JSON.stringify(reads));
82
+ }
83
+
84
+ module.exports = { PLAN, addressOf, answers, record };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+ // Evaluates the resolved config in a process of its own and writes its `webServer` entries to the
3
+ // file named by the first argument. The second argument is the config path, empty when the runner
4
+ // is to find it.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { createRequire } = require('node:module');
8
+
9
+ (async () => {
10
+ const [output, configPath] = process.argv.slice(2);
11
+ const application = createRequire(path.join(process.cwd(), 'package.json'));
12
+ const runner = createRequire(application.resolve('@playwright/test/package.json'));
13
+ // The public FullConfig loses the individual entries when webServer is an array.
14
+ const { configLoader } = runner('playwright/lib/common');
15
+ const config = await configLoader.loadConfigFromFile(configPath || undefined, { retries: 0 });
16
+ fs.writeFileSync(output, JSON.stringify({
17
+ configFile: config.config.configFile,
18
+ webServers: config.webServers.map(({ name, url, port, reuseExistingServer }) => ({ name, url, port, reuseExistingServer })),
19
+ }));
20
+ })().catch(error => {
21
+ console.error(error);
22
+ process.exit(1);
23
+ });
package/index.js CHANGED
@@ -4,9 +4,10 @@
4
4
  const fs = require('node:fs');
5
5
  const os = require('node:os');
6
6
  const path = require('node:path');
7
- const { spawn, execFileSync } = require('node:child_process');
7
+ const { spawn, spawnSync, execFileSync } = require('node:child_process');
8
8
  const { createRequire } = require('node:module');
9
9
  const manifest = require('./package.json');
10
+ const { addressOf, answers } = require('./components');
10
11
 
11
12
  // Standard output belongs exclusively to the adapter report, including when a config logs.
12
13
  const writeReport = process.stdout.write.bind(process.stdout);
@@ -111,43 +112,76 @@ function applicationRunner() {
111
112
  return application;
112
113
  }
113
114
 
115
+ const NO_ADDRESS = 'no address in the runner configuration';
116
+ const ANSWERS = 'something else answers there';
117
+ const NOT_MADE = { start: 'the start read was not made', stop: 'the stop read was not made' };
118
+
119
+ function evaluateConfig(configPath, folder, index) {
120
+ const output = path.join(folder, `evaluation-${index}.json`);
121
+ const status = spawnSync(process.execPath, [path.join(__dirname, 'evaluate-config.js'), output, configPath || ''], { stdio: ['ignore', 2, 2] });
122
+ if (status.status !== 0) return undefined;
123
+ return JSON.parse(fs.readFileSync(output, 'utf8'));
124
+ }
125
+
126
+ // What the config says about each component the request lists: one address, none, or a refusal.
127
+ function addressesIn(evaluation, components) {
128
+ return components.map(component => {
129
+ const entries = evaluation.webServers.filter(server => server.name === component.name);
130
+ if (entries.length > 1) throw new Error(`the config has ${entries.length} webServer entries named "${component.name}", and a component's entry must be one`);
131
+ return entries.length ? addressOf(entries[0]) : undefined;
132
+ });
133
+ }
134
+
135
+ function readsOf(folder, phase) {
136
+ const file = path.join(folder, `${phase}.json`);
137
+ return fs.existsSync(file) ? new Map(JSON.parse(fs.readFileSync(file, 'utf8')).map(({ name, read }) => [name, read])) : new Map();
138
+ }
139
+
114
140
  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');
141
+ const components = request.components || [];
118
142
  const args = process.argv.slice(2);
119
143
  const configIndex = args.findIndex(arg => arg === '--config' || arg === '-c');
120
144
  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)) {
145
+ temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'azimuth-playwright-'));
146
+
147
+ const evaluation = evaluateConfig(configPath, temporary, 1);
148
+ if (!evaluation) return { build: 'failed', tests: [] };
149
+ if (!evaluation.webServers.length) throw new Error('the resolved config has no webServer entry');
150
+ if (evaluation.webServers.some(server => server.reuseExistingServer)) {
130
151
  throw new Error('the resolved config sets reuseExistingServer to true');
131
152
  }
153
+ const addresses = addressesIn(evaluation, components);
154
+ const second = evaluateConfig(configPath, temporary, 2);
155
+ if (!second) throw new Error('the resolved config could not be evaluated a second time');
156
+ const later = addressesIn(second, components);
157
+ components.forEach((component, index) => {
158
+ if (addresses[index] !== later[index]) {
159
+ throw new Error(`the address of "${component.name}" is ${addresses[index] ?? 'missing'} at one evaluation of the config and ${later[index] ?? 'missing'} at the next`);
160
+ }
161
+ });
162
+
163
+ const looked = await Promise.all(addresses.map(address => address && answers(address)));
164
+ const occupied = looked.some(Boolean);
132
165
 
133
- temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'azimuth-playwright-'));
134
166
  const output = path.join(temporary, 'report.json');
135
167
  const cli = application.resolve('@playwright/test/cli');
136
- async function launch(extra) {
168
+ async function launch(extra, wrap) {
137
169
  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'], {
170
+ const loader = wrap ? ['--require', path.join(__dirname, 'wrap-config.js')] : [];
171
+ const { status, signal } = await new Promise((resolve, reject) => {
172
+ const child = spawn(process.execPath, [...loader, cli, 'test', ...args, ...extra, '--retries=0', '--reporter=line,json'], {
140
173
  stdio: ['ignore', 2, 2],
141
- env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_FILE: output, PLAYWRIGHT_JSON_OUTPUT_NAME: output, PLAYWRIGHT_JSON_ONLY_FAILURES: '0' },
174
+ env: { ...process.env, ...(wrap ? { AZIMUTH_PLAYWRIGHT_PLAN: wrap } : {}), PLAYWRIGHT_JSON_OUTPUT_FILE: output, PLAYWRIGHT_JSON_OUTPUT_NAME: output, PLAYWRIGHT_JSON_ONLY_FAILURES: '0' },
142
175
  });
143
176
  child.on('error', reject);
144
- child.on('exit', (code, signal) => signal ? reject(new Error(`the runner ended with ${signal}`)) : resolve(code));
177
+ child.on('exit', (code, signal) => resolve({ status: code, signal }));
145
178
  });
146
179
  const report = fs.existsSync(output) ? JSON.parse(fs.readFileSync(output, 'utf8')) : null;
147
- return { status, report };
180
+ return { status, signal, report };
148
181
  }
149
182
 
150
183
  const listed = await launch(['--list']);
184
+ if (listed.signal) throw new Error(`the runner ended with ${listed.signal}`);
151
185
  const listing = specs(listed.report);
152
186
  if (listed.status !== 0) return { build: 'failed', tests: [] };
153
187
  const marked = [...listing].map(([identity, spec]) => {
@@ -158,14 +192,35 @@ async function run(request, application) {
158
192
  const asked = new Set(request.checks);
159
193
  const selected = [...new Set(marked.flatMap(test => test.checks).filter(check => asked.has(check)))];
160
194
  let ran = new Map();
161
- if (selected.length) {
195
+ let started = false;
196
+ const readable = components.filter((component, index) => addresses[index]);
197
+ if (selected.length && !occupied) {
162
198
  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');
199
+ let plan;
200
+ if (readable.length) {
201
+ const file = path.join(temporary, 'plan.json');
202
+ fs.writeFileSync(file, JSON.stringify({
203
+ config: fs.realpathSync(evaluation.configFile),
204
+ folder: temporary,
205
+ components: readable.map(component => ({ name: component.name, address: addresses[components.indexOf(component)], report: component.report })),
206
+ }));
207
+ plan = file;
208
+ }
209
+ const executed = await launch(['--grep', filter], plan);
210
+ started = true;
211
+ // A runner that is killed writes no report, and nothing it reports is then a failure of the suite.
212
+ if (!executed.signal) {
213
+ ran = specs(executed.report);
214
+ if (executed.report.errors.length || (executed.status !== 0 && ![...ran.values()].some(spec => outcome(spec.tests, spec.tests.length) === 'failed'))) {
215
+ throw new Error('the runner failed outside a test');
216
+ }
217
+ }
218
+ if (plan && !executed.signal && !fs.existsSync(path.join(temporary, 'wrapped'))) {
219
+ throw new Error('the global setup of this config could not be wrapped; a config that the runner loads as an ES module is not supported');
167
220
  }
168
221
  }
222
+ const starts = readsOf(temporary, 'start');
223
+ const stops = readsOf(temporary, 'stop');
169
224
  return {
170
225
  build: 'ok',
171
226
  tests: marked.map(({ identity, spec, checks }) => {
@@ -177,6 +232,15 @@ async function run(request, application) {
177
232
  duration_ms: rows.reduce((sum, row) => sum + (row.results[0]?.duration || 0), 0),
178
233
  };
179
234
  }),
235
+ components: components.map((component, index) => {
236
+ if (!addresses[index]) return { name: component.name, error: NO_ADDRESS, reads: [] };
237
+ if (looked[index]) return { name: component.name, error: ANSWERS, reads: [] };
238
+ if (!started) return { name: component.name, reads: [] };
239
+ return {
240
+ name: component.name,
241
+ reads: ['start', 'stop'].map(phase => (phase === 'start' ? starts : stops).get(component.name) || { phase, error: NOT_MADE[phase] }),
242
+ };
243
+ }),
180
244
  };
181
245
  }
182
246
 
package/package.json CHANGED
@@ -1,12 +1,17 @@
1
1
  {
2
2
  "name": "@azimuth-sh/playwright",
3
- "version": "0.2.0-alpha.6",
3
+ "version": "0.2.0-alpha.9",
4
4
  "description": "The Azimuth test adapter for Playwright",
5
5
  "bin": {
6
6
  "azimuth-playwright": "index.js"
7
7
  },
8
8
  "files": [
9
9
  "index.js",
10
+ "components.js",
11
+ "evaluate-config.js",
12
+ "wrap-config.js",
13
+ "start-read.js",
14
+ "stop-read.js",
10
15
  "README.md"
11
16
  ],
12
17
  "license": "Apache-2.0",
package/start-read.js ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+ const { record } = require('./components');
3
+
4
+ module.exports = () => record('start');
package/stop-read.js ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+ const { record } = require('./components');
3
+
4
+ module.exports = () => record('stop');
package/wrap-config.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+ // Preloaded into the runner only. The runner offers no option to add a global setup, so the
3
+ // config's exports are changed as the runner loads them, and the suite's own entries stay between
4
+ // the two reads.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const Module = require('node:module');
8
+ const { PLAN } = require('./components');
9
+
10
+ // The runner starts its workers with the same options, and a worker has no plan to wrap anything
11
+ // with: the variable is gone from its environment.
12
+ if (process.env.AZIMUTH_PLAYWRIGHT_PLAN) {
13
+ const plan = JSON.parse(fs.readFileSync(process.env.AZIMUTH_PLAYWRIGHT_PLAN, 'utf8'));
14
+ // The suite's servers and tests inherit the environment, and none of this is theirs.
15
+ delete process.env.AZIMUTH_PLAYWRIGHT_PLAN;
16
+ globalThis[PLAN] = plan;
17
+ wrap(plan);
18
+ }
19
+
20
+ function wrap(plan) {
21
+ const wrapped = new WeakSet();
22
+ const entries = value => (value === undefined || value === null ? [] : Array.isArray(value) ? value : [value]);
23
+ const load = Module._load;
24
+ Module._load = function (request, parent, isMain) {
25
+ const exported = load.apply(this, arguments);
26
+ if (typeof request !== 'string' || path.basename(request) !== path.basename(plan.config)) return exported;
27
+ if (!exported || typeof exported !== 'object' || wrapped.has(exported)) return exported;
28
+ if (Module._resolveFilename(request, parent, isMain) !== plan.config) return exported;
29
+ const config = exported.default && typeof exported.default === 'object' ? exported.default : exported;
30
+ config.globalSetup = [path.join(__dirname, 'start-read.js'), ...entries(config.globalSetup)];
31
+ config.globalTeardown = [...entries(config.globalTeardown), path.join(__dirname, 'stop-read.js')];
32
+ wrapped.add(exported);
33
+ fs.writeFileSync(path.join(plan.folder, 'wrapped'), '');
34
+ return exported;
35
+ };
36
+ }