Unverified Commit 672b02b2 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[next-playwright] Use unique cookie values for instant navigation testing lock (#91250)

Co-authored-by: 's avatarCursor Agent <cursoragent@cursor.com>
parent 63dff61b
......@@ -12,6 +12,6 @@
"devDependencies": {
"rimraf": "6.0.1",
"next": "workspace:*",
"playwright": "^1.40.0"
"playwright": "1.58.2"
}
}
......@@ -255,8 +255,8 @@
"octokit": "3.1.0",
"outdent": "0.8.0",
"pixrem": "5.0.0",
"playwright": "1.48.0",
"playwright-chromium": "1.48.0",
"playwright": "1.58.2",
"playwright-chromium": "1.58.2",
"postcss": "8.4.31",
"postcss-nested": "4.2.1",
"postcss-pseudoelements": "5.0.0",
......
......@@ -26,6 +26,7 @@
}
},
"devDependencies": {
"@playwright/test": "1.58.2",
"typescript": "5.9.2"
}
}
......@@ -74,11 +74,14 @@ export async function instant<T>(
// navigation-testing-lock.ts, which acquires the in-memory navigation lock.
const { hostname } = new URL(resolveURL(page, options))
await step('Acquire Instant Lock', () =>
page
.context()
.addCookies([
{ name: INSTANT_COOKIE, value: '[0]', domain: hostname, path: '/' },
])
page.context().addCookies([
{
name: INSTANT_COOKIE,
value: JSON.stringify([0, `p${Math.random()}`]),
domain: hostname,
path: '/',
},
])
)
try {
return await fn()
......
......@@ -167,7 +167,7 @@
"@next/react-refresh-utils": "16.2.0-canary.100",
"@next/swc": "16.2.0-canary.100",
"@opentelemetry/api": "1.6.0",
"@playwright/test": "1.51.1",
"@playwright/test": "1.58.2",
"@rspack/core": "1.6.7",
"@storybook/addon-a11y": "8.6.0",
"@storybook/addon-essentials": "8.6.0",
......
......@@ -5,11 +5,6 @@
* during instant navigation captures, and owns all cookie state
* transitions (pending → captured-MPA, pending → captured-SPA).
*
* The cookie value is a JSON array:
* [0] — pending (waiting to capture)
* [1, null] — captured MPA page load
* [1, { from, to }] — captured SPA navigation (from/to route trees)
*
* External actors (Playwright, devtools) set [0] to start a lock scope
* and delete the cookie to end one. Next.js writes captured values.
* The CookieStore handler distinguishes them by value: pending = external,
......@@ -22,17 +17,30 @@ import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
type InstantNavCookieState = 'pending' | 'mpa' | 'spa'
type InstantCookie =
// pending (waiting to capture)
| [captured: 0, id: string]
// captured MPA page load
| [captured: 1, id: string, state: null]
// captured SPA navigation (from/to route trees)
| [
captured: 1,
id: string,
state: { from: FlightRouterState; to: FlightRouterState | null },
]
function parseCookieValue(raw: string): InstantNavCookieState {
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) {
return parsed[1] === null ? 'mpa' : 'spa'
if (Array.isArray(parsed) && parsed.length >= 3) {
const rawState = parsed[2]
return rawState === null ? 'mpa' : 'spa'
}
} catch {}
return 'pending'
}
function writeCookieValue(value: unknown[]): void {
function writeCookieValue(value: InstantCookie): void {
if (typeof cookieStore === 'undefined') {
return
}
......@@ -101,7 +109,7 @@ export function startListeningForInstantNavigationCookie(): void {
})
}
writeCookieValue([1, null])
writeCookieValue([1, `c${Math.random()}`, null])
acquireLock()
}
......@@ -151,7 +159,7 @@ export function transitionToCapturedSPA(
toTree: FlightRouterState | null
): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }])
writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])
}
}
......@@ -164,7 +172,7 @@ export function updateCapturedSPAToTree(
toTree: FlightRouterState
): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }])
writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])
}
}
......
......@@ -30,14 +30,15 @@ export type InstantNavCookieData =
function parseCookieValue(raw: string): InstantNavCookieData {
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) {
if (parsed[1] === null) {
if (Array.isArray(parsed) && parsed.length >= 3) {
const rawState = parsed[2]
if (rawState === null) {
return { state: 'mpa' }
}
// SPA capture: parsed[1] is { from, to }
if (typeof parsed[1] === 'object' && parsed[1] !== null) {
const fromTree: FlightRouterState = parsed[1].from ?? ['', {}]
const toTree: FlightRouterState | null = parsed[1].to ?? null
// SPA capture: rawState is { from, to }
if (typeof rawState === 'object' && rawState !== null) {
const fromTree: FlightRouterState = rawState.from ?? ['', {}]
const toTree: FlightRouterState | null = rawState.to ?? null
return { state: 'spa', fromTree, toTree }
}
return { state: 'spa', fromTree: ['', {}], toTree: null }
......
......@@ -44,7 +44,7 @@ export function InstantNavsPanel() {
if (typeof cookieStore !== 'undefined') {
cookieStore.set({
name: COOKIE_NAME,
value: '[0]',
value: JSON.stringify([0, `p${Math.random()}`]),
path: '/',
})
}
......@@ -55,7 +55,7 @@ export function InstantNavsPanel() {
if (typeof cookieStore !== 'undefined') {
cookieStore.set({
name: COOKIE_NAME,
value: '[0]',
value: JSON.stringify([0, `p${Math.random()}`]),
path: '/',
})
}
......
This diff is collapsed.
......@@ -116,7 +116,8 @@ describe.each([['', '/docs']])(
const script = document.createElement('script')
script.src = "${next.url}/_next/static/chunks/pages/_app.js"
script.onerror = (err) => {
script.onerror = (error) => {
console.error('script error', error)
statusEl.innerText = 'error'
}
script.onload = () => {
......@@ -126,7 +127,13 @@ describe.each([['', '/docs']])(
})()`
// ensure direct port with mismatching port is blocked
const browser = await webdriver(`http://127.0.0.1:${port}`, '/about')
const browser = await webdriver(
`http://127.0.0.1:${port}`,
'/about',
{
permissions: ['local-network-access'],
}
)
await browser.eval(scriptSnippet)
await retry(async () => {
......@@ -136,6 +143,7 @@ describe.each([['', '/docs']])(
})
// ensure different host is blocked
// Requires local-network-access permission to send a request to next.url
await browser.get(`https://example.vercel.sh/`)
await browser.eval(scriptSnippet)
......@@ -145,7 +153,11 @@ describe.each([['', '/docs']])(
)
})
expect(next.cliOutput).toContain('Cross origin request detected from')
expect(next.cliOutput).toContain(
// We're not sending an Origin header
// TODO: redundant spacing
'Cross origin request detected to'
)
} finally {
server.close()
}
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('use-router-with-rewrites', () => {
const { next } = nextTestSetup({
......@@ -68,30 +69,33 @@ describe('use-router-with-rewrites', () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-push').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('1')
})
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/1')
expect(await browser.elementByCss('p').text()).toBe('1')
})
it('should preserve current pathname when using useRouter.replace with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-replace').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('2')
})
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/2')
expect(await browser.elementByCss('p').text()).toBe('2')
})
it('should preserve current pathname when using Link with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementByCss('a').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('3')
})
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/3')
expect(await browser.elementByCss('p').text()).toBe('3')
})
})
})
......@@ -17,6 +17,7 @@ import {
check,
getRedboxHeader,
normalizeManifest,
retry,
} from 'next-test-utils'
import cheerio from 'cheerio'
......@@ -245,11 +246,12 @@ function runTests({ dev }) {
await browser.eval('window.beforeNav = 1')
await browser.elementByCss(`#${id}`).click()
await check(() => browser.eval('window.location.pathname'), pathname)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual(
navQuery
)
await retry(async () => {
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual(
navQuery
)
})
expect(await browser.eval('window.location.pathname')).toBe(pathname)
expect(await browser.eval('window.location.hash')).toBe(hash)
expect(
......
......@@ -12,6 +12,7 @@ import {
Locator,
Request as PlaywrightRequest,
Response as PlaywrightResponse,
BrowserContextOptions,
} from 'playwright'
import path from 'path'
......@@ -19,10 +20,13 @@ type EventType = 'request' | 'response'
type PageLog = { source: string; message: string; args: unknown[] }
export type Permissions = BrowserContextOptions['permissions']
let page: Page
let browser: Browser | undefined
let context: BrowserContext | undefined
let contextHasJSEnabled: boolean = true
let contextPermissions: Permissions = undefined
let pageLogs: Array<Promise<PageLog> | PageLog> = []
let websocketFrames: Array<{ payload: string | Buffer }> = []
......@@ -167,7 +171,8 @@ export class Playwright<TCurrent = undefined> {
javaScriptEnabled: boolean,
ignoreHTTPSErrors: boolean,
headless: boolean,
userAgent: string | undefined
userAgent: string | undefined,
permissions: Permissions
) {
let device
......@@ -182,7 +187,13 @@ export class Playwright<TCurrent = undefined> {
}
if (browser) {
if (contextHasJSEnabled !== javaScriptEnabled) {
if (
contextHasJSEnabled !== javaScriptEnabled ||
// Even triggers on same set of permissions, but we don't want to deal
// with the complexity of diffing them, so we just always recreate the
// context when permissions are set.
contextPermissions !== permissions
) {
// If we have switched from having JS enable/disabled we need to recreate the context.
await teardown(this.teardownTracing.bind(this))
await context?.close()
......@@ -192,8 +203,10 @@ export class Playwright<TCurrent = undefined> {
ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}),
...device,
permissions,
})
contextHasJSEnabled = javaScriptEnabled
contextPermissions = permissions
}
return
}
......@@ -205,6 +218,7 @@ export class Playwright<TCurrent = undefined> {
ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}),
...device,
permissions,
})
contextHasJSEnabled = javaScriptEnabled
}
......@@ -214,14 +228,16 @@ export class Playwright<TCurrent = undefined> {
await page?.close()
}
async launchBrowser(browserName: string, launchOptions: Record<string, any>) {
async launchBrowser(
browserName: string,
launchOptions: { headless: boolean }
) {
if (browserName === 'safari') {
return await webkit.launch(launchOptions)
} else if (browserName === 'firefox') {
return await firefox.launch({
...launchOptions,
firefoxUserPrefs: {
...launchOptions.firefoxUserPrefs,
// The "fission.webContentIsolationStrategy" pref must be
// set to 1 on Firefox due to the bug where a new history
// state is pushed on a page reload.
......@@ -231,9 +247,13 @@ export class Playwright<TCurrent = undefined> {
},
})
} else {
let launchArgs: string[] = []
if (!launchOptions.headless) {
launchArgs.push('--auto-open-devtools-for-tabs')
}
return await chromium.launch({
devtools: !launchOptions.headless,
...launchOptions,
args: launchArgs,
ignoreDefaultArgs: ['--disable-back-forward-cache'],
})
}
......
import { debugPrint, getFullUrl } from 'next-test-utils'
import os from 'os'
import {
Permissions,
Playwright,
PlaywrightNavigationWaitUntil,
} from './browsers/playwright'
......@@ -48,6 +49,7 @@ if (typeof afterAll === 'function') {
}
export interface WebdriverOptions {
permissions?: Permissions
/**
* whether to wait for React hydration to finish
*/
......@@ -121,6 +123,7 @@ export default async function webdriver(
extraHTTPHeaders,
locale,
disableJavaScript,
permissions,
ignoreHTTPSErrors,
headless,
cpuThrottleRate,
......@@ -141,7 +144,8 @@ export default async function webdriver(
Boolean(ignoreHTTPSErrors),
// allow headless to be overwritten for a particular test
typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS,
userAgent
userAgent,
permissions
)
;(global as any).browserName = browserName
......
......@@ -48,7 +48,7 @@
"minimist": "^1.2.8",
"picocolors": "1.0.1",
"pidusage-tree": "^2.0.5",
"playwright-chromium": "1.48.0",
"playwright-chromium": "1.58.2",
"split2": "^4.2.0",
"tree-kill": "^1.2.2"
}
......
......@@ -348,7 +348,7 @@ export async function newBrowserSession(options: {
}): Promise<BrowserSession> {
const browser = await chromium.launch({
headless: options.headless ?? process.env.HEADLESS !== 'false',
devtools: true,
args: options.headless ? undefined : ['--auto-open-devtools-for-tabs'],
timeout: 60000,
})
const context = await browser.newContext({
......
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