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({ PW_TARGET: 'local-dev' }), ci = read({ CI: '1', PW_EXTENDED_LAYOUT: '1', PW_WORKERS: '1', PW_TARGET: 'local-dev', }); 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.equal( read({ PW_TARGET: 'remote', PW_BASE_URL: 'http://127.0.0.1:5174/' }) .webServer, undefined, ); 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); } });