Skip to content

Commit

Permalink
api(browserType): remove devices, errors (#1368)
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Mar 13, 2020
1 parent 0d7cb29 commit 9aa56a6
Show file tree
Hide file tree
Showing 17 changed files with 122 additions and 203 deletions.
46 changes: 0 additions & 46 deletions docs/api.md
Expand Up @@ -3706,9 +3706,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.

<!-- GEN:toc -->
- [browserType.connect(options)](#browsertypeconnectoptions)
- [browserType.devices](#browsertypedevices)
- [browserType.downloadBrowserIfNeeded([progress])](#browsertypedownloadbrowserifneededprogress)
- [browserType.errors](#browsertypeerrors)
- [browserType.executablePath()](#browsertypeexecutablepath)
- [browserType.launch([options])](#browsertypelaunchoptions)
- [browserType.launchPersistentContext(userDataDir, [options])](#browsertypelaunchpersistentcontextuserdatadir-options)
Expand All @@ -3724,56 +3722,12 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.

This methods attaches Playwright to an existing browser instance.

#### browserType.devices
- returns: <[Object]>

Returns a list of devices to be used with [`browser.newContext([options])`](#browsernewcontextoptions) and [`browser.newPage([options])`](#browsernewpageoptions). Actual list of devices can be found in [src/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts).

```js
const { webkit } = require('playwright');
const iPhone = webkit.devices['iPhone 6'];

(async () => {
const browser = await webkit.launch();
const context = await browser.newContext({
viewport: iPhone.viewport,
userAgent: iPhone.userAgent
});
const page = await context.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();
```

#### browserType.downloadBrowserIfNeeded([progress])
- `progress` <[function]> If download is initiated, this function is called with two parameters: `downloadedBytes` and `totalBytes`.
- returns: <[Promise]> promise that resolves when browser is successfully downloaded.

Download browser binary if it is missing.

#### browserType.errors
- returns: <[Object]>
- `TimeoutError` <[function]> A class of [TimeoutError].

Playwright methods might throw errors if they are unable to fulfill a request. For example, [page.waitForSelector(selector[, options])](#pagewaitforelementselector-options)
might fail if the selector doesn't match any nodes during the given timeframe.

For certain types of errors Playwright uses specific error classes.
These classes are available via [`browserType.errors`](#browsertypeerrors) or [`playwright.errors`](#playwrighterrors).

An example of handling a timeout error:
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
try {
await page.waitForSelector('.foo');
} catch (e) {
if (e instanceof webkit.errors.TimeoutError) {
// Do something if this is a timeout.
}
}
```

#### browserType.executablePath()
- returns: <[string]> A path where Playwright expects to find a bundled browser.

Expand Down
4 changes: 0 additions & 4 deletions src/server/browserType.ts
Expand Up @@ -14,8 +14,6 @@
* limitations under the License.
*/

import * as types from '../types';
import { TimeoutError } from '../errors';
import { Browser, ConnectOptions } from '../browser';
import { BrowserContext } from '../browserContext';
import { BrowserServer } from './browserServer';
Expand Down Expand Up @@ -50,6 +48,4 @@ export interface BrowserType {
launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;
connect(options: ConnectOptions): Promise<Browser>;
downloadBrowserIfNeeded(progress?: OnProgressCallback): Promise<void>;
devices: types.Devices;
errors: { TimeoutError: typeof TimeoutError };
}
10 changes: 0 additions & 10 deletions src/server/chromium.ts
Expand Up @@ -20,8 +20,6 @@ import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from '../server/browserFetcher';
import { DeviceDescriptors } from '../deviceDescriptors';
import * as types from '../types';
import { assert, helper } from '../helper';
import { CRBrowser } from '../chromium/crBrowser';
import * as platform from '../platform';
Expand Down Expand Up @@ -166,14 +164,6 @@ export class Chromium implements BrowserType {
return this._resolveExecutablePath().executablePath;
}

get devices(): types.Devices {
return DeviceDescriptors;
}

get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}

private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const {
devtools = false,
Expand Down
10 changes: 0 additions & 10 deletions src/server/firefox.ts
Expand Up @@ -21,14 +21,12 @@ import * as path from 'path';
import * as util from 'util';
import { ConnectOptions, LaunchType } from '../browser';
import { BrowserContext } from '../browserContext';
import { DeviceDescriptors } from '../deviceDescriptors';
import { TimeoutError } from '../errors';
import { Events } from '../events';
import { FFBrowser } from '../firefox/ffBrowser';
import { kBrowserCloseMessageId } from '../firefox/ffConnection';
import { assert, helper } from '../helper';
import * as platform from '../platform';
import * as types from '../types';
import { BrowserFetcher, BrowserFetcherOptions, OnProgressCallback } from './browserFetcher';
import { BrowserServer } from './browserServer';
import { BrowserArgOptions, BrowserType, LaunchOptions } from './browserType';
Expand Down Expand Up @@ -174,14 +172,6 @@ export class Firefox implements BrowserType {
return this._resolveExecutablePath().executablePath;
}

get devices(): types.Devices {
return DeviceDescriptors;
}

get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}

private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const {
devtools = false,
Expand Down
11 changes: 0 additions & 11 deletions src/server/webkit.ts
Expand Up @@ -16,9 +16,6 @@
*/

import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from './browserFetcher';
import { DeviceDescriptors } from '../deviceDescriptors';
import { TimeoutError } from '../errors';
import * as types from '../types';
import { WKBrowser } from '../webkit/wkBrowser';
import { execSync } from 'child_process';
import { PipeTransport } from './pipeTransport';
Expand Down Expand Up @@ -163,14 +160,6 @@ export class WebKit implements BrowserType {
return this._resolveExecutablePath().executablePath;
}

get devices(): types.Devices {
return DeviceDescriptors;
}

get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}

_defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const {
devtools = false,
Expand Down
14 changes: 7 additions & 7 deletions test/chromium/launcher.spec.js
Expand Up @@ -29,7 +29,7 @@ const TMP_FOLDER = path.join(os.tmpdir(), 'pw_tmp_folder-');
/**
* @type {TestSuite}
*/
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, WIN}) {
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, WIN}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
Expand All @@ -50,17 +50,17 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
it('should throw with remote-debugging-pipe argument', async() => {
const options = Object.assign({}, defaultBrowserOptions);
options.args = ['--remote-debugging-pipe'].concat(options.args || []);
const error = await playwright.launchServer(options).catch(e => e);
const error = await browserType.launchServer(options).catch(e => e);
expect(error.message).toContain('Playwright manages remote debugging connection itself');
});
it('should throw with remote-debugging-port argument', async() => {
const options = Object.assign({}, defaultBrowserOptions);
options.args = ['--remote-debugging-port=9222'].concat(options.args || []);
const error = await playwright.launchServer(options).catch(e => e);
const error = await browserType.launchServer(options).catch(e => e);
expect(error.message).toContain('Playwright manages remote debugging connection itself');
});
it('should open devtools when "devtools: true" option is given', async({server}) => {
const browser = await playwright.launch(Object.assign({devtools: true}, headfulOptions));
const browser = await browserType.launch(Object.assign({devtools: true}, headfulOptions));
const context = await browser.newContext();
const browserSession = await browser.createBrowserSession();
await browserSession.send('Target.setDiscoverTargets', { discover: true });
Expand All @@ -79,7 +79,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('extensions', () => {
it('should return background pages', async() => {
const userDataDir = await makeUserDataDir();
const context = await playwright.launchPersistentContext(userDataDir, extensionOptions);
const context = await browserType.launchPersistentContext(userDataDir, extensionOptions);
const backgroundPages = await context.backgroundPages();
let backgroundPage = backgroundPages.length
? backgroundPages[0]
Expand All @@ -94,7 +94,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('BrowserFetcher', function() {
it('should download and extract linux binary', async({server}) => {
const downloadsFolder = await mkdtempAsync(TMP_FOLDER);
const browserFetcher = playwright._createBrowserFetcher({
const browserFetcher = browserType._createBrowserFetcher({
platform: 'linux',
path: downloadsFolder,
host: server.PREFIX
Expand Down Expand Up @@ -123,7 +123,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p

describe('BrowserContext', function() {
it('should not create pages automatically', async function() {
const browser = await playwright.launch();
const browser = await browserType.launch();
const browserSession = await browser.createBrowserSession();
const targets = [];
browserSession.on('Target.targetCreated', async ({targetInfo}) => {
Expand Down
6 changes: 3 additions & 3 deletions test/chromium/oopif.spec.js
Expand Up @@ -17,7 +17,7 @@
/**
* @type {ChromiumTestSuite}
*/
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROMIUM, WEBKIT}) {
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
Expand All @@ -28,7 +28,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p

describe('OOPIF', function() {
beforeAll(async function(state) {
state.browser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {
state.browser = await browserType.launch(Object.assign({}, defaultBrowserOptions, {
args: (defaultBrowserOptions.args || []).concat(['--site-per-process']),
}));
});
Expand Down Expand Up @@ -65,7 +65,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
it.fail(true)('should report google.com frame with headful', async({server}) => {
// TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548
// https://google.com is isolated by default in Chromium embedder.
const browser = await playwright.launch(headfulOptions);
const browser = await browserType.launch(headfulOptions);
const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE);
await page.route('**/*', request => {
Expand Down
4 changes: 2 additions & 2 deletions test/chromium/tracing.spec.js
Expand Up @@ -20,15 +20,15 @@ const path = require('path');
/**
* @type {ChromiumTestSuite}
*/
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, ASSETS_DIR}) {
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, ASSETS_DIR}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;

describe('Chromium.startTracing', function() {
beforeEach(async function(state) {
state.outputFile = path.join(ASSETS_DIR, `trace-${state.parallelIndex}.json`);
state.browser = await playwright.launch(defaultBrowserOptions);
state.browser = await browserType.launch(defaultBrowserOptions);
state.page = await state.browser.newPage();
});
afterEach(async function(state) {
Expand Down
6 changes: 3 additions & 3 deletions test/cookies.spec.js
Expand Up @@ -18,7 +18,7 @@
/**
* @type {PageTestSuite}
*/
module.exports.describe = function({testRunner, expect, playwright, defaultBrowserOptions, MAC, FFOX, CHROMIUM, WEBKIT}) {
module.exports.describe = function({testRunner, expect, browserType, defaultBrowserOptions, MAC, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
Expand Down Expand Up @@ -276,12 +276,12 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
}
});
it.slow()('should isolate cookies between launches', async({server}) => {
const browser1 = await playwright.launch(defaultBrowserOptions);
const browser1 = await browserType.launch(defaultBrowserOptions);
const context1 = await browser1.newContext();
await context1.addCookies([{url: server.EMPTY_PAGE, name: 'cookie-in-context-1', value: 'value', expires: Date.now() / 1000 + 10000}]);
await browser1.close();

const browser2 = await playwright.launch(defaultBrowserOptions);
const browser2 = await browserType.launch(defaultBrowserOptions);
const context2 = await browser2.newContext();
const cookies = await context2.cookies();
expect(cookies.length).toBe(0);
Expand Down
4 changes: 2 additions & 2 deletions test/defaultbrowsercontext.spec.js
Expand Up @@ -20,15 +20,15 @@ const { makeUserDataDir, removeUserDataDir } = require('./utils');
/**
* @type {PageTestSuite}
*/
module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions, playwright, WEBKIT }) {
module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions, browserType, WEBKIT }) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;

describe('launchPersistentContext()', function() {
beforeEach(async state => {
state.userDataDir = await makeUserDataDir();
state.browserContext = await playwright.launchPersistentContext(state.userDataDir, defaultBrowserOptions);
state.browserContext = await browserType.launchPersistentContext(state.userDataDir, defaultBrowserOptions);
state.page = await state.browserContext.newPage();
});
afterEach(async state => {
Expand Down
4 changes: 2 additions & 2 deletions test/fixtures.spec.js
Expand Up @@ -21,7 +21,7 @@ const {spawn, execSync} = require('child_process');
/**
* @type {TestSuite}
*/
module.exports.describe = function({testRunner, expect, product, playwright, playwrightPath, defaultBrowserOptions, WIN, FFOX, CHROMIUM, WEBKIT}) {
module.exports.describe = function({testRunner, expect, product, browserType, playwrightPath, defaultBrowserOptions, WIN, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
Expand Down Expand Up @@ -58,7 +58,7 @@ module.exports.describe = function({testRunner, expect, product, playwright, pla
browserPid = +match[1];
});
res.on('error', (...args) => console.log("ERROR", ...args));
const browser = await playwright.connect({ wsEndpoint: await wsEndPointPromise });
const browser = await browserType.connect({ wsEndpoint: await wsEndPointPromise });
const promises = [
new Promise(resolve => browser.once('disconnected', resolve)),
new Promise(resolve => res.on('exit', resolve)),
Expand Down
10 changes: 5 additions & 5 deletions test/headful.spec.js
Expand Up @@ -19,7 +19,7 @@ const { makeUserDataDir, removeUserDataDir } = require('./utils');
/**
* @type {TestSuite}
*/
module.exports.describe = function({testRunner, expect, playwright, defaultBrowserOptions, FFOX, CHROMIUM, WEBKIT, WIN}) {
module.exports.describe = function({testRunner, expect, browserType, defaultBrowserOptions, FFOX, CHROMIUM, WEBKIT, WIN}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
Expand All @@ -34,7 +34,7 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
describe('Headful', function() {
it('should have default url when launching browser', async function() {
const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, headfulOptions);
const browserContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const pages = (await browserContext.pages()).map(page => page.url());
expect(pages).toEqual(['about:blank']);
await browserContext.close();
Expand All @@ -44,13 +44,13 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
it.fail((WIN && CHROMIUM) || FFOX)('headless should be able to read cookies written by headful', async({server}) => {
const userDataDir = await makeUserDataDir();
// Write a cookie in headful chrome
const headfulContext = await playwright.launchPersistentContext(userDataDir, headfulOptions);
const headfulContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const headfulPage = await headfulContext.newPage();
await headfulPage.goto(server.EMPTY_PAGE);
await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await headfulContext.close();
// Read the cookie from headless chrome
const headlessContext = await playwright.launchPersistentContext(userDataDir, headlessOptions);
const headlessContext = await browserType.launchPersistentContext(userDataDir, headlessOptions);
const headlessPage = await headlessContext.newPage();
await headlessPage.goto(server.EMPTY_PAGE);
const cookie = await headlessPage.evaluate(() => document.cookie);
Expand All @@ -61,7 +61,7 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
});
it.fail(FFOX)('should close browser with beforeunload page', async({server}) => {
const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, headfulOptions);
const browserContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const page = await browserContext.newPage();
await page.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers
Expand Down

0 comments on commit 9aa56a6

Please sign in to comment.