chore(tooling): 对齐协作规范与浏览器验收工具
验证:713 项单测、8 视口环境、代码及格式检查通过;未运行生产构建。
This commit is contained in:
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
runtimeOptions,
|
||||
positiveInteger,
|
||||
browserRuntime,
|
||||
} from '../../scripts/playwright-runtime.mjs';
|
||||
import {
|
||||
contextOptions,
|
||||
projectViewports,
|
||||
} from '../../scripts/browser-environment.mjs';
|
||||
import { latestReport } from '../../scripts/run-playwright.mjs';
|
||||
import {
|
||||
installGuards,
|
||||
openBackgroundPage,
|
||||
checkFocus,
|
||||
} from '../../scripts/playwright-runner-focus.mjs';
|
||||
import { EventEmitter } from 'node:events';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const options = (env) =>
|
||||
runtimeOptions({ defaultPort: 4175, defaultWorkers: 4, env });
|
||||
|
||||
test('worker counts reject invalid input rather than silently using defaults', () => {
|
||||
for (const value of [
|
||||
'',
|
||||
'0',
|
||||
'-1',
|
||||
'1.5',
|
||||
'2e2',
|
||||
' 2 ',
|
||||
'1\n',
|
||||
'Infinity',
|
||||
'NaN',
|
||||
'01',
|
||||
'9007199254740992',
|
||||
null,
|
||||
false,
|
||||
[2],
|
||||
{},
|
||||
]) {
|
||||
assert.throws(() => options({ PW_WORKERS: value }), /PW_WORKERS.*positive/);
|
||||
}
|
||||
assert.equal(options({}).workers, 4);
|
||||
assert.equal(options({ CI: '1' }).workers, 1);
|
||||
assert.equal(options({ PW_WORKERS: '2' }).workers, 2);
|
||||
assert.throws(
|
||||
() => positiveInteger(undefined, 'resources.concurrency'),
|
||||
/resources.concurrency/,
|
||||
);
|
||||
assert.throws(
|
||||
() => positiveInteger(-1, 'resources.concurrency'),
|
||||
/resources.concurrency/,
|
||||
);
|
||||
});
|
||||
|
||||
test('headless, offscreen and CI flags enforce the same contract', () => {
|
||||
assert.equal(options({}).headless, false);
|
||||
assert.equal(options({}).offscreen, true);
|
||||
assert.equal(options({ PW_HEADLESS: '1' }).headless, true);
|
||||
assert.equal(options({ CI: 'false' }).isCI, false);
|
||||
assert.equal(options({ CI: '0' }).isCI, false);
|
||||
assert.throws(
|
||||
() => options({ CI: '1', PW_HEADLESS: '0' }),
|
||||
/CI requires headless/,
|
||||
);
|
||||
for (const extra of [
|
||||
{ CI: '1' },
|
||||
{ PW_HEADLESS: '1' },
|
||||
{ CODEX_THREAD_ID: 'test-agent' },
|
||||
{ CLAUDECODE: '1' },
|
||||
]) {
|
||||
assert.throws(
|
||||
() => options({ UI_VISUAL_OFFSCREEN: '0', ...extra }),
|
||||
/only allowed for manual/,
|
||||
);
|
||||
}
|
||||
for (const key of [
|
||||
'PW_HEADLESS',
|
||||
'PW_EXTENDED_LAYOUT',
|
||||
'PW_VIDEO',
|
||||
'PW_REQUIRE_ALL',
|
||||
'UI_VISUAL_OFFSCREEN',
|
||||
]) {
|
||||
assert.throws(() => options({ [key]: 'true' }), /must be 0 or 1/);
|
||||
}
|
||||
});
|
||||
|
||||
test('standalone capture policy does not inherit the runner target or worker strategy', () => {
|
||||
const capture = browserRuntime({
|
||||
PW_TARGET: 'remote',
|
||||
PW_WORKERS: 'not-a-runner-value',
|
||||
PW_HEADLESS: '1',
|
||||
});
|
||||
assert.equal(capture.headless, true);
|
||||
assert.ok(capture.launchArgs.includes('--hide-scrollbars'));
|
||||
});
|
||||
|
||||
test('targets and run directories reject ambiguous or unsafe values', () => {
|
||||
for (const env of [
|
||||
{ PW_TARGET: 'unknown' },
|
||||
{ PW_TARGET: 'remote' },
|
||||
{ PW_BASE_URL: 'https://127.0.0.1:4175/' },
|
||||
{ PW_BASE_URL: 'http://localhost:4175/' },
|
||||
{ PW_BASE_URL: 'http://user:pass@127.0.0.1:4175/' },
|
||||
{ PW_BASE_URL: 'http://127.0.0.1:4175/?v=1' },
|
||||
{ PW_RUN_ID: '../other' },
|
||||
{ PW_RUN_ID: '' },
|
||||
{ PW_RUN_ID: 'a/b' },
|
||||
{ PW_RUN_ID: 'a\n' },
|
||||
])
|
||||
assert.throws(() => options(env));
|
||||
const a = options({}),
|
||||
b = options({});
|
||||
assert.notEqual(a.runId, b.runId);
|
||||
assert.notEqual(a.reportDir, b.reportDir);
|
||||
assert.equal(options({ PW_RUN_ID: a.runId }).outputDir, a.outputDir);
|
||||
assert.equal(
|
||||
options({ PW_TARGET: 'remote', PW_BASE_URL: 'https://example.test/sub/' })
|
||||
.baseURL.pathname,
|
||||
'/sub/',
|
||||
);
|
||||
});
|
||||
|
||||
test('mobile retains UA, touch and DPR while using the requested CSS viewport', () => {
|
||||
assert.equal(projectViewports.length, 8);
|
||||
const mobile = contextOptions('mobile');
|
||||
assert.deepEqual(mobile.viewport, { width: 360, height: 800 });
|
||||
assert.equal(mobile.deviceScaleFactor, 2.75);
|
||||
assert.equal(mobile.hasTouch, true);
|
||||
assert.equal(mobile.isMobile, true);
|
||||
assert.match(mobile.userAgent, /Mobile/);
|
||||
assert.equal(contextOptions('tablet').hasTouch, false);
|
||||
});
|
||||
|
||||
test('config isolates HTML, JUnit and traces and supports extended projects', () => {
|
||||
const env = { ...process.env };
|
||||
for (const key of Object.keys(env))
|
||||
if (/^(PW_|UI_VISUAL_OFFSCREEN$|CI$)/.test(key)) delete env[key];
|
||||
const script = `import c from './playwright.config.js'; console.log(JSON.stringify(c))`;
|
||||
const read = (extra, args = []) =>
|
||||
JSON.parse(
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
['--input-type=module', '-e', script, '--', ...args],
|
||||
{
|
||||
cwd: root,
|
||||
env: { ...env, ...extra },
|
||||
encoding: 'utf8',
|
||||
stdio: 'pipe',
|
||||
},
|
||||
),
|
||||
);
|
||||
const base = read({}),
|
||||
ci = read({ CI: '1', PW_EXTENDED_LAYOUT: '1', PW_WORKERS: '1' });
|
||||
assert.equal(base.projects.length, 2);
|
||||
assert.equal(ci.projects.length, 8);
|
||||
assert.equal(base.use.headless, false);
|
||||
assert.equal(ci.use.headless, true);
|
||||
assert.ok(
|
||||
ci.reporter
|
||||
.find(([kind]) => kind === 'junit')[1]
|
||||
.outputFile.startsWith(ci.outputDir + '/'),
|
||||
);
|
||||
assert.equal(
|
||||
base.reporter.find(([kind]) => kind === 'html')[1].outputFolder,
|
||||
`playwright-report/${base.metadata.runId}`,
|
||||
);
|
||||
assert.ok(base.use.launchOptions.args.includes('--hide-scrollbars'));
|
||||
assert.ok(base.webServer.command.includes('--strictPort'));
|
||||
assert.deepEqual(read({}, ['--list']).reporter, [['list']]);
|
||||
assert.throws(
|
||||
() => read({ CI: '1' }, ['--headed']),
|
||||
/CI requires headless non-interactive/,
|
||||
);
|
||||
});
|
||||
|
||||
test('report command finds the latest complete report and ignores incomplete runs', async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), 'pw-report-test-'));
|
||||
try {
|
||||
for (const name of ['older', 'newer', 'incomplete'])
|
||||
await mkdir(path.join(directory, name));
|
||||
for (const name of ['older', 'newer'])
|
||||
await writeFile(path.join(directory, name, 'index.html'), 'report');
|
||||
await utimes(path.join(directory, 'older', 'index.html'), 1, 1);
|
||||
assert.equal(await latestReport(directory), path.join(directory, 'newer'));
|
||||
await writeFile(path.join(directory, 'index.html'), 'legacy report');
|
||||
await utimes(
|
||||
path.join(directory, 'index.html'),
|
||||
Date.now() / 1000 + 10,
|
||||
Date.now() / 1000 + 10,
|
||||
);
|
||||
assert.equal(await latestReport(directory), directory);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('focus guard records forbidden calls even if the caller catches the error', async () => {
|
||||
const browser = { newPage() {}, newContext() {} },
|
||||
original = browser.newContext;
|
||||
const context = new EventEmitter();
|
||||
const page = { bringToFront() {} };
|
||||
const guard = installGuards(browser, context, page);
|
||||
for (const call of [
|
||||
() => browser.newContext(),
|
||||
() => browser.newPage(),
|
||||
() => context.newPage(),
|
||||
() => page.bringToFront(),
|
||||
])
|
||||
assert.throws(call, /焦点守护/);
|
||||
let closed = false;
|
||||
context.emit('page', {
|
||||
url: () => 'about:blank',
|
||||
close: async () => {
|
||||
closed = true;
|
||||
},
|
||||
});
|
||||
assert.equal(closed, true);
|
||||
assert.equal(guard.violations.length, 5);
|
||||
guard.restore();
|
||||
assert.equal(browser.newContext, original);
|
||||
});
|
||||
|
||||
test('background page uses the existing context and rejects ambiguous contexts', async () => {
|
||||
let parameters;
|
||||
const cdp = {
|
||||
send: async (command, args) =>
|
||||
command === 'Target.getBrowserContexts'
|
||||
? { browserContextIds: ['one'] }
|
||||
: (parameters = args),
|
||||
detach: async () => {},
|
||||
};
|
||||
const browser = { newBrowserCDPSession: async () => cdp };
|
||||
const page = {};
|
||||
assert.equal(
|
||||
await openBackgroundPage(browser, { waitForEvent: async () => page }),
|
||||
page,
|
||||
);
|
||||
assert.equal(parameters.background, true);
|
||||
assert.equal(parameters.browserContextId, 'one');
|
||||
cdp.send = async () => ({ browserContextIds: ['one', 'two'] });
|
||||
await assert.rejects(openBackgroundPage(browser, {}), /无法唯一确定/);
|
||||
});
|
||||
|
||||
test('foreground activation or an unknown probe stops the run after recording evidence', async () => {
|
||||
for (const state of [null, { parentPid: process.pid }]) {
|
||||
const info = { annotations: [], titlePath: ['guard test'] };
|
||||
await assert.rejects(
|
||||
checkFocus({ query: async () => state }, '页面创建后', info),
|
||||
/焦点/,
|
||||
);
|
||||
assert.equal(info.annotations.length, 1);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
FOCUS_EVENTS,
|
||||
FOCUS_SAFE_ARGS,
|
||||
FocusGuardError,
|
||||
classifyFocus,
|
||||
createFocusLog,
|
||||
installFocusGuards,
|
||||
parseForegroundOutput,
|
||||
} from '../../scripts/playwright-focus-guard.mjs';
|
||||
|
||||
test('focus-safe args keep the window offscreen and unthrottled', () => {
|
||||
for (const arg of [
|
||||
'--window-position=-32000,-32000',
|
||||
'--disable-backgrounding-occluded-windows',
|
||||
'--disable-renderer-backgrounding',
|
||||
'--disable-background-timer-throttling',
|
||||
])
|
||||
assert.ok(FOCUS_SAFE_ARGS.includes(arg), arg);
|
||||
assert.ok(Object.isFrozen(FOCUS_SAFE_ARGS));
|
||||
});
|
||||
|
||||
test('guards forbid newPage / bringToFront and close unexpected pages', async () => {
|
||||
const context = new EventEmitter();
|
||||
context.newPage = async () => 'opened';
|
||||
const page = { bringToFront: async () => 'front' };
|
||||
const extra = {
|
||||
closed: false,
|
||||
url: () => 'https://example.test/popup',
|
||||
close: async () => {
|
||||
extra.closed = true;
|
||||
},
|
||||
};
|
||||
const log = createFocusLog(() => {});
|
||||
const remove = installFocusGuards(context, page, log);
|
||||
|
||||
await assert.rejects(context.newPage(), FocusGuardError);
|
||||
await assert.rejects(page.bringToFront(), FocusGuardError);
|
||||
context.emit('page', page);
|
||||
context.emit('page', extra);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(extra.closed, true);
|
||||
assert.deepEqual(
|
||||
log.entries.map((entry) => entry.type),
|
||||
[FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE],
|
||||
);
|
||||
|
||||
remove();
|
||||
assert.equal(await context.newPage(), 'opened');
|
||||
assert.equal(context.listenerCount('page'), 0);
|
||||
});
|
||||
|
||||
test('startup activation is logged; only a later background-to-foreground transition is fatal', () => {
|
||||
assert.deepEqual(
|
||||
classifyFocus({
|
||||
phase: 'startup',
|
||||
previous: 'background',
|
||||
current: 'foreground',
|
||||
}),
|
||||
{ event: FOCUS_EVENTS.STARTUP, fatal: false },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyFocus({
|
||||
phase: 'running',
|
||||
previous: 'foreground',
|
||||
current: 'foreground',
|
||||
}),
|
||||
{ event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyFocus({
|
||||
phase: 'running',
|
||||
previous: 'background',
|
||||
current: 'foreground',
|
||||
}),
|
||||
{ event: FOCUS_EVENTS.REACTIVATED, fatal: true },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyFocus({
|
||||
phase: 'running',
|
||||
previous: 'background',
|
||||
current: 'unknown',
|
||||
}),
|
||||
{ event: FOCUS_EVENTS.UNKNOWN, fatal: true },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyFocus({
|
||||
phase: 'running',
|
||||
previous: 'background',
|
||||
current: 'background',
|
||||
}),
|
||||
{ event: null, fatal: false },
|
||||
);
|
||||
});
|
||||
|
||||
test('foreground probe output maps to background, foreground or unknown', () => {
|
||||
assert.equal(parseForegroundOutput('100|200,300\r\n').state, 'background');
|
||||
assert.equal(parseForegroundOutput('300|200,300').state, 'foreground');
|
||||
assert.equal(parseForegroundOutput('300|').state, 'unknown');
|
||||
assert.equal(parseForegroundOutput('garbled').state, 'unknown');
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createServer } from 'node:net';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { verifyBuild } from '../../scripts/verify-build.mjs';
|
||||
|
||||
test('static build validation rejects missing entry resources', async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-preview-'));
|
||||
try {
|
||||
await assert.rejects(verifyBuild(directory), /ENOENT/);
|
||||
await writeFile(
|
||||
path.join(directory, 'index.html'),
|
||||
'<script src="/assets/app.js"></script>',
|
||||
);
|
||||
await assert.rejects(verifyBuild(directory), /ENOENT/);
|
||||
await mkdir(path.join(directory, 'assets'));
|
||||
await writeFile(path.join(directory, 'assets/app.js'), 'export {}');
|
||||
assert.equal((await verifyBuild(directory)).assets, 1);
|
||||
await writeFile(path.join(directory, 'logo.svg'), '<svg/>');
|
||||
await writeFile(
|
||||
path.join(directory, 'index.html'),
|
||||
'<link rel="icon" href="__WL_BRAND_FAVICON__"><script src="/assets/app.js"></script><script>const example = \'<img src="/not-a-build-resource.png">\'</script>',
|
||||
);
|
||||
assert.equal((await verifyBuild(directory)).assets, 2);
|
||||
await writeFile(
|
||||
path.join(directory, 'index.html'),
|
||||
'<script src="../outside.js"></script>',
|
||||
);
|
||||
await assert.rejects(verifyBuild(directory), /escapes output/);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('preview refuses an occupied port instead of silently choosing the next port', async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-preview-'));
|
||||
const blocker = createServer();
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(directory, 'index.html'),
|
||||
'<script src="/app.js"></script>',
|
||||
);
|
||||
await writeFile(path.join(directory, 'app.js'), 'export {}');
|
||||
await new Promise((resolve) => blocker.listen(0, '127.0.0.1', resolve));
|
||||
const port = blocker.address().port;
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fileURLToPath(
|
||||
new URL('../../scripts/preview-dist.mjs', import.meta.url),
|
||||
),
|
||||
'--port',
|
||||
String(port),
|
||||
],
|
||||
{
|
||||
cwd: fileURLToPath(new URL('../../', import.meta.url)),
|
||||
env: { ...process.env, PW_DIST_DIR: directory },
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: 20000,
|
||||
},
|
||||
);
|
||||
let output = '';
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
child.on('error', reject);
|
||||
child.on('close', (code) => resolve({ code, output }));
|
||||
});
|
||||
assert.notEqual(result.code, 0);
|
||||
assert.match(result.output, /already in use/);
|
||||
} finally {
|
||||
await new Promise((resolve) => blocker.close(resolve));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user