Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions packages/renderers/testing/playwright/bounded.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// A bound on each request a test makes of the stage page, kept in the test process.
import type {StageState} from '../src/types.js'

/**
* How long one stage request may take before it fails, ms. The stage's own waits are bounded in the page (a frame's
* arrival at its height at 60 s, a probe measurement at 10 s) and a heavy scenario loads in under 15 s on a slow
* runner, so a request still unanswered after this is stuck: a renderer that never acknowledged a paint (`seek` waits
* for it with no bound of its own), or a page that no longer runs. The bound is in the test process because the page's
* own timers can't fire in the second case: WebKit runs the sandboxed renderer frame in the host page's process,
* so a renderer stuck in its document stops the host's event loop with it.
*/
export const stageRequestTimeoutMs = 90_000

/** What the test last heard from the stage, for a request that goes unanswered. */
export class StageRecord {
scenario: string | undefined
state: StageState | undefined
answered: string | undefined
at = Date.now()

/** Notes a request's answer: a state it returned, and that the page still answered then. */
heard(what: string, value: unknown): void {
this.answered = what
this.at = Date.now()
if (isState(value)) this.state = value
}

/** The stage's last known state, in a line. */
describe(): string {
const state = this.state
const shown = state
? `status ${state.status}${state.bundle ? `, renderer ${state.bundle}` : ''}${state.comparisonMode ? `, ${state.comparisonMode}` : ''}, progress ${state.progress}, painted ${state.rendered ?? 'nothing'}${state.height === undefined ? '' : `, asked for ${state.height}px`}${state.errors.length ? `, errors: ${state.errors.join('; ')}` : ''}`
: 'no state yet'
const last = this.answered ? `; it last answered ${this.answered} ${((Date.now() - this.at) / 1000).toFixed(1)} s before` : ''
return `${shown}${last}`
}
}

function isState(value: unknown): value is StageState {
return typeof value === 'object' && value !== null && 'status' in value && 'progress' in value && 'errors' in value
}

/**
* Resolves with `request`, or fails after `stageRequestTimeoutMs` naming it, the scenario and the stage's last known
* state. A request left unanswered is rejected once Playwright closes the page; that rejection is ignored.
*/
export async function bounded<T>(record: StageRecord, what: string, request: Promise<T>, timeoutMs = stageRequestTimeoutMs): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
const expired = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
request.catch(() => {})
const scenario = record.scenario ? ` for ${record.scenario}` : ''
reject(
new Error(
`The stage page didn't answer ${what}${scenario} within ${timeoutMs / 1000} s: a renderer that never acknowledged its paint, or a page (with the renderer frame in its process) that stopped running. Last known: ${record.describe()}.`,
),
)
}, timeoutMs)
})
try {
const value = await Promise.race([request, expired])
record.heard(what, value)
return value
} finally {
clearTimeout(timer)
}
}
55 changes: 35 additions & 20 deletions packages/renderers/testing/playwright/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {DefaultComparatorOptions, Comparison, Extraction} from '@githubnext
import type {FilterPayload, RendererOptions} from '@githubnext/projections-renderer-sdk/protocol'
import type {FixturesInspector, InspectorOptions} from './server.js'
import {startInspector} from './server.js'
import {bounded, StageRecord} from './bounded.js'
import type {
CheckId,
CheckResult,
Expand All @@ -33,6 +34,7 @@ declare global {
}

export {connectInspector, startInspector} from './server.js'
export {stageRequestTimeoutMs} from './bounded.js'
export type {FixturesInspector, InspectorOptions} from './server.js'

/**
Expand Down Expand Up @@ -106,9 +108,15 @@ export interface StageHandle {
state(): Promise<StageState>
}

function handle(page: Page, subject: StageSubject): StageHandle {
/** A request of the stage page, bounded (see `bounded`) and named `what` in a failure. */
const ask = <T>(record: StageRecord, what: string, run: () => Promise<T>): Promise<T> => bounded(record, what, run())

function handle(page: Page, subject: StageSubject, record: StageRecord): StageHandle {
const call = <T>(what: string, run: () => Promise<T>) => ask(record, what, run)
const seek = (progress: number, options: StageSeek = {}) =>
page.evaluate(([progress, options]) => window.projectionsStage.seek(progress, options), [progress, options] as const)
call(`seek(${progress})`, () =>
page.evaluate(([progress, options]) => window.projectionsStage.seek(progress, options), [progress, options] as const),
)
return {
page,
frame: page.frameLocator('#stage-frame iframe'),
Expand All @@ -125,16 +133,20 @@ function handle(page: Page, subject: StageSubject): StageHandle {
await check(progress)
}
},
select: id => page.evaluate(id => window.projectionsStage.select(id), id),
setOptions: options => page.evaluate(options => window.projectionsStage.setOptions(options), options),
action: id => page.evaluate(id => window.projectionsStage.action(id), id),
hover: id => page.evaluate(id => window.projectionsStage.hover(id), id),
filter: payload => page.evaluate(payload => window.projectionsStage.filter(payload), payload),
setEnvironment: environment => page.evaluate(environment => window.projectionsStage.setEnvironment(environment), environment),
setWidth: width => page.evaluate(width => window.projectionsStage.setWidth(width), width),
measure: <T>(call: ProbeCall, args?: unknown) =>
page.evaluate(([call, args]) => window.projectionsStage.measure(call, args), [call, args] as const) as Promise<T>,
state: () => page.evaluate(() => window.projectionsStage.state()),
select: id => call('select', () => page.evaluate(id => window.projectionsStage.select(id), id)),
setOptions: options => call('setOptions', () => page.evaluate(options => window.projectionsStage.setOptions(options), options)),
action: id => call(`action(${id})`, () => page.evaluate(id => window.projectionsStage.action(id), id)),
hover: id => call('hover', () => page.evaluate(id => window.projectionsStage.hover(id), id)),
filter: payload => call('filter', () => page.evaluate(payload => window.projectionsStage.filter(payload), payload)),
setEnvironment: environment =>
call('setEnvironment', () => page.evaluate(environment => window.projectionsStage.setEnvironment(environment), environment)),
setWidth: width => call(`setWidth(${width})`, () => page.evaluate(width => window.projectionsStage.setWidth(width), width)),
measure: <T>(probe: ProbeCall, args?: unknown) =>
call(
`measure(${probe})`,
() => page.evaluate(([probe, args]) => window.projectionsStage.measure(probe, args), [probe, args] as const) as Promise<T>,
),
state: () => call('state', () => page.evaluate(() => window.projectionsStage.state())),
}
}

