Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
/**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { playwrightTest as test, expect } from '../../config/browserTest';
import http from 'http';
import fs from 'fs';
import path from 'path';
import { getUserAgent, server as coreServer } from '../../../packages/playwright-core/lib/coreBundle';
import { suppressCertificateWarning } from '../../config/utils';
const { WebSocketTransport, nullProgress } = coreServer;
type Frame = coreServer.Frame;
test('CD-001 should connect to an existing cdp session', async ({ browserType, mode }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-002 should connect when an existing page has no renderer', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41714' },
}, async ({ browserType, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
// Prepare a page without a renderer, e.g. one discarded by the Memory Saver.
const cdpBrowser1 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const context1 = cdpBrowser1.contexts()[0];
const healthyPage1 = await context1.newPage();
await healthyPage1.goto(server.PREFIX + '/title.html');
const crashedPage1 = await context1.newPage();
await crashedPage1.goto(server.EMPTY_PAGE);
crashedPage1.goto('chrome://crash').catch(() => {});
await crashedPage1.waitForEvent('crash');
await cdpBrowser1.close();
// Connecting again should not hang on the page without a renderer,
// and should not report it at all.
const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const pages = cdpBrowser2.contexts()[0].pages();
expect(pages.map(page => page.url())).toEqual([server.PREFIX + '/title.html']);
expect(await pages[0].title()).toBe('Woof-Woof');
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-003 should connect when the opener of an existing page has no renderer', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41714' },
}, async ({ browserType, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
// The popup should be in a different process to survive the crash of the opener.
args: ['--remote-debugging-port=' + port, '--site-per-process']
});
try {
const cdpBrowser1 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const crashedPage1 = await cdpBrowser1.contexts()[0].newPage();
await crashedPage1.goto(server.EMPTY_PAGE);
const [popup1] = await Promise.all([
crashedPage1.waitForEvent('popup'),
crashedPage1.evaluate(url => { window.open(url); }, server.CROSS_PROCESS_PREFIX + '/title.html'),
]);
await popup1.waitForLoadState();
crashedPage1.goto('chrome://crash').catch(() => {});
await crashedPage1.waitForEvent('crash');
await cdpBrowser1.close();
// Connecting again should not report the opener, and should not wait for it.
const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const pages = cdpBrowser2.contexts()[0].pages();
expect(pages.map(page => page.url())).toEqual([server.CROSS_PROCESS_PREFIX + '/title.html']);
expect(await pages[0].title()).toBe('Woof-Woof');
expect(await pages[0].opener()).toBe(null);
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-004 should connect when an existing page has been discarded', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41714' },
}, async ({ browserType, createUserDataDir, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const userDataDir = await createUserDataDir();
// chrome://discards is an internal debug page that is only available with this pref.
fs.writeFileSync(path.join(userDataDir, 'Local State'), JSON.stringify({ internal_only_uis_enabled: true }));
const context = await browserType.launchPersistentContext(userDataDir, {
headless: false,
// Emulating the viewport of a discarded tab crashes the browser in
// WebContentsImpl::SetDeviceEmulationSize, because it has no view.
viewport: null,
args: [
'--remote-debugging-port=' + port,
// Chrome refuses to discard tabs with DevTools attached, and we attach to all of them.
'--enable-features=AllowDevtoolsConnectedDiscard',
],
});
try {
const victimUrl = server.PREFIX + '/title.html';
const victim = await context.newPage();
await victim.goto(victimUrl);
const discards = await context.newPage();
await discards.goto('chrome://discards/');
// Discarding replaces the tab's WebContents, but the url in the table survives.
const row = discards.getByRole('row', { name: victimUrl });
await row.getByText('Urgent Discard').click();
await expect(row).toContainText('discarded');
// The renderer process is shut down asynchronously after the discard.
await discards.waitForTimeout(3000);
await testInfo.attach('discards rows', { body: (await discards.getByRole('row').allInnerTexts()).map(text => text.replace(/\s+/g, ' ')).join('\n') });
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
await testInfo.attach('targets', { body: JSON.stringify(targets, null, 2), contentType: 'application/json' });
// Connecting should not hang on the discarded page, and the page should not be reported.
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const pages = cdpBrowser.contexts()[0].pages();
expect(pages.map(page => page.url()).sort()).toEqual(['about:blank', discards.url()].sort());
await cdpBrowser.close();
} finally {
await context.close();
}
});
test('CD-005 should cleanup artifacts dir after connectOverCDP disconnects due to ws close', async ({ browserType, toImpl, mode }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const dir = toImpl(cdpBrowser).options.artifactsDir;
const exists1 = fs.existsSync(dir);
await Promise.all([
new Promise(f => cdpBrowser.on('disconnected', f)),
browserServer.close()
]);
const exists2 = fs.existsSync(dir);
expect(exists1).toBe(true);
expect(exists2).toBe(false);
});
test('CD-006 should reject pending CDPSession calls when the browser is killed', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43200' },
}, async ({ browserType, mode }, testInfo) => {
test.skip(mode !== 'default', 'launchServer is only available in-process');
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launchServer({
args: ['--remote-debugging-port=' + port]
});
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const context = cdpBrowser.contexts()[0];
const page = await context.newPage();
const session = await context.newCDPSession(page);
const sendPromise = session.send('Runtime.evaluate', { expression: 'new Promise(() => {})', awaitPromise: true }).catch(e => e);
await browserServer.kill();
const error = await sendPromise;
expect(error.message).toContain('Target page, context or browser has been closed');
});
test('CD-007 should write traces to provided artifactsDir on connectOverCDP', async ({ browserType, toImpl, trace }, testInfo) => {
test.skip(trace === 'on');
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
const artifactsDir = testInfo.outputPath('custom-artifacts');
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
artifactsDir,
});
expect(toImpl(cdpBrowser).options.artifactsDir).toBe(artifactsDir);
expect(toImpl(cdpBrowser).options.tracesDir).toBe(artifactsDir);
const context = cdpBrowser.contexts()[0];
await context.tracing.start({ name: 'cdp-trace', snapshots: true, screenshots: true });
const page = await context.newPage();
await page.setContent('<button>Hello</button>');
await context.tracing.stopChunk();
expect(fs.existsSync(path.join(artifactsDir, 'cdp-trace.trace'))).toBe(true);
expect(fs.existsSync(path.join(artifactsDir, 'cdp-trace.network'))).toBe(true);
expect(fs.existsSync(path.join(artifactsDir, 'resources'))).toBe(true);
await Promise.all([
new Promise(f => cdpBrowser.on('disconnected', f)),
browserServer.close()
]);
expect(fs.existsSync(artifactsDir)).toBe(true);
} finally {
await browserServer.close().catch(() => {});
}
});
test('CD-008 should connectOverCDP and manage downloads in default context', async ({ browserType, mode, server }, testInfo) => {
server.setRoute('/downloadWithFilename', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=file.txt');
res.end(`Hello world`);
});
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const browser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const page = await browser.contexts()[0].newPage();
await page.setContent(`<a href="${server.PREFIX}/downloadWithFilename">download</a>`);
const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('a')
]);
expect(download.page()).toBe(page);
expect(download.url()).toBe(`${server.PREFIX}/downloadWithFilename`);
expect(download.suggestedFilename()).toBe(`file.txt`);
const userPath = testInfo.outputPath('download.txt');
await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world');
} finally {
await browserServer.close();
}
});
test('CD-009 should connect to an existing cdp session twice', async ({ browserType, mode, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser1 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const contexts1 = cdpBrowser1.contexts();
expect(contexts1.length).toBe(1);
const [context1] = contexts1;
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
const contexts2 = cdpBrowser2.contexts();
expect(contexts2.length).toBe(1);
const [context2] = contexts2;
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
expect(context1.pages().length).toBe(2);
expect(context2.pages().length).toBe(2);
await page1.evaluate(() => alert('dialog race'));
await expect(context2.pages()[0].title()).resolves.toBe('');
await cdpBrowser1.close();
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-010 should connect to existing page with iframe and navigate', async ({ browserType, mode, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
{
const context1 = await browserServer.newContext();
const page = await context1.newPage();
await page.goto(server.PREFIX + '/frames/one-frame.html');
}
const cdpBrowser = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
await contexts[0].pages()[0].goto(server.EMPTY_PAGE);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-011 should connect to existing service workers', async ({ browserType, mode, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser1 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}`,
});
const context = cdpBrowser1.contexts()[0];
const page = await cdpBrowser1.contexts()[0].newPage();
const [worker] = await Promise.all([
context.waitForEvent('serviceworker'),
page.goto(server.PREFIX + '/serviceworkers/empty/sw.html')
]);
expect(await worker.evaluate(() => self.toString())).toBe('[object ServiceWorkerGlobalScope]');
await cdpBrowser1.close();
const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}`,
});
const context2 = cdpBrowser2.contexts()[0];
expect(context2.serviceWorkers().length).toBe(1);
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-012 should connect over a ws endpoint', async ({ browserType, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const json = await new Promise<string>((resolve, reject) => {
http.get(`http://127.0.0.1:${port}/json/version/`, resp => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => resolve(data));
}).on('error', reject);
});
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: JSON.parse(json).webSocketDebuggerUrl,
});
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
await cdpBrowser.close();
// also connect with the deprecated wsEndpoint option
const cdpBrowser2 = await browserType.connectOverCDP({
wsEndpoint: JSON.parse(json).webSocketDebuggerUrl,
});
const contexts2 = cdpBrowser2.contexts();
expect(contexts2.length).toBe(1);
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-013 should send extra headers with connect request', async ({ browserType, server }, testInfo) => {
{
const [request] = await Promise.all([
server.waitForWebSocketConnectionRequest(),
browserType.connectOverCDP({
wsEndpoint: `ws://localhost:${server.PORT}/ws`,
headers: {
'User-Agent': 'Playwright',
'foo': 'bar',
},
timeout: 100,
}).catch(() => {})
]);
expect(request.headers['user-agent']).toBe('Playwright');
expect(request.headers['foo']).toBe('bar');
}
{
const [request] = await Promise.all([
server.waitForRequest('/json/version/'),
browserType.connectOverCDP({
endpointURL: `http://localhost:${server.PORT}`,
headers: {
'User-Agent': 'Playwright',
'foo': 'bar',
},
timeout: 100,
}).catch(() => {})
]);
expect(request.headers['user-agent']).toBe('Playwright');
expect(request.headers['foo']).toBe('bar');
}
});
test('CD-014 should keep URL parameters when adding json/version', {
annotation: {
type: 'issue',
description: 'https://github.com/microsoft/playwright/issues/36097'
}
}, async ({ browserType, server }) => {
await Promise.all([
server.waitForRequest('/browser/json/version/?foo=bar'),
browserType.connectOverCDP(`http://localhost:${server.PORT}/browser/?foo=bar`).catch(() => {})
]);
});
test('CD-015 should append /json/version with a slash if there isnt one', {
annotation: {
type: 'issue',
description: 'https://github.com/microsoft/playwright/issues/36378'
}
}, async ({ browserType, server }) => {
await Promise.all([
server.waitForRequest('/browser/json/version/?foo=bar'),
browserType.connectOverCDP(`http://localhost:${server.PORT}/browser?foo=bar`).catch(() => {})
]);
});
test('CD-016 should send default User-Agent header with connect request', async ({ browserType, server }, testInfo) => {
{
const [request] = await Promise.all([
server.waitForWebSocketConnectionRequest(),
browserType.connectOverCDP({
wsEndpoint: `ws://localhost:${server.PORT}/ws`,
headers: {
'foo': 'bar',
},
timeout: 100,
}).catch(() => {})
]);
expect(request.headers['user-agent']).toBe(getUserAgent());
expect(request.headers['foo']).toBe('bar');
}
});
test('CD-017 should report all pages in an existing browser', async ({ browserType }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
for (let i = 0; i < 3; i++)
await contexts[0].newPage();
await cdpBrowser.close();
const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
expect(cdpBrowser2.contexts()[0].pages().length).toBe(3);
await cdpBrowser2.close();
} finally {
await browserServer.close();
}
});
test('CD-018 should connect via https', async ({ browserType, httpsServer, mode }, testInfo) => {
test.skip(mode !== 'default'); // Out of process transport does not allow us to set env vars dynamically.
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
const json = await new Promise<string>((resolve, reject) => {
http.get(`http://127.0.0.1:${port}/json/version/`, resp => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => resolve(data));
}).on('error', reject);
});
httpsServer.setRoute('/json/version/', (req, res) => {
res.writeHead(200);
res.end(json);
});
const oldValue = process.env['NODE_TLS_REJECT_UNAUTHORIZED'];
// https://stackoverflow.com/a/21961005/552185
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
suppressCertificateWarning();
try {
const cdpBrowser = await browserType.connectOverCDP(`https://localhost:${httpsServer.PORT}/`);
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
for (let i = 0; i < 3; i++)
await contexts[0].newPage();
await cdpBrowser.close();
} finally {
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = oldValue;
await browserServer.close();
}
});
test('CD-019 should return valid browser from context.browser()', async ({ browserType }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
expect(contexts[0].browser()).toBe(cdpBrowser);
const context2 = await cdpBrowser.newContext();
expect(context2.browser()).toBe(cdpBrowser);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-020 should report an expected error when the endpointURL returns a non-expected status code', async ({ browserType, server }) => {
server.setRoute('/json/version/', (req, resp) => {
resp.statusCode = 404;
resp.end(JSON.stringify({
webSocketDebuggerUrl: 'dont-use-me',
}));
});
await expect(browserType.connectOverCDP({
endpointURL: server.PREFIX,
})).rejects.toThrowError(`browserType.connectOverCDP: Unexpected status 404 when connecting to ${server.PREFIX}/json/version/`);
});
test('CD-021 should report an expected error when the endpoint URL JSON webSocketDebuggerUrl is undefined', async ({ browserType, server }) => {
server.setRoute('/json/version/', (req, resp) => {
resp.end(JSON.stringify({
webSocketDebuggerUrl: undefined,
}));
});
await expect(browserType.connectOverCDP({
endpointURL: server.PREFIX,
})).rejects.toThrowError('browserType.connectOverCDP: Invalid URL');
});
test('CD-022 should connect to an existing cdp session when passed as a first argument', async ({ browserType }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-023 should use proxy with connectOverCDP', async ({ browserType, server }, testInfo) => {
server.setRoute('/target.html', async (req, res) => {
res.end('<html><title>Served by the proxy</title></html>');
});
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
const context = await cdpBrowser.newContext({
proxy: { server: `localhost:${server.PORT}` }
});
const page = await context.newPage();
await page.goto('http://non-existent.test/target.html');
expect(await page.title()).toBe('Served by the proxy');
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-024 should use env proxy with connectOverCDP discovery request', async ({ browserType, server, proxyServer, mode }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/40394' });
test.skip(mode !== 'default'); // Out of process transport does not allow us to set env vars dynamically.
proxyServer.forwardTo(server.PORT);
const oldValue = process.env.HTTP_PROXY;
try {
process.env.HTTP_PROXY = proxyServer.URL;
const error = await browserType.connectOverCDP(server.PREFIX).catch(e => e);
expect(error.message).toContain(`Unexpected status 404 when connecting to ${server.PREFIX}/json/version/`);
expect(proxyServer.requestUrls).toEqual([`${server.PREFIX}/json/version/`]);
} finally {
if (oldValue === undefined)
delete process.env.HTTP_PROXY;
else
process.env.HTTP_PROXY = oldValue;
}
});
test('CD-025 should send target Host header when using env HTTP proxy with connectOverCDP', async ({ browserType, server, proxyServer, mode }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/40811' });
test.skip(mode !== 'default'); // Out of process transport does not allow us to set env vars dynamically.
proxyServer.forwardTo(server.PORT);
const oldValue = process.env.HTTP_PROXY;
try {
process.env.HTTP_PROXY = proxyServer.URL;
const error = await browserType.connectOverCDP(server.PREFIX).catch(e => e);
expect(error.message).toContain(`Unexpected status 404 when connecting to ${server.PREFIX}/json/version/`);
expect(proxyServer.requestHosts).toEqual([new URL(server.PREFIX).host]);
} finally {
if (oldValue === undefined)
delete process.env.HTTP_PROXY;
else
process.env.HTTP_PROXY = oldValue;
}
});
test('CD-026 should be able to connect via localhost', async ({ browserType }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP(`http://localhost:${port}`);
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-027 emulate media should not be affected by second connectOverCDP with noDefaults', async ({ browserType }, testInfo) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/24109' });
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
async function isPrint(page) {
return await page.evaluate(() => matchMedia('print').matches);
}
const browser1 = await browserType.connectOverCDP(`http://localhost:${port}`);
const context1 = await browser1.newContext();
const page1 = await context1.newPage();
await page1.emulateMedia({ media: 'print' });
expect(await isPrint(page1)).toBe(true);
const browser2 = await browserType.connectOverCDP(`http://localhost:${port}`, { noDefaults: true });
expect(await isPrint(page1)).toBe(true);
await Promise.all([
browser1.close(),
browser2.close()
]);
} finally {
await browserServer.close();
}
});
test('CD-028 should allow tracing over cdp session', async ({ browserType, trace }, testInfo) => {
test.skip(trace === 'on');
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const [context] = cdpBrowser.contexts();
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.evaluate(() => 2 + 2);
const traceZip = testInfo.outputPath('trace.zip');
await context.tracing.stop({ path: traceZip });
await cdpBrowser.close();
expect(fs.existsSync(traceZip)).toBe(true);
} finally {
await browserServer.close();
}
});
test('CD-029 setInputFiles should preserve lastModified timestamp', async ({ browserType, asset }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/27452' });
const port = 9339 + test.info().workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const [context] = cdpBrowser.contexts();
const page = await context.newPage();
await page.setContent(`<input type=file multiple=true/>`);
const input = page.locator('input');
const files = ['file-to-upload.txt', 'file-to-upload-2.txt'];
await input.setInputFiles(files.map(f => asset(f)));
expect(await input.evaluate(e => [...(e as HTMLInputElement).files].map(f => f.name))).toEqual(files);
const timestamps = await input.evaluate(e => [...(e as HTMLInputElement).files].map(f => f.lastModified));
const expectedTimestamps = files.map(file => Math.round(fs.statSync(asset(file)).mtimeMs));
// On Linux browser sometimes reduces the timestamp by 1ms: 1696272058110.0715 -> 1696272058109 or even
// rounds it to seconds in WebKit: 1696272058110 -> 1696272058000.
for (let i = 0; i < timestamps.length; i++)
expect(Math.abs(timestamps[i] - expectedTimestamps[i]), `expected: ${expectedTimestamps}; actual: ${timestamps}`).toBeLessThanOrEqual(1000);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});
test('CD-030 setInputFiles should use local path when isLocal is set', async ({ browserType, toImpl }) => {
const port = 9339 + test.info().workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const cdpBrowser1 = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
expect(toImpl(cdpBrowser1)._isBrowserCollocatedWithServer).toBe(false);
const cdpBrowser2 = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`, { isLocal: true });
expect(toImpl(cdpBrowser2)._isBrowserCollocatedWithServer).toBe(true);
} finally {
await browserServer.close();
}
});
test('CD-031 should print custom ws close error', async ({ browserType, server }) => {
server.onceWebSocketConnection((ws, request) => {
ws.on('message', message => {
ws.close(4123, 'Oh my!');
});
});
const error = await browserType.connectOverCDP(`ws://localhost:${server.PORT}/ws`).catch(e => e);
expect(error.message).toContain(`Browser logs:\n\nOh my!\n`);
});
test('CD-032 should not reuse utility worlds between two clients', async ({ browserType, toImpl }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const browser1 = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
const context1 = browser1.contexts()[0];
expect(context1.pages().length).toBe(0);
const page1 = await context1.newPage();
const frameImpl1 = toImpl(page1.mainFrame()) as Frame;
await frameImpl1.evaluateExpression(nullProgress, 'window.foo = 42', { world: 'utility' });
const browser2 = await browserType.connectOverCDP(`http://127.0.0.1:${port}/`);
const context2 = browser2.contexts()[0];
const page2 = context2.pages()[0];
const frameImpl2 = toImpl(page2.mainFrame()) as Frame;
const result = await frameImpl2.evaluateExpression(nullProgress, 'window.foo', { world: 'utility' });
await browser1.close();
await browser2.close();
expect(result).toBeUndefined();
} finally {
await browserServer.close();
}
});
test('CD-033 should get title and URL of existing page', async ({ browserType, mode, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
const browsers = [];
try {
{
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
browsers.push(cdpBrowser);
const [context] = cdpBrowser.contexts();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => document.title = 'my title');
}
{
const cdpBrowser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
browsers.push(cdpBrowser);
const [context] = cdpBrowser.contexts();
const [page] = context.pages();
expect(page.url()).toBe(server.EMPTY_PAGE);
expect(await page.title()).toBe('my title');
}
} finally {
for (const browser of browsers)
await browser.close();
await browserServer.close();
}
});
test('CD-034 should skip default overrides with noDefaults', async ({ browserType, mode, server }, testInfo) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/40158' });
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const browser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
noDefaults: true,
});
const defaultContext = browser.contexts()[0];
const page = await defaultContext.newPage();
// Browser.setDownloadBehavior was not sent, so no Playwright download event fires.
server.setRoute('/download', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=file.txt');
res.end('Hello world');
});
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
let sawDownload = false;
page.on('download', () => { sawDownload = true; });
await page.click('a');
await page.waitForTimeout(500);
expect(sawDownload).toBe(false);
await browser.close();
} finally {
await browserServer.close();
}
});
test('CD-035 noDefaults should not affect new contexts', async ({ browserType, mode, server }, testInfo) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/40158' });
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const browser = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
noDefaults: true,
});
// New contexts should still get normal Playwright defaults.
const newContext = await browser.newContext();
const page = await newContext.newPage();
const hasFocus = await page.evaluate(() => document.hasFocus());
expect(hasFocus).toBe(true);
await newContext.close();
await browser.close();
} finally {
await browserServer.close();
}
});
test('CD-036 should connect over CDP using a ConnectionTransport', async ({ browserType, mode, server }, testInfo) => {
test.skip(mode !== 'default', 'Passing a transport to connectOverCDP is only available in-process');
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
args: ['--remote-debugging-port=' + port]
});
try {
const json = await new Promise<string>((resolve, reject) => {
http.get(`http://127.0.0.1:${port}/json/version/`, resp => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => resolve(data));
}).on('error', reject);
});
const wsEndpoint = JSON.parse(json).webSocketDebuggerUrl;
const transport = await WebSocketTransport.connect(undefined, wsEndpoint);
const cdpBrowser = await browserType.connectOverCDP(transport);
const contexts = cdpBrowser.contexts();
expect(contexts.length).toBe(1);
const page = await contexts[0].newPage();
await page.goto(server.EMPTY_PAGE);
expect(page.url()).toBe(server.EMPTY_PAGE);
await cdpBrowser.close();
} finally {
await browserServer.close();
}
});