Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat: create FF default profile prefs dynamically (#250)
Pavel Feldmana9568af21d53
diff --git a/install.js b/install.jsindex 9da4545241..04cc06cbf1 100644--- a/install.js+++ b/install.js@@ -75,10 +75,6 @@ async function downloadBrowser(browser, playwright) {// Remove previous chromium revisions.const cleanupOldVersions = localRevisions.filter(revision => revision !== revisionInfo.revision).map(revision => browserFetcher.remove(revision));await Promise.all([...cleanupOldVersions]);- if (browser === 'firefox') {- const installFirefoxPreferences = require('./misc/install-preferences');- await installFirefoxPreferences(revisionInfo.executablePath);- }return revisionInfo;}diff --git a/misc/00-playwright-prefs.js b/misc/00-playwright-prefs.jsdeleted file mode 100644index 1895d2d1b7..0000000000--- a/misc/00-playwright-prefs.js+++ /dev/null@@ -1,3 +0,0 @@-// Any comment. You must start the file with a single-line comment!-pref("general.config.filename", "playwright.cfg");-pref("general.config.obscure_value", 0);diff --git a/misc/install-preferences.js b/misc/install-preferences.jsdeleted file mode 100644index 7a4f4bc520..0000000000--- a/misc/install-preferences.js+++ /dev/null@@ -1,59 +0,0 @@-const os = require('os');-const fs = require('fs');-const path = require('path');-const util = require('util');--// Install browser preferences after downloading and unpacking-// firefox instances.-// Based on: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Enterprise_deployment_before_60#Configuration-async function installFirefoxPreferences(executablePath) {- const firefoxFolder = path.dirname(executablePath);- const mkdirAsync = util.promisify(fs.mkdir.bind(fs));-- let prefPath = '';- let configPath = '';- if (os.platform() === 'darwin') {- prefPath = path.join(firefoxFolder, '..', 'Resources', 'defaults', 'pref');- configPath = path.join(firefoxFolder, '..', 'Resources');- } else if (os.platform() === 'linux') {- if (!fs.existsSync(path.join(firefoxFolder, 'browser', 'defaults')))- await mkdirAsync(path.join(firefoxFolder, 'browser', 'defaults'));- if (!fs.existsSync(path.join(firefoxFolder, 'browser', 'defaults', 'preferences')))- await mkdirAsync(path.join(firefoxFolder, 'browser', 'defaults', 'preferences'));- prefPath = path.join(firefoxFolder, 'browser', 'defaults', 'preferences');- configPath = firefoxFolder;- } else if (os.platform() === 'win32') {- prefPath = path.join(firefoxFolder, 'defaults', 'pref');- configPath = firefoxFolder;- } else {- throw new Error('Unsupported platform: ' + os.platform());- }-- await Promise.all([- copyFile({- from: path.join(__dirname, '00-playwright-prefs.js'),- to: path.join(prefPath, '00-playwright-prefs.js'),- }),- copyFile({- from: path.join(__dirname, 'playwright.cfg'),- to: path.join(configPath, 'playwright.cfg'),- }),- ]);-}--function copyFile({from, to}) {- var rd = fs.createReadStream(from);- var wr = fs.createWriteStream(to);- return new Promise(function(resolve, reject) {- rd.on('error', reject);- wr.on('error', reject);- wr.on('finish', resolve);- rd.pipe(wr);- }).catch(function(error) {- rd.destroy();- wr.end();- throw error;- });-}--module.exports = installFirefoxPreferences;diff --git a/misc/playwright.cfg b/misc/playwright.cfgdeleted file mode 100644index d77b8b7c2a..0000000000--- a/misc/playwright.cfg+++ /dev/null@@ -1,215 +0,0 @@-// Any comment. You must start the file with a comment!--// Make sure Shield doesn't hit the network.-// pref("app.normandy.api_url", "");-pref("app.normandy.enabled", false);--// Disable updater-pref("app.update.enabled", false);-// make absolutely sure it is really off-pref("app.update.auto", false);-pref("app.update.mode", 0);-pref("app.update.service.enabled", false);--// Dislabe newtabpage-pref("browser.startup.homepage", 'about:blank');-pref("browser.newtabpage.enabled", false);-// Disable topstories-pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);--// Isolate contexts-pref("permissions.isolateBy.privateBrowsing", true);--// DevTools JSONViewer sometimes fails to load dependencies with its require.js.-// This doesn't affect Playwright operations, but spams console with a lot of-// unpleasant errors.-// (bug 1424372)-pref("devtools.jsonview.enabled", false);--// Increase the APZ content response timeout in tests to 1 minute.-// This is to accommodate the fact that test environments tends to be-// slower than production environments (with the b2g emulator being-// the slowest of them all), resulting in the production timeout value-// sometimes being exceeded and causing false-positive test failures.-//-// (bug 1176798, bug 1177018, bug 1210465)-pref("apz.content_response_timeout", 60000);--// Allow creating files in content process - required for-// |Page.setFileInputFiles| protocol method.-pref("dom.file.createInChild", true);--// Indicate that the download panel has been shown once so that-// whichever download test runs first doesn't show the popup-// inconsistently.-pref("browser.download.panel.shown", true);--// Background thumbnails in particular cause grief, and disabling-// thumbnails in general cannot hurt-pref("browser.pagethumbnails.capturing_disabled", true);--// Disable safebrowsing components.-pref("browser.safebrowsing.blockedURIs.enabled", false);-pref("browser.safebrowsing.downloads.enabled", false);-pref("browser.safebrowsing.passwords.enabled", false);-pref("browser.safebrowsing.malware.enabled", false);-pref("browser.safebrowsing.phishing.enabled", false);--// Disable updates to search engines.-pref("browser.search.update", false);--// Do not restore the last open set of tabs if the browser has crashed-pref("browser.sessionstore.resume_from_crash", false);--// Don't check for the default web browser during startup.-pref("browser.shell.checkDefaultBrowser", false);--// Do not redirect user when a milstone upgrade of Firefox is detected-pref("browser.startup.homepage_override.mstone", "ignore");--// Disable browser animations (tabs, fullscreen, sliding alerts)-pref("toolkit.cosmeticAnimations.enabled", false);--// Close the window when the last tab gets closed-pref("browser.tabs.closeWindowWithLastTab", true);--// Do not allow background tabs to be zombified on Android, otherwise for-// tests that open additional tabs, the test harness tab itself might get-// unloaded-pref("browser.tabs.disableBackgroundZombification", false);--// Do not warn when closing all open tabs-pref("browser.tabs.warnOnClose", false);--// Do not warn when closing all other open tabs-pref("browser.tabs.warnOnCloseOtherTabs", false);--// Do not warn when multiple tabs will be opened-pref("browser.tabs.warnOnOpen", false);--// Disable first run splash page on Windows 10-pref("browser.usedOnWindows10.introURL", "");--// Disable the UI tour.-//-// Should be set in profile.-pref("browser.uitour.enabled", false);--// Turn off search suggestions in the location bar so as not to trigger-// network connections.-pref("browser.urlbar.suggest.searches", false);--// Do not warn on quitting Firefox-pref("browser.warnOnQuit", false);--// Do not show datareporting policy notifications which can-// interfere with tests-pref(- "datareporting.healthreport.documentServerURI",- "http://%(server)s/dummy/healthreport/",-);-pref("datareporting.healthreport.logging.consoleEnabled", false);-pref("datareporting.healthreport.service.enabled", false);-pref("datareporting.healthreport.service.firstRun", false);-pref("datareporting.healthreport.uploadEnabled", false);-pref("datareporting.policy.dataSubmissionEnabled", false);-pref("datareporting.policy.dataSubmissionPolicyAccepted", false);-pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);--// Automatically unload beforeunload alerts-pref("dom.disable_beforeunload", false);--// Disable popup-blocker-pref("dom.disable_open_during_load", false);--// Disable the ProcessHangMonitor-pref("dom.ipc.reportProcessHangs", false);--// Disable slow script dialogues-pref("dom.max_chrome_script_run_time", 0);-pref("dom.max_script_run_time", 0);--// Only load extensions from the application and user profile-// AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION-pref("extensions.autoDisableScopes", 0);-pref("extensions.enabledScopes", 5);--// Disable metadata caching for installed add-ons by default-pref("extensions.getAddons.cache.enabled", false);--// Disable installing any distribution extensions or add-ons.-pref("extensions.installDistroAddons", false);--// Turn off extension updates so they do not bother tests-pref("extensions.update.enabled", false);-pref("extensions.update.notifyUser", false);--// Make sure opening about:addons will not hit the network-pref(- "extensions.webservice.discoverURL",- "http://%(server)s/dummy/discoveryURL",-);--pref("extensions.screenshots.disabled", true);-pref("extensions.screenshots.upload-disabled", true);--// Allow the application to have focus even it runs in the background-pref("focusmanager.testmode", true);--// Disable useragent updates-pref("general.useragent.updates.enabled", false);--// Always use network provider for geolocation tests so we bypass the-// macOS dialog raised by the corelocation provider-pref("geo.provider.testing", true);--// Do not scan Wifi-pref("geo.wifi.scan", false);--// Show chrome errors and warnings in the error console-pref("javascript.options.showInConsole", true);--// Do not prompt with long usernames or passwords in URLs-pref("network.http.phishy-userpass-length", 255);--// Do not prompt for temporary redirects-pref("network.http.prompt-temp-redirect", false);--// Disable speculative connections so they are not reported as leaking-// when they are hanging around-pref("network.http.speculative-parallel-limit", 0);--// Do not automatically switch between offline and online-pref("network.manage-offline-status", false);--// Make sure SNTP requests do not hit the network-pref("network.sntp.pools", "%(server)s");--// Local documents have access to all other local documents,-// including directory listings-pref("security.fileuri.strict_origin_policy", false);--// Tests do not wait for the notification button security delay-pref("security.notification_enable_delay", 0);--// Ensure blocklist updates do not hit the network-pref("services.settings.server", "http://%(server)s/dummy/blocklist/");--// Do not automatically fill sign-in forms with known usernames and-// passwords-pref("signon.autofillForms", false);--// Disable password capture, so that tests that include forms are not-// influenced by the presence of the persistent doorhanger notification-pref("signon.rememberSignons", false);--// Disable first-run welcome page-pref("startup.homepage_welcome_url", "about:blank");-pref("startup.homepage_welcome_url.additional", "");--// Prevent starting into safe mode after application crashes-pref("toolkit.startup.max_resumed_crashes", -1);-lockPref("toolkit.crashreporter.enabled", false);--// Disable crash reporter.-Components.classes["@mozilla.org/toolkit/crash-reporter;1"].getService(Components.interfaces.nsICrashReporter).submitReports = false;diff --git a/src/firefox/Launcher.ts b/src/firefox/Launcher.tsindex 71bd7b49ce..2008a60ded 100644--- a/src/firefox/Launcher.ts+++ b/src/firefox/Launcher.ts@@ -28,6 +28,7 @@ import { WebSocketTransport } from '../transport';import { launchProcess, waitForLine } from '../processLauncher';const mkdtempAsync = util.promisify(fs.mkdtemp);+const writeFileAsync = util.promisify(fs.writeFile);const FIREFOX_PROFILE_PATH = path.join(os.tmpdir(), 'playwright_firefox_profile-');@@ -90,7 +91,7 @@ export class Launcher {let temporaryProfileDir = null;if (!firefoxArguments.includes('-profile') && !firefoxArguments.includes('--profile')) {- temporaryProfileDir = await mkdtempAsync(FIREFOX_PROFILE_PATH);+ temporaryProfileDir = await createProfile();firefoxArguments.push(`-profile`, temporaryProfileDir);}@@ -212,3 +213,214 @@ export function createBrowserFetcher(projectRoot: string, options: BrowserFetche};});}++const DUMMY_UMA_SERVER = 'dummy.test';+const DEFAULT_PREFERENCES = {+ // Make sure Shield doesn't hit the network.+ 'app.normandy.api_url': '',+ // Disable Firefox old build background check+ 'app.update.checkInstallTime': false,+ // Disable automatically upgrading Firefox+ 'app.update.disabledForTesting': true,++ // Increase the APZ content response timeout to 1 minute+ 'apz.content_response_timeout': 60000,++ // Prevent various error message on the console+ // jest-puppeteer asserts that no error message is emitted by the console+ 'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cm,-fp',+++ // Enable the dump function: which sends messages to the system+ // console+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1543115+ 'browser.dom.window.dump.enabled': true,+ // Disable topstories+ 'browser.newtabpage.activity-stream.feeds.section.topstories': false,+ // Always display a blank page+ 'browser.newtabpage.enabled': false,+ // Background thumbnails in particular cause grief: and disabling+ // thumbnails in general cannot hurt+ 'browser.pagethumbnails.capturing_disabled': true,++ // Disable safebrowsing components.+ 'browser.safebrowsing.blockedURIs.enabled': false,+ 'browser.safebrowsing.downloads.enabled': false,+ 'browser.safebrowsing.malware.enabled': false,+ 'browser.safebrowsing.passwords.enabled': false,+ 'browser.safebrowsing.phishing.enabled': false,++ // Disable updates to search engines.+ 'browser.search.update': false,+ // Do not restore the last open set of tabs if the browser has crashed+ 'browser.sessionstore.resume_from_crash': false,+ // Skip check for default browser on startup+ 'browser.shell.checkDefaultBrowser': false,++ // Disable newtabpage+ 'browser.startup.homepage': 'about:blank',+ // Do not redirect user when a milstone upgrade of Firefox is detected+ 'browser.startup.homepage_override.mstone': 'ignore',+ // Start with a blank page about:blank+ 'browser.startup.page': 0,++ // Do not allow background tabs to be zombified on Android: otherwise for+ // tests that open additional tabs: the test harness tab itself might get+ // unloaded+ 'browser.tabs.disableBackgroundZombification': false,+ // Do not warn when closing all other open tabs+ 'browser.tabs.warnOnCloseOtherTabs': false,+ // Do not warn when multiple tabs will be opened+ 'browser.tabs.warnOnOpen': false,++ // Disable the UI tour.+ 'browser.uitour.enabled': false,+ // Turn off search suggestions in the location bar so as not to trigger+ // network connections.+ 'browser.urlbar.suggest.searches': false,+ // Disable first run splash page on Windows 10+ 'browser.usedOnWindows10.introURL': '',+ // Do not warn on quitting Firefox+ 'browser.warnOnQuit': false,++ // Do not show datareporting policy notifications which can+ // interfere with tests+ 'datareporting.healthreport.about.reportUrl': `http://${DUMMY_UMA_SERVER}/dummy/abouthealthreport/`,+ 'datareporting.healthreport.documentServerURI': `http://${DUMMY_UMA_SERVER}/dummy/healthreport/`,+ 'datareporting.healthreport.logging.consoleEnabled': false,+ 'datareporting.healthreport.service.enabled': false,+ 'datareporting.healthreport.service.firstRun': false,+ 'datareporting.healthreport.uploadEnabled': false,+ 'datareporting.policy.dataSubmissionEnabled': false,+ 'datareporting.policy.dataSubmissionPolicyAccepted': false,+ 'datareporting.policy.dataSubmissionPolicyBypassNotification': true,++ // DevTools JSONViewer sometimes fails to load dependencies with its require.js.+ // This doesn't affect Puppeteer but spams console (Bug 1424372)+ 'devtools.jsonview.enabled': false,++ // Disable popup-blocker+ 'dom.disable_open_during_load': false,++ // Enable the support for File object creation in the content process+ // Required for |Page.setFileInputFiles| protocol method.+ 'dom.file.createInChild': true,++ // Disable the ProcessHangMonitor+ 'dom.ipc.reportProcessHangs': false,++ // Disable slow script dialogues+ 'dom.max_chrome_script_run_time': 0,+ 'dom.max_script_run_time': 0,++ // Only load extensions from the application and user profile+ // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION+ 'extensions.autoDisableScopes': 0,+ 'extensions.enabledScopes': 5,++ // Disable metadata caching for installed add-ons by default+ 'extensions.getAddons.cache.enabled': false,++ // Disable installing any distribution extensions or add-ons.+ 'extensions.installDistroAddons': false,++ // Disabled screenshots extension+ 'extensions.screenshots.disabled': true,++ // Turn off extension updates so they do not bother tests+ 'extensions.update.enabled': false,++ // Turn off extension updates so they do not bother tests+ 'extensions.update.notifyUser': false,++ // Make sure opening about:addons will not hit the network+ 'extensions.webservice.discoverURL': `http://${DUMMY_UMA_SERVER}/dummy/discoveryURL`,++ // Allow the application to have focus even it runs in the background+ 'focusmanager.testmode': true,+ // Disable useragent updates+ 'general.useragent.updates.enabled': false,+ // Always use network provider for geolocation tests so we bypass the+ // macOS dialog raised by the corelocation provider+ 'geo.provider.testing': true,+ // Do not scan Wifi+ 'geo.wifi.scan': false,+ // No hang monitor+ 'hangmonitor.timeout': 0,+ // Show chrome errors and warnings in the error console+ 'javascript.options.showInConsole': true,++ // Disable download and usage of OpenH264: and Widevine plugins+ 'media.gmp-manager.updateEnabled': false,+ // Prevent various error message on the console+ // jest-puppeteer asserts that no error message is emitted by the console+ 'network.cookie.cookieBehavior': 0,++ // Do not prompt for temporary redirects+ 'network.http.prompt-temp-redirect': false,++ // Disable speculative connections so they are not reported as leaking+ // when they are hanging around+ 'network.http.speculative-parallel-limit': 0,++ // Do not automatically switch between offline and online+ 'network.manage-offline-status': false,++ // Make sure SNTP requests do not hit the network+ 'network.sntp.pools': DUMMY_UMA_SERVER,++ // Disable Flash.+ 'plugin.state.flash': 0,++ 'privacy.trackingprotection.enabled': false,++ // Enable Remote Agent+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1544393+ 'remote.enabled': true,++ // Don't do network connections for mitm priming+ 'security.certerrors.mitm.priming.enabled': false,+ // Local documents have access to all other local documents,+ // including directory listings+ 'security.fileuri.strict_origin_policy': false,+ // Do not wait for the notification button security delay+ 'security.notification_enable_delay': 0,++ // Ensure blocklist updates do not hit the network+ 'services.settings.server': `http://${DUMMY_UMA_SERVER}/dummy/blocklist/`,++ // Do not automatically fill sign-in forms with known usernames and+ // passwords+ 'signon.autofillForms': false,+ // Disable password capture, so that tests that include forms are not+ // influenced by the presence of the persistent doorhanger notification+ 'signon.rememberSignons': false,++ // Disable first-run welcome page+ 'startup.homepage_welcome_url': 'about:blank',++ // Disable first-run welcome page+ 'startup.homepage_welcome_url.additional': '',++ // Disable browser animations (tabs, fullscreen, sliding alerts)+ 'toolkit.cosmeticAnimations.enabled': false,++ // We want to collect telemetry, but we don't want to send in the results+ 'toolkit.telemetry.server': `https://${DUMMY_UMA_SERVER}/dummy/telemetry/`,+ // Prevent starting into safe mode after application crashes+ 'toolkit.startup.max_resumed_crashes': -1,+};++async function createProfile(extraPrefs?: object): Promise<string> {+ const profilePath = await mkdtempAsync(path.join(os.tmpdir(), 'playwright_dev_firefox_profile-'));+ const prefsJS = [];+ const userJS = [];++ const prefs = { ...DEFAULT_PREFERENCES, ...extraPrefs };+ for (const [key, value] of Object.entries(prefs))+ userJS.push(`user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`);++ await writeFileAsync(path.join(profilePath, 'user.js'), userJS.join('\n'));+ await writeFileAsync(path.join(profilePath, 'prefs.js'), prefsJS.join('\n'));+ return profilePath;+}diff --git a/test/playwright.spec.js b/test/playwright.spec.jsindex 610fe3884d..c82f07e311 100644--- a/test/playwright.spec.js+++ b/test/playwright.spec.js@@ -88,11 +88,6 @@ module.exports.addTests = ({testRunner, product, playwrightPath}) => {ASSETS_DIR,};- beforeAll(async() => {- if (FFOX && defaultBrowserOptions.executablePath)- await require('../misc/install-preferences')(defaultBrowserOptions.executablePath);- });-describe('Browser', function() {beforeAll(async state => {state.browser = await playwright.launch(defaultBrowserOptions);