test: add tests for port-forwarding via playwrightclient (#6860)q

This commit is contained in:
Max Schmitt 2021-06-02 17:19:01 -07:00 committed by GitHub
parent 4fa792ee89
commit c09726b023
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 119 additions and 115 deletions

View file

@ -54,7 +54,7 @@ export function runDriver() {
}
export async function runServer(port: number | undefined) {
const wsEndpoint = await PlaywrightServer.startDefault({port});
const wsEndpoint = await (await PlaywrightServer.startDefault()).listen(port);
console.log('Listening on ' + wsEndpoint); // eslint-disable-line no-console
}

View file

@ -33,7 +33,6 @@ export interface PlaywrightServerDelegate {
}
export type PlaywrightServerOptions = {
port?: number;
acceptForwardedPorts?: boolean
};
@ -42,7 +41,7 @@ export class PlaywrightServer {
private _clientsCount = 0;
private _delegate: PlaywrightServerDelegate;
static async startDefault({port = 0, acceptForwardedPorts }: PlaywrightServerOptions): Promise<string> {
static async startDefault({ acceptForwardedPorts }: PlaywrightServerOptions = {}): Promise<PlaywrightServer> {
const cleanup = async () => {
await gracefullyCloseAll().catch(e => {});
serverSelectors.unregisterAll();
@ -62,8 +61,7 @@ export class PlaywrightServer {
};
},
};
const server = new PlaywrightServer(delegate);
return server.listen(port);
return new PlaywrightServer(delegate);
}
constructor(delegate: PlaywrightServerDelegate) {

View file

@ -74,7 +74,7 @@ class ServiceMode {
});
});
this._serviceProcess.on('exit', this._onExit);
this._client = await PlaywrightClient.connect(`ws://localhost:${port}/ws`);
this._client = await PlaywrightClient.connect({wsEndpoint: `ws://localhost:${port}/ws`});
this._playwrightObejct = this._client.playwright();
return this._playwrightObejct;
}

View file

