Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test Mode: report onFetch interceptions in the test #55456

Merged
merged 4 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 18 additions & 18 deletions packages/next/src/experimental/testmode/playwright/next-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,29 @@ import type { NextWorkerFixture, FetchHandler } from './next-worker-fixture'
import type { NextOptions } from './next-options'
import type { FetchHandlerResult } from '../proxy'
import { handleRoute } from './page-route'
import { reportFetch } from './report'

export interface NextFixture {
onFetch: (handler: FetchHandler) => void
}

class NextFixtureImpl implements NextFixture {
public readonly testId: string
private fetchHandlers: FetchHandler[] = []

constructor(
public testId: string,
private testInfo: TestInfo,
private options: NextOptions,
private worker: NextWorkerFixture,
private page: Page
) {
this.testId = testInfo.testId
const testHeaders = {
'Next-Test-Proxy-Port': String(worker.proxyPort),
'Next-Test-Data': testId,
'Next-Test-Data': this.testId,
}
const handleFetch = this.handleFetch.bind(this)
worker.onFetch(testId, handleFetch)
worker.onFetch(this.testId, handleFetch)
this.page.route('**', (route) =>
handleRoute(route, page, testHeaders, handleFetch)
)
Expand All @@ -37,16 +40,18 @@ class NextFixtureImpl implements NextFixture {
}

private async handleFetch(request: Request): Promise<FetchHandlerResult> {
for (const handler of this.fetchHandlers.slice().reverse()) {
const result = handler(request)
if (result) {
return result
return reportFetch(this.testInfo, request, (req) => {
for (const handler of this.fetchHandlers.slice().reverse()) {
const result = handler(req.clone())
if (result) {
return result
}
}
}
if (this.options.fetchLoopback) {
return fetch(request)
}
return undefined
if (this.options.fetchLoopback) {
return fetch(req.clone())
}
return undefined
})
}
}

Expand All @@ -64,12 +69,7 @@ export async function applyNextFixture(
page: Page
}
): Promise<void> {
const fixture = new NextFixtureImpl(
testInfo.testId,
nextOptions,
nextWorker,
page
)
const fixture = new NextFixtureImpl(testInfo, nextOptions, nextWorker, page)

await use(fixture)

Expand Down
104 changes: 104 additions & 0 deletions packages/next/src/experimental/testmode/playwright/report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import type { TestInfo } from '@playwright/test'
import type { FetchHandler } from './next-worker-fixture'
import { step } from './step'

async function parseBody(
r: Pick<Request, 'headers' | 'json' | 'text' | 'arrayBuffer' | 'formData'>
): Promise<Record<string, unknown>> {
const contentType = r.headers.get('content-type')
let error: string | undefined
let text: string | undefined
let json: unknown
let formData: FormData | undefined
let buffer: ArrayBuffer | undefined
if (contentType?.includes('text')) {
try {
text = await r.text()
} catch (e) {
error = 'failed to parse text'
}
} else if (contentType?.includes('json')) {
try {
json = await r.json()
} catch (e) {
error = 'failed to parse json'
}
} else if (contentType?.includes('form-data')) {
try {
formData = await r.formData()
} catch (e) {
error = 'failed to parse formData'
}
} else {
try {
buffer = await r.arrayBuffer()
} catch (e) {
error = 'failed to parse arrayBuffer'
}
}
return {
...(contentType ? { contentType } : null),
...(error ? { error } : null),
...(text ? { text } : null),
...(json ? { json: JSON.stringify(json) } : null),
...(formData ? { formData: JSON.stringify(Array.from(formData)) } : null),
...(buffer && buffer.byteLength > 0
? { buffer: `base64;${Buffer.from(buffer).toString('base64')}` }
: null),
}
}

export async function reportFetch(
testInfo: TestInfo,
req: Request,
handler: FetchHandler
): Promise<Awaited<ReturnType<FetchHandler>>> {
return step(
testInfo,
{
title: `next.onFetch: ${req.method} ${req.url}`,
category: 'next.onFetch',
apiName: 'next.onFetch',
params: {
method: req.method,
url: req.url,
...(await parseBody(req.clone())),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to report the entire body here or just allow parsing that from the response?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Report the whole body. The workflow is basically: a developer takes the next unhandled request, copies it's URL and body, and creates a handler for it. Repeat.

},
},
async (complete) => {
const res = await handler(req)
if (res === undefined || res == null) {
complete({ error: { message: 'unhandled' } })
} else if (typeof res === 'string' && res !== 'continue') {
complete({ error: { message: res } })
} else {
let body: Record<string, unknown>
if (typeof res === 'string') {
body = { response: res }
} else {
const { status, statusText } = res
body = {
status,
...(statusText ? { statusText } : null),
...(await parseBody(res.clone())),
}
}
await step(
testInfo,
{
title: `next.onFetch.fulfilled: ${req.method} ${req.url}`,
category: 'next.onFetch',
apiName: 'next.onFetch.fulfilled',
params: {
...body,
'request.url': req.url,
'request.method': req.method,
},
},
async () => undefined
).catch(() => undefined)
}
return res
}
)
}
57 changes: 57 additions & 0 deletions packages/next/src/experimental/testmode/playwright/step.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { TestInfo } from '@playwright/test'
// eslint-disable-next-line import/no-extraneous-dependencies
import { test } from '@playwright/test'

export interface StepProps {
category: string
title: string
apiName?: string
params?: Record<string, string | number | boolean | null | undefined>
}

// Access the internal Playwright API until it's exposed publicly.
// See https://github.com/microsoft/playwright/issues/27059.
interface TestInfoWithRunAsStep extends TestInfo {
_runAsStep: <T>(
stepInfo: StepProps,
handler: (result: { complete: Complete }) => Promise<T>
) => Promise<T>
}

type Complete = (result: { error?: any }) => void

function isWithRunAsStep(
testInfo: TestInfo
): testInfo is TestInfoWithRunAsStep {
return '_runAsStep' in testInfo
}

export async function step<T>(
testInfo: TestInfo,
props: StepProps,
handler: (complete: Complete) => Promise<Awaited<T>>
): Promise<Awaited<T>> {
if (isWithRunAsStep(testInfo)) {
return testInfo._runAsStep(props, ({ complete }) => handler(complete))
}

// Fallback to the `test.step()`.
let result: Awaited<T>
let reportedError: any
try {
console.log(props.title, props)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
console.log(props.title, props)

Is this console.log intentional?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it was intentional. In case this private API goes away, there should be still a way to print the information somewhere. For Playwright, console is as good place as any. For now, we should not be triggering this code. And, hopefully, we'll be able to use a public API from Playwright soon enough.

await test.step(props.title, async () => {
result = await handler(({ error }) => {
reportedError = error
if (reportedError) {
throw reportedError
}
})
})
} catch (error) {
if (error !== reportedError) {
throw error
}
}
return result!
}