test: slim down test utils (#1701)

This commit is contained in:
Dmitry Gozman 2020-04-07 19:15:48 -07:00 committed by GitHub
parent d21e2c9b46
commit af01d15f62
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 29 additions and 94 deletions

View File

@ -14,8 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
const { waitEvent } = require('../utils');
/** /**
* @type {ChromiumTestSuite} * @type {ChromiumTestSuite}
*/ */
@ -49,7 +47,7 @@ module.exports.describe = function({FFOX, CHROMIUM, WEBKIT}) {
await page.coverage.stopJSCoverage(); await page.coverage.stopJSCoverage();
// generate a script in page and wait for the event. // generate a script in page and wait for the event.
const [event] = await Promise.all([ const [event] = await Promise.all([
waitEvent(client, 'Debugger.scriptParsed'), new Promise(f => client.on('Debugger.scriptParsed', f)),
page.evaluate('//# sourceURL=foo.js') page.evaluate('//# sourceURL=foo.js')
]); ]);
// expect events to be dispatched. // expect events to be dispatched.

View File

@ -112,7 +112,11 @@ module.exports.describe = function({FFOX, CHROMIUM, WEBKIT}) {
// validate framenavigated events // validate framenavigated events
const navigatedFrames = []; const navigatedFrames = [];
page.on('framenavigated', frame => navigatedFrames.push(frame)); page.on('framenavigated', frame => navigatedFrames.push(frame));
await utils.navigateFrame(page, 'frame1', './empty.html'); await page.evaluate(() => {
const frame = document.getElementById('frame1');
frame.src = './empty.html';
return new Promise(x => frame.onload = x);
});
expect(navigatedFrames.length).toBe(1); expect(navigatedFrames.length).toBe(1);
expect(navigatedFrames[0].url()).toBe(server.EMPTY_PAGE); expect(navigatedFrames[0].url()).toBe(server.EMPTY_PAGE);
@ -127,7 +131,7 @@ module.exports.describe = function({FFOX, CHROMIUM, WEBKIT}) {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await Promise.all([ await Promise.all([
page.goto(server.EMPTY_PAGE + '#foo'), page.goto(server.EMPTY_PAGE + '#foo'),
utils.waitEvent(page, 'framenavigated') page.waitForEvent('framenavigated')
]); ]);
expect(page.url()).toBe(server.EMPTY_PAGE + '#foo'); expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');
}); });
@ -223,7 +227,7 @@ module.exports.describe = function({FFOX, CHROMIUM, WEBKIT}) {
}); });
expect(frame1.isDetached()).toBe(true); expect(frame1.isDetached()).toBe(true);
const [frame2] = await Promise.all([ const [frame2] = await Promise.all([
utils.waitEvent(page, 'frameattached'), page.waitForEvent('frameattached'),
page.evaluate(() => document.body.appendChild(window.frame)), page.evaluate(() => document.body.appendChild(window.frame)),
]); ]);
expect(frame2.isDetached()).toBe(false); expect(frame2.isDetached()).toBe(false);

View File

