Unverified Commit 5b8c866c authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[test] Skip hooks of suites skipped by a lazy `@force-gate` (#98169)

A `describe` gated by a lazy `// @force-gate` (a condition read off the
fixture's resolved config, like `cacheComponents`) cannot be skipped at
collection time, so the gate runtime force-passes its tests at runtime
and `nextTestSetup` skips the fixture build. Hooks registered inside
such a `describe` still ran, because only the `it`/`test` globals were
wrapped. A hook that touches the `next` instance (for example a
`beforeEach` that reads `next.cliOutput`) then failed with `next
instance is not initialized yet` and failed the supposedly skipped
suite.

The gate runtime now wraps the
`beforeAll`/`afterAll`/`beforeEach`/`afterEach` globals as well and
skips a hook registered under a lazy `@force-gate` when that gate
evaluates false against the fixture's resolved config. Only a false lazy
force-gate skips a hook: an inverted `@gate` still runs its tests and
therefore needs its hooks, and a static `@force-gate` already skips the
whole `describe` at collection time. The hooks `nextTestSetup` registers
itself are marked with the new `ungatedHook` helper so that the skip
decision and the fixture cleanup still run.

The `cacheComponents disabled, edge app router` describe in
`test/e2e/cache-handlers-upstream-wiring` is converted from the
`process.env.__NEXT_CACHE_COMPONENTS` `describe.skip` ternary to `//
@force-gate !cacheComponents`, replacing a fake-green skip and
exercising the fixed path. The `!deploy` conversion of the remaining
describes is left to the branch that introduces the `deploy` condition.
Co-authored-by: 's avatarClaude Code (kimi-k3[1m]) <noreply@anthropic.com>
parent 5cca033c
......@@ -159,7 +159,9 @@ single dimension.
body's cleanup (e.g. a browser context left offline), so later tests may
fail for cascade reasons. Acceptable for a tripwire, but don't puzzle over
the individual failure messages in a gated-off run.
- `afterEach` failures (e.g. redbox matchers) are not gated — only the body is.
- `afterEach` failures (e.g. redbox matchers) are not gated, only the body is.
Hooks under a false lazy `@force-gate` are the exception: they are skipped
with the suite instead of running against a fixture that was never booted.
- `jest.retryTimes(1)` on non-dev CI means a _flaky_ gated-false test passes
whenever it happens to fail; the tripwire is only deterministic for
deterministic tests.
......
......@@ -98,40 +98,38 @@ describe('cache-handlers-upstream-wiring', () => {
})
})
})
;(process.env.__NEXT_CACHE_COMPONENTS ? describe.skip : describe)(
'cacheComponents disabled, edge app router',
() => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'fixtures/edge-without-cache-components'),
skipDeployment: true,
})
// @force-gate !cacheComponents
describe('cacheComponents disabled, edge app router', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'fixtures/edge-without-cache-components'),
skipDeployment: true,
})
if (skipped) {
return
}
if (skipped) {
return
}
let outputIndex = 0
let outputIndex = 0
beforeEach(() => {
outputIndex = next.cliOutput.length
})
beforeEach(() => {
outputIndex = next.cliOutput.length
})
it('uses configured cacheHandler for edge app page and edge app route', async () => {
const edgePageResponse = await next.fetch('/edge-page')
expect(edgePageResponse.status).toBe(200)
it('uses configured cacheHandler for edge app page and edge app route', async () => {
const edgePageResponse = await next.fetch('/edge-page')
expect(edgePageResponse.status).toBe(200)
const edgeRouteResponse = await next.fetch('/api/edge-route')
expect(edgeRouteResponse.status).toBe(200)
expect(await edgeRouteResponse.json()).toEqual({ ok: true })
const edgeRouteResponse = await next.fetch('/api/edge-route')
expect(edgeRouteResponse.status).toBe(200)
expect(await edgeRouteResponse.json()).toEqual({ ok: true })
await retry(async () => {
const output = next.cliOutput.slice(outputIndex)
const constructorLogs =
output.match(/WiringIncrementalCacheHandler::constructor/g) ?? []
await retry(async () => {
const output = next.cliOutput.slice(outputIndex)
const constructorLogs =
output.match(/WiringIncrementalCacheHandler::constructor/g) ?? []
expect(constructorLogs.length).toBeGreaterThanOrEqual(2)
})
expect(constructorLogs.length).toBeGreaterThanOrEqual(2)
})
}
)
})
})
})
......@@ -17,6 +17,7 @@ import {
getActiveDescribeGates,
hasLazyForceGate,
findLazyForceSkip,
ungatedHook,
} from '../gate/runtime'
export type { NextInstance }
......@@ -382,74 +383,84 @@ export function nextTestSetup(
let next: NextInstance | undefined
if (!skipped) {
beforeAll(async () => {
if (!buildForceGated) {
next = await createNext(options)
return
}
// Try to decide the force-gate against the *source* fixture first,
// before paying for the fixture setup (which includes a dependency
// install when the run is isolated). The config resolver falls back to
// the repo's own `next` when the directory has no install, and the env
// mirrors what `getSpawnOpts` hands every fixture child process. An
// inline `files` object has no directory to resolve against, and any
// resolution failure (e.g. a config that imports from the fixture's
// own node_modules) falls through to the instance-based decision below.
if (typeof options.files === 'string') {
const config = await loadResolvedConfig({
dir: options.files,
phase: isNextDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,
env: {
...process.env,
...options.env,
NODE_ENV: (options.env?.NODE_ENV ||
'') as NodeJS.ProcessEnv['NODE_ENV'],
PORT: '0',
__NEXT_TEST_MODE: 'e2e',
},
}).catch(() => null)
const earlySkip = config && findLazyForceSkip(describeGates, config)
if (earlySkip) {
// No instance ever exists on this path, so register the resolved
// config directly for the per-test force-pass decisions.
registerFixture({ getResolvedConfig: async () => config })
// `ungatedHook`: this hook makes the lazy `@force-gate` skip decision, so
// it must run even (especially) when that decision is "skip".
beforeAll(
ungatedHook(async () => {
if (!buildForceGated) {
next = await createNext(options)
return
}
// Try to decide the force-gate against the *source* fixture first,
// before paying for the fixture setup (which includes a dependency
// install when the run is isolated). The config resolver falls back to
// the repo's own `next` when the directory has no install, and the env
// mirrors what `getSpawnOpts` hands every fixture child process. An
// inline `files` object has no directory to resolve against, and any
// resolution failure (e.g. a config that imports from the fixture's
// own node_modules) falls through to the instance-based decision below.
if (typeof options.files === 'string') {
const config = await loadResolvedConfig({
dir: options.files,
phase: isNextDev
? PHASE_DEVELOPMENT_SERVER
: PHASE_PRODUCTION_BUILD,
env: {
...process.env,
...options.env,
NODE_ENV: (options.env?.NODE_ENV ||
'') as NodeJS.ProcessEnv['NODE_ENV'],
PORT: '0',
__NEXT_TEST_MODE: 'e2e',
},
}).catch(() => null)
const earlySkip = config && findLazyForceSkip(describeGates, config)
if (earlySkip) {
// No instance ever exists on this path, so register the resolved
// config directly for the per-test force-pass decisions.
registerFixture({ getResolvedConfig: async () => config })
require('console').warn(
` ⚠ suite build skipped by \`@force-gate ${earlySkip.source}\` ` +
`(decided from the source fixture; setup skipped)`
)
return
}
}
// Set the fixture up (so its config is resolvable) without building, then
// resolve the force-gate. If it's false, skip the build entirely — the
// inherited gate makes every test force-pass, so nothing touches `next`.
const instance = await createNext({ ...options, skipStart: true })
next = instance
const config = await instance.getResolvedConfig()
const forceSkip = findLazyForceSkip(describeGates, config)
if (forceSkip) {
require('console').warn(
` ⚠ suite build skipped by \`@force-gate ${earlySkip.source}\` ` +
`(decided from the source fixture; setup skipped)`
` ⚠ suite build skipped by \`@force-gate ${forceSkip.source}\``
)
return
}
}
// Set the fixture up (so its config is resolvable) without building, then
// resolve the force-gate. If it's false, skip the build entirely — the
// inherited gate makes every test force-pass, so nothing touches `next`.
const instance = await createNext({ ...options, skipStart: true })
next = instance
const config = await instance.getResolvedConfig()
const forceSkip = findLazyForceSkip(describeGates, config)
if (forceSkip) {
require('console').warn(
` ⚠ suite build skipped by \`@force-gate ${forceSkip.source}\``
)
return
}
try {
await instance.start()
} catch (err) {
await instance.destroy().catch(() => {})
next = undefined
throw err
}
})
afterAll(async () => {
// Gracefully destroy the instance if `createNext` success.
// If next instance is not available, it's likely beforeAll hook failed and unnecessarily throws another error
// by attempting to destroy on undefined.
await next?.destroy()
// The early force-skip path registers a config source without an
// instance (an instance clears itself on destroy).
if (!next) clearFixture()
})
try {
await instance.start()
} catch (err) {
await instance.destroy().catch(() => {})
next = undefined
throw err
}
})
)
// `ungatedHook`: teardown must run even when the suite was force-skipped,
// otherwise the fixture leaks into the next describe's gate decisions.
afterAll(
ungatedHook(async () => {
// Gracefully destroy the instance if `createNext` success.
// If next instance is not available, it's likely beforeAll hook failed and unnecessarily throws another error
// by attempting to destroy on undefined.
await next?.destroy()
// The early force-skip path registers a config source without an
// instance (an instance clears itself on destroy).
if (!next) clearFixture()
})
)
}
const nextProxy = new Proxy<NextInstance>({} as NextInstance, {
......
......@@ -201,7 +201,9 @@ var is not what the fixture actually resolved.
through Jest's native `test.failing` and the inversion is Jest's own. A
lazy gate can't be decided until the fixture's config resolves, so those
tests wrap the body and invert the outcome at runtime. The `it`/`test`
globals are wrapped so a gate on a `describe` reaches the tests inside.
globals are wrapped so a gate on a `describe` reaches the tests inside. The
`beforeAll`/`afterAll`/`beforeEach`/`afterEach` globals are wrapped too, but
only to skip hooks registered under a false lazy `@force-gate`.
4. `state.ts` holds the fixture `createNext()` registered;
`NextInstance.getResolvedConfig()` resolves its config out of process (in
process, `loadConfig` would mutate the Jest worker's `process.env` from the
......@@ -226,7 +228,9 @@ A suite with no lazy gate never resolves a config, so the cost is zero.
anyway. In practice `createRouterAct` and Playwright fail fast instead of
stalling.
- Only the test body is gated. A failure from an `afterEach` (e.g. the redbox
matchers) still fails the test.
matchers) still fails the test. Hooks registered inside a `describe` whose
lazy `@force-gate` is false are the one exception: the suite's build and
tests are skipped, so its hooks are skipped too.
- `jest.retryTimes(1)` is on for non-dev CI. A stale gate fails deterministically
on both attempts, but a *flaky* gated-false test now "passes" whenever it
happens to fail.
......
......@@ -29,12 +29,19 @@
*
* ## `@force-gate`
*
* `// @force-gate <condition>` skips the test for real (`○ skipped`) when the
* condition is false. That requires a decision at collection time, so it only
* accepts static conditions, and it gives up the stale-gate tripwire entirely.
* Prefer `@gate`; reach for `@force-gate` only when running the body is
* impossible rather than merely failing — dev mode has no build output, deploy
* mode cannot touch the filesystem.
* `// @force-gate <condition>` skips the test when the condition is false,
* giving up the stale-gate tripwire entirely. Prefer `@gate`; reach for
* `@force-gate` only when running the body is impossible rather than merely
* failing: dev mode has no build output, deploy mode cannot touch the
* filesystem.
*
* A static condition is decided at collection time, a real Jest
* `○ skipped`. A *lazy* one (read off the fixture's resolved config) cannot
* be known then, so it force-passes the test at runtime instead (see
* `wrapGatedBody`), and on a `describe` it also skips the fixture build
* (`nextTestSetup`). Hooks registered inside such a `describe` are skipped
* too (see `wrapGatedHook`): the fixture they would prepare or inspect was
* never booted.
*/
import { evaluate, parse, type ExprNode } from './expr'
......@@ -71,6 +78,23 @@ const describeGateStack: Gate[] = []
/** Bodies this module already wrapped, so inherited gates are not re-applied. */
const gatedBodies = new WeakSet<Function>()
/**
* Hook callbacks the harness itself registered (`nextTestSetup`'s setup and
* teardown) while a gated `describe` body was being collected. They must run
* even when a lazy `@force-gate` skips the suite: they are what makes the
* skip decision, and they clear the fixture afterwards.
*/
const ungatedHooks = new WeakSet<Function>()
/**
* Marks a hook callback as harness-internal so `wrapHookGlobals` leaves it
* alone. Suite code never needs this.
*/
export function ungatedHook<T extends Function>(hook: T): T {
ungatedHooks.add(hook)
return hook
}
function staleGateMessage(gate: Gate): string {
return (
`Gated test passed unexpectedly.\n\n` +
......@@ -280,6 +304,39 @@ function wrapGatedBody(
return body as jest.ProvidesCallback
}
/**
* The hook counterpart of `wrapGatedBody`, for a `beforeAll` / `afterAll` /
* `beforeEach` / `afterEach` registered inside a `describe` that carries a
* lazy `@force-gate`. When the gate force-skips the suite (and its build),
* the hooks must not run either: they would prepare or inspect a fixture that
* was never booted, while the suite's tests all force-pass without them.
*
* Only a false lazy `@force-gate` skips a hook. An inverted `@gate` still
* runs its tests, so they need their hooks, and a static `@force-gate` skips
* the whole `describe` at collection time, hooks included.
*/
function wrapGatedHook(
gates: Gate[],
callback: Function
): () => Promise<unknown> {
return async function gatedHook(this: unknown): Promise<unknown> {
if (!hasFixture()) {
// The condition cannot be resolved here: either this hook runs before
// `nextTestSetup`'s own `beforeAll` registered the fixture, or it is an
// `afterAll` running after the fixture was cleared. Run as if ungated.
return callback.apply(this)
}
const config = await getResolvedConfigForGates()
if (findLazyForceSkip(gates, config) !== null) {
// Silent: the suite-level "build skipped" warning and the per-test
// force-pass warnings already carry the signal, and a static
// `describe.skip` skips hooks silently too.
return
}
return callback.apply(this)
}
}
/**
* The body for a test registered through Jest's own `test.failing`, used when
* a false static `@gate` is known at collection time. Jest inverts the outcome
......@@ -514,10 +571,51 @@ function wrapTestGlobals(): void {
}
}
/**
* The hook counterpart of `wrapTestGlobals`. Hooks carry no pragma, so the
* only thing that can skip one is a lazy `@force-gate` inherited from the
* enclosing `describe`, which is exactly the case where the fixture was never
* booted and running the hook would fail (or worse, hang) for no benefit.
*/
function wrapHookGlobals(): void {
for (const key of [
'beforeAll',
'afterAll',
'beforeEach',
'afterEach',
] as const) {
const original = (global as any)[key]
if (typeof original !== 'function' || original.__gateWrapped) continue
const wrapped = new Proxy(original, {
apply(target, thisArg, args: any[]) {
const [callback] = args
if (
typeof callback !== 'function' ||
// A `done`-style hook cannot be observed; leave it alone.
callback.length > 0 ||
!hasLazyForceGate(describeGateStack) ||
ungatedHooks.has(callback)
) {
return Reflect.apply(target, thisArg, args)
}
return Reflect.apply(target, thisArg, [
wrapGatedHook([...describeGateStack], callback),
...args.slice(1),
])
},
})
Object.defineProperty(wrapped, '__gateWrapped', { value: true })
;(global as any)[key] = wrapped
}
}
/** Called from `test/jest-setup-after-env.ts`. */
export function installGate(): void {
;(global as any)._test_gate = _test_gate
wrapTestGlobals()
wrapHookGlobals()
}
/** Test-only: the parse/validate half, without registering anything. */
......
......@@ -415,4 +415,47 @@ describe('@gate runtime', () => {
).resolves.toBeUndefined()
})
})
// A lazy `@force-gate` on a describe force-passes the tests and skips the
// fixture build, so hooks registered inside such a describe must not run:
// they would touch a fixture that was never booted. These describes go
// through the real pragma path like the ones above. The wrapper describe
// carries no pragma, so its `beforeEach` is not gated and re-pins a config
// with cacheComponents on before each test (the file-level `afterEach`
// clears it again).
describe('a lazy @force-gate on a describe', () => {
beforeEach(() => {
registerFixture({
getResolvedConfig: async () => ({ cacheComponents: true }),
})
})
// @force-gate !cacheComponents
describe('skipped suite', () => {
beforeEach(() => {
throw new Error('beforeEach must be skipped')
})
afterEach(() => {
throw new Error('afterEach must be skipped')
})
it('force-passes without running its hooks or body', () => {
throw new Error('body must not run')
})
})
// @force-gate cacheComponents
describe('held suite', () => {
let hookRan = false
beforeEach(() => {
hookRan = true
})
it('runs hooks when the gate holds', () => {
expect(hookRan).toBe(true)
})
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment