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

api(route): allow fulfilling with a file path #1301

Merged
merged 1 commit into from
Mar 9, 2020
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
14 changes: 9 additions & 5 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,7 @@ Browser-specific Coverage implementation, only available for Chromium atm. See [
- `'load'` - consider navigation to be finished when the `load` event is fired.
- `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
- `'networkidle0'` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.
- `'networkidle2'` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.
- `'networkidle2'` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.
- `'nowait'` - do not wait.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully double clicked. The Promise will be rejected if there is no element matching `selector`.
Expand Down Expand Up @@ -3377,8 +3377,9 @@ page.on('requestfailed', request => {
- `response` <[Object]> Response that will fulfill this request
- `status` <[number]> Response status code, defaults to `200`.
- `headers` <[Object]> Optional response headers. Header values will be converted to a string.
- `contentType` <[string]> If set, equals to setting `Content-Type` response header
- `body` <[string]|[Buffer]> Optional response body
- `contentType` <[string]> If set, equals to setting `Content-Type` response header.
- `body` <[string]|[Buffer]> Optional response body.
- `path` <[string]> Optional file path to respond with. The content type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
- returns: <[Promise]>

Fulfills request with given response. To use this, request interception should
Expand All @@ -3397,8 +3398,11 @@ await page.route('**/*', request => {
});
```

> **NOTE** Mocking responses for dataURL requests is not supported.
> Calling `request.fulfill` for a dataURL request is a noop.
An example of serving static file:

```js
await page.route('**/xhr_endpoint', request => request.fulfill({ path: 'mock_data.json' }));
```

#### request.headers()
- returns: <[Object]> An object with HTTP headers associated with the request. All header names are lower-case.
Expand Down
2 changes: 1 addition & 1 deletion src/chromium/crNetworkManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ class InterceptableRequest implements network.RequestDelegate {
});
}

async fulfill(response: { status: number; headers: network.Headers; contentType: string; body: (string | platform.BufferType); }) {
async fulfill(response: network.FulfillResponse) {
const responseBody = response.body && helper.isString(response.body) ? platform.Buffer.from(response.body) : (response.body || null);

const responseHeaders: { [s: string]: string; } = {};
Expand Down
2 changes: 1 addition & 1 deletion src/firefox/ffNetworkManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ class InterceptableRequest implements network.RequestDelegate {
});
}

async fulfill(response: { status: number; headers: network.Headers; contentType: string; body: (string | platform.BufferType); }) {
async fulfill(response: network.FulfillResponse) {
const responseBody = response.body && helper.isString(response.body) ? platform.Buffer.from(response.body) : (response.body || null);

const responseHeaders: { [s: string]: string; } = {};
Expand Down
19 changes: 17 additions & 2 deletions src/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,18 @@ export class Request {
await this._delegate.abort(errorCode);
}

async fulfill(response: { status: number; headers: Headers; contentType: string; body: (string | platform.BufferType); }) { // Mocking responses for dataURL requests is not currently supported.
async fulfill(response: FulfillResponse & { path?: string }) {
assert(this._delegate, 'Request Interception is not enabled!');
assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
if (response.path) {
response = {
status: response.status,
headers: response.headers,
contentType: platform.getMimeType(response.path),
body: await platform.readFileBuffer(response.path)
};
}
await this._delegate.fulfill(response);
}

Expand Down Expand Up @@ -304,9 +312,16 @@ export class Response {
}
}

export type FulfillResponse = {
status?: number,
headers?: Headers,
contentType?: string,
body?: string | platform.BufferType,
};

export interface RequestDelegate {
abort(errorCode: string): Promise<void>;
fulfill(response: { status: number; headers: Headers; contentType: string; body: (string | platform.BufferType); }): Promise<void>;
fulfill(response: FulfillResponse): Promise<void>;
continue(overrides: { method?: string; headers?: Headers; postData?: string; }): Promise<void>;
}

Expand Down
5 changes: 5 additions & 0 deletions src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ export async function readFileAsync(file: string, encoding: string): Promise<str
return await promisify(nodeFS.readFile)(file, encoding);
}

export async function readFileBuffer(file: string): Promise<BufferType> {
assertFileAccess();
return await promisify(nodeFS.readFile)(file);
}

export async function writeFileAsync(file: string, data: any) {
assertFileAccess();
return await promisify(nodeFS.writeFile)(file, data);
Expand Down
2 changes: 1 addition & 1 deletion src/webkit/wkInterceptableRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class WKInterceptableRequest implements network.RequestDelegate {
});
}

async fulfill(response: { status: number; headers: network.Headers; contentType: string; body: (string | platform.BufferType); }) {
async fulfill(response: network.FulfillResponse) {
await this._interceptedPromise;

const base64Encoded = !!response.body && !helper.isString(response.body);
Expand Down
11 changes: 11 additions & 0 deletions test/interception.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,17 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
const img = await page.$('img');
expect(await img.screenshot()).toBeGolden('mock-binary-response.png');
});
it('should work with file path', async({page, server}) => {
await page.route('**/*', request => request.fulfill({ contentType: 'shouldBeIgnored', path: path.join(__dirname, 'assets', 'pptr.png') }));
await page.evaluate(PREFIX => {
const img = document.createElement('img');
img.src = PREFIX + '/does-not-exist.png';
document.body.appendChild(img);
return new Promise(fulfill => img.onload = fulfill);
}, server.PREFIX);
const img = await page.$('img');
expect(await img.screenshot()).toBeGolden('mock-binary-response.png');
});
it('should stringify intercepted request response headers', async({page, server}) => {
await page.route('**/*', request => {
request.fulfill({
Expand Down