chore: stop using console.assert everywhere (#2646)

Since Node 10, `console.assert` no longer throws an AssertionError.
(This is generally good since it aligns Node.js with Browsers.)

This patch migrates all usages of `console.assert` in our codebase.
- All the `lib/` and testing code is migrated onto a handmade `assert`
function. This is to make Puppeteer transpilation / bundling easier.
- All the tooling is switched to use Node's `assert` module.

Fixes #2547.
This commit is contained in:
Andrey Lushnikov 2018-05-31 16:53:51 -07:00 committed by GitHub
parent 35e3f12afa
commit 0b94fa70eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 105 additions and 83 deletions

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const { helper } = require('./helper'); const { helper, assert } = require('./helper');
const Target = require('./Target'); const Target = require('./Target');
const EventEmitter = require('events'); const EventEmitter = require('events');
const TaskQueue = require('./TaskQueue'); const TaskQueue = require('./TaskQueue');
@ -108,7 +108,7 @@ class Browser extends EventEmitter {
const context = (browserContextId && this._contexts.has(browserContextId)) ? this._contexts.get(browserContextId) : this._defaultContext; const context = (browserContextId && this._contexts.has(browserContextId)) ? this._contexts.get(browserContextId) : this._defaultContext;
const target = new Target(targetInfo, context, () => this._connection.createSession(targetInfo.targetId), this._ignoreHTTPSErrors, this._setDefaultViewport, this._screenshotTaskQueue); const target = new Target(targetInfo, context, () => this._connection.createSession(targetInfo.targetId), this._ignoreHTTPSErrors, this._setDefaultViewport, this._screenshotTaskQueue);
console.assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated'); assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated');
this._targets.set(event.targetInfo.targetId, target); this._targets.set(event.targetInfo.targetId, target);
if (await target._initializedPromise) { if (await target._initializedPromise) {
@ -136,7 +136,7 @@ class Browser extends EventEmitter {
*/ */
_targetInfoChanged(event) { _targetInfoChanged(event) {
const target = this._targets.get(event.targetInfo.targetId); const target = this._targets.get(event.targetInfo.targetId);
console.assert(target, 'target should exist before targetInfoChanged'); assert(target, 'target should exist before targetInfoChanged');
const previousURL = target.url(); const previousURL = target.url();
const wasInitialized = target._isInitialized; const wasInitialized = target._isInitialized;
target._targetInfoChanged(event.targetInfo); target._targetInfoChanged(event.targetInfo);
@ -167,7 +167,7 @@ class Browser extends EventEmitter {
async _createPageInContext(contextId) { async _createPageInContext(contextId) {
const {targetId} = await this._connection.send('Target.createTarget', {url: 'about:blank', browserContextId: contextId || undefined}); const {targetId} = await this._connection.send('Target.createTarget', {url: 'about:blank', browserContextId: contextId || undefined});
const target = await this._targets.get(targetId); const target = await this._targets.get(targetId);
console.assert(await target._initializedPromise, 'Failed to create target for page'); assert(await target._initializedPromise, 'Failed to create target for page');
const page = await target.page(); const page = await target.page();
return page; return page;
} }
@ -268,7 +268,7 @@ class BrowserContext extends EventEmitter {
} }
async close() { async close() {
console.assert(this._id, 'Non-incognito profiles cannot be closed!'); assert(this._id, 'Non-incognito profiles cannot be closed!');
await this._browser._disposeContext(this._id); await this._browser._disposeContext(this._id);
} }
} }

View File

@ -20,7 +20,7 @@ const path = require('path');
const extract = require('extract-zip'); const extract = require('extract-zip');
const util = require('util'); const util = require('util');
const URL = require('url'); const URL = require('url');
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const removeRecursive = require('rimraf'); const removeRecursive = require('rimraf');
// @ts-ignore // @ts-ignore
const ProxyAgent = require('https-proxy-agent'); const ProxyAgent = require('https-proxy-agent');
@ -63,10 +63,10 @@ class BrowserFetcher {
this._platform = 'linux'; this._platform = 'linux';
else if (platform === 'win32') else if (platform === 'win32')
this._platform = os.arch() === 'x64' ? 'win64' : 'win32'; this._platform = os.arch() === 'x64' ? 'win64' : 'win32';
console.assert(this._platform, 'Unsupported platform: ' + os.platform()); assert(this._platform, 'Unsupported platform: ' + os.platform());
} }
const supportedPlatforms = ['mac', 'linux', 'win32', 'win64']; const supportedPlatforms = ['mac', 'linux', 'win32', 'win64'];
console.assert(supportedPlatforms.includes(this._platform), 'Unsupported platform: ' + this._platform); assert(supportedPlatforms.includes(this._platform), 'Unsupported platform: ' + this._platform);
} }
/** /**
@ -138,7 +138,7 @@ class BrowserFetcher {
*/ */
async remove(revision) { async remove(revision) {
const folderPath = this._getFolderPath(revision); const folderPath = this._getFolderPath(revision);
console.assert(await existsAsync(folderPath), `Failed to remove: revision ${revision} is not downloaded`); assert(await existsAsync(folderPath), `Failed to remove: revision ${revision} is not downloaded`);
await new Promise(fulfill => removeRecursive(folderPath, fulfill)); await new Promise(fulfill => removeRecursive(folderPath, fulfill));
} }

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const debugProtocol = require('debug')('puppeteer:protocol'); const debugProtocol = require('debug')('puppeteer:protocol');
const debugSession = require('debug')('puppeteer:session'); const debugSession = require('debug')('puppeteer:session');
@ -228,7 +228,7 @@ class CDPSession extends EventEmitter {
this._sessions.delete(object.params.sessionId); this._sessions.delete(object.params.sessionId);
} }
} }
console.assert(!object.id); assert(!object.id);
this.emit(object.method, object.params); this.emit(object.method, object.params);
} }
} }

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const {helper, debugError} = require('./helper'); const {helper, debugError, assert} = require('./helper');
/** /**
* @typedef {Object} CoverageEntry * @typedef {Object} CoverageEntry
@ -81,7 +81,7 @@ class JSCoverage {
* @param {!Object} options * @param {!Object} options
*/ */
async start(options = {}) { async start(options = {}) {
console.assert(!this._enabled, 'JSCoverage is already enabled'); assert(!this._enabled, 'JSCoverage is already enabled');
this._resetOnNavigation = options.resetOnNavigation === undefined ? true : !!options.resetOnNavigation; this._resetOnNavigation = options.resetOnNavigation === undefined ? true : !!options.resetOnNavigation;
this._enabled = true; this._enabled = true;
this._scriptURLs.clear(); this._scriptURLs.clear();
@ -126,7 +126,7 @@ class JSCoverage {
* @return {!Promise<!Array<!CoverageEntry>>} * @return {!Promise<!Array<!CoverageEntry>>}
*/ */
async stop() { async stop() {
console.assert(this._enabled, 'JSCoverage is not enabled'); assert(this._enabled, 'JSCoverage is not enabled');
this._enabled = false; this._enabled = false;
const [profileResponse] = await Promise.all([ const [profileResponse] = await Promise.all([
this._client.send('Profiler.takePreciseCoverage'), this._client.send('Profiler.takePreciseCoverage'),
@ -169,7 +169,7 @@ class CSSCoverage {
* @param {!Object} options * @param {!Object} options
*/ */
async start(options = {}) { async start(options = {}) {
console.assert(!this._enabled, 'CSSCoverage is already enabled'); assert(!this._enabled, 'CSSCoverage is already enabled');
this._resetOnNavigation = options.resetOnNavigation === undefined ? true : !!options.resetOnNavigation; this._resetOnNavigation = options.resetOnNavigation === undefined ? true : !!options.resetOnNavigation;
this._enabled = true; this._enabled = true;
this._stylesheetURLs.clear(); this._stylesheetURLs.clear();
@ -214,7 +214,7 @@ class CSSCoverage {
* @return {!Promise<!Array<!CoverageEntry>>} * @return {!Promise<!Array<!CoverageEntry>>}
*/ */
async stop() { async stop() {
console.assert(this._enabled, 'CSSCoverage is not enabled'); assert(this._enabled, 'CSSCoverage is not enabled');
this._enabled = false; this._enabled = false;
const [ruleTrackingResponse] = await Promise.all([ const [ruleTrackingResponse] = await Promise.all([
this._client.send('CSS.stopRuleUsageTracking'), this._client.send('CSS.stopRuleUsageTracking'),

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
class Dialog { class Dialog {
/** /**
@ -56,7 +56,7 @@ class Dialog {
* @param {string=} promptText * @param {string=} promptText
*/ */
async accept(promptText) { async accept(promptText) {
console.assert(!this._handled, 'Cannot accept dialog which is already handled!'); assert(!this._handled, 'Cannot accept dialog which is already handled!');
this._handled = true; this._handled = true;
await this._client.send('Page.handleJavaScriptDialog', { await this._client.send('Page.handleJavaScriptDialog', {
accept: true, accept: true,
@ -65,7 +65,7 @@ class Dialog {
} }
async dismiss() { async dismiss() {
console.assert(!this._handled, 'Cannot dismiss dialog which is already handled!'); assert(!this._handled, 'Cannot dismiss dialog which is already handled!');
this._handled = true; this._handled = true;
await this._client.send('Page.handleJavaScriptDialog', { await this._client.send('Page.handleJavaScriptDialog', {
accept: false accept: false

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
class ExecutionContext { class ExecutionContext {
/** /**
@ -123,8 +123,8 @@ class ExecutionContext {
* @return {!Promise<!JSHandle>} * @return {!Promise<!JSHandle>}
*/ */
async queryObjects(prototypeHandle) { async queryObjects(prototypeHandle) {
console.assert(!prototypeHandle._disposed, 'Prototype JSHandle is disposed!'); assert(!prototypeHandle._disposed, 'Prototype JSHandle is disposed!');
console.assert(prototypeHandle._remoteObject.objectId, 'Prototype JSHandle must not be referencing primitive value'); assert(prototypeHandle._remoteObject.objectId, 'Prototype JSHandle must not be referencing primitive value');
const response = await this._client.send('Runtime.queryObjects', { const response = await this._client.send('Runtime.queryObjects', {
prototypeObjectId: prototypeHandle._remoteObject.objectId prototypeObjectId: prototypeHandle._remoteObject.objectId
}); });

View File

@ -16,7 +16,7 @@
const fs = require('fs'); const fs = require('fs');
const EventEmitter = require('events'); const EventEmitter = require('events');
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const {ExecutionContext, JSHandle} = require('./ExecutionContext'); const {ExecutionContext, JSHandle} = require('./ExecutionContext');
const ElementHandle = require('./ElementHandle'); const ElementHandle = require('./ElementHandle');
@ -116,7 +116,7 @@ class FrameManager extends EventEmitter {
_onFrameAttached(frameId, parentFrameId) { _onFrameAttached(frameId, parentFrameId) {
if (this._frames.has(frameId)) if (this._frames.has(frameId))
return; return;
console.assert(parentFrameId); assert(parentFrameId);
const parentFrame = this._frames.get(parentFrameId); const parentFrame = this._frames.get(parentFrameId);
const frame = new Frame(this._client, this._page, parentFrame, frameId); const frame = new Frame(this._client, this._page, parentFrame, frameId);
this._frames.set(frame._id, frame); this._frames.set(frame._id, frame);
@ -129,7 +129,7 @@ class FrameManager extends EventEmitter {
_onFrameNavigated(framePayload) { _onFrameNavigated(framePayload) {
const isMainFrame = !framePayload.parentId; const isMainFrame = !framePayload.parentId;
let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id); let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id);
console.assert(isMainFrame || frame, 'We either navigate top level or have old version of the navigated frame'); assert(isMainFrame || frame, 'We either navigate top level or have old version of the navigated frame');
// Detach all child frames first. // Detach all child frames first.
if (frame) { if (frame) {
@ -220,7 +220,7 @@ class FrameManager extends EventEmitter {
*/ */
createJSHandle(contextId, remoteObject) { createJSHandle(contextId, remoteObject) {
const context = this._contextIdToContext.get(contextId); const context = this._contextIdToContext.get(contextId);
console.assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId); assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId);
if (remoteObject.subtype === 'node') if (remoteObject.subtype === 'node')
return new ElementHandle(context, this._client, remoteObject, this._page, this); return new ElementHandle(context, this._client, remoteObject, this._page, this);
return new JSHandle(context, this._client, remoteObject); return new JSHandle(context, this._client, remoteObject);
@ -588,7 +588,7 @@ class Frame {
*/ */
async click(selector, options = {}) { async click(selector, options = {}) {
const handle = await this.$(selector); const handle = await this.$(selector);
console.assert(handle, 'No node found for selector: ' + selector); assert(handle, 'No node found for selector: ' + selector);
await handle.click(options); await handle.click(options);
await handle.dispose(); await handle.dispose();
} }
@ -598,7 +598,7 @@ class Frame {
*/ */
async focus(selector) { async focus(selector) {
const handle = await this.$(selector); const handle = await this.$(selector);
console.assert(handle, 'No node found for selector: ' + selector); assert(handle, 'No node found for selector: ' + selector);
await handle.focus(); await handle.focus();
await handle.dispose(); await handle.dispose();
} }
@ -608,7 +608,7 @@ class Frame {
*/ */
async hover(selector) { async hover(selector) {
const handle = await this.$(selector); const handle = await this.$(selector);
console.assert(handle, 'No node found for selector: ' + selector); assert(handle, 'No node found for selector: ' + selector);
await handle.hover(); await handle.hover();
await handle.dispose(); await handle.dispose();
} }
@ -620,7 +620,7 @@ class Frame {
*/ */
select(selector, ...values){ select(selector, ...values){
for (const value of values) for (const value of values)
console.assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"'); assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');
return this.$eval(selector, (element, values) => { return this.$eval(selector, (element, values) => {
if (element.nodeName.toLowerCase() !== 'select') if (element.nodeName.toLowerCase() !== 'select')
throw new Error('Element is not a <select> element.'); throw new Error('Element is not a <select> element.');
@ -643,7 +643,7 @@ class Frame {
*/ */
async tap(selector) { async tap(selector) {
const handle = await this.$(selector); const handle = await this.$(selector);
console.assert(handle, 'No node found for selector: ' + selector); assert(handle, 'No node found for selector: ' + selector);
await handle.tap(); await handle.tap();
await handle.dispose(); await handle.dispose();
} }
@ -655,7 +655,7 @@ class Frame {
*/ */
async type(selector, text, options) { async type(selector, text, options) {
const handle = await this.$(selector); const handle = await this.$(selector);
console.assert(handle, 'No node found for selector: ' + selector); assert(handle, 'No node found for selector: ' + selector);
await handle.type(text, options); await handle.type(text, options);
await handle.dispose(); await handle.dispose();
} }
@ -818,9 +818,9 @@ class WaitTask {
*/ */
constructor(frame, predicateBody, title, polling, timeout, ...args) { constructor(frame, predicateBody, title, polling, timeout, ...args) {
if (helper.isString(polling)) if (helper.isString(polling))
console.assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling); assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);
else if (helper.isNumber(polling)) else if (helper.isNumber(polling))
console.assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling); assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);
else else
throw new Error('Unknown polling options: ' + polling); throw new Error('Unknown polling options: ' + polling);

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const keyDefinitions = require('./USKeyboardLayout'); const keyDefinitions = require('./USKeyboardLayout');
/** /**
@ -93,7 +93,7 @@ class Keyboard {
}; };
const definition = keyDefinitions[keyString]; const definition = keyDefinitions[keyString];
console.assert(definition, `Unknown key: "${keyString}"`); assert(definition, `Unknown key: "${keyString}"`);
if (definition.key) if (definition.key)
description.key = definition.key; description.key = definition.key;

View File

@ -22,7 +22,7 @@ const {Connection} = require('./Connection');
const {Browser} = require('./Browser'); const {Browser} = require('./Browser');
const readline = require('readline'); const readline = require('readline');
const fs = require('fs'); const fs = require('fs');
const {helper, debugError} = require('./helper'); const {helper, assert, debugError} = require('./helper');
const ChromiumRevision = require(path.join(helper.projectRoot(), 'package.json')).puppeteer.chromium_revision; const ChromiumRevision = require(path.join(helper.projectRoot(), 'package.json')).puppeteer.chromium_revision;
const mkdtempAsync = helper.promisify(fs.mkdtemp); const mkdtempAsync = helper.promisify(fs.mkdtemp);
@ -60,7 +60,7 @@ class Launcher {
*/ */
static async launch(options) { static async launch(options) {
options = Object.assign({}, options || {}); options = Object.assign({}, options || {});
console.assert(!options.ignoreDefaultArgs || !options.appMode, '`appMode` flag cannot be used together with `ignoreDefaultArgs`'); assert(!options.ignoreDefaultArgs || !options.appMode, '`appMode` flag cannot be used together with `ignoreDefaultArgs`');
let temporaryUserDataDir = null; let temporaryUserDataDir = null;
const chromeArguments = []; const chromeArguments = [];
if (!options.ignoreDefaultArgs) if (!options.ignoreDefaultArgs)
@ -100,7 +100,7 @@ class Launcher {
if (typeof chromeExecutable !== 'string') { if (typeof chromeExecutable !== 'string') {
const browserFetcher = new BrowserFetcher(); const browserFetcher = new BrowserFetcher();
const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision); const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision);
console.assert(revisionInfo.local, `Chromium revision is not downloaded. Run "npm install" or "yarn install"`); assert(revisionInfo.local, `Chromium revision is not downloaded. Run "npm install" or "yarn install"`);
chromeExecutable = revisionInfo.executablePath; chromeExecutable = revisionInfo.executablePath;
} }
if (Array.isArray(options.args)) if (Array.isArray(options.args))

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const {FrameManager} = require('./FrameManager'); const {FrameManager} = require('./FrameManager');
class NavigatorWatcher { class NavigatorWatcher {
@ -25,9 +25,9 @@ class NavigatorWatcher {
* @param {!Object=} options * @param {!Object=} options
*/ */
constructor(frameManager, frame, timeout, options = {}) { constructor(frameManager, frame, timeout, options = {}) {
console.assert(options.networkIdleTimeout === undefined, 'ERROR: networkIdleTimeout option is no longer supported.'); assert(options.networkIdleTimeout === undefined, 'ERROR: networkIdleTimeout option is no longer supported.');
console.assert(options.networkIdleInflight === undefined, 'ERROR: networkIdleInflight option is no longer supported.'); assert(options.networkIdleInflight === undefined, 'ERROR: networkIdleInflight option is no longer supported.');
console.assert(options.waitUntil !== 'networkidle', 'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead'); assert(options.waitUntil !== 'networkidle', 'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead');
let waitUntil = ['load']; let waitUntil = ['load'];
if (Array.isArray(options.waitUntil)) if (Array.isArray(options.waitUntil))
waitUntil = options.waitUntil.slice(); waitUntil = options.waitUntil.slice();
@ -35,7 +35,7 @@ class NavigatorWatcher {
waitUntil = [options.waitUntil]; waitUntil = [options.waitUntil];
this._expectedLifecycle = waitUntil.map(value => { this._expectedLifecycle = waitUntil.map(value => {
const protocolEvent = puppeteerToProtocolLifecycle[value]; const protocolEvent = puppeteerToProtocolLifecycle[value];
console.assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value); assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
return protocolEvent; return protocolEvent;
}); });

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const EventEmitter = require('events'); const EventEmitter = require('events');
const {helper, debugError} = require('./helper'); const {helper, assert, debugError} = require('./helper');
const Multimap = require('./Multimap'); const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter { class NetworkManager extends EventEmitter {
@ -69,7 +69,7 @@ class NetworkManager extends EventEmitter {
this._extraHTTPHeaders = {}; this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) { for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key]; const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`); assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value; this._extraHTTPHeaders[key.toLowerCase()] = value;
} }
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders }); await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
@ -407,8 +407,8 @@ class Request {
* @param {!Object=} overrides * @param {!Object=} overrides
*/ */
async continue(overrides = {}) { async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!'); assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!'); assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true; this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', { await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId, interceptionId: this._interceptionId,
@ -430,8 +430,8 @@ class Request {
// Mocking responses for dataURL requests is not currently supported. // Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:')) if (this._url.startsWith('data:'))
return; return;
console.assert(this._allowInterception, 'Request Interception is not enabled!'); assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!'); assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true; this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null); const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
@ -476,9 +476,9 @@ class Request {
*/ */
async abort(errorCode = 'failed') { async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode]; const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode); assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!'); assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!'); assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true; this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', { await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId, interceptionId: this._interceptionId,

View File

@ -24,7 +24,7 @@ const EmulationManager = require('./EmulationManager');
const {FrameManager} = require('./FrameManager'); const {FrameManager} = require('./FrameManager');
const {Keyboard, Mouse, Touchscreen} = require('./Input'); const {Keyboard, Mouse, Touchscreen} = require('./Input');
const Tracing = require('./Tracing'); const Tracing = require('./Tracing');
const {helper, debugError} = require('./helper'); const {helper, debugError, assert} = require('./helper');
const {Coverage} = require('./Coverage'); const {Coverage} = require('./Coverage');
const Worker = require('./Worker'); const Worker = require('./Worker');
@ -346,11 +346,11 @@ class Page extends EventEmitter {
const item = Object.assign({}, cookie); const item = Object.assign({}, cookie);
if (!item.url && startsWithHTTP) if (!item.url && startsWithHTTP)
item.url = pageURL; item.url = pageURL;
console.assert( assert(
item.url !== 'about:blank', item.url !== 'about:blank',
`Blank page can not have cookie "${item.name}"` `Blank page can not have cookie "${item.name}"`
); );
console.assert( assert(
!String.prototype.startsWith.call(item.url || '', 'data:'), !String.prototype.startsWith.call(item.url || '', 'data:'),
`Data URL page can not have cookie "${item.name}"` `Data URL page can not have cookie "${item.name}"`
); );
@ -510,7 +510,7 @@ class Page extends EventEmitter {
dialogType = Dialog.Type.Prompt; dialogType = Dialog.Type.Prompt;
else if (event.type === 'beforeunload') else if (event.type === 'beforeunload')
dialogType = Dialog.Type.BeforeUnload; dialogType = Dialog.Type.BeforeUnload;
console.assert(dialogType, 'Unknown javascript dialog type: ' + event.type); assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt); const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
this.emit(Page.Events.Dialog, dialog); this.emit(Page.Events.Dialog, dialog);
} }
@ -680,7 +680,7 @@ class Page extends EventEmitter {
* @param {?string} mediaType * @param {?string} mediaType
*/ */
async emulateMedia(mediaType) { async emulateMedia(mediaType) {
console.assert(mediaType === 'screen' || mediaType === 'print' || mediaType === null, 'Unsupported media type: ' + mediaType); assert(mediaType === 'screen' || mediaType === 'print' || mediaType === null, 'Unsupported media type: ' + mediaType);
await this._client.send('Emulation.setEmulatedMedia', {media: mediaType || ''}); await this._client.send('Emulation.setEmulatedMedia', {media: mediaType || ''});
} }
@ -736,7 +736,7 @@ class Page extends EventEmitter {
// options.type takes precedence over inferring the type from options.path // options.type takes precedence over inferring the type from options.path
// because it may be a 0-length file with no extension created beforehand (i.e. as a temp file). // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).
if (options.type) { if (options.type) {
console.assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type); assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
screenshotType = options.type; screenshotType = options.type;
} else if (options.path) { } else if (options.path) {
const mimeType = mime.getType(options.path); const mimeType = mime.getType(options.path);
@ -744,24 +744,24 @@ class Page extends EventEmitter {
screenshotType = 'png'; screenshotType = 'png';
else if (mimeType === 'image/jpeg') else if (mimeType === 'image/jpeg')
screenshotType = 'jpeg'; screenshotType = 'jpeg';
console.assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType); assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);
} }
if (!screenshotType) if (!screenshotType)
screenshotType = 'png'; screenshotType = 'png';
if (options.quality) { if (options.quality) {
console.assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots'); assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');
console.assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality)); assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));
console.assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer'); assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
console.assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality); assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);
} }
console.assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive'); assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
if (options.clip) { if (options.clip) {
console.assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x)); assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));
console.assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y)); assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));
console.assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width)); assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));
console.assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height)); assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));
} }
return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options)); return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));
} }
@ -824,7 +824,7 @@ class Page extends EventEmitter {
let paperHeight = 11; let paperHeight = 11;
if (options.format) { if (options.format) {
const format = Page.PaperFormats[options.format.toLowerCase()]; const format = Page.PaperFormats[options.format.toLowerCase()];
console.assert(format, 'Unknown paper format: ' + options.format); assert(format, 'Unknown paper format: ' + options.format);
paperWidth = format.width; paperWidth = format.width;
paperHeight = format.height; paperHeight = format.height;
} else { } else {
@ -870,7 +870,7 @@ class Page extends EventEmitter {
* @param {!{runBeforeUnload: (boolean|undefined)}=} options * @param {!{runBeforeUnload: (boolean|undefined)}=} options
*/ */
async close(options = {runBeforeUnload: undefined}) { async close(options = {runBeforeUnload: undefined}) {
console.assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.'); assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
const runBeforeUnload = !!options.runBeforeUnload; const runBeforeUnload = !!options.runBeforeUnload;
if (runBeforeUnload) { if (runBeforeUnload) {
await this._client.send('Page.close'); await this._client.send('Page.close');
@ -1043,7 +1043,7 @@ function convertPrintParameterToInches(parameter) {
valueText = text; valueText = text;
} }
const value = Number(valueText); const value = Number(valueText);
console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text); assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
pixels = value * unitToPixels[unit]; pixels = value * unitToPixels[unit];
} else { } else {
throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter)); throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
const {helper} = require('./helper'); const {helper, assert} = require('./helper');
const fs = require('fs'); const fs = require('fs');
const openAsync = helper.promisify(fs.open); const openAsync = helper.promisify(fs.open);
@ -34,7 +34,7 @@ class Tracing {
* @param {!Object} options * @param {!Object} options
*/ */
async start(options) { async start(options) {
console.assert(!this._recording, 'Cannot start recording trace while already recording trace.'); assert(!this._recording, 'Cannot start recording trace while already recording trace.');
const defaultCategories = [ const defaultCategories = [
'-*', 'devtools.timeline', 'v8.execute', 'disabled-by-default-devtools.timeline', '-*', 'devtools.timeline', 'v8.execute', 'disabled-by-default-devtools.timeline',

View File

@ -28,7 +28,7 @@ class Helper {
*/ */
static evaluationString(fun, ...args) { static evaluationString(fun, ...args) {
if (Helper.isString(fun)) { if (Helper.isString(fun)) {
console.assert(args.length === 0, 'Cannot evaluate a string with arguments'); assert(args.length === 0, 'Cannot evaluate a string with arguments');
return /** @type {string} */ (fun); return /** @type {string} */ (fun);
} }
return `(${fun})(${args.map(serializeArgument).join(',')})`; return `(${fun})(${args.map(serializeArgument).join(',')})`;
@ -78,7 +78,7 @@ class Helper {
* @return {*} * @return {*}
*/ */
static valueFromRemoteObject(remoteObject) { static valueFromRemoteObject(remoteObject) {
console.assert(!remoteObject.objectId, 'Cannot extract value when objectId is given'); assert(!remoteObject.objectId, 'Cannot extract value when objectId is given');
if (remoteObject.unserializableValue) { if (remoteObject.unserializableValue) {
switch (remoteObject.unserializableValue) { switch (remoteObject.unserializableValue) {
case '-0': case '-0':
@ -242,7 +242,17 @@ class Helper {
} }
} }
/**
* @param {*} value
* @param {string=} message
*/
function assert(value, message) {
if (!value)
throw new Error(message);
}
module.exports = { module.exports = {
helper: Helper, helper: Helper,
assert,
debugError debugError
}; };

View File

@ -22,7 +22,7 @@ const GOLDEN_DIR = path.join(__dirname, 'golden');
const OUTPUT_DIR = path.join(__dirname, 'output'); const OUTPUT_DIR = path.join(__dirname, 'output');
const {TestRunner, Reporter, Matchers} = require('../utils/testrunner/'); const {TestRunner, Reporter, Matchers} = require('../utils/testrunner/');
const {helper} = require('../lib/helper'); const {helper, assert} = require('../lib/helper');
if (process.env.COVERAGE) if (process.env.COVERAGE)
helper.recordPublicAPICoverage(); helper.recordPublicAPICoverage();
@ -40,7 +40,7 @@ const extensionPath = path.resolve(__dirname, '../test/assets/simple-extension')
if (executablePath) if (executablePath)
console.warn(`${YELLOW_COLOR}WARN: running tests with ${executablePath}${RESET_COLOR}`); console.warn(`${YELLOW_COLOR}WARN: running tests with ${executablePath}${RESET_COLOR}`);
// Make sure the `npm install` was run after the chromium roll. // Make sure the `npm install` was run after the chromium roll.
console.assert(fs.existsSync(puppeteer.executablePath()), `Chromium is not Downloaded. Run 'npm install' and try to re-run tests`); assert(fs.existsSync(puppeteer.executablePath()), `Chromium is not Downloaded. Run 'npm install' and try to re-run tests`);
const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10); const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);
const defaultBrowserOptions = { const defaultBrowserOptions = {

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
const assert = require('assert');
const puppeteer = require('..'); const puppeteer = require('..');
const https = require('https'); const https = require('https');
const SUPPORTER_PLATFORMS = ['linux', 'mac', 'win32', 'win64']; const SUPPORTER_PLATFORMS = ['linux', 'mac', 'win32', 'win64'];
@ -40,7 +41,7 @@ class Table {
* @param {!Array<string>} values * @param {!Array<string>} values
*/ */
drawRow(values) { drawRow(values) {
console.assert(values.length === this.widths.length); assert(values.length === this.widths.length);
let row = ''; let row = '';
for (let i = 0; i < values.length; ++i) for (let i = 0; i < values.length; ++i)
row += padCenter(values[i], this.widths[i]); row += padCenter(values[i], this.widths[i]);

View File

@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
const assert = require('assert');
const esprima = require('esprima'); const esprima = require('esprima');
const ESTreeWalker = require('../../ESTreeWalker'); const ESTreeWalker = require('../../ESTreeWalker');
const Documentation = require('./Documentation'); const Documentation = require('./Documentation');
@ -59,8 +60,8 @@ class JSOutline {
} }
_onMethodDefinition(node) { _onMethodDefinition(node) {
console.assert(this._currentClassName !== null); assert(this._currentClassName !== null);
console.assert(node.value.type === 'FunctionExpression'); assert(node.value.type === 'FunctionExpression');
const methodName = this._extractText(node.key); const methodName = this._extractText(node.key);
if (node.kind === 'get') { if (node.kind === 'get') {
const property = Documentation.Member.createProperty(methodName); const property = Documentation.Member.createProperty(methodName);

View File

@ -44,7 +44,8 @@ class Expect {
function applyMatcher(matcherName, matcher, inverse, value, ...args) { function applyMatcher(matcherName, matcher, inverse, value, ...args) {
const result = matcher.call(null, value, ...args); const result = matcher.call(null, value, ...args);
const message = `expect.${inverse ? 'not.' : ''}${matcherName} failed` + (result.message ? `: ${result.message}` : ''); const message = `expect.${inverse ? 'not.' : ''}${matcherName} failed` + (result.message ? `: ${result.message}` : '');
console.assert(result.pass !== inverse, message); if (result.pass === inverse)
throw new Error(message);
} }
} }
} }

View File

@ -316,7 +316,7 @@ class TestRunner extends EventEmitter {
} }
_addHook(hookName, callback) { _addHook(hookName, callback) {
console.assert(this._currentSuite[hookName] === null, `Only one ${hookName} hook available per suite`); assert(this._currentSuite[hookName] === null, `Only one ${hookName} hook available per suite`);
const hook = new UserCallback(callback, this._timeout); const hook = new UserCallback(callback, this._timeout);
this._currentSuite[hookName] = hook; this._currentSuite[hookName] = hook;
} }
@ -389,6 +389,15 @@ class TestRunner extends EventEmitter {
} }
} }
/**
* @param {*} value
* @param {string=} message
*/
function assert(value, message) {
if (!value)
throw new Error(message);
}
TestRunner.Events = { TestRunner.Events = {
Started: 'started', Started: 'started',
TestStarted: 'teststarted', TestStarted: 'teststarted',