Expand All @@ -150,14 +162,15 @@ export async function openStage(
request: OpenRequest | ({scenario: string} & Omit<Partial<StageLoad>, 'subject' | 'renderer'>),
): Promise<StageHandle> {
await stagePage(page, inspector)
const record = new StageRecord()
if ('scenario' in request) {
const {scenario, ...overrides} = request
await page.evaluate(([scenario, overrides]) => window.projectionsStage.loadScenario(scenario, overrides), [
scenario,
overrides,
] as const)
const subject = await page.evaluate(() => window.projectionsStage.subject())
return handle(page, subject)
record.scenario = scenario
await ask(record, 'loadScenario', () =>
page.evaluate(([scenario, overrides]) => window.projectionsStage.loadScenario(scenario, overrides), [scenario, overrides] as const),
)
const subject = await ask(record, 'subject', () => page.evaluate(() => window.projectionsStage.subject()))
return handle(page, subject, record)
}
const {extraction, before, after, comparison, comparatorOptions, ...rest} = request as OpenRequest &
Partial<{
Expand All @@ -182,8 +195,10 @@ export async function openStage(
))
subject = {mode: 'comparison', before, after, comparison: computed}
} else throw new Error('openStage needs a scenario, an extraction, or before and after extractions')
await page.evaluate(json => window.projectionsStage.load(JSON.parse(json)), JSON.stringify({...rest, subject} satisfies StageLoad))
return handle(page, subject)
await ask(record, 'load', () =>
page.evaluate(json => window.projectionsStage.load(JSON.parse(json)), JSON.stringify({...rest, subject} satisfies StageLoad)),
)
return handle(page, subject, record)
}

/** Opens the fixtures workbench, optionally at one scenario. */
Expand Down
14 changes: 14 additions & 0 deletions packages/renderers/testing/test/helpers.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {join} from 'node:path'
import {test} from 'node:test'
import {allChecks, checkTitles, runChecks} from '../dist/src/index.js'
import {checkFailures, connectInspector, samples, scenarioKeys} from '../dist/playwright/index.js'
import {StageRecord, bounded} from '../dist/playwright/bounded.js'

test('scenario keys use the directory name for scenarios.json and the file name otherwise', () => {
const root = mkdtempSync(join(tmpdir(), 'projections-testing-'))
Expand Down Expand Up @@ -654,3 +655,16 @@ test('nested-accents measures the animation in animated mode, after the diff', a
// The diff is measured first; the animation's first step is loaded in animated mode again, the next sought.
assert.deepEqual(calls.slice(1), ['load animated 0', 'load diff 1', 'load animated 0.5', 'seek 0.75'])
})

test('a stage request the page never answers fails, naming it, the scenario and what the stage last said', async () => {
const record = new StageRecord()
record.scenario = 'graph/npm-express-5'
const state = {status: 'ready', bundle: 'graph', comparisonMode: 'diff', progress: 1, rendered: 1, height: 1217, errors: []}
assert.equal(await bounded(record, 'state', Promise.resolve(state), 1000), state)
await assert.rejects(
bounded(record, 'measure(settle)', new Promise(() => {}), 50),
error =>
/didn't answer measure\(settle\) for graph\/npm-express-5 within 0\.05 s/.test(error.message) &&
/status ready, renderer graph, diff, progress 1, painted 1, asked for 1217px; it last answered state/.test(error.message),
)
})
Loading