/** * Copyright 2017 Google Inc. All rights reserved. * * 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. */ const fs = require('fs'); const path = require('path'); const utils = require('./utils'); const {waitEvent} = utils; let asyncawait = true; try { new Function('async function foo() {await 1}'); } catch (e) { asyncawait = false; } module.exports.addTests = function({testRunner, expect, headless, Errors, DeviceDescriptors}) { const {describe, xdescribe, fdescribe, describe_fails_ffox} = testRunner; const {it, fit, xit, it_fails_ffox} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {TimeoutError} = Errors; const iPhone = DeviceDescriptors['iPhone 6']; describe('Page.close', function() { it('should reject all promises when page is closed', async({context}) => { const newPage = await context.newPage(); const neverResolves = newPage.evaluate(() => new Promise(r => {})); newPage.close(); let error = null; await neverResolves.catch(e => error = e); expect(error.message).toContain('Protocol error'); }); it('should not be visible in browser.pages', async({browser}) => { const newPage = await browser.newPage(); expect(await browser.pages()).toContain(newPage); await newPage.close(); expect(await browser.pages()).not.toContain(newPage); }); it_fails_ffox('should run beforeunload if asked for', async({context, server}) => { const newPage = await context.newPage(); await newPage.goto(server.PREFIX + '/beforeunload.html'); // We have to interact with a page so that 'beforeunload' handlers // fire. await newPage.click('body'); newPage.close({ runBeforeUnload: true }); const dialog = await waitEvent(newPage, 'dialog'); expect(dialog.type()).toBe('beforeunload'); expect(dialog.defaultValue()).toBe(''); expect(dialog.message()).toBe(''); dialog.accept(); await waitEvent(newPage, 'close'); }); it('should set the page close state', async({context}) => { const newPage = await context.newPage(); expect(newPage.isClosed()).toBe(false); await newPage.close(); expect(newPage.isClosed()).toBe(true); }); }); describe('Page.Events.Load', function() { it('should fire when expected', async({page, server}) => { await Promise.all([ page.goto('about:blank'), utils.waitEvent(page, 'load'), ]); }); }); (asyncawait ? describe_fails_ffox : xdescribe)('Async stacks', () => { it('should work', async({page, server}) => { server.setRoute('/empty.html', (req, res) => { res.statusCode = 204; res.end(); }); let error = null; await page.goto(server.EMPTY_PAGE).catch(e => error = e); expect(error).not.toBe(null); expect(error.message).toContain('net::ERR_ABORTED'); }); }); describe_fails_ffox('Page.Events.error', function() { it('should throw when page crashes', async({page}) => { let error = null; page.on('error', err => error = err); page.goto('chrome://crash').catch(e => {}); await waitEvent(page, 'error'); expect(error.message).toBe('Page crashed!'); }); }); describe_fails_ffox('Page.Events.Popup', function() { it('should work', async({page}) => { const [popup] = await Promise.all([ new Promise(x => page.once('popup', x)), page.evaluate(() => window.open('about:blank')), ]); expect(await page.evaluate(() => !!window.opener)).toBe(false); expect(await popup.evaluate(() => !!window.opener)).toBe(true); }); it('should work with noopener', async({page}) => { const [popup] = await Promise.all([ new Promise(x => page.once('popup', x)), page.evaluate(() => window.open('about:blank', null, 'noopener')), ]); expect(await page.evaluate(() => !!window.opener)).toBe(false); expect(await popup.evaluate(() => !!window.opener)).toBe(false); }); it('should work with clicking target=_blank', async({page, server}) => { await page.goto(server.EMPTY_PAGE); await page.setContent('yo'); const [popup] = await Promise.all([ new Promise(x => page.once('popup', x)), page.click('a'), ]); expect(await page.evaluate(() => !!window.opener)).toBe(false); expect(await popup.evaluate(() => !!window.opener)).toBe(true); }); it('should work with fake-clicking target=_blank and rel=noopener', async({page, server}) => { await page.goto(server.EMPTY_PAGE); await page.setContent('yo'); const [popup] = await Promise.all([ new Promise(x => page.once('popup', x)), page.$eval('a', a => a.click()), ]); expect(await page.evaluate(() => !!window.opener)).toBe(false); expect(await popup.evaluate(() => !!window.opener)).toBe(false); }); it('should work with clicking target=_blank and rel=noopener', async({page, server}) => { await page.goto(server.EMPTY_PAGE); await page.setContent('yo'); const [popup] = await Promise.all([ new Promise(x => page.once('popup', x)), page.click('a'), ]); expect(await page.evaluate(() => !!window.opener)).toBe(false); expect(await popup.evaluate(() => !!window.opener)).toBe(false); }); }); describe_fails_ffox('BrowserContext.overridePermissions', function() { function getPermission(page, name) { return page.evaluate(name => navigator.permissions.query({name}).then(result => result.state), name); } it('should be prompt by default', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); expect(await getPermission(page, 'geolocation')).toBe('prompt'); }); it('should deny permission when not listed', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, []); expect(await getPermission(page, 'geolocation')).toBe('denied'); }); it('should fail when bad permission is given', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); let error = null; await context.overridePermissions(server.EMPTY_PAGE, ['foo']).catch(e => error = e); expect(error.message).toBe('Unknown permission: foo'); }); it('should grant permission when listed', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']); expect(await getPermission(page, 'geolocation')).toBe('granted'); }); it('should reset permissions', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']); expect(await getPermission(page, 'geolocation')).toBe('granted'); await context.clearPermissionOverrides(); expect(await getPermission(page, 'geolocation')).toBe('prompt'); }); it('should trigger permission onchange', async({page, server, context}) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { window.events = []; return navigator.permissions.query({name: 'clipboard-read'}).then(function(result) { window.events.push(result.state); result.onchange = function() { window.events.push(result.state); }; }); }); expect(await page.evaluate(() => window.events)).toEqual(['prompt']); await context.overridePermissions(server.EMPTY_PAGE, []); expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied']); await context.overridePermissions(server.EMPTY_PAGE, ['clipboard-read']); expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied', 'granted']); await context.clearPermissionOverrides(); expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied', 'granted', 'prompt']); }); }); describe_fails_ffox('Page.setGeolocation', function() { it('should work', async({page, server, context}) => { await context.overridePermissions(server.PREFIX, ['geolocation']); await page.goto(server.EMPTY_PAGE); await page.setGeolocation({longitude: 10, latitude: 10}); const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => { resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); }))); expect(geolocation).toEqual({ latitude: 10, longitude: 10 }); }); it('should throw when invalid longitude', async({page, server, context}) => { let error = null; try { await page.setGeolocation({longitude: 200, latitude: 10}); } catch (e) { error = e; } expect(error.message).toContain('Invalid longitude "200"'); }); }); describe_fails_ffox('Page.setOfflineMode', function() { it('should work', async({page, server}) => { await page.setOfflineMode(true); let error = null; await page.goto(server.EMPTY_PAGE).catch(e => error = e); expect(error).toBeTruthy(); await page.setOfflineMode(false); const response = await page.reload(); expect(response.status()).toBe(200); }); it('should emulate navigator.onLine', async({page, server}) => { expect(await page.evaluate(() => window.navigator.onLine)).toBe(true); await page.setOfflineMode(true); expect(await page.evaluate(() => window.navigator.onLine)).toBe(false); await page.setOfflineMode(false); expect(await page.evaluate(() => window.navigator.onLine)).toBe(true); }); }); describe_fails_ffox('ExecutionContext.queryObjects', function() { it('should work', async({page, server}) => { // Instantiate an object await page.evaluate(() => window.set = new Set(['hello', 'world'])); const prototypeHandle = await page.evaluateHandle(() => Set.prototype); const objectsHandle = await page.queryObjects(prototypeHandle); const count = await page.evaluate(objects => objects.length, objectsHandle); expect(count).toBe(1); const values = await page.evaluate(objects => Array.from(objects[0].values()), objectsHandle); expect(values).toEqual(['hello', 'world']); }); it('should fail for disposed handles', async({page, server}) => { const prototypeHandle = await page.evaluateHandle(() => HTMLBodyElement.prototype); await prototypeHandle.dispose(); let error = null; await page.queryObjects(prototypeHandle).catch(e => error = e); expect(error.message).toBe('Prototype JSHandle is disposed!'); }); it('should fail primitive values as prototypes', async({page, server}) => { const prototypeHandle = await page.evaluateHandle(() => 42); let error = null; await page.queryObjects(prototypeHandle).catch(e => error = e); expect(error.message).toBe('Prototype JSHandle must not be referencing primitive value'); }); }); describe('Page.Events.Console', function() { it('should work', async({page, server}) => { let message = null; page.once('console', m => message = m); await Promise.all([ page.evaluate(() => console.log('hello', 5, {foo: 'bar'})), waitEvent(page, 'console') ]); expect(message.text()).toEqual('hello 5 JSHandle@object'); expect(message.type()).toEqual('log'); expect(await message.args()[0].jsonValue()).toEqual('hello'); expect(await message.args()[1].jsonValue()).toEqual(5); expect(await message.args()[2].jsonValue()).toEqual({foo: 'bar'}); }); it('should work for different console API calls', async({page, server}) => { const messages = []; page.on('console', msg => messages.push(msg)); // All console events will be reported before `page.evaluate` is finished. await page.evaluate(() => { // A pair of time/timeEnd generates only one Console API call. console.time('calling console.time'); console.timeEnd('calling console.time'); console.trace('calling console.trace'); console.dir('calling console.dir'); console.warn('calling console.warn'); console.error('calling console.error'); console.log(Promise.resolve('should not wait until resolved!')); }); expect(messages.map(msg => msg.type())).toEqual([ 'timeEnd', 'trace', 'dir', 'warning', 'error', 'log' ]); expect(messages[0].text()).toContain('calling console.time'); expect(messages.slice(1).map(msg => msg.text())).toEqual([ 'calling console.trace', 'calling console.dir', 'calling console.warn', 'calling console.error', 'JSHandle@promise', ]); }); it('should not fail for window object', async({page, server}) => { let message = null; page.once('console', msg => message = msg); await Promise.all([ page.evaluate(() => console.error(window)), waitEvent(page, 'console') ]); expect(message.text()).toBe('JSHandle@object'); }); it_fails_ffox('should trigger correct Log', async({page, server}) => { await page.goto('about:blank'); const [message] = await Promise.all([ waitEvent(page, 'console'), page.evaluate(async url => fetch(url).catch(e => {}), server.EMPTY_PAGE) ]); expect(message.text()).toContain('No \'Access-Control-Allow-Origin\''); expect(message.type()).toEqual('error'); }); it_fails_ffox('should have location when fetch fails', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [message] = await Promise.all([ waitEvent(page, 'console'), page.setContent(``), ]); expect(message.text()).toContain(`ERR_NAME_NOT_RESOLVED`); expect(message.type()).toEqual('error'); expect(message.location()).toEqual({ url: 'http://wat/', lineNumber: undefined }); }); it_fails_ffox('should have location for console API calls', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [message] = await Promise.all([ waitEvent(page, 'console'), page.goto(server.PREFIX + '/consolelog.html'), ]); expect(message.text()).toBe('yellow'); expect(message.type()).toBe('log'); expect(message.location()).toEqual({ url: server.PREFIX + '/consolelog.html', lineNumber: 7, columnNumber: 14, }); }); // @see https://github.com/GoogleChrome/puppeteer/issues/3865 it_fails_ffox('should not throw when there are console messages in detached iframes', async({browser, page, server}) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(async() => { // 1. Create a popup that Puppeteer is not connected to. const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0'); await new Promise(x => win.onload = x); // 2. In this popup, create an iframe that console.logs a message. win.document.body.innerHTML = ``; const frame = win.document.querySelector('iframe'); await new Promise(x => frame.onload = x); // 3. After that, remove the iframe. frame.remove(); }); const popupTarget = page.browserContext().targets().find(target => target !== page.target()); // 4. Connect to the popup and make sure it doesn't throw. await popupTarget.page(); }); }); describe('Page.Events.DOMContentLoaded', function() { it('should fire when expected', async({page, server}) => { page.goto('about:blank'); await waitEvent(page, 'domcontentloaded'); }); }); describe_fails_ffox('Page.metrics', function() { it('should get metrics from a page', async({page, server}) => { await page.goto('about:blank'); const metrics = await page.metrics(); checkMetrics(metrics); }); it('metrics event fired on console.timeStamp', async({page, server}) => { const metricsPromise = new Promise(fulfill => page.once('metrics', fulfill)); await page.evaluate(() => console.timeStamp('test42')); const metrics = await metricsPromise; expect(metrics.title).toBe('test42'); checkMetrics(metrics.metrics); }); function checkMetrics(metrics) { const metricsToCheck = new Set([ 'Timestamp', 'Documents', 'Frames', 'JSEventListeners', 'Nodes', 'LayoutCount', 'RecalcStyleCount', 'LayoutDuration', 'RecalcStyleDuration', 'ScriptDuration', 'TaskDuration', 'JSHeapUsedSize', 'JSHeapTotalSize', ]); for (const name in metrics) { expect(metricsToCheck.has(name)).toBeTruthy(); expect(metrics[name]).toBeGreaterThanOrEqual(0); metricsToCheck.delete(name); } expect(metricsToCheck.size).toBe(0); } }); describe_fails_ffox('Page.waitForRequest', function() { it('should work', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest(server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with predicate', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest(request => request.url() === server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should respect timeout', async({page, server}) => { let error = null; await page.waitForRequest(() => false, {timeout: 1}).catch(e => error = e); expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default timeout', async({page, server}) => { let error = null; page.setDefaultTimeout(1); await page.waitForRequest(() => false).catch(e => error = e); expect(error).toBeInstanceOf(TimeoutError); }); it('should work with no timeout', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest(server.PREFIX + '/digits/2.png', {timeout: 0}), page.evaluate(() => setTimeout(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }, 50)) ]); expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); }); describe_fails_ffox('Page.waitForResponse', function() { it('should work', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should respect timeout', async({page, server}) => { let error = null; await page.waitForResponse(() => false, {timeout: 1}).catch(e => error = e); expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default timeout', async({page, server}) => { let error = null; page.setDefaultTimeout(1); await page.waitForResponse(() => false).catch(e => error = e); expect(error).toBeInstanceOf(TimeoutError); }); it('should work with predicate', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(response => response.url() === server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with no timeout', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(server.PREFIX + '/digits/2.png', {timeout: 0}), page.evaluate(() => setTimeout(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }, 50)) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); }); describe_fails_ffox('Page.exposeFunction', function() { it('should work', async({page, server}) => { await page.exposeFunction('compute', function(a, b) { return a * b; }); const result = await page.evaluate(async function() { return await compute(9, 4); }); expect(result).toBe(36); }); it('should throw exception in page context', async({page, server}) => { await page.exposeFunction('woof', function() { throw new Error('WOOF WOOF'); }); const {message, stack} = await page.evaluate(async() => { try { await woof(); } catch (e) { return {message: e.message, stack: e.stack}; } }); expect(message).toBe('WOOF WOOF'); expect(stack).toContain(__filename); }); it('should support throwing "null"', async({page, server}) => { await page.exposeFunction('woof', function() { throw null; }); const thrown = await page.evaluate(async() => { try { await woof(); } catch (e) { return e; } }); expect(thrown).toBe(null); }); it('should be callable from-inside evaluateOnNewDocument', async({page, server}) => { let called = false; await page.exposeFunction('woof', function() { called = true; }); await page.evaluateOnNewDocument(() => woof()); await page.reload(); expect(called).toBe(true); }); it('should survive navigation', async({page, server}) => { await page.exposeFunction('compute', function(a, b) { return a * b; }); await page.goto(server.EMPTY_PAGE); const result = await page.evaluate(async function() { return await compute(9, 4); }); expect(result).toBe(36); }); it('should await returned promise', async({page, server}) => { await page.exposeFunction('compute', function(a, b) { return Promise.resolve(a * b); }); const result = await page.evaluate(async function() { return await compute(3, 5); }); expect(result).toBe(15); }); it('should work on frames', async({page, server}) => { await page.exposeFunction('compute', function(a, b) { return Promise.resolve(a * b); }); await page.goto(server.PREFIX + '/frames/nested-frames.html'); const frame = page.frames()[1]; const result = await frame.evaluate(async function() { return await compute(3, 5); }); expect(result).toBe(15); }); it('should work on frames before navigation', async({page, server}) => { await page.goto(server.PREFIX + '/frames/nested-frames.html'); await page.exposeFunction('compute', function(a, b) { return Promise.resolve(a * b); }); const frame = page.frames()[1]; const result = await frame.evaluate(async function() { return await compute(3, 5); }); expect(result).toBe(15); }); }); describe('Page.Events.PageError', function() { it('should fire', async({page, server}) => { let error = null; page.once('pageerror', e => error = e); await Promise.all([ page.goto(server.PREFIX + '/error.html'), waitEvent(page, 'pageerror') ]); expect(error.message).toContain('Fancy'); }); }); describe_fails_ffox('Page.setUserAgent', function() { it('should work', async({page, server}) => { expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla'); page.setUserAgent('foobar'); const [request] = await Promise.all([ server.waitForRequest('/empty.html'), page.goto(server.EMPTY_PAGE), ]); expect(request.headers['user-agent']).toBe('foobar'); }); it('should emulate device user-agent', async({page, server}) => { await page.goto(server.PREFIX + '/mobile.html'); expect(await page.evaluate(() => navigator.userAgent)).toContain('Chrome'); await page.setUserAgent(iPhone.userAgent); expect(await page.evaluate(() => navigator.userAgent)).toContain('Safari'); }); }); describe('Page.setContent', function() { const expectedOutput = '