@ -323,7 +323,7 @@ module.exports.describe = function({defaultBrowserOptions, playwright, FFOX, CHR
await page.route('**/*', async r => route = r); await page.route('**/*', async r => route = r);
page.$eval('iframe', (frame, url) => frame.src = url, server.EMPTY_PAGE), page.$eval('iframe', (frame, url) => frame.src = url, server.EMPTY_PAGE),
// Wait for request interception. // Wait for request interception.
await utils.waitEvent(page, 'request'); await page.waitForEvent('request');
// Delete frame to cause request to be canceled. // Delete frame to cause request to be canceled.
await page.$eval('iframe', frame => frame.remove()); await page.$eval('iframe', frame => frame.remove());
let error = null; let error = null;

View File

@ -91,7 +91,7 @@ module.exports.describe = function({defaultBrowserOptions, playwright, browserTy
it('should fire close event', async () => { it('should fire close event', async () => {
const browserServer = await browserType.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
await Promise.all([ await Promise.all([
utils.waitEvent(browserServer, 'close'), new Promise(f => browserServer.on('close', f)),
browserServer.close(), browserServer.close(),
]); ]);
}); });

View File

@ -61,7 +61,7 @@ module.exports.describe = function({defaultBrowserOptions, browserType, FFOX, CH
remoteBrowser2.on('disconnected', () => ++disconnectedRemote2); remoteBrowser2.on('disconnected', () => ++disconnectedRemote2);
await Promise.all([ await Promise.all([
utils.waitEvent(remoteBrowser2, 'disconnected'), new Promise(f => remoteBrowser2.on('disconnected', f)),
remoteBrowser2.close(), remoteBrowser2.close(),
]); ]);
@ -70,8 +70,8 @@ module.exports.describe = function({defaultBrowserOptions, browserType, FFOX, CH
expect(disconnectedRemote2).toBe(1); expect(disconnectedRemote2).toBe(1);
await Promise.all([ await Promise.all([
utils.waitEvent(remoteBrowser1, 'disconnected'), new Promise(f => remoteBrowser1.on('disconnected', f)),
utils.waitEvent(originalBrowser, 'disconnected'), new Promise(f => originalBrowser.on('disconnected', f)),
browserServer.close(), browserServer.close(),
]); ]);

View File

@ -16,8 +16,6 @@
*/ */
const path = require('path'); const path = require('path');
const utils = require('./utils');
const {waitEvent} = utils;
const vm = require('vm'); const vm = require('vm');
/** /**
@ -48,7 +46,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
// fire. // fire.
await newPage.click('body'); await newPage.click('body');
const pageClosingPromise = newPage.close({ runBeforeUnload: true }); const pageClosingPromise = newPage.close({ runBeforeUnload: true });
const dialog = await waitEvent(newPage, 'dialog'); const dialog = await newPage.waitForEvent('dialog');
expect(dialog.type()).toBe('beforeunload'); expect(dialog.type()).toBe('beforeunload');
expect(dialog.defaultValue()).toBe(''); expect(dialog.defaultValue()).toBe('');
if (CHROMIUM) if (CHROMIUM)
@ -93,7 +91,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
it('should fire when expected', async({page, server}) => { it('should fire when expected', async({page, server}) => {
await Promise.all([ await Promise.all([
page.goto('about:blank'), page.goto('about:blank'),
utils.waitEvent(page, 'load'), page.waitForEvent('load'),
]); ]);
}); });
}); });
@ -121,7 +119,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
page._delegate._session.send('Page.crash', {}).catch(e => {}); page._delegate._session.send('Page.crash', {}).catch(e => {});
else if (FFOX) else if (FFOX)
page._delegate._session.send('Page.crash', {}).catch(e => {}); page._delegate._session.send('Page.crash', {}).catch(e => {});
await waitEvent(page, 'error'); await new Promise(f => page.on('error', f));
expect(error.message).toBe('Page crashed!'); expect(error.message).toBe('Page crashed!');
}); });
}); });
@ -152,7 +150,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
page.once('console', m => message = m); page.once('console', m => message = m);
await Promise.all([ await Promise.all([
page.evaluate(() => console.log('hello', 5, {foo: 'bar'})), page.evaluate(() => console.log('hello', 5, {foo: 'bar'})),
waitEvent(page, 'console') page.waitForEvent('console')
]); ]);
expect(message.text()).toEqual('hello 5 JSHandle@object'); expect(message.text()).toEqual('hello 5 JSHandle@object');
expect(message.type()).toEqual('log'); expect(message.type()).toEqual('log');
@ -191,14 +189,14 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
page.once('console', msg => message = msg); page.once('console', msg => message = msg);
await Promise.all([ await Promise.all([
page.evaluate(() => console.error(window)), page.evaluate(() => console.error(window)),
waitEvent(page, 'console') page.waitForEvent('console')
]); ]);
expect(message.text()).toBe('JSHandle@object'); expect(message.text()).toBe('JSHandle@object');
}); });
it('should trigger correct Log', async({page, server}) => { it('should trigger correct Log', async({page, server}) => {
await page.goto('about:blank'); await page.goto('about:blank');
const [message] = await Promise.all([ const [message] = await Promise.all([
waitEvent(page, 'console'), page.waitForEvent('console'),
page.evaluate(async url => fetch(url).catch(e => {}), server.EMPTY_PAGE) page.evaluate(async url => fetch(url).catch(e => {}), server.EMPTY_PAGE)
]); ]);
expect(message.text()).toContain('Access-Control-Allow-Origin'); expect(message.text()).toContain('Access-Control-Allow-Origin');
@ -207,7 +205,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
it('should have location for console API calls', async({page, server}) => { it('should have location for console API calls', async({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [message] = await Promise.all([ const [message] = await Promise.all([
waitEvent(page, 'console'), page.waitForEvent('console'),
page.goto(server.PREFIX + '/consolelog.html'), page.goto(server.PREFIX + '/consolelog.html'),
]); ]);
expect(message.text()).toBe('yellow'); expect(message.text()).toBe('yellow');
@ -248,7 +246,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
describe('Page.Events.DOMContentLoaded', function() { describe('Page.Events.DOMContentLoaded', function() {
it('should fire when expected', async({page, server}) => { it('should fire when expected', async({page, server}) => {
const navigatedPromise = page.goto('about:blank'); const navigatedPromise = page.goto('about:blank');
await waitEvent(page, 'domcontentloaded'); await page.waitForEvent('domcontentloaded');
await navigatedPromise; await navigatedPromise;
}); });
}); });
@ -494,7 +492,7 @@ module.exports.describe = function({playwright, FFOX, CHROMIUM, WEBKIT}) {
page.once('pageerror', e => error = e); page.once('pageerror', e => error = e);
await Promise.all([ await Promise.all([
page.goto(server.PREFIX + '/error.html'), page.goto(server.PREFIX + '/error.html'),
waitEvent(page, 'pageerror') new Promise(f => page.on('pageerror', f))
]); ]);
expect(error.message).toContain('Fancy'); expect(error.message).toContain('Fancy');
}); });

View File

@ -64,22 +64,6 @@ function traceAPICoverage(apiCoverage, events, className, classType) {
} }
const utils = module.exports = { const utils = module.exports = {
promisify: function (nodeFunction) {
function promisified(...args) {
return new Promise((resolve, reject) => {
function callback(err, ...result) {
if (err)
return reject(err);
if (result.length === 1)
return resolve(result[0]);
return resolve(result);
}
nodeFunction.call(null, ...args, callback);
});
}
return promisified;
},
recordAPICoverage: function(api, events, ignoredMethodsArray = []) { recordAPICoverage: function(api, events, ignoredMethodsArray = []) {
const coverage = new Map(); const coverage = new Map();
const ignoredMethods = new Set(ignoredMethodsArray); const ignoredMethods = new Set(ignoredMethodsArray);
@ -117,27 +101,15 @@ const utils = module.exports = {
* @return {!Playwright.Frame} * @return {!Playwright.Frame}
*/ */
attachFrame: async function(page, frameId, url) { attachFrame: async function(page, frameId, url) {
const frames = new Set(page.frames()); const handle = await page.evaluateHandle(async ({ frameId, url }) => {
const handle = await page.evaluateHandle(attachFrame, { frameId, url });
try {
return await handle.asElement().contentFrame();
} catch(e) {
// we might not support contentFrame, but this can still work ok.
for (const frame of page.frames()) {
if (!frames.has(frame))
return frame;
}
}
return null;
async function attachFrame({ frameId, url }) {
const frame = document.createElement('iframe'); const frame = document.createElement('iframe');
frame.src = url; frame.src = url;
frame.id = frameId; frame.id = frameId;
document.body.appendChild(frame); document.body.appendChild(frame);
await new Promise(x => frame.onload = x); await new Promise(x => frame.onload = x);
return frame; return frame;
} }, { frameId, url });
return handle.asElement().contentFrame();
}, },
/** /**
@ -145,27 +117,9 @@ const utils = module.exports = {
* @param {string} frameId * @param {string} frameId
*/ */
detachFrame: async function(page, frameId) { detachFrame: async function(page, frameId) {
await page.evaluate(detachFrame, frameId); await page.evaluate(frameId => {
document.getElementById(frameId).remove();
function detachFrame(frameId) { }, frameId);
const frame = document.getElementById(frameId);
frame.remove();
}
},
/**
* @param {!Page} page
* @param {string} frameId
* @param {string} url
*/
navigateFrame: async function(page, frameId, url) {
await page.evaluate(navigateFrame, { frameId, url });
function navigateFrame({ frameId, url }) {
const frame = document.getElementById(frameId);
frame.src = url;
return new Promise(x => frame.onload = x);
}
}, },
/** /**
@ -190,22 +144,6 @@ const utils = module.exports = {
return result; return result;
}, },
/**
* @param {!EventEmitter} emitter
* @param {string} eventName
* @return {!Promise<!Object>}
*/
waitEvent: function(emitter, eventName, predicate = () => true) {
return new Promise(fulfill => {
emitter.on(eventName, function listener(event) {
if (!predicate(event))
return;
emitter.removeListener(eventName, listener);
fulfill(event);
});
});
},
initializeFlakinessDashboardIfNeeded: async function(testRunner) { initializeFlakinessDashboardIfNeeded: async function(testRunner) {
// Generate testIDs for all tests and verify they don't clash. // Generate testIDs for all tests and verify they don't clash.
// This will add |test.testId| for every test. // This will add |test.testId| for every test.

View File

@ -15,9 +15,6 @@
* limitations under the License. * limitations under the License.
*/ */
const utils = require('./utils');
const { waitEvent } = utils;
/** /**
* @type {PageTestSuite} * @type {PageTestSuite}
*/ */
@ -49,7 +46,7 @@ module.exports.describe = function({FFOX, CHROMIUM, WEBKIT, LINUX}) {
}); });
it('should report console logs', async function({page}) { it('should report console logs', async function({page}) {
const [message] = await Promise.all([ const [message] = await Promise.all([
waitEvent(page, 'console'), page.waitForEvent('console'),
page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))), page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))),
]); ]);
expect(message.text()).toBe('1'); expect(message.text()).toBe('1');