From f8361c5beb3fb96b84fae2e73459a7508bb197a2 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 20:54:07 +0000 Subject: [PATCH] browser tests: deterministic under load The afterAll hook of tests/console-fill.test.ts timed out (30 s) in 2 of 3 runs with 10 CPU hogs. Cause: Google Chrome (the fallback when playwright's Chromium is not downloaded) hangs in its own shutdown after loading http pages until its 10 s teardown watchdog fires; under load that passed 30 s. - tests/helpers/browser.ts: one shared launch per file as a browser server with a 60 s launch timeout, killed at the end (throwaway profile, nothing to flush); a launch timeout fails instead of silently skipping; contexts and engine runs tracked per test and closed in afterEach (capped); event-driven waits for engine log lines - console-fill: explicit test timeouts, slow tests marked, waits expected to succeed get a long cap (they return at once), sign-in / watching navTimeoutMs 1.5 s -> 5 s, persistent-profile Chromium closed in finally, temp account dirs removed - site-overflow, console-session: same plumbing (site-overflow's afterAll had bun's 5 s default) - console session: launchTimeoutMs option (tests only) --- cli/console/session.ts | 6 +- tests/console-fill.test.ts | 142 +++++++++++++++++++--------------- tests/console-session.test.ts | 21 +++-- tests/helpers/browser.ts | 120 ++++++++++++++++++++++++++++ tests/site-overflow.test.ts | 27 ++++--- 5 files changed, 233 insertions(+), 83 deletions(-) create mode 100644 tests/helpers/browser.ts diff --git a/cli/console/session.ts b/cli/console/session.ts index 5c4e9e06..867c9628 100644 --- a/cli/console/session.ts +++ b/cli/console/session.ts @@ -168,6 +168,8 @@ export interface OpenOpts { hosts?: string[]; headless?: boolean; platform?: string; + /** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */ + launchTimeoutMs?: number; say: (m: string) => void; } @@ -233,7 +235,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise { /* kept on purpose */ }); diff --git a/tests/console-fill.test.ts b/tests/console-fill.test.ts index 9075c5e0..434a23ed 100644 --- a/tests/console-fill.test.ts +++ b/tests/console-fill.test.ts @@ -1,7 +1,11 @@ // storebound console fill: pure answer building (rule 5: only what the config proves is certain), the click gate, the // sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from -// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches. -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium is +// installed (a launch that times out fails instead). Load-proofing (tests/helpers/browser.ts): one launch with a long +// launch timeout, every context closed right after its test, event-driven waits for log lines, explicit test timeouts. +// Slow on purpose (marked SLOW): the sign-in / watching tests and the account tests wait out real "not here" timeouts +// of the engine (navTimeoutMs / navMs, scaled down through the options) and the profile tests relaunch Chromium. +import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -12,6 +16,7 @@ import { parseArgs } from '../cli/lib/args'; import { type ShipConfig, validateExtras } from '../cli/lib/config'; import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers'; import { consoleReached, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, navAllowed, navPlan, playDeveloperId, switchAllowed } from '../cli/lib/console-forms'; +import { AFTER_ALL_MS, AFTER_EACH_MS, capped, CLOSE_TIMEOUT_MS, LAUNCH_TIMEOUT_MS, launchTestBrowser, logLines, testScope } from './helpers/browser'; const config: ShipConfig = { app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, @@ -160,14 +165,18 @@ describe('--dry --json', () => { // ---- the engine against the modeled pages ---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -let browser: any = null; -let skipWhy = ''; -try { - const { chromium } = await import('playwright'); - try { browser = await chromium.launch({ headless: true }); } catch { browser = await chromium.launch({ headless: true, channel: 'chrome' }); } -} catch (e) { skipWhy = (e as Error).message.split('\n')[0]!; } -if (!browser) console.warn(`console-fill browser tests skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`); +// launched once for the whole file (module level: bun's hook timeouts do not apply, LAUNCH_TIMEOUT_MS does) +const shared = await launchTestBrowser('playwright'); +const { browser, skipWhy } = shared; +if (!browser) console.warn(`console-fill browser tests skipped: no Chromium installed (${skipWhy}). Run \`bunx playwright install chromium\`.`); +/** The contexts and engine runs of the current test, closed / awaited right after it (afterEach below). */ +const scope = testScope(() => browser); +/** Browser tests: a few seconds each on an idle machine; the timeout leaves room for a loaded one. */ +const BROWSER_TEST_MS = 30_000; +/** SLOW tests (engine "not here" timeouts, Chromium relaunches): ~5-10 s idle. */ +const SLOW_TEST_MS = 90_000; +/** Engine waits that are expected to SUCCEED: they return as soon as the element is there, so a long cap costs nothing. */ +const FOUND_MS = 15_000; const FIX = join(import.meta.dir, 'fixtures', 'console'); /** Console URLs of the navigation plans -> modeled pages (bases: asc = asc, play = play). */ @@ -191,10 +200,12 @@ beforeAll(() => { } }); base = `http://127.0.0.1:${server.port}/`; }); -afterAll(async () => { server?.stop(true); await browser?.close(); }, 30_000); // closing every context of the run can take a few seconds +// bounded: every context is closed per test (afterEach) and each close is capped (tests/helpers/browser.ts) +afterEach(() => scope.settle(), AFTER_EACH_MS); +afterAll(async () => { await shared.close(); server?.stop(true); }, AFTER_ALL_MS); async function open(file: string) { - const page = await browser.newPage(); + const page = await scope.newPage(); await page.goto(base + file); return page; } @@ -223,7 +234,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { // the next poll finds nothing left to do expect((await fillPage(page, def, pageAnswers('apple-app-record'), new Set([0]))).section).toBeNull(); await page.close(); - }); + }, BROWSER_TEST_MS); test('User Access under a plain heading (real App Store Connect): the radios are found in the dialog', async () => { const page = await open('apple-app-record-heading.html'); @@ -233,7 +244,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(s.filled).toContain('name'); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('a lasting partial miss fills every field that was found and leaves only the missing one', async () => { const page = await open('apple-app-record-renamed.html'); @@ -246,7 +257,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(await checked(page, 'iOS')).toBe(true); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('a renamed label stops filling and falls back to guidance', async () => { const page = await open('apple-app-record-renamed.html'); @@ -258,7 +269,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(await clicks(page)).toEqual([]); expect(consoleResult('apple-app-record', config).guidance).toContain('Name: Example Game'); await page.close(); - }); + }, BROWSER_TEST_MS); test('app privacy: section by section as the owner moves on; Next / Save / Publish never clicked', async () => { const page = await open('apple-app-privacy.html'); @@ -291,7 +302,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(done.size).toBe(def.sections.length); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('content rating: full email in the page, Game, purchases yes, the rest empty + highlighted', async () => { const page = await open('play-content-rating.html'); @@ -312,7 +323,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(await page.getByRole('radiogroup', { name: /loot boxes/ }).getByRole('radio').evaluateAll((els: HTMLInputElement[]) => els.some(e => e.checked))).toBe(false); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('target audience: ages, appeal highlighted, ads yes', async () => { const page = await open('play-target-audience.html'); @@ -329,7 +340,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(await checked(page, /^Yes, my app contains ads/, 'radio')).toBe(true); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('sign-in detector and safeClick', async () => { const signin = await open('signin.html'); @@ -344,7 +355,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { expect(await safeClick(page.getByRole('button', { name: 'Cancel' }), 'Cancel')).toBe(true); expect(await clicks(page)).toEqual(['Cancel']); await page.close(); - }); + }, BROWSER_TEST_MS); }); // ---- navigation to the form after sign-in ---- @@ -394,10 +405,10 @@ describe('navigation plan (pure)', () => { }); describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { - const quiet = { timeoutMs: 1500, say: () => {} }; + const quiet = { timeoutMs: FOUND_MS, say: () => {} }; // every navigation with `quiet` is expected to succeed const navClicks = (page: any): Promise => page.evaluate(() => (window as any).__navClicks()); const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); }; - const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; + const fresh = async () => { const p = await scope.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => { const page = await fresh(); @@ -409,7 +420,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(s.filled).toContain('name'); expect(await clicks(page)).toEqual(['+']); // the + button only, never Create / Submit for Review await page.close(); - }); + }, BROWSER_TEST_MS); test('App Store Connect (TR): Uygulama Ekle > Yeni Uygulama; Oluştur and İncelemeye Gönder never clicked', async () => { const page = await fresh(); @@ -418,7 +429,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(await navClicks(page)).toEqual(['Uygulama Ekle', 'Yeni Uygulama']); expect(await clicks(page)).toEqual(['+']); await page.close(); - }); + }, BROWSER_TEST_MS); test('a missing step stops navigation, names the step and clicks nothing', async () => { const page = await fresh(); @@ -429,7 +440,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(await navClicks(page)).toEqual([]); expect(formMeta('apple-app-record', config).open[0]).toContain('New App'); await page.close(); - }); + }, BROWSER_TEST_MS); test('App Privacy: appId deep link, or app list > the app > App Privacy; two apps of one name -> stop and list', async () => { let page = await fresh(); @@ -447,7 +458,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(r).toMatchObject({ ok: false, failed: 'the app in the list', candidates: ['Example Game', 'Example Game'] }); expect(await navClicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('Play: the app by package name > Policy and programs > App content > Start / Manage; nothing deny-listed clicked', async () => { for (const [form, link, heading] of [['play-content-rating', 'Start', 'Content rating'], ['play-target-audience', 'Manage', 'Target audience and content']] as const) { @@ -460,7 +471,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(await page.getByRole('heading', { level: 1 }).textContent()).toBe(heading); await page.close(); } - }); + }, BROWSER_TEST_MS); test('navClick refuses a Start button, Start rollout, Save and Publish even when pointed at them', async () => { const page = await open('play-app-content.html'); @@ -472,7 +483,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect((await navClick(page.getByRole('button', { name: 'Publish' }))).clicked).toBe(false); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); test('already on the form: nothing is clicked', async () => { const page = await open('play-content-rating.html'); @@ -480,14 +491,14 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { expect(r).toMatchObject({ ok: true, steps: ['already open'] }); expect(await clicks(page)).toEqual([]); await page.close(); - }); + }, BROWSER_TEST_MS); }); // ---- sign-in during navigation, watching after the fallback, the session kept across relaunches ---- /** A browser context whose console hosts (appstoreconnect / idmsa / play.google.com) are served from the fixtures. */ async function consoleBrowser(map: (u: URL, cookie: string) => string | null): Promise { - const ctx = await browser.newContext(); + const ctx = scope.track(await browser.newContext()); await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, async (route: any) => { const u = new URL(route.request().url()); const cookie: string = (await route.request().headerValue('cookie')) ?? ''; @@ -500,22 +511,25 @@ async function consoleBrowser(map: (u: URL, cookie: string) => string | null): P const done = new Promise(r => ctx.on('close', () => { closed = true; r(); })); return { mode: 'profile', context: ctx, page, pages: () => ctx.pages(), closed: done, isClosed: () => closed, close: () => ctx.close(), cleanup: () => {} }; } -const until = async (what: string, fn: () => boolean | Promise, ms = 20_000, said?: string[]) => { - const end = Date.now() + ms; - while (Date.now() < end) { if (await fn()) return; await Bun.sleep(50); } - throw new Error(`timed out waiting for: ${what}${said ? `\n${said.join("\n")}` : ""}`); -}; -const tmpAccounts = () => join(mkdtempSync(join(tmpdir(), 'storebound-accounts-')), 'console-accounts.json'); -const fast = (said: string[]) => ({ say: (m: string) => { said.push(m); }, tickMs: 100, navTimeoutMs: 1500, signInWaitMs: 30_000, accountsFile: tmpAccounts(), env: {} }); +const tmpDirs: string[] = []; +afterAll(() => { for (const d of tmpDirs) rmSync(d, { recursive: true, force: true }); }); +const tmpAccounts = () => { const d = mkdtempSync(join(tmpdir(), 'storebound-accounts-')); tmpDirs.push(d); return join(d, 'console-accounts.json'); }; +/** + * The engine's timings scaled down for tests (production: tick 1 s, 20 s per navigation step, 10 min for a sign-in). + * navTimeoutMs is both how long a step that IS there may take to show up (headroom for a loaded machine) and what a + * step that is NOT there costs (the watching tests wait that out once), so it stays a few seconds, not FOUND_MS. + */ +const fast = (log: ReturnType) => ({ say: log.say, tickMs: 100, navTimeoutMs: 5000, signInWaitMs: 30_000, accountsFile: tmpAccounts(), env: {} }); +const FILLED = (lines: string[]) => lines.some(m => /^New App: filled \d+/.test(m)); describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the real console hosts, routed locally)', () => { test('ASC /login with an idmsa frame and no password field: detected mid-navigation, never touched; after sign-in navigation restarts at step 1', async () => { const b = await consoleBrowser((u, cookie) => u.hostname === 'idmsa.apple.com' ? 'idmsa-signin.html' : u.hostname !== 'appstoreconnect.apple.com' ? null : u.pathname === '/login' ? 'asc-login.html' : u.pathname === '/apps' ? (cookie.includes('myacinfo=') ? 'asc-apps.html' : 'asc-shell.html') : null); - const said: string[] = []; - const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) }); - await until('the sign-in hint', () => said.some(m => m.startsWith('sign in in the browser window'))); + const log = logLines(), said = log.lines; + const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) })); + await log.wait('the sign-in hint', l => l.some(m => m.startsWith('sign in in the browser window'))); expect(said.some(m => /^a sign-in page appeared at step/.test(m))).toBe(true); // the shell looked signed in, then /login expect(said.some(m => m.includes('Keep me signed in'))).toBe(true); expect(new URL(b.page.url()).pathname).toBe('/login'); @@ -524,40 +538,40 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the expect(await frame.evaluate(() => (window as any).__clicks)).toEqual([]); // nothing clicked on the sign-in form expect(await frame.locator('#acc').inputValue()).toBe(''); // nothing typed await b.page.evaluate(() => (window as any).__signIn()); // the owner signs in - await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said); + await log.wait('the New App dialog filled', FILLED); expect(said).toContain('signed in: opening the form again from step 1'); expect(await b.page.getByRole('textbox', { name: 'Name', exact: true }).inputValue()).toBe('Example Game'); expect(await clicks(b.page)).toEqual(['+']); // never Create / Submit for Review await b.context.close(); expect((await run).filled).toBeGreaterThan(0); - }, 40_000); + }, SLOW_TEST_MS); test('after the printed steps storebound keeps watching: the owner opens Apps by hand, navigation resumes at step 2 and fills', async () => { const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('owner') ? 'asc-apps.html' : 'asc-apps-noplus.html') : null); - const said: string[] = []; - const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) }); - await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps'))); + const log = logLines(), said = log.lines; + const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) })); + await log.wait('the printed steps', l => l.some(m => m.startsWith('open the form: Apps'))); expect(await clicks(b.page)).toEqual([]); await b.page.evaluate(() => { location.href = '/apps?owner=1'; }); // the owner navigates - await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said); + await log.wait('the New App dialog filled', FILLED); expect(said).toContain('the page changed: storebound opens the form from step 2/4'); expect(await b.page.evaluate(() => (window as any).__navClicks())).toEqual(['Add Apps', 'New App']); expect(await clicks(b.page)).toEqual(['+']); await b.context.close(); await run; - }, 40_000); + }, SLOW_TEST_MS); test('after the printed steps: the owner opens the dialog by hand, storebound sees it and fills it', async () => { const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('dialog') ? 'apple-app-record.html' : 'asc-apps-noplus.html') : null); - const said: string[] = []; - const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) }); - await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps'))); + const log = logLines(); + const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) })); + await log.wait('the printed steps', l => l.some(m => m.startsWith('open the form: Apps'))); await b.page.evaluate(() => { location.href = '/apps?dialog=1'; }); - await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said); + await log.wait('the New App dialog filled', FILLED); expect(await clicks(b.page)).toEqual([]); // not even + : the dialog was open await b.context.close(); await run; - }, 40_000); + }, SLOW_TEST_MS); test('resumeAt: the furthest step visible now, never the initial page load', async () => { const page = await open('asc-apps.html'); @@ -568,15 +582,17 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the await page.goto(base + 'asc-apps-noplus.html'); expect(await resumeAt(page, plan)).toBeNull(); await page.close(); - }); + }, BROWSER_TEST_MS); for (const store of ['apple', 'play'] as const) { test(`${store}: a session cookie survives closing and relaunching storebound's own profile`, async () => { const dir = mkdtempSync(join(tmpdir(), `storebound-profile-${store}-`)); const root = join(import.meta.dir, '..'); + // its own Chromium (a persistent profile), launched twice: SLOW, and the launch timeout is raised like the shared one + const opts = { store, profileDir: dir, fresh: true, headless: true, say: () => {}, launchTimeoutMs: LAUNCH_TIMEOUT_MS }; + let b: ConsoleBrowser | null = null; try { - const opts = { store, profileDir: dir, fresh: true, headless: true, say: () => {} }; - let b = await openConsoleBrowser(root, opts); + b = await openConsoleBrowser(root, opts); await b.page.goto(base + 'session-set'); await b.close(); // graceful: Chromium writes its cookie store await b.closed; @@ -586,8 +602,12 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the expect(await b.page.textContent('#c')).toBe('kept'); await b.close(); await b.closed; - } finally { rmSync(dir, { recursive: true, force: true }); } - }, 60_000); + } finally { + // a failed assertion must not leave this Chromium running into the next test + if (b && !b.isClosed()) await capped(b.context.close(), CLOSE_TIMEOUT_MS); + rmSync(dir, { recursive: true, force: true }); + } + }, 2 * LAUNCH_TIMEOUT_MS + SLOW_TEST_MS); // two Chromium launches (each capped) plus the test itself } }); @@ -627,7 +647,7 @@ describe('accounts (pure)', () => { describe.skipIf(!browser)('accounts (headless, modeled pages)', () => { const navClicks = (page: any): Promise => page.evaluate(() => (window as any).__navClicks()); - const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; + const fresh = async () => { const p = await scope.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; const DENIED = ['Sign Out', 'Edit Profile', 'Create', 'Submit for Review', 'Create app', 'Create developer account', 'Save', 'Publish']; test('App Store Connect, 3 teams, the bundle id in the 2nd: switched through the account menu, remembered, then picked first', async () => { @@ -655,7 +675,7 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => { expect(said2).toContain('team 1/3: Example Games Ltd'); for (const n of DENIED) expect(await navClicks(page)).not.toContain(n); await page.close(); - }, 60_000); + }, SLOW_TEST_MS); test('Play, one login in 5 developer accounts, the app in the 4th: found by package name, remembered, then opened directly', async () => { const file = tmpAccounts(), said: string[] = []; @@ -682,7 +702,7 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => { expect((await openAcross(page, { form: 'play-target-audience', config, say: m => { said3.push(m); }, bases: pb, navMs: 1500, file: tmpAccounts(), env: { STOREBOUND_PLAY_DEVELOPER_ID: '4444' } })).nav.ok).toBe(true); expect(said3.some(m => m.includes('developer accounts'))).toBe(false); await page.close(); - }, 60_000); + }, SLOW_TEST_MS); test('Play: a package in none of the developer accounts is said plainly; nothing deny-listed clicked', async () => { const page = await fresh(); @@ -693,5 +713,5 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => { expect(await clicks(page)).toEqual([]); for (const n of DENIED) expect(await navClicks(page)).not.toContain(n); await page.close(); - }, 60_000); + }, SLOW_TEST_MS); }); diff --git a/tests/console-session.test.ts b/tests/console-session.test.ts index f6602149..ec513de7 100644 --- a/tests/console-session.test.ts +++ b/tests/console-session.test.ts @@ -8,6 +8,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { chromeDataDir, CONSOLE_HOSTS, cookieApplies, copySession, devToolsEndpoint, filterCookies, NEVER_COPY, openConsoleBrowser, pickProfile, sessionFiles } from '../cli/console/session'; +import { capped, CLOSE_TIMEOUT_MS, LAUNCH_TIMEOUT_MS } from './helpers/browser'; const scratch = mkdtempSync(join(tmpdir(), 'sb-session-test-')); afterAll(() => rmSync(scratch, { recursive: true, force: true })); @@ -138,15 +139,19 @@ describe.skipIf(!hasChrome)('copy mode with real Chrome (throwaway profile, loca } }); const site = `http://127.0.0.1:${server.port}`, other = `http://localhost:${server.port}`; const src = tmp('chrome-real'); + // two real Chrome launches: SLOW; launch timeouts raised like the shared browser's (tests/helpers/browser.ts), and + // whatever is still open is closed in `finally`, so a failed assertion leaves no Chrome running + let seed: any = null, b: any = null; try { - const opts = { channel: 'chrome', headless: true, ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'] }; - const seed = await chromium.launchPersistentContext(src, opts); + const opts = { channel: 'chrome', headless: true, timeout: LAUNCH_TIMEOUT_MS, ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'] }; + seed = await chromium.launchPersistentContext(src, opts); const p0 = seed.pages()[0] ?? await seed.newPage(); await p0.goto(`${site}/set`); await p0.goto(`${other}/set`); await seed.close(); + seed = null; const said: string[] = []; - const b = await openConsoleBrowser(join(import.meta.dir, '..'), { - store: 'apple', profileDir: tmp('own-profile'), say: m => said.push(m), chromeDir: src, hosts: ['127.0.0.1'], headless: true, platform: 'darwin', + b = await openConsoleBrowser(join(import.meta.dir, '..'), { + store: 'apple', profileDir: tmp('own-profile'), say: m => said.push(m), chromeDir: src, hosts: ['127.0.0.1'], headless: true, platform: 'darwin', launchTimeoutMs: LAUNCH_TIMEOUT_MS, }); expect(b.mode).toBe('copy'); expect(said.join('\n')).toContain('your Chrome sign-in'); @@ -159,6 +164,10 @@ describe.skipIf(!hasChrome)('copy mode with real Chrome (throwaway profile, loca await b.context.close(); await b.closed; expect(existsSync(b.tempDir!)).toBe(false); - } finally { server.stop(true); } - }, 60_000); + } finally { + if (seed) await capped(seed.close(), CLOSE_TIMEOUT_MS); + if (b && !b.isClosed()) { await capped(b.context.close(), CLOSE_TIMEOUT_MS); b.cleanup(); } + server.stop(true); + } + }, 2 * LAUNCH_TIMEOUT_MS); // bounded by the two launches; ~3 s on an idle machine }); diff --git a/tests/helpers/browser.ts b/tests/helpers/browser.ts new file mode 100644 index 00000000..7568a95d --- /dev/null +++ b/tests/helpers/browser.ts @@ -0,0 +1,120 @@ +// Shared plumbing of the headless browser tests (tests/console-fill.test.ts, tests/site-overflow.test.ts, +// tests/console-session.test.ts). They used to time out now and then, mostly when the machine was busy: +// - the afterAll browser close (30 s, "(unnamed)" hook timeout). Cause: Google Chrome (the fallback when +// playwright's own Chromium is not downloaded) often hangs in its own shutdown after loading http pages and only +// exits when its 10 s teardown watchdog fires ("Teardown watchdog expired" in DEBUG=pw:browser); under load that +// passed 30 s. Measured on an idle machine: 10-30 s per close. The shared browser is a throwaway profile with nothing +// to flush, so it is launched as a browser server and KILLED at the end (milliseconds), not closed gracefully +// - Chromium's 30 s default launch timeout: one launch per file now, with an explicit, generous launch timeout; a +// launch that times out fails the file instead of quietly skipping it (a skip under load would hide lost +// coverage); only a browser that is not installed skips +// - every context of the run left open until afterAll, and a failed test's contexts and engine loops running into +// the next test: every context a test opens is tracked and closed right after it (afterEach) +// - polling sleeps in the waits for log lines: event-driven now (resolved on each new line) +// Hook timeouts are bounded by the numbers below (each close is capped), never open-ended. +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** Launching Chromium: well above a cold start on a loaded machine (seconds), far below "hung". */ +export const LAUNCH_TIMEOUT_MS = 60_000; +/** One context close, or an engine run ending after its window closed; longer is abandoned (and the browser killed). */ +export const CLOSE_TIMEOUT_MS = 15_000; +/** + * Hook timeouts. afterEach: a test's contexts close in parallel, each capped at CLOSE_TIMEOUT_MS, then the engine runs + * it started, each capped at CLOSE_TIMEOUT_MS. afterAll: disconnect (capped) and kill the browser server. + */ +export const AFTER_EACH_MS = 2 * CLOSE_TIMEOUT_MS + 5_000; +export const AFTER_ALL_MS = CLOSE_TIMEOUT_MS + 5_000; + +/** Waits for `p` (its error ignored) or `ms`, whichever is first: true when `p` settled in time. Never rejects. */ +export async function capped(p: Promise, ms: number): Promise { + let t: ReturnType | undefined; + const ok = await Promise.race([p.then(() => true, () => true), new Promise(r => { t = setTimeout(() => r(false), ms); })]); + clearTimeout(t); + return ok; +} + +export interface TestBrowser { + /** A connected Playwright Browser, or null when no Chromium is installed (then the browser tests skip). */ + browser: any; + skipWhy: string; + /** afterAll: disconnects and kills the browser process (a throwaway profile: nothing to flush). Fast and bounded. */ + close: () => Promise; +} + +/** + * Launches headless Chromium once, as a browser server the tests connect to: playwright's own build, else Google Chrome + * (channel "chrome"). `browser` is null only when neither is installed; a launch that times out or crashes throws. + */ +export async function launchTestBrowser(pkg: 'playwright' | 'playwright-core'): Promise { + const none = (e: unknown): TestBrowser => ({ browser: null, skipWhy: firstLine(e), close: async () => {} }); + let chromium: any; + try { chromium = (await import(pkg)).chromium; } catch (e) { return none(e); } + const opts = { headless: true, timeout: LAUNCH_TIMEOUT_MS }; + let server: any; + try { server = await chromium.launchServer(opts); } catch (e) { + if (!notInstalled(e)) throw e; + try { server = await chromium.launchServer({ ...opts, channel: 'chrome' }); } catch (e2) { + if (!notInstalled(e2)) throw e2; + return none(e); + } + } + let browser: any; + try { browser = await chromium.connect(server.wsEndpoint(), { timeout: LAUNCH_TIMEOUT_MS }); } catch (e) { await server.kill(); throw e; } + return { + browser, skipWhy: '', + close: async () => { + await capped(browser.close(), CLOSE_TIMEOUT_MS); // a connected browser: closes its contexts and disconnects + await server.kill(); // SIGKILL, then playwright removes the temporary profile + }, + }; +} +const firstLine = (e: unknown) => (e as Error).message.split('\n')[0]!; +/** Playwright's "no such browser" errors (bundled build not downloaded, Chrome channel not installed). */ +const notInstalled = (e: unknown) => /Executable doesn't exist|distribution '[^']+' is not found|Failed to launch .* because executable/i.test((e as Error).message); + +/** + * The contexts and engine runs of the current test. `newPage` opens a page in a fresh context (as browser.newPage + * does) and tracks it; `track` adds one opened elsewhere; `settle` (afterEach) closes them all and waits for the runs. + */ +export function testScope(browser: () => any) { + const contexts = new Set(); + const runs = new Set>(); + return { + async newPage(opts?: Record): Promise { + const ctx = await browser().newContext(opts); + contexts.add(ctx); + return ctx.newPage(); + }, + track(ctx: T): T { contexts.add(ctx); return ctx; }, + /** An engine run (fillSession ...) that ends when its context closes. */ + run(p: Promise): Promise { runs.add(p); return p; }, + async settle(): Promise { + const cs = [...contexts], rs = [...runs]; + contexts.clear(); runs.clear(); + await Promise.all(cs.map(c => capped(c.close(), CLOSE_TIMEOUT_MS))); + await Promise.all(rs.map(r => capped(r, CLOSE_TIMEOUT_MS))); + }, + }; +} + +/** + * The log lines of an engine run (`say`), with event-driven waits: `wait` resolves on the line that makes `pred` + * true (checked on every new line, no polling) and fails after `ms` with every line seen so far. + */ +export function logLines() { + const lines: string[] = []; + const waiters = new Set<() => void>(); + return { + lines, + say: (m: string) => { lines.push(m); for (const w of [...waiters]) w(); }, + wait(what: string, pred: (lines: string[]) => boolean, ms = 30_000): Promise { + if (pred(lines)) return Promise.resolve(); + return new Promise((resolve, reject) => { + const check = () => { if (pred(lines)) { done(); resolve(); } }; + const t = setTimeout(() => { done(); reject(new Error(`timed out after ${ms} ms waiting for: ${what}\n${lines.join('\n')}`)); }, ms); + const done = () => { clearTimeout(t); waiters.delete(check); }; + waiters.add(check); + }); + }, + }; +} diff --git a/tests/site-overflow.test.ts b/tests/site-overflow.test.ts index a2dc1398..d37a9904 100644 --- a/tests/site-overflow.test.ts +++ b/tests/site-overflow.test.ts @@ -1,28 +1,28 @@ // The site (site/index.html) never scrolls sideways: at every viewport width from 320 to 1440 px (10 px steps), in the // light and the dark theme, document.documentElement.scrollWidth stays within innerWidth. On a failure it names the // elements whose right edge passes the viewport outside any scroll container (pseudo-elements show as their owner). -// Uses the bundled playwright-core with its Chromium (or Google Chrome); skips when neither can launch. -import { afterAll, describe, expect, test } from 'bun:test'; +// Uses the bundled playwright-core with its Chromium (or Google Chrome); skips when neither is installed (a launch that +// times out on a busy machine fails instead). One launch, the context closed right after each test, capped closes +// (tests/helpers/browser.ts). SLOW on purpose: 113 widths x 2 themes, each a resize and a layout read. +import { afterAll, afterEach, describe, expect, test } from 'bun:test'; import { join } from 'node:path'; +import { AFTER_ALL_MS, AFTER_EACH_MS, launchTestBrowser, testScope } from './helpers/browser'; const page = 'file://' + join(import.meta.dir, '..', 'site', 'index.html'); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -let browser: any = null; -let skipWhy = ''; -try { - const { chromium } = await import('playwright-core'); - try { browser = await chromium.launch({ headless: true }); } catch { browser = await chromium.launch({ headless: true, channel: 'chrome' }); } -} catch (e) { skipWhy = (e as Error).message.split('\n')[0]!; } -if (!browser) console.warn(`site overflow test skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`); +const shared = await launchTestBrowser('playwright-core'); +const { browser, skipWhy } = shared; +if (!browser) console.warn(`site overflow test skipped: no Chromium installed (${skipWhy}). Run \`bunx playwright install chromium\`.`); +const scope = testScope(() => browser); -afterAll(async () => { await browser?.close(); }); +// bounded: one context per test, each close capped (bun's 5 s default hook timeout was too tight for Chrome's slow shutdown) +afterEach(() => scope.settle(), AFTER_EACH_MS); +afterAll(() => shared.close(), AFTER_ALL_MS); describe.skipIf(!browser)('site: no horizontal overflow', () => { for (const scheme of ['light', 'dark'] as const) { test(`320-1440 px, ${scheme}`, async () => { - const ctx = await browser.newContext({ colorScheme: scheme, viewport: { width: 1440, height: 900 } }); - const p = await ctx.newPage(); + const p = await scope.newPage({ colorScheme: scheme, viewport: { width: 1440, height: 900 } }); await p.goto(page, { waitUntil: 'load' }); const bad: string[] = []; for (let w = 320; w <= 1440; w += 10) { @@ -44,7 +44,6 @@ describe.skipIf(!browser)('site: no horizontal overflow', () => { }); if (r) bad.push(r); } - await ctx.close(); expect(bad).toEqual([]); }, 120_000); }