@ -15,111 +15,135 @@
*/
import http from 'http';
import net from 'net';
import { contextTest as it, expect } from './config/browserTest';
import { PlaywrightClient } from '../lib/remote/playwrightClient';
import { PlaywrightServer } from '../lib/remote/playwrightServer';
import { contextTest, expect } from './config/browserTest';
import type { LaunchOptions, ConnectOptions } from '../index';
import type { Page, BrowserServer } from '..';
it.skip(({ mode }) => mode !== 'default');
it.fixme(({platform, browserName}) => platform === 'darwin' && browserName === 'webkit');
type PageFactoryOptions = {
acceptForwardedPorts: boolean
forwardPorts: number[]
};
let targetTestServer: http.Server;
let port!: number;
it.beforeAll(async ({}, test) => {
port = 30_000 + test.workerIndex * 4;
targetTestServer = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end('<html><body>from-retargeted-server</body></html>');
}).listen(port);
type LaunchMode = 'playwrightclient' | 'launchServer';
const it = contextTest.extend<{ pageFactory: (options?: PageFactoryOptions) => Promise<Page>, launchMode: LaunchMode }>({
launchMode: [ 'launchServer', { scope: 'test' }],
pageFactory: async ({ launchMode, browserType, browserName, browserOptions }, run) => {
const browserServers: BrowserServer[] = [];
const playwrightServers: PlaywrightServer[] = [];
await run(async (options?: PageFactoryOptions): Promise<Page> => {
const { acceptForwardedPorts, forwardPorts } = options;
if (launchMode === 'playwrightclient') {
const server = await PlaywrightServer.startDefault({
acceptForwardedPorts,
});
playwrightServers.push(server);
const wsEndpoint = await server.listen(0);
const service = await PlaywrightClient.connect({
wsEndpoint,
forwardPorts,
});
const playwright = service.playwright();
const browser = await playwright[browserName].launch(browserOptions);
return await browser.newPage();
}
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: acceptForwardedPorts
} as LaunchOptions);
browserServers.push(browserServer);
const browser = await browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: forwardPorts
} as ConnectOptions);
return await browser.newPage();
});
for (const browserServer of browserServers)
await browserServer.close();
for (const playwrightServer of playwrightServers)
await playwrightServer.close();
},
});
it.fixme(({ platform, browserName }) => platform === 'darwin' && browserName === 'webkit');
it.skip(({ mode }) => mode !== 'default');
it.beforeEach(() => {
delete process.env.PW_TEST_PROXY_TARGET;
});
it.afterAll(() => {
targetTestServer.close();
});
it('should forward non-forwarded requests', async ({ browserType, browserOptions, server }, workerInfo) => {
process.env.PW_TEST_PROXY_TARGET = port.toString();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body>original-target</body></html>');
async function startTestServer() {
const server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end('<html><body>from-retargeted-server</body></html>');
});
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: true
} as LaunchOptions);
const browser = await browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: []
} as ConnectOptions);
const page = await browser.newPage();
await page.goto(server.PREFIX + '/foo.html');
expect(await page.content()).toContain('original-target');
expect(reachedOriginalTarget).toBe(true);
await browserServer.close();
});
await new Promise(resolve => server.listen(0, resolve));
return {
testServerPort: (server.address() as net.AddressInfo).port,
stopTestServer: () => server.close()
};
}
it('should proxy local requests', async ({ browserType, browserOptions, server }, workerInfo) => {
process.env.PW_TEST_PROXY_TARGET = port.toString();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body></body></html>');
for (const launchMode of ['playwrightclient', 'launchServer'] as LaunchMode[]) {
it.describe(`${launchMode}:`, () => {
it.use({ launchMode });
it('should forward non-forwarded requests', async ({ pageFactory, server }) => {
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body>original-target</body></html>');
});
const page = await pageFactory({ acceptForwardedPorts: true, forwardPorts: [] });
await page.goto(server.PREFIX + '/foo.html');
expect(await page.content()).toContain('original-target');
expect(reachedOriginalTarget).toBe(true);
});
it('should proxy local requests', async ({ pageFactory, server }, workerInfo) => {
const { testServerPort, stopTestServer } = await startTestServer();
process.env.PW_TEST_PROXY_TARGET = testServerPort.toString();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body></body></html>');
});
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory({ acceptForwardedPorts: true, forwardPorts: [examplePort] });
await page.goto(`http://localhost:${examplePort}/foo.html`);
expect(await page.content()).toContain('from-retargeted-server');
expect(reachedOriginalTarget).toBe(false);
stopTestServer();
});
it('should lead to the error page for forwarded requests when the connection is refused', async ({ pageFactory }, workerInfo) => {
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory({ acceptForwardedPorts: true, forwardPorts: [examplePort] });
const response = await page.goto(`http://localhost:${examplePort}`);
expect(response.status()).toBe(502);
await page.waitForSelector('text=Connection error');
});
it('should lead to the error page for non-forwarded requests when the connection is refused', async ({ pageFactory }) => {
process.env.PW_TEST_PROXY_TARGET = '50001';
const page = await pageFactory({ acceptForwardedPorts: true, forwardPorts: [] });
const response = await page.goto(`http://localhost:44123/non-existing-url`);
expect(response.status()).toBe(502);
await page.waitForSelector('text=Connection error');
});
it('should should not allow to connect when the server does not allow port-forwarding', async ({ pageFactory }) => {
await expect(pageFactory({ acceptForwardedPorts: false, forwardPorts: [] })).rejects.toThrowError('Port forwarding needs to be enabled when launching the server via BrowserType.launchServer.');
await expect(pageFactory({ acceptForwardedPorts: false, forwardPorts: [1234] })).rejects.toThrowError('Port forwarding needs to be enabled when launching the server via BrowserType.launchServer.');
});
});
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: true
} as LaunchOptions);
const browser = await browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: [examplePort]
} as ConnectOptions);
const page = await browser.newPage();
await page.goto(`http://localhost:${examplePort}/foo.html`);
expect(await page.content()).toContain('from-retargeted-server');
expect(reachedOriginalTarget).toBe(false);
await browserServer.close();
});
}
it('should lead to the error page for forwarded requests when the connection is refused', async ({ browserType, browserOptions, browserName, isWindows}, workerInfo) => {
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: true
} as LaunchOptions);
const browser = await browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: [examplePort]
} as ConnectOptions);
const page = await browser.newPage();
const response = await page.goto(`http://localhost:${examplePort}`);
expect(response.status()).toBe(502);
await page.waitForSelector('text=Connection error');
await browserServer.close();
});
it('should lead to the error page for non-forwarded requests when the connection is refused', async ({ browserName, browserType, browserOptions, isWindows}, workerInfo) => {
process.env.PW_TEST_PROXY_TARGET = '50001';
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: true
} as LaunchOptions);
const browser = await browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: []
} as ConnectOptions);
const page = await browser.newPage();
const response = await page.goto(`http://localhost:44123/non-existing-url`);
expect(response.status()).toBe(502);
await page.waitForSelector('text=Connection error');
await browserServer.close();
});
it('should not allow connecting a second client when _acceptForwardedPorts is used', async ({ browserType, browserOptions }, workerInfo) => {
it('launchServer: should not allow connecting a second client when _acceptForwardedPorts is used', async ({ browserType, browserOptions }, workerInfo) => {
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: true
@ -143,21 +167,3 @@ it('should not allow connecting a second client when _acceptForwardedPorts is us
await browserServer.close();
});
it('should should not allow to connect when the server does not allow port-forwarding', async ({ browserType, browserOptions }, workerInfo) => {
const browserServer = await browserType.launchServer({
...browserOptions,
_acceptForwardedPorts: false
} as LaunchOptions);
await expect(browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: []
} as ConnectOptions)).rejects.toThrowError('browserType.connect: Port forwarding needs to be enabled when launching the server via BrowserType.launchServer.');
await expect(browserType.connect({
wsEndpoint: browserServer.wsEndpoint(),
_forwardPorts: [1234]
} as ConnectOptions)).rejects.toThrowError('browserType.connect: Port forwarding needs to be enabled when launching the server via BrowserType.launchServer.');
await browserServer.close();
});