diff --git a/.env.example b/.env.example index bdd47dedb82d5..e6fe48e89000d 100644 --- a/.env.example +++ b/.env.example @@ -8,8 +8,10 @@ # - '{version}': any major.minor PHP version from 5.2 onwards. ## -# The site will be available at http://localhost:LOCAL_PORT +# The development site will be available at http://localhost:LOCAL_PORT. E2E uses +# LOCAL_PORT + 1 unless LOCAL_E2E_PORT is provided at runtime or in this file. LOCAL_PORT=8889 +LOCAL_E2E_PORT= # Where to run WordPress from. Valid options are 'src' and 'build'. LOCAL_DIR=src diff --git a/.gitignore b/.gitignore index 24b4282326304..70e6b864a807b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ # Configuration files with possibly sensitive information .env wp-config.php +/wp-config-e2e* wp-tests-config.php .htaccess @@ -47,6 +48,8 @@ wp-tests-config.php /packagehash.txt /.gutenberg-hash /artifacts +/tests/e2e/.database-state.json +/tests/e2e/.database-lock* /setup.log /coverage @@ -76,6 +79,7 @@ wp-tests-config.php !/src/wp-content/themes/ipsum /src/wp-content/upgrade /src/wp-content/uploads +/src/wp-content/uploads-e2e /src/wp-content/advanced-cache.php /src/wp-content/blog-deleted.php /src/wp-content/blog-inactive.php diff --git a/docker-compose.yml b/docker-compose.yml index 62bce43174293..db26751f3d35c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,6 +11,7 @@ services: ports: - ${LOCAL_PORT-8889}:80 + - ${LOCAL_E2E_PORT:-8890}:80 environment: LOCAL_DIR: ${LOCAL_DIR-src} @@ -161,6 +162,14 @@ services: php: condition: service_started + memcached-e2e: + image: memcached + + networks: + - wpdevnet + + command: memcached -m 64 + volumes: # So that sites aren't wiped every time containers are restarted, MySQL uses a persistent volume. mysql: {} diff --git a/package.json b/package.json index 30e853bd255bd..20b284121a53a 100644 --- a/package.json +++ b/package.json @@ -150,7 +150,8 @@ "test:performance": "wp-scripts test-playwright --config tests/performance/playwright.config.js", "test:php": "node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit", "test:coverage": "npm run test:php -- --coverage-html ./coverage/html/ --coverage-php ./coverage/php/report.php --coverage-text=./coverage/text/report.txt", - "test:e2e": "wp-scripts test-playwright --config tests/e2e/playwright.config.js", + "test:e2e": "npm run test:e2e:config && wp-scripts test-playwright --config tests/e2e/playwright.config.js", + "test:e2e:config": "node --test tests/e2e/config/database.test.cjs", "test:visual": "wp-scripts test-playwright --config tests/visual-regression/playwright.config.js", "typecheck:php": "node ./tools/local-env/scripts/docker.js run --rm php composer phpstan --", "typecheck:php:baselines": "node ./tools/local-env/scripts/docker.js run --rm php composer phpstan:baselines --", diff --git a/tests/e2e/README.md b/tests/e2e/README.md index b0bf60e2ebafa..6e7b6bced3221 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -5,7 +5,7 @@ End-To-End (E2E) tests for WordPress. ## Running the tests -The e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`. +The e2e tests require a production-like environment to run. By default, the development site remains at `http://localhost:8889`, and the E2E site uses the next port, `http://localhost:8890`. The E2E port defaults to `LOCAL_PORT + 1`; set `LOCAL_E2E_PORT` to choose another port. Both sites use the configured `LOCAL_DIR` tree. If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md). @@ -17,12 +17,16 @@ npm run test:e2e which will run the test suite using a headless browser. -If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this: +The E2E site has its own `wp-config-e2e.php`, `wordpress_develop_e2e` database, `uploads-e2e` directory, and Memcached service when persistent caching is enabled. The development URL keeps using its original database and configuration throughout the run. E2E setup restores its temporary host-and-port routing after the tests. + +If using a custom URL, it must point to an isolated WordPress test site with a disposable database and uploads directory. Set `WP_E2E_ISOLATED=true` to confirm that setup, along with the base URL, username and password. Playwright will use that site without starting the local Docker environment: ``` -WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e +WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password WP_E2E_ISOLATED=true npm run test:e2e ``` -**DO NOT run these tests in an actual production environment, as they will delete all your content.** +The E2E setup clears test posts, blocks, and preferences. Do not point it at a production or development site. + +The local E2E setup holds a lock while it prepares the separate site configuration. A second E2E run in the same checkout exits before changing configuration. Interrupted runs restore the routing and regenerate the E2E config, including its original table prefix. PHPUnit continues to use `wordpress_develop_tests`. For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode: diff --git a/tests/e2e/config/database.js b/tests/e2e/config/database.js new file mode 100644 index 0000000000000..69e6cc93b636f --- /dev/null +++ b/tests/e2e/config/database.js @@ -0,0 +1,887 @@ +/** + * External dependencies + */ +const { randomUUID } = require( 'node:crypto' ); +const { spawnSync } = require( 'node:child_process' ); +const { + copyFile, + link, + mkdir, + readFile, + rm, + rename, + stat, + writeFile, +} = require( 'node:fs/promises' ); +const path = require( 'node:path' ); +const dotenv = require( 'dotenv' ); +const dotenvExpand = require( 'dotenv-expand' ); + +dotenvExpand.expand( + dotenv.config( { path: path.join( process.cwd(), '.env' ) } ) +); + +const E2E_DB_NAME = 'wordpress_develop_e2e'; +const E2E_UPLOADS = 'wp-content/uploads-e2e'; +const E2E_CONFIG_FILE = 'wp-config-e2e.php'; +const ROOT_CONFIG_FILE = 'wp-config.php'; +const E2E_MEMCACHED_HOST = 'memcached-e2e'; +const E2E_DIRECTORY = path.join( process.cwd(), 'tests/e2e' ); +const statePath = path.join( E2E_DIRECTORY, '.database-state.json' ); +const lockPath = path.join( E2E_DIRECTORY, '.database-lock' ); +const recoveryLockPath = `${ lockPath }.recovery`; +const rootConfigPath = path.join( process.cwd(), ROOT_CONFIG_FILE ); +const e2eConfigPath = path.join( process.cwd(), E2E_CONFIG_FILE ); +const E2E_CONFIG_ROUTER_START = '/* BEGIN WP Core E2E config routing. */'; +const E2E_CONFIG_ROUTER_END = '/* END WP Core E2E config routing. */'; + +let lockId; + +/** + * Get the local environment's WordPress document root. + * + * @param {string} [localDir] Document root configured in the local environment. + * @return {string} The document root directory. + */ +function getLocalDir( localDir = process.env.LOCAL_DIR || 'src' ) { + if ( ! /^[A-Za-z0-9_-]+$/.test( localDir ) ) { + throw new Error( 'LOCAL_DIR is not a safe WordPress document root.' ); + } + + return localDir; +} + +/** + * Get the test URL for the configured local environment or custom target. + * + * @return {string} Test environment URL. + */ +function getBaseURL() { + const localPort = process.env.LOCAL_PORT || '8889'; + const e2ePort = getE2EPort(); + const baseURL = new URL( + process.env.WP_BASE_URL || `http://localhost:${ e2ePort }` + ); + const port = + baseURL.port || ( baseURL.protocol === 'https:' ? '443' : '80' ); + + if ( + [ 'localhost', '127.0.0.1' ].includes( baseURL.hostname ) && + port === localPort + ) { + baseURL.port = e2ePort; + } + + return baseURL.href; +} + +/** + * Set the base URL used by both Playwright and the E2E test utilities. + * + * @return {string} Test environment URL. + */ +function setTestBaseURL() { + const baseURL = getBaseURL(); + process.env.WP_BASE_URL = baseURL; + return baseURL; +} + +/** + * Get the local E2E site's port, one above the development site's port by default. + * + * @return {string} E2E site port. + */ +function getE2EPort() { + const localPort = Number( process.env.LOCAL_PORT || '8889' ); + const e2ePort = Number( process.env.LOCAL_E2E_PORT || localPort + 1 ); + if ( + ! Number.isInteger( localPort ) || + localPort < 1 || + localPort > 65535 || + ! Number.isInteger( e2ePort ) || + e2ePort < 1 || + e2ePort > 65535 || + localPort === e2ePort + ) { + throw new Error( + 'LOCAL_PORT and LOCAL_E2E_PORT must be distinct valid TCP ports.' + ); + } + return String( e2ePort ); +} + +/** + * Run a WP-CLI command in the local development environment. + * + * @param {string[]} args WP-CLI arguments. + * @param {string} localDir WordPress document root. + * @param {string} configFile Path to the configuration file in `/var/www`. + * @return {{ status: number, stdout: string, stderr: string }} WP-CLI command result. + */ +function runWpCli( + args, + localDir = getLocalDir(), + configFile = ROOT_CONFIG_FILE +) { + if ( ! /^[A-Za-z0-9_.-]+$/.test( configFile ) ) { + throw new Error( 'The WordPress configuration path is not safe.' ); + } + + const result = spawnSync( + process.execPath, + [ + path.join( process.cwd(), 'tools/local-env/scripts/docker.js' ), + 'exec', + '--env', + `WP_CONFIG_PATH=/var/www/${ configFile }`, + '--user', + 'wp_php', + 'cli', + 'wp', + ...args, + `--path=/var/www/${ getLocalDir( localDir ) }`, + ], + { + cwd: process.cwd(), + encoding: 'utf8', + } + ); + + if ( result.error ) { + throw result.error; + } + + return { + status: result.status ?? 1, + stdout: result.stdout || '', + stderr: result.stderr || '', + }; +} + +/** + * Run WP-CLI and throw if it fails. + * + * @param {string[]} args WP-CLI arguments. + * @param {string} localDir WordPress document root. + * @param {string} configFile Path to the configuration file in `/var/www`. + * @return {string} Command output. + */ +function wpCli( + args, + localDir = getLocalDir(), + configFile = ROOT_CONFIG_FILE +) { + const result = runWpCli( args, localDir, configFile ); + + if ( result.status !== 0 ) { + throw new Error( + result.stderr.trim() || + `WP-CLI command failed: ${ args.join( ' ' ) }` + ); + } + + return result.stdout.trim(); +} + +/** + * Get a wp-config.php constant, returning null when it is not defined. + * + * @param {string} name Constant name. + * @param {string} localDir WordPress document root. + * @return {?string} Constant value, or null if undefined. + */ +function getConfigConstant( name, localDir ) { + const result = runWpCli( + [ 'config', 'get', name, '--type=constant' ], + localDir + ); + + if ( result.status === 0 ) { + return result.stdout.trim(); + } + + if ( /not defined/i.test( result.stderr ) ) { + return null; + } + + throw new Error( + result.stderr.trim() || `Unable to read the ${ name } setting.` + ); +} + +/** + * Get a wp-config.php variable, returning null when it is not defined. + * + * @param {string} name Variable name. + * @param {string} localDir WordPress document root. + * @return {?string} The configured variable value. + */ +function getConfigVariable( name, localDir ) { + const result = runWpCli( + [ 'config', 'get', name, '--type=variable' ], + localDir + ); + + if ( result.status === 0 ) { + return result.stdout.trim(); + } + + if ( /not defined/i.test( result.stderr ) ) { + return null; + } + + throw new Error( + result.stderr.trim() || `Unable to read the ${ name } setting.` + ); +} + +/** + * Atomically replace a local configuration file. + * + * @param {string} filePath File to replace. + * @param {string} contents New file contents. + * @return {Promise} + */ +async function replaceFileAtomically( filePath, contents ) { + const temporaryPath = `${ filePath }.${ randomUUID() }.tmp`; + try { + const originalFile = await stat( filePath ); + await writeFile( temporaryPath, contents, { + encoding: 'utf8', + mode: originalFile.mode & 0o777, + } ); + await rename( temporaryPath, filePath ); + } finally { + await rm( temporaryPath, { force: true } ); + } +} + +/** + * Add the host-and-port router that keeps development and E2E requests on separate configs. + * + * @return {Promise} + */ +async function addE2EConfigRouter() { + const config = await readFile( rootConfigPath, 'utf8' ); + if ( + config.includes( E2E_CONFIG_ROUTER_START ) || + config.includes( E2E_CONFIG_ROUTER_END ) + ) { + throw new Error( 'The E2E configuration router is already present.' ); + } + if ( ! config.startsWith( '} + */ +async function removeE2EConfigRouter() { + const config = await readFile( rootConfigPath, 'utf8' ); + const start = config.indexOf( E2E_CONFIG_ROUTER_START ); + const end = config.indexOf( E2E_CONFIG_ROUTER_END ); + if ( start === -1 && end === -1 ) { + return; + } + if ( start === -1 || end < start ) { + throw new Error( 'The E2E configuration router is incomplete.' ); + } + + let endAfterBlock = end + E2E_CONFIG_ROUTER_END.length; + if ( config.slice( endAfterBlock, endAfterBlock + 2 ) === '\r\n' ) { + endAfterBlock += 2; + } else if ( config[ endAfterBlock ] === '\n' ) { + endAfterBlock++; + } + + await replaceFileAtomically( + rootConfigPath, + `${ config.slice( 0, start ) }${ config.slice( endAfterBlock ) }` + ); +} + +/** + * Create a standalone configuration for the E2E site. + * + * @param {string} localDir WordPress document root. + * @return {Promise} + */ +async function createE2EConfig( localDir ) { + const temporaryConfigFile = `wp-config-e2e.${ lockId }.tmp.php`; + const temporaryConfigPath = path.join( process.cwd(), temporaryConfigFile ); + await copyFile( rootConfigPath, temporaryConfigPath ); + + try { + wpCli( + [ 'config', 'set', 'DB_NAME', E2E_DB_NAME, '--type=constant' ], + localDir, + temporaryConfigFile + ); + wpCli( + [ 'config', 'set', 'UPLOADS', E2E_UPLOADS, '--type=constant' ], + localDir, + temporaryConfigFile + ); + wpCli( + [ + 'config', + 'set', + 'WP_CACHE_KEY_SALT', + `e2e-${ randomUUID() }-`, + '--type=constant', + ], + localDir, + temporaryConfigFile + ); + wpCli( + [ + 'config', + 'set', + 'memcached_servers', + `array( array( '${ E2E_MEMCACHED_HOST }', 11211 ) )`, + '--raw', + '--type=variable', + ], + localDir, + temporaryConfigFile + ); + await rename( temporaryConfigPath, e2eConfigPath ); + } catch ( error ) { + await rm( temporaryConfigPath, { force: true } ); + throw error; + } +} + +/** + * Check whether the URL points to the E2E port in Core's local environment. + * + * @param {string} baseURL Test environment URL. + * @return {boolean} Whether the URL points to the configured local environment. + */ +function isDefaultEnvironment( baseURL ) { + const url = new URL( baseURL ); + const port = + url.port || ( url.protocol === 'https:' ? '443' : '80' ); + const e2ePort = getE2EPort(); + + return ( + [ 'localhost', '127.0.0.1' ].includes( url.hostname ) && + url.protocol === 'http:' && + port === e2ePort + ); +} + +/** + * Check whether a process is still running. + * + * @param {number} pid Process ID. + * @return {boolean} Whether the process is running or its state cannot be verified. + */ +function isProcessRunning( pid ) { + try { + process.kill( pid, 0 ); + return true; + } catch ( error ) { + return error.code !== 'ESRCH'; + } +} + +/** + * Read the current run lock. + * + * @param {string} [lockFilePath] Lock file path. + * @return {Promise} Current lock owner. + */ +async function readLock( lockFilePath = lockPath ) { + try { + const owner = JSON.parse( await readFile( lockFilePath, 'utf8' ) ); + if ( ! Number.isInteger( owner.pid ) || typeof owner.id !== 'string' ) { + throw new Error( 'Invalid E2E database lock.' ); + } + + return owner; + } catch ( error ) { + if ( error.code === 'ENOENT' ) { + return null; + } + + throw new Error( `Cannot safely read ${ lockFilePath }. ${ error.message }` ); + } +} + +/** + * Create a lock file with complete owner data using an atomic hard link. + * + * @param {{ pid: number, id: string }} owner Lock owner. + * @param {string} [lockFilePath] Lock file path. + * @return {Promise} + */ +async function createLock( owner, lockFilePath = lockPath ) { + const temporaryPath = `${ lockFilePath }.${ owner.id }.tmp`; + await writeFile( temporaryPath, JSON.stringify( owner ), { flag: 'wx' } ); + try { + await link( temporaryPath, lockFilePath ); + } finally { + await rm( temporaryPath, { force: true } ); + } +} + +/** + * Remove a recovery lock left behind by a process that has exited. + * + * @return {Promise} Whether the recovery lock is absent or was removed. + */ +async function removeStaleRecoveryLock() { + let recoveryOwner; + try { + recoveryOwner = await readLock( recoveryLockPath ); + } catch ( error ) { + // Older versions wrote an empty recovery marker. Only remove it once it is + // old enough that its owner cannot still be in the recovery section. + const markerContents = await readFile( recoveryLockPath, 'utf8' ); + if ( markerContents !== '' ) { + throw error; + } + try { + const marker = await stat( recoveryLockPath ); + if ( Date.now() - marker.mtimeMs < 5000 ) { + return false; + } + } catch ( statError ) { + if ( statError.code === 'ENOENT' ) { + return true; + } + throw statError; + } + + await rm( recoveryLockPath, { force: true } ); + return true; + } + + if ( ! recoveryOwner ) { + return true; + } + if ( isProcessRunning( recoveryOwner.pid ) ) { + return false; + } + + const currentOwner = await readLock( recoveryLockPath ); + if ( currentOwner?.id !== recoveryOwner.id ) { + return false; + } + await rm( recoveryLockPath, { force: true } ); + return true; +} + +/** + * Acquire the checkout-wide lock before changing wp-config.php. + * + * @return {Promise} + */ +async function acquireLock() { + await mkdir( E2E_DIRECTORY, { recursive: true } ); + const owner = { pid: process.pid, id: randomUUID() }; + + try { + await createLock( owner ); + lockId = owner.id; + return; + } catch ( error ) { + if ( error.code !== 'EEXIST' ) { + throw error; + } + } + + const existingOwner = await readLock(); + if ( ! existingOwner ) { + return acquireLock(); + } + if ( isProcessRunning( existingOwner.pid ) ) { + throw new Error( + 'Another E2E run is using this checkout. Wait for it to finish before starting another run.' + ); + } + + const recoveryOwner = { pid: process.pid, id: randomUUID() }; + try { + await createLock( recoveryOwner, recoveryLockPath ); + } catch ( error ) { + if ( error.code === 'EEXIST' ) { + if ( await removeStaleRecoveryLock() ) { + return acquireLock(); + } + throw new Error( + 'Another process is recovering an interrupted E2E run. Wait for it to finish before starting another run.' + ); + } + throw error; + } + + try { + const currentRecoveryOwner = await readLock( recoveryLockPath ); + if ( currentRecoveryOwner?.id !== recoveryOwner.id ) { + throw new Error( + 'Another process took over E2E recovery. Wait for it to finish before starting another run.' + ); + } + + const currentOwner = await readLock(); + if ( currentOwner && isProcessRunning( currentOwner.pid ) ) { + throw new Error( + 'Another E2E run is using this checkout. Wait for it to finish before starting another run.' + ); + } + + await rm( lockPath, { force: true } ); + try { + await createLock( owner ); + lockId = owner.id; + } catch ( error ) { + if ( error.code !== 'EEXIST' ) { + throw error; + } + return acquireLock(); + } + } finally { + const currentRecoveryOwner = await readLock( recoveryLockPath ); + if ( currentRecoveryOwner?.id === recoveryOwner.id ) { + await rm( recoveryLockPath, { force: true } ); + } + } +} + +/** + * Release the lock if this process still owns it. + * + * @return {Promise} + */ +async function releaseLock() { + if ( ! lockId ) { + return; + } + + const owner = await readLock(); + if ( owner?.id === lockId ) { + await rm( lockPath, { force: true } ); + } + lockId = undefined; +} + +/** + * Restore a saved configuration, including after a run was interrupted. + * + * @return {Promise} Whether a saved configuration was restored. + */ +async function restoreSavedConfiguration() { + let state; + try { + state = JSON.parse( await readFile( statePath, 'utf8' ) ); + } catch ( error ) { + if ( error.code === 'ENOENT' ) { + return false; + } + + throw error; + } + + if ( + typeof state.lockId !== 'string' || + ! /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + state.lockId + ) || + typeof state.localDir !== 'string' + ) { + throw new Error( + 'Invalid saved database configuration; refusing to restore it.' + ); + } + const legacyConfiguration = state.configurationMode !== 'separate'; + if ( + legacyConfiguration && + ( typeof state.originalDbName !== 'string' || + ! /^[A-Za-z0-9_-]+$/.test( state.originalDbName ) ) + ) { + throw new Error( + 'Invalid saved database name; refusing to restore it.' + ); + } + if ( + state.originalTablePrefix !== undefined && + ( typeof state.originalTablePrefix !== 'string' || + ! /^[A-Za-z0-9_]+$/.test( state.originalTablePrefix ) ) + ) { + throw new Error( + 'Invalid saved table prefix; refusing to restore it.' + ); + } + if ( + legacyConfiguration && + state.originalUploads !== null && + typeof state.originalUploads !== 'string' + ) { + throw new Error( + 'Invalid saved uploads configuration; refusing to restore it.' + ); + } + if ( + legacyConfiguration && + state.originalCacheKeySalt !== null && + typeof state.originalCacheKeySalt !== 'string' + ) { + throw new Error( + 'Invalid saved object-cache configuration; refusing to restore it.' + ); + } + + const localDir = getLocalDir( state.localDir ); + + if ( legacyConfiguration ) { + wpCli( + [ 'config', 'set', 'DB_NAME', state.originalDbName, '--type=constant' ], + localDir + ); + wpCli( + [ + 'config', + 'set', + 'table_prefix', + state.originalTablePrefix || 'wp_', + '--type=variable', + ], + localDir + ); + + if ( state.originalUploads === null ) { + wpCli( [ 'config', 'delete', 'UPLOADS', '--type=constant' ], localDir ); + } else { + wpCli( + [ + 'config', + 'set', + 'UPLOADS', + state.originalUploads, + '--type=constant', + ], + localDir + ); + } + + if ( state.originalCacheKeySalt === null ) { + wpCli( + [ 'config', 'delete', 'WP_CACHE_KEY_SALT', '--type=constant' ], + localDir + ); + } else { + wpCli( + [ + 'config', + 'set', + 'WP_CACHE_KEY_SALT', + state.originalCacheKeySalt, + '--type=constant', + ], + localDir + ); + } + } + + await removeE2EConfigRouter(); + await rm( e2eConfigPath, { force: true } ); + await rm( + path.join( process.cwd(), `wp-config-e2e.${ state.lockId }.tmp.php` ), + { force: true } + ); + await rm( statePath, { force: true } ); + return true; +} + +/** + * Set up the E2E suite with its own database, uploads and cache namespace. + * + * @param {string} baseURL Test environment URL. + * @return {Promise} Whether the local environment was switched. + */ +async function setupE2EDatabase( baseURL ) { + if ( ! isDefaultEnvironment( baseURL ) ) { + if ( process.env.WP_E2E_ISOLATED !== 'true' ) { + throw new Error( + 'Core E2E tests require an isolated test site when WP_BASE_URL is customized. Set WP_E2E_ISOLATED=true only when the site uses a disposable database and uploads directory.' + ); + } + + return false; + } + + await acquireLock(); + let configurationMayBeMutated = false; + + try { + // Recover configuration left behind if a previous run was interrupted. + try { + await readFile( statePath, 'utf8' ); + configurationMayBeMutated = true; + } catch ( error ) { + if ( error.code !== 'ENOENT' ) { + throw error; + } + } + if ( configurationMayBeMutated ) { + await restoreSavedConfiguration(); + configurationMayBeMutated = false; + } + + const localDir = getLocalDir(); + const originalDbName = wpCli( + [ 'config', 'get', 'DB_NAME', '--type=constant' ], + localDir, + ROOT_CONFIG_FILE + ); + if ( ! /^[A-Za-z0-9_-]+$/.test( originalDbName ) ) { + throw new Error( + 'The development database name is not safe to change for E2E tests.' + ); + } + + if ( originalDbName === E2E_DB_NAME ) { + throw new Error( + `The development environment already uses the E2E database (${ E2E_DB_NAME }). Refusing to reset it.` + ); + } + + const originalUploads = getConfigConstant( 'UPLOADS', localDir ); + const originalCacheKeySalt = getConfigConstant( + 'WP_CACHE_KEY_SALT', + localDir + ); + const originalTablePrefix = getConfigVariable( + 'table_prefix', + localDir + ); + if ( ! originalTablePrefix || ! /^[A-Za-z0-9_]+$/.test( originalTablePrefix ) ) { + throw new Error( + 'The development table prefix is not safe to copy to the E2E configuration.' + ); + } + + const state = { + lockId, + localDir, + configurationMode: 'separate', + originalDbName, + originalTablePrefix, + originalUploads, + originalCacheKeySalt, + }; + + // Recreate the dedicated database through WordPress's existing connection. + // The MySQL CLI may not trust the self-signed certificate in CI. + const resetDatabaseCommand = `global $wpdb; foreach ( array( "DROP DATABASE IF EXISTS ${ E2E_DB_NAME }", "CREATE DATABASE ${ E2E_DB_NAME }" ) as $query ) { if ( false === $wpdb->query( $query ) ) { WP_CLI::error( $wpdb->last_error ); } }`; + wpCli( + [ 'eval', resetDatabaseCommand, `--url=http://localhost:${ process.env.LOCAL_PORT || '8889' }` ], + localDir, + ROOT_CONFIG_FILE + ); + + const temporaryStatePath = `${ statePath }.${ lockId }.tmp`; + await writeFile( temporaryStatePath, JSON.stringify( state ), 'utf8' ); + await rename( temporaryStatePath, statePath ); + configurationMayBeMutated = true; + await createE2EConfig( localDir ); + await addE2EConfigRouter(); + wpCli( + [ + 'core', + 'install', + `--url=${ new URL( baseURL ).origin }`, + '--title=WordPress E2E Tests', + `--admin_user=${ process.env.WP_USERNAME || 'admin' }`, + `--admin_password=${ process.env.WP_PASSWORD || 'password' }`, + '--admin_email=admin@example.com', + '--skip-email', + ], + localDir, + E2E_CONFIG_FILE + ); + } catch ( error ) { + if ( configurationMayBeMutated ) { + try { + await restoreSavedConfiguration(); + configurationMayBeMutated = false; + } catch ( restoreError ) { + error.message += ` Configuration restore also failed: ${ restoreError.message }`; + throw error; + } + } + + await releaseLock(); + throw error; + } + + return true; +} + +/** + * Restore the site's original database, uploads, and cache configuration. + * + * @return {Promise} + */ +async function restoreE2EDatabase() { + let state; + try { + state = JSON.parse( await readFile( statePath, 'utf8' ) ); + } catch ( error ) { + if ( error.code === 'ENOENT' ) { + await releaseLock(); + return; + } + + throw error; + } + if ( ! state || typeof state.lockId !== 'string' ) { + throw new Error( 'Invalid saved E2E database lock; refusing to restore it.' ); + } + + const owner = await readLock(); + if ( ! owner || owner.id !== state.lockId ) { + throw new Error( + 'Cannot restore E2E configuration because this process does not own the database lock.' + ); + } + + if ( ! lockId && owner.pid !== process.pid ) { + throw new Error( + 'Cannot restore E2E configuration from a process that does not own the database lock.' + ); + } + + await restoreSavedConfiguration(); + await releaseLock(); +} + +module.exports = { + getBaseURL, + isDefaultEnvironment, + restoreE2EDatabase, + setTestBaseURL, + setupE2EDatabase, +}; diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs new file mode 100644 index 0000000000000..37864fdf9df6a --- /dev/null +++ b/tests/e2e/config/database.test.cjs @@ -0,0 +1,348 @@ +const { test } = require( 'node:test' ); +const assert = require( 'node:assert/strict' ); +const childProcess = require( 'node:child_process' ); +const { mkdtemp, mkdir, readFile, rm, utimes, writeFile } = require( 'node:fs/promises' ); +const os = require( 'node:os' ); +const path = require( 'node:path' ); +const databasePath = require.resolve( './database.js' ); + +/** + * Load the database module without reusing its cached environment configuration. + * + * @return {Object} Database configuration API. + */ +function loadDatabase() { + delete require.cache[ databasePath ]; + return require( databasePath ); +} + +test( 'passes the request host, including its port, to PHP', async () => { + const nginxConfig = await readFile( + path.join( process.cwd(), 'tools/local-env/default.template' ), + 'utf8' + ); + assert.match( nginxConfig, /fastcgi_param HTTP_HOST \$http_host;/ ); +} ); + +test( 'uses a separate local E2E port and classifies local URLs', ( t ) => { + const { getBaseURL, isDefaultEnvironment, setTestBaseURL } = loadDatabase(); + const originalPort = process.env.LOCAL_PORT; + const originalE2EPort = process.env.LOCAL_E2E_PORT; + const originalBaseURL = process.env.WP_BASE_URL; + t.after( () => { + if ( originalPort === undefined ) { + delete process.env.LOCAL_PORT; + } else { + process.env.LOCAL_PORT = originalPort; + } + if ( originalE2EPort === undefined ) { + delete process.env.LOCAL_E2E_PORT; + } else { + process.env.LOCAL_E2E_PORT = originalE2EPort; + } + if ( originalBaseURL === undefined ) { + delete process.env.WP_BASE_URL; + } else { + process.env.WP_BASE_URL = originalBaseURL; + } + } ); + + process.env.LOCAL_PORT = '8899'; + delete process.env.LOCAL_E2E_PORT; + delete process.env.WP_BASE_URL; + assert.equal( getBaseURL(), 'http://localhost:8900/' ); + assert.equal( setTestBaseURL(), 'http://localhost:8900/' ); + assert.equal( process.env.WP_BASE_URL, 'http://localhost:8900/' ); + assert.equal( isDefaultEnvironment( 'http://localhost:8900' ), true ); + assert.equal( isDefaultEnvironment( 'http://127.0.0.1:8900' ), true ); + assert.equal( isDefaultEnvironment( 'http://localhost:8899' ), false ); + assert.equal( isDefaultEnvironment( 'http://localhost:8889' ), false ); + assert.equal( isDefaultEnvironment( 'https://localhost:8900' ), false ); + process.env.WP_BASE_URL = 'http://localhost:8899'; + assert.equal( getBaseURL(), 'http://localhost:8900/' ); + assert.equal( setTestBaseURL(), 'http://localhost:8900/' ); + assert.equal( isDefaultEnvironment( getBaseURL() ), true ); + process.env.LOCAL_E2E_PORT = '8899'; + assert.throws( () => getBaseURL(), /distinct valid TCP ports/ ); +} ); + +test( 'custom test sites require explicit isolation confirmation', async ( t ) => { + const { setupE2EDatabase } = loadDatabase(); + const originalIsolation = process.env.WP_E2E_ISOLATED; + t.after( () => { + if ( originalIsolation === undefined ) { + delete process.env.WP_E2E_ISOLATED; + } else { + process.env.WP_E2E_ISOLATED = originalIsolation; + } + } ); + + delete process.env.WP_E2E_ISOLATED; + await assert.rejects( + setupE2EDatabase( 'https://wordpress.example.test' ), + /WP_BASE_URL is customized/i + ); + + process.env.WP_E2E_ISOLATED = 'true'; + assert.equal( + await setupE2EDatabase( 'https://wordpress.example.test' ), + false + ); +} ); + +test( 'isolates database setup and rejects another run in the same checkout', async ( t ) => { + const originalCwd = process.cwd(); + const originalEnvironment = { + LOCAL_DIR: process.env.LOCAL_DIR, + LOCAL_PORT: process.env.LOCAL_PORT, + LOCAL_E2E_PORT: process.env.LOCAL_E2E_PORT, + WP_BASE_URL: process.env.WP_BASE_URL, + }; + const testRoot = await mkdtemp( path.join( os.tmpdir(), 'wp-e2e-database-' ) ); + await mkdir( path.join( testRoot, 'tests/e2e' ), { recursive: true } ); + await writeFile( + path.join( testRoot, 'wp-config.php' ), + " { + commands.push( args ); + if ( args.includes( 'get' ) && args.includes( 'DB_NAME' ) ) { + return { status: 0, stdout: 'wordpress_develop', stderr: '' }; + } + if ( + args.includes( 'get' ) && + ( args.includes( 'UPLOADS' ) || + args.includes( 'WP_CACHE_KEY_SALT' ) ) + ) { + return { + status: 1, + stdout: '', + stderr: 'The constant is not defined.', + }; + } + if ( args.includes( 'get' ) && args.includes( 'table_prefix' ) ) { + return { status: 0, stdout: 'wp_', stderr: '' }; + } + return { status: 0, stdout: '', stderr: '' }; + } ); + + const database = loadDatabase(); + t.after( async () => { + process.chdir( originalCwd ); + for ( const [ key, value ] of Object.entries( originalEnvironment ) ) { + if ( value === undefined ) { + delete process.env[ key ]; + } else { + process.env[ key ] = value; + } + } + const resolvedTestRoot = path.resolve( testRoot ); + assert.ok( resolvedTestRoot.startsWith( `${ path.resolve( os.tmpdir() ) }${ path.sep }` ) ); + await rm( resolvedTestRoot, { recursive: true, force: true } ); + } ); + + assert.equal( + await database.setupE2EDatabase( 'http://localhost:8900' ), + true + ); + const rootConfig = await readFile( path.join( testRoot, 'wp-config.php' ), 'utf8' ); + assert.match( rootConfig, /BEGIN WP Core E2E config routing/ ); + assert.match( rootConfig, /DB_NAME', 'wordpress_develop'/ ); + assert.match( + await readFile( path.join( testRoot, 'wp-config-e2e.php' ), 'utf8' ), + /\$table_prefix = 'wp_';/ + ); + const firstRunCommandCount = commands.length; + await assert.rejects( + database.setupE2EDatabase( 'http://localhost:8900' ), + /Another E2E run is using this checkout/ + ); + assert.equal( commands.length, firstRunCommandCount ); + assert.ok( + commands.every( ( args ) => + args.includes( '--path=/var/www/build' ) + ) + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'eval' ) && + args.includes( '--url=http://localhost:8899' ) && + args.some( + ( arg ) => + arg.includes( + 'DROP DATABASE IF EXISTS wordpress_develop_e2e' + ) && + arg.includes( + 'CREATE DATABASE wordpress_develop_e2e' + ) + ) + ) + ); + assert.equal( + commands.some( ( args ) => args.includes( 'db' ) ), + false + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'WP_CACHE_KEY_SALT' ) && + args.includes( 'set' ) && + args.some( ( arg ) => + arg.includes( 'WP_CONFIG_PATH=/var/www/wp-config-e2e.' ) + ) + ) + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'DB_NAME' ) && + args.includes( 'wordpress_develop_e2e' ) && + args.some( ( arg ) => + arg.includes( 'WP_CONFIG_PATH=/var/www/wp-config-e2e.' ) + ) + ) + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'memcached_servers' ) && + args.some( ( arg ) => arg.includes( 'memcached-e2e' ) ) + ) + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'install' ) && + args.includes( '--url=http://localhost:8900' ) && + args.includes( 'WP_CONFIG_PATH=/var/www/wp-config-e2e.php' ) + ) + ); + + await database.restoreE2EDatabase(); + assert.doesNotMatch( + await readFile( path.join( testRoot, 'wp-config.php' ), 'utf8' ), + /BEGIN WP Core E2E config routing/ + ); + await assert.rejects( + readFile( path.join( testRoot, 'wp-config-e2e.php' ), 'utf8' ), + { code: 'ENOENT' } + ); +} ); + +test( 'recovers a stale setup marker and regenerates a clean E2E table prefix', async ( t ) => { + const originalCwd = process.cwd(); + const originalEnvironment = { + LOCAL_DIR: process.env.LOCAL_DIR, + LOCAL_PORT: process.env.LOCAL_PORT, + LOCAL_E2E_PORT: process.env.LOCAL_E2E_PORT, + WP_BASE_URL: process.env.WP_BASE_URL, + }; + const testRoot = await mkdtemp( path.join( os.tmpdir(), 'wp-e2e-recovery-' ) ); + const e2eDirectory = path.join( testRoot, 'tests/e2e' ); + const interruptedLockId = '11111111-1111-4111-8111-111111111111'; + await mkdir( e2eDirectory, { recursive: true } ); + await writeFile( + path.join( testRoot, 'wp-config.php' ), + " { + if ( pid !== process.pid ) { + const error = new Error( 'Process not found.' ); + error.code = 'ESRCH'; + throw error; + } + } ); + t.mock.method( childProcess, 'spawnSync', ( _command, args ) => { + if ( args.includes( 'get' ) && args.includes( 'DB_NAME' ) ) { + return { status: 0, stdout: 'wordpress_develop', stderr: '' }; + } + if ( args.includes( 'get' ) && args.includes( 'table_prefix' ) ) { + return { status: 0, stdout: 'wp_', stderr: '' }; + } + if ( + args.includes( 'get' ) && + ( args.includes( 'UPLOADS' ) || + args.includes( 'WP_CACHE_KEY_SALT' ) ) + ) { + return { + status: 1, + stdout: '', + stderr: 'The constant is not defined.', + }; + } + return { status: 0, stdout: '', stderr: '' }; + } ); + + const database = loadDatabase(); + t.after( async () => { + process.chdir( originalCwd ); + for ( const [ key, value ] of Object.entries( originalEnvironment ) ) { + if ( value === undefined ) { + delete process.env[ key ]; + } else { + process.env[ key ] = value; + } + } + const resolvedTestRoot = path.resolve( testRoot ); + assert.ok( resolvedTestRoot.startsWith( `${ path.resolve( os.tmpdir() ) }${ path.sep }` ) ); + await rm( resolvedTestRoot, { recursive: true, force: true } ); + } ); + + assert.equal( + await database.setupE2EDatabase( 'http://localhost:8900' ), + true + ); + assert.match( + await readFile( path.join( testRoot, 'wp-config-e2e.php' ), 'utf8' ), + /\$table_prefix = 'wp_';/ + ); + assert.doesNotMatch( + await readFile( path.join( testRoot, 'wp-config-e2e.php' ), 'utf8' ), + /wp_e2e_/ + ); + await assert.rejects( + readFile( path.join( testRoot, `wp-config-e2e.${ interruptedLockId }.tmp.php` ) ), + { code: 'ENOENT' } + ); + await database.restoreE2EDatabase(); +} ); diff --git a/tests/e2e/config/global-setup.js b/tests/e2e/config/global-setup.js index be45c9fb22a21..73f28b0471eff 100644 --- a/tests/e2e/config/global-setup.js +++ b/tests/e2e/config/global-setup.js @@ -14,48 +14,69 @@ import { RequestUtils } from '@wordpress/e2e-test-utils-playwright'; * Internal dependencies */ import { removeMuPlugins } from '../fixtures/site'; +import database from './database.js'; + +const { restoreE2EDatabase, setupE2EDatabase } = database; /** + * Set up the E2E environment. * - * @param {import('@playwright/test').FullConfig} config - * @returns {Promise} + * @param {import('@playwright/test').FullConfig} config Playwright configuration. + * @return {Promise} Promise that resolves when setup is complete. */ async function globalSetup( config ) { const { storageState, baseURL } = config.projects[ 0 ].use; const storageStatePath = typeof storageState === 'string' ? storageState : undefined; - // An interrupted run can leave this behind, and it breaks the whole site. - const documentRoot = join( process.cwd(), process.env.LOCAL_DIR ?? 'src' ); - rmSync( join( documentRoot, '.maintenance' ), { force: true } ); - removeMuPlugins(); - - const requestContext = await request.newContext( { - baseURL, - } ); - - const requestUtils = new RequestUtils( requestContext, { - storageStatePath, - } ); - - // Authenticate and save the storageState to disk. - await requestUtils.setupRest(); - - /* - * Switch the theme before the other resets. switch_theme() updates the `template` - * and `stylesheet` options one at a time, so a request that loads between the two - * sees a mismatched theme pair and can fail with a PHP error. - */ - await requestUtils.activateTheme( 'twentytwentyone' ); - - // Reset the test environment before running the tests. - await Promise.all( [ - requestUtils.deleteAllPosts(), - requestUtils.deleteAllBlocks(), - requestUtils.resetPreferences(), - ] ); - - await requestContext.dispose(); + let shouldRestoreDatabase = false; + let requestContext; + + try { + shouldRestoreDatabase = await setupE2EDatabase( baseURL ); + + // An interrupted run can leave this behind, and it breaks the whole site. + const documentRoot = join( process.cwd(), process.env.LOCAL_DIR ?? 'src' ); + rmSync( join( documentRoot, '.maintenance' ), { force: true } ); + removeMuPlugins(); + + requestContext = await request.newContext( { + baseURL, + } ); + + const requestUtils = new RequestUtils( requestContext, { + storageStatePath, + } ); + + // Authenticate and save the storageState to disk. + await requestUtils.setupRest(); + + /* + * Switch the theme before the other resets. switch_theme() updates the `template` + * and `stylesheet` options one at a time, so a request that loads between the two + * sees a mismatched theme pair and can fail with a PHP error. + */ + await requestUtils.activateTheme( 'twentytwentyone' ); + + // Reset the test environment before running the tests. + await Promise.all( [ + requestUtils.deleteAllPosts(), + requestUtils.deleteAllBlocks(), + requestUtils.resetPreferences(), + ] ); + } catch ( error ) { + if ( shouldRestoreDatabase ) { + try { + await restoreE2EDatabase(); + } catch ( restoreError ) { + error.message += ` Configuration restore also failed: ${ restoreError.message }`; + } + } + + throw error; + } finally { + await requestContext?.dispose(); + } } export default globalSetup; diff --git a/tests/e2e/config/global-teardown.js b/tests/e2e/config/global-teardown.js new file mode 100644 index 0000000000000..0ad483955aa0b --- /dev/null +++ b/tests/e2e/config/global-teardown.js @@ -0,0 +1,21 @@ +/** + * Internal dependencies + */ +import database from './database.js'; + +const { isDefaultEnvironment, restoreE2EDatabase } = database; + +/** + * Restore the development environment configuration after the E2E suite completes. + * + * @param {import('@playwright/test').FullConfig} config Playwright configuration. + * @return {Promise} + */ +async function globalTeardown( config ) { + const { baseURL } = config.projects[ 0 ].use; + if ( isDefaultEnvironment( baseURL ) ) { + await restoreE2EDatabase(); + } +} + +export default globalTeardown; diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index c4c8e4a1441bc..2355b626a6813 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -7,6 +7,11 @@ import { defineConfig, devices } from '@playwright/test'; /** * WordPress dependencies */ +const database = require( './config/database.js' ); + +const { isDefaultEnvironment, setTestBaseURL } = database; + +const baseURL = setTestBaseURL(); const baseConfig = require( '@wordpress/scripts/config/playwright.config' ); process.env.WP_ARTIFACTS_PATH ??= path.join( process.cwd(), 'artifacts' ); @@ -22,16 +27,26 @@ const SERIAL_SPECS = [ 'theme-activation.test.js', ]; +const webServer = isDefaultEnvironment( baseURL ) + ? { + ...baseConfig.webServer, + command: 'npm run env:start', + port: new URL( baseURL ).port || '80', + } + : undefined; + const config = defineConfig( { ...baseConfig, + use: { + ...baseConfig.use, + baseURL, + }, globalSetup: require.resolve( './config/global-setup.js' ), + globalTeardown: require.resolve( './config/global-teardown.js' ), workers: '50%', retries: process.env.CI ? 1 : 0, reporter: process.env.CI ? [ [ 'github' ], [ 'list' ] ] : [ [ 'list' ] ], - webServer: { - ...baseConfig.webServer, - command: 'npm run env:start', - }, + webServer, projects: [ { name: 'all', diff --git a/tests/e2e/specs/install.test.js b/tests/e2e/specs/install.test.js index 917dc20836804..cd70b397622fb 100644 --- a/tests/e2e/specs/install.test.js +++ b/tests/e2e/specs/install.test.js @@ -12,6 +12,7 @@ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; /** * Internal dependencies */ +import database from '../config/database.js'; import { wpCli } from '../utils/wp-cli'; let wpConfigOriginal; @@ -20,6 +21,7 @@ let wpConfigOriginal; // constant since it has to stay in sync between the config rewrite and the // cleanup query below. const TEST_TABLE_PREFIX = 'wp_e2e_'; +const { getBaseURL, isDefaultEnvironment } = database; /** * Drops any tables left over under TEST_TABLE_PREFIX. @@ -58,7 +60,7 @@ function dropE2eTables() { test.describe( 'WordPress installation process', () => { const wpConfig = join( process.cwd(), - 'wp-config.php', + isDefaultEnvironment( getBaseURL() ) ? 'wp-config-e2e.php' : 'wp-config.php', ); @@ -138,7 +140,9 @@ test.describe( 'WordPress installation process', () => { await page.getByLabel( /Confirm use of weak password/ ).check() await page.getByLabel( 'Your Email' ).fill( 'test@example.com' ); - await page.getByRole( 'button', { name: 'Install WordPress' } ).click(); + await page.getByRole( 'button', { name: 'Install WordPress' } ).click( { + timeout: 30_000, + } ); // Installation finished, can now log in. diff --git a/tests/e2e/utils/wp-cli.js b/tests/e2e/utils/wp-cli.js index f336ad375d99e..4500422446167 100644 --- a/tests/e2e/utils/wp-cli.js +++ b/tests/e2e/utils/wp-cli.js @@ -4,6 +4,13 @@ import { execFileSync } from 'node:child_process'; import { join } from 'node:path'; +/** + * Internal dependencies + */ +import database from '../config/database.js'; + +const { getBaseURL, isDefaultEnvironment } = database; + /** * Runs a WP-CLI command in the local environment's `cli` container. * @@ -15,16 +22,26 @@ import { join } from 'node:path'; * @return {string|null} The command's standard output, or `null` if `options.stdio` does not pipe it. */ export function wpCli( args, options = {} ) { + const baseURL = getBaseURL(); + const configArgs = isDefaultEnvironment( baseURL ) + ? [ '--env', 'WP_CONFIG_PATH=/var/www/wp-config-e2e.php' ] + : []; + const urlArgs = args.some( ( argument ) => argument.startsWith( '--url=' ) ) + ? [] + : [ `--url=${ baseURL }` ]; + return execFileSync( process.execPath, [ join( process.cwd(), 'tools/local-env/scripts/docker.js' ), 'exec', + ...configArgs, '--user', 'wp_php', 'cli', 'wp', `--path=/var/www/${ process.env.LOCAL_DIR ?? 'src' }`, + ...urlArgs, ...args, ], { diff --git a/tools/local-env/default.template b/tools/local-env/default.template index 2cd95b9447df8..b04f437f0bbea 100644 --- a/tools/local-env/default.template +++ b/tools/local-env/default.template @@ -51,6 +51,7 @@ server { fastcgi_pass php:9000; fastcgi_index index.php; include fastcgi_params; + fastcgi_param HTTP_HOST $http_host; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_pass_header Authorization; diff --git a/tools/local-env/scripts/docker.js b/tools/local-env/scripts/docker.js index 0ef6d469d19d6..b48228ba7b514 100644 --- a/tools/local-env/scripts/docker.js +++ b/tools/local-env/scripts/docker.js @@ -7,6 +7,7 @@ const local_env_utils = require( './utils' ); local_env_utils.ensure_env_file(); dotenvExpand.expand( dotenv.config() ); +process.env.LOCAL_E2E_PORT ||= String( Number( process.env.LOCAL_PORT || 8889 ) + 1 ); // Use Xdebug to generate HTML code coverage reports, unless PCOV is enabled and Xdebug is not. if ( diff --git a/tools/local-env/scripts/start.js b/tools/local-env/scripts/start.js index 970fc4b944ed6..3bd49e383d195 100644 --- a/tools/local-env/scripts/start.js +++ b/tools/local-env/scripts/start.js @@ -8,6 +8,7 @@ const local_env_utils = require( './utils' ); local_env_utils.ensure_env_file(); dotenvExpand.expand( dotenv.config() ); +process.env.LOCAL_E2E_PORT ||= String( Number( process.env.LOCAL_PORT || 8889 ) + 1 ); // Check if the Docker service is running. try { @@ -23,7 +24,7 @@ try { // Start the local-env containers. const containers = [ 'wordpress-develop', 'cli' ]; if ( process.env.LOCAL_PHP_MEMCACHED === 'true' ) { - containers.push( 'memcached' ); + containers.push( 'memcached', 'memcached-e2e' ); } // `up` pulls any image that is missing, so it is re-attempted for the same reasons as `env:pull`.