From acb208e441ef9a2f02e1d415053fad6b07123c04 Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 15:47:19 +0530 Subject: [PATCH 1/9] Tests: isolate the Core E2E environment --- .gitignore | 3 + package.json | 3 +- tests/e2e/README.md | 10 +- tests/e2e/config/database.js | 543 ++++++++++++++++++++++++++++ tests/e2e/config/database.test.cjs | 51 +++ tests/e2e/config/global-setup.js | 85 +++-- tests/e2e/config/global-teardown.js | 20 + tests/e2e/playwright.config.js | 23 +- 8 files changed, 697 insertions(+), 41 deletions(-) create mode 100644 tests/e2e/config/database.js create mode 100644 tests/e2e/config/database.test.cjs create mode 100644 tests/e2e/config/global-teardown.js diff --git a/.gitignore b/.gitignore index 24b4282326304..7e9f229fffbb5 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,8 @@ wp-tests-config.php /packagehash.txt /.gutenberg-hash /artifacts +/tests/e2e/.database-state.json +/tests/e2e/.database-lock* /setup.log /coverage @@ -76,6 +78,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/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..75e9d8d7563d9 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/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: +By default, the tests use the `wordpress_develop_e2e` database and a separate `uploads-e2e` directory. The database, uploads, and object-cache settings in `wp-config.php` are restored 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 switches `wp-config.php`. A second E2E run in the same checkout exits before changing the configuration. 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..0a6388888b76c --- /dev/null +++ b/tests/e2e/config/database.js @@ -0,0 +1,543 @@ +/** + * External dependencies + */ +const { randomUUID } = require( 'node:crypto' ); +const { spawnSync } = require( 'node:child_process' ); +const { + link, + mkdir, + open, + readFile, + rm, + rename, + 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_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`; + +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() { + return new URL( + process.env.WP_BASE_URL || + `http://localhost:${ process.env.LOCAL_PORT || '8889' }` + ).href; +} + +/** + * Run a WP-CLI command in the local development environment. + * + * @param {string[]} args WP-CLI arguments. + * @param {string} localDir WordPress document root. + * @return {{ status: number, stdout: string, stderr: string }} WP-CLI command result. + */ +function runWpCli( args, localDir = getLocalDir() ) { + const result = spawnSync( + process.execPath, + [ + path.join( process.cwd(), 'tools/local-env/scripts/docker.js' ), + 'exec', + '--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. + * @return {string} Command output. + */ +function wpCli( args, localDir = getLocalDir() ) { + const result = runWpCli( args, localDir ); + + 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.` + ); +} + +/** + * Check whether the URL uses Core's default local test 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 localPort = process.env.LOCAL_PORT || '8889'; + + return ( + [ 'localhost', '127.0.0.1' ].includes( url.hostname ) && + url.protocol === 'http:' && + port === localPort + ); +} + +/** + * 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. + * + * @return {Promise} Current lock owner. + */ +async function readLock() { + try { + const owner = JSON.parse( await readFile( lockPath, '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 the E2E database lock. ${ error.message }` + ); + } +} + +/** + * Create a lock file with complete owner data using an atomic hard link. + * + * @param {{ pid: number, id: string }} owner Lock owner. + * @return {Promise} + */ +async function createLock( owner ) { + const temporaryPath = `${ lockPath }.${ owner.id }.tmp`; + await writeFile( temporaryPath, JSON.stringify( owner ), { flag: 'wx' } ); + try { + await link( temporaryPath, lockPath ); + } finally { + await rm( temporaryPath, { force: 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.' + ); + } + + let recoveryHandle; + try { + recoveryHandle = await open( recoveryLockPath, 'wx' ); + } catch ( error ) { + if ( error.code === 'EEXIST' ) { + throw new Error( + 'Another process is recovering an interrupted E2E run. Wait for it to finish before starting another run.' + ); + } + throw error; + } + + try { + 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 { + await recoveryHandle.close(); + 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.originalDbName !== 'string' || + ! /^[A-Za-z0-9_-]+$/.test( state.originalDbName ) + ) { + throw new Error( + 'Invalid saved database configuration; refusing to restore it.' + ); + } + if ( + state.originalUploads !== null && + typeof state.originalUploads !== 'string' + ) { + throw new Error( + 'Invalid saved uploads configuration; refusing to restore it.' + ); + } + if ( + state.originalCacheKeySalt !== null && + typeof state.originalCacheKeySalt !== 'string' + ) { + throw new Error( + 'Invalid saved object-cache configuration; refusing to restore it.' + ); + } + + const localDir = getLocalDir( state.localDir ); + + wpCli( + [ 'config', 'set', 'DB_NAME', state.originalDbName, '--type=constant' ], + 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 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 + ); + 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 state = { + lockId, + localDir, + originalDbName, + originalUploads, + originalCacheKeySalt, + }; + + // Create the dedicated database without touching the PHPUnit database. + wpCli( + [ 'db', 'query', `CREATE DATABASE IF NOT EXISTS ${ E2E_DB_NAME }` ], + localDir + ); + + const temporaryStatePath = `${ statePath }.${ lockId }.tmp`; + await writeFile( temporaryStatePath, JSON.stringify( state ), 'utf8' ); + await rename( temporaryStatePath, statePath ); + configurationMayBeMutated = true; + wpCli( + [ 'config', 'set', 'DB_NAME', E2E_DB_NAME, '--type=constant' ], + localDir + ); + wpCli( + [ 'config', 'set', 'UPLOADS', E2E_UPLOADS, '--type=constant' ], + localDir + ); + wpCli( + [ + 'config', + 'set', + 'WP_CACHE_KEY_SALT', + `e2e-${ randomUUID() }-`, + '--type=constant', + ], + localDir + ); + wpCli( [ 'db', 'reset', '--yes' ], localDir ); + 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 + ); + } 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; + } + + 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, + setupE2EDatabase, +}; diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs new file mode 100644 index 0000000000000..3fc9fe786024c --- /dev/null +++ b/tests/e2e/config/database.test.cjs @@ -0,0 +1,51 @@ +const { test } = require( 'node:test' ); +const assert = require( 'node:assert/strict' ); +const { getBaseURL, isDefaultEnvironment, setupE2EDatabase } = require( './database.js' ); + +test( 'uses the local environment port when classifying a URL', ( t ) => { + const originalPort = process.env.LOCAL_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 ( originalBaseURL === undefined ) { + delete process.env.WP_BASE_URL; + } else { + process.env.WP_BASE_URL = originalBaseURL; + } + } ); + + process.env.LOCAL_PORT = '8899'; + delete process.env.WP_BASE_URL; + assert.equal( getBaseURL(), 'http://localhost:8899/' ); + assert.equal( isDefaultEnvironment( 'http://localhost:8899' ), true ); + assert.equal( isDefaultEnvironment( 'http://127.0.0.1:8899' ), true ); + assert.equal( isDefaultEnvironment( 'http://localhost:8889' ), false ); + assert.equal( isDefaultEnvironment( 'https://localhost:8899' ), false ); +} ); + +test( 'custom test sites require explicit isolation confirmation', async ( t ) => { + 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 + ); +} ); diff --git a/tests/e2e/config/global-setup.js b/tests/e2e/config/global-setup.js index be45c9fb22a21..08442bafbecf6 100644 --- a/tests/e2e/config/global-setup.js +++ b/tests/e2e/config/global-setup.js @@ -14,48 +14,67 @@ import { RequestUtils } from '@wordpress/e2e-test-utils-playwright'; * Internal dependencies */ import { removeMuPlugins } from '../fixtures/site'; +import database from './database.js'; + +const { restoreE2EDatabase, setupE2EDatabase } = database; /** - * * @param {import('@playwright/test').FullConfig} config - * @returns {Promise} + * @return {Promise} */ 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..3652d9207b0f4 --- /dev/null +++ b/tests/e2e/config/global-teardown.js @@ -0,0 +1,20 @@ +/** + * Internal dependencies + */ +import database from './database.js'; + +const { isDefaultEnvironment, restoreE2EDatabase } = database; + +/** + * Restore the development environment configuration after the E2E suite completes. + * + * @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..3d2939f770219 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -7,8 +7,13 @@ import { defineConfig, devices } from '@playwright/test'; /** * WordPress dependencies */ +const database = require( './config/database.js' ); const baseConfig = require( '@wordpress/scripts/config/playwright.config' ); +const { getBaseURL, isDefaultEnvironment } = database; + +const baseURL = getBaseURL(); + process.env.WP_ARTIFACTS_PATH ??= path.join( process.cwd(), 'artifacts' ); process.env.STORAGE_STATE_PATH ??= path.join( process.env.WP_ARTIFACTS_PATH, @@ -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', From 219465543fe6e5e7988974fb9f112b2b214fa663 Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 17:21:34 +0530 Subject: [PATCH 2/9] Tests: Extend installation action timeout --- tests/e2e/specs/install.test.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/e2e/specs/install.test.js b/tests/e2e/specs/install.test.js index 917dc20836804..5110807430361 100644 --- a/tests/e2e/specs/install.test.js +++ b/tests/e2e/specs/install.test.js @@ -138,7 +138,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. From 39c0c0179dc6c4ff9f863dddcc529bda2b517688 Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 20:03:08 +0530 Subject: [PATCH 3/9] Tests: Harden E2E isolation state validation --- tests/e2e/config/database.js | 11 +++- tests/e2e/config/database.test.cjs | 96 +++++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 4 deletions(-) diff --git a/tests/e2e/config/database.js b/tests/e2e/config/database.js index 0a6388888b76c..68bd017da7833 100644 --- a/tests/e2e/config/database.js +++ b/tests/e2e/config/database.js @@ -58,7 +58,7 @@ function getBaseURL() { /** * Run a WP-CLI command in the local development environment. * - * @param {string[]} args WP-CLI arguments. + * @param {string[]} args WP-CLI arguments. * @param {string} localDir WordPress document root. * @return {{ status: number, stdout: string, stderr: string }} WP-CLI command result. */ @@ -115,8 +115,8 @@ function wpCli( args, localDir = getLocalDir() ) { /** * Get a wp-config.php constant, returning null when it is not defined. * - * @param {string} name Constant name. - * @param {string} localDir WordPress document root. + * @param {string} name Constant name. + * @param {string} localDir WordPress document root. * @return {?string} Constant value, or null if undefined. */ function getConfigConstant( name, localDir ) { @@ -312,6 +312,8 @@ async function restoreSavedConfiguration() { } if ( + typeof state.lockId !== 'string' || + typeof state.localDir !== 'string' || typeof state.originalDbName !== 'string' || ! /^[A-Za-z0-9_-]+$/.test( state.originalDbName ) ) { @@ -517,6 +519,9 @@ async function restoreE2EDatabase() { 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 ) { diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index 3fc9fe786024c..8e53a972b32b5 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -1,8 +1,23 @@ const { test } = require( 'node:test' ); const assert = require( 'node:assert/strict' ); -const { getBaseURL, isDefaultEnvironment, setupE2EDatabase } = require( './database.js' ); +const childProcess = require( 'node:child_process' ); +const { mkdtemp, mkdir, rm } = 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( 'uses the local environment port when classifying a URL', ( t ) => { + const { getBaseURL, isDefaultEnvironment } = loadDatabase(); const originalPort = process.env.LOCAL_PORT; const originalBaseURL = process.env.WP_BASE_URL; t.after( () => { @@ -28,6 +43,7 @@ test( 'uses the local environment port when classifying a URL', ( t ) => { } ); 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 ) { @@ -49,3 +65,81 @@ test( 'custom test sites require explicit isolation confirmation', async ( t ) = 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, + }; + const testRoot = await mkdtemp( path.join( os.tmpdir(), 'wp-e2e-database-' ) ); + await mkdir( path.join( testRoot, 'tests/e2e' ), { recursive: true } ); + process.chdir( testRoot ); + process.env.LOCAL_DIR = 'build'; + process.env.LOCAL_PORT = '8899'; + + const commands = []; + t.mock.method( childProcess, 'spawnSync', ( _command, args ) => { + 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.', + }; + } + 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:8899' ), + true + ); + const firstRunCommandCount = commands.length; + await assert.rejects( + database.setupE2EDatabase( 'http://localhost:8899' ), + /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.some( ( arg ) => + arg.includes( 'CREATE DATABASE IF NOT EXISTS wordpress_develop_e2e' ) + ) + ) + ); + assert.ok( + commands.some( ( args ) => + args.includes( 'WP_CACHE_KEY_SALT' ) && args.includes( 'set' ) + ) + ); + + await database.restoreE2EDatabase(); +} ); From 40a4e2ab64e62b4d78b51b6134127d0285b9f2f4 Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 20:29:35 +0530 Subject: [PATCH 4/9] Avoid MySQL CLI in E2E database setup --- tests/e2e/config/database.js | 10 ++++------ tests/e2e/config/database.test.cjs | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/tests/e2e/config/database.js b/tests/e2e/config/database.js index 68bd017da7833..c445313ab9983 100644 --- a/tests/e2e/config/database.js +++ b/tests/e2e/config/database.js @@ -442,11 +442,10 @@ async function setupE2EDatabase( baseURL ) { originalCacheKeySalt, }; - // Create the dedicated database without touching the PHPUnit database. - wpCli( - [ 'db', 'query', `CREATE DATABASE IF NOT EXISTS ${ E2E_DB_NAME }` ], - localDir - ); + // 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 ], localDir ); const temporaryStatePath = `${ statePath }.${ lockId }.tmp`; await writeFile( temporaryStatePath, JSON.stringify( state ), 'utf8' ); @@ -470,7 +469,6 @@ async function setupE2EDatabase( baseURL ) { ], localDir ); - wpCli( [ 'db', 'reset', '--yes' ], localDir ); wpCli( [ 'core', diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index 8e53a972b32b5..e281fb20edf8a 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -130,11 +130,22 @@ test( 'isolates database setup and rejects another run in the same checkout', as ); assert.ok( commands.some( ( args ) => - args.some( ( arg ) => - arg.includes( 'CREATE DATABASE IF NOT EXISTS wordpress_develop_e2e' ) + args.includes( 'eval' ) && + 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' ) From d2b073518a3f05b7211700920ea1436ee1ee5d9f Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 23:37:40 +0530 Subject: [PATCH 5/9] Separate-E2E-site-configuration --- .env.example | 4 +- .gitignore | 1 + docker-compose.yml | 9 + tests/e2e/README.md | 6 +- tests/e2e/config/database.js | 472 +++++++++++++++++++++++----- tests/e2e/config/database.test.cjs | 195 +++++++++++- tests/e2e/config/global-setup.js | 6 +- tests/e2e/config/global-teardown.js | 1 + tests/e2e/specs/install.test.js | 4 +- tests/e2e/utils/wp-cli.js | 17 + tools/local-env/scripts/docker.js | 1 + tools/local-env/scripts/start.js | 3 +- 12 files changed, 630 insertions(+), 89 deletions(-) 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 7e9f229fffbb5..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 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/tests/e2e/README.md b/tests/e2e/README.md index 75e9d8d7563d9..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,7 +17,7 @@ npm run test:e2e which will run the test suite using a headless browser. -By default, the tests use the `wordpress_develop_e2e` database and a separate `uploads-e2e` directory. The database, uploads, and object-cache settings in `wp-config.php` are restored after the tests. +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: @@ -26,7 +26,7 @@ WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password WP_E2E_ ``` 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 switches `wp-config.php`. A second E2E run in the same checkout exits before changing the configuration. PHPUnit continues to use `wordpress_develop_tests`. +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 index c445313ab9983..2da483f005129 100644 --- a/tests/e2e/config/database.js +++ b/tests/e2e/config/database.js @@ -4,12 +4,13 @@ const { randomUUID } = require( 'node:crypto' ); const { spawnSync } = require( 'node:child_process' ); const { + copyFile, link, mkdir, - open, readFile, rm, rename, + stat, writeFile, } = require( 'node:fs/promises' ); const path = require( 'node:path' ); @@ -22,10 +23,17 @@ dotenvExpand.expand( 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; @@ -49,20 +57,65 @@ function getLocalDir( localDir = process.env.LOCAL_DIR || 'src' ) { * @return {string} Test environment URL. */ function getBaseURL() { - return new URL( - process.env.WP_BASE_URL || - `http://localhost:${ process.env.LOCAL_PORT || '8889' }` - ).href; + 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; +} + +/** + * 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[]} 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() ) { +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, [ @@ -74,6 +127,7 @@ function runWpCli( args, localDir = getLocalDir() ) { 'wp', ...args, `--path=/var/www/${ getLocalDir( localDir ) }`, + `--config-file=/var/www/${ configFile }`, ], { cwd: process.cwd(), @@ -95,12 +149,17 @@ function runWpCli( args, localDir = getLocalDir() ) { /** * Run WP-CLI and throw if it fails. * - * @param {string[]} args WP-CLI arguments. - * @param {string} localDir WordPress document root. + * @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() ) { - const result = runWpCli( args, localDir ); +function wpCli( + args, + localDir = getLocalDir(), + configFile = ROOT_CONFIG_FILE +) { + const result = runWpCli( args, localDir, configFile ); if ( result.status !== 0 ) { throw new Error( @@ -139,7 +198,170 @@ function getConfigConstant( name, localDir ) { } /** - * Check whether the URL uses Core's default local test environment. + * 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. @@ -148,12 +370,12 @@ function isDefaultEnvironment( baseURL ) { const url = new URL( baseURL ); const port = url.port || ( url.protocol === 'https:' ? '443' : '80' ); - const localPort = process.env.LOCAL_PORT || '8889'; + const e2ePort = getE2EPort(); return ( [ 'localhost', '127.0.0.1' ].includes( url.hostname ) && url.protocol === 'http:' && - port === localPort + port === e2ePort ); } @@ -175,11 +397,12 @@ function isProcessRunning( pid ) { /** * Read the current run lock. * + * @param {string} [lockFilePath] Lock file path. * @return {Promise} Current lock owner. */ -async function readLock() { +async function readLock( lockFilePath = lockPath ) { try { - const owner = JSON.parse( await readFile( lockPath, 'utf8' ) ); + const owner = JSON.parse( await readFile( lockFilePath, 'utf8' ) ); if ( ! Number.isInteger( owner.pid ) || typeof owner.id !== 'string' ) { throw new Error( 'Invalid E2E database lock.' ); } @@ -190,28 +413,74 @@ async function readLock() { return null; } - throw new Error( - `Cannot safely read the E2E database lock. ${ error.message }` - ); + 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 {{ pid: number, id: string }} owner Lock owner. + * @param {string} [lockFilePath] Lock file path. * @return {Promise} */ -async function createLock( owner ) { - const temporaryPath = `${ lockPath }.${ owner.id }.tmp`; +async function createLock( owner, lockFilePath = lockPath ) { + const temporaryPath = `${ lockFilePath }.${ owner.id }.tmp`; await writeFile( temporaryPath, JSON.stringify( owner ), { flag: 'wx' } ); try { - await link( temporaryPath, lockPath ); + 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. * @@ -241,11 +510,14 @@ async function acquireLock() { ); } - let recoveryHandle; + const recoveryOwner = { pid: process.pid, id: randomUUID() }; try { - recoveryHandle = await open( recoveryLockPath, 'wx' ); + 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.' ); @@ -254,6 +526,13 @@ async function acquireLock() { } 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( @@ -272,8 +551,10 @@ async function acquireLock() { return acquireLock(); } } finally { - await recoveryHandle.close(); - await rm( recoveryLockPath, { force: true } ); + const currentRecoveryOwner = await readLock( recoveryLockPath ); + if ( currentRecoveryOwner?.id === recoveryOwner.id ) { + await rm( recoveryLockPath, { force: true } ); + } } } @@ -313,15 +594,36 @@ async function restoreSavedConfiguration() { if ( typeof state.lockId !== 'string' || - typeof state.localDir !== 'string' || - typeof state.originalDbName !== 'string' || - ! /^[A-Za-z0-9_-]+$/.test( state.originalDbName ) + ! /^[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' ) { @@ -330,6 +632,7 @@ async function restoreSavedConfiguration() { ); } if ( + legacyConfiguration && state.originalCacheKeySalt !== null && typeof state.originalCacheKeySalt !== 'string' ) { @@ -340,38 +643,62 @@ async function restoreSavedConfiguration() { const localDir = getLocalDir( state.localDir ); - wpCli( - [ 'config', 'set', 'DB_NAME', state.originalDbName, '--type=constant' ], - localDir - ); - - if ( state.originalUploads === null ) { - wpCli( [ 'config', 'delete', 'UPLOADS', '--type=constant' ], localDir ); - } else { + if ( legacyConfiguration ) { wpCli( - [ 'config', 'set', 'UPLOADS', state.originalUploads, '--type=constant' ], + [ 'config', 'set', 'DB_NAME', state.originalDbName, '--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', + '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; } @@ -414,7 +741,8 @@ async function setupE2EDatabase( baseURL ) { const localDir = getLocalDir(); const originalDbName = wpCli( [ 'config', 'get', 'DB_NAME', '--type=constant' ], - localDir + localDir, + ROOT_CONFIG_FILE ); if ( ! /^[A-Za-z0-9_-]+$/.test( originalDbName ) ) { throw new Error( @@ -433,11 +761,22 @@ async function setupE2EDatabase( baseURL ) { '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, }; @@ -445,30 +784,18 @@ async function setupE2EDatabase( baseURL ) { // 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 ], localDir ); + 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; - wpCli( - [ 'config', 'set', 'DB_NAME', E2E_DB_NAME, '--type=constant' ], - localDir - ); - wpCli( - [ 'config', 'set', 'UPLOADS', E2E_UPLOADS, '--type=constant' ], - localDir - ); - wpCli( - [ - 'config', - 'set', - 'WP_CACHE_KEY_SALT', - `e2e-${ randomUUID() }-`, - '--type=constant', - ], - localDir - ); + await createE2EConfig( localDir ); + await addE2EConfigRouter(); wpCli( [ 'core', @@ -480,7 +807,8 @@ async function setupE2EDatabase( baseURL ) { '--admin_email=admin@example.com', '--skip-email', ], - localDir + localDir, + E2E_CONFIG_FILE ); } catch ( error ) { if ( configurationMayBeMutated ) { diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index e281fb20edf8a..d03579bab119e 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -1,7 +1,7 @@ const { test } = require( 'node:test' ); const assert = require( 'node:assert/strict' ); const childProcess = require( 'node:child_process' ); -const { mkdtemp, mkdir, rm } = require( 'node:fs/promises' ); +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' ); @@ -16,9 +16,10 @@ function loadDatabase() { return require( databasePath ); } -test( 'uses the local environment port when classifying a URL', ( t ) => { +test( 'uses a separate local E2E port and classifies local URLs', ( t ) => { const { getBaseURL, isDefaultEnvironment } = 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 ) { @@ -26,6 +27,11 @@ test( 'uses the local environment port when classifying a URL', ( t ) => { } 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 { @@ -34,12 +40,19 @@ test( 'uses the local environment port when classifying a URL', ( t ) => { } ); process.env.LOCAL_PORT = '8899'; + delete process.env.LOCAL_E2E_PORT; delete process.env.WP_BASE_URL; - assert.equal( getBaseURL(), 'http://localhost:8899/' ); - assert.equal( isDefaultEnvironment( 'http://localhost:8899' ), true ); - assert.equal( isDefaultEnvironment( 'http://127.0.0.1:8899' ), true ); + assert.equal( getBaseURL(), '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:8899' ), false ); + assert.equal( isDefaultEnvironment( 'https://localhost:8900' ), false ); + process.env.WP_BASE_URL = 'http://localhost:8899'; + assert.equal( getBaseURL(), '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 ) => { @@ -71,12 +84,20 @@ test( 'isolates database setup and rejects another run in the same checkout', as 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' ), + " { @@ -95,6 +116,9 @@ test( 'isolates database setup and rejects another run in the same checkout', as 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: '' }; } ); @@ -114,12 +138,19 @@ test( 'isolates database setup and rejects another run in the same checkout', as } ); assert.equal( - await database.setupE2EDatabase( 'http://localhost:8899' ), + 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:8899' ), + database.setupE2EDatabase( 'http://localhost:8900' ), /Another E2E run is using this checkout/ ); assert.equal( commands.length, firstRunCommandCount ); @@ -131,6 +162,7 @@ test( 'isolates database setup and rejects another run in the same checkout', as assert.ok( commands.some( ( args ) => args.includes( 'eval' ) && + args.includes( '--url=http://localhost:8899' ) && args.some( ( arg ) => arg.includes( @@ -148,9 +180,154 @@ test( 'isolates database setup and rejects another run in the same checkout', as ); assert.ok( commands.some( ( args ) => - args.includes( 'WP_CACHE_KEY_SALT' ) && args.includes( 'set' ) + args.includes( 'WP_CACHE_KEY_SALT' ) && + args.includes( 'set' ) && + args.some( ( arg ) => arg.includes( 'wp-config-e2e.' ) ) ) ); + assert.ok( + commands.some( ( args ) => + args.includes( 'DB_NAME' ) && + args.includes( 'wordpress_develop_e2e' ) && + args.some( ( arg ) => arg.includes( '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( '--config-file=/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 08442bafbecf6..73f28b0471eff 100644 --- a/tests/e2e/config/global-setup.js +++ b/tests/e2e/config/global-setup.js @@ -19,8 +19,10 @@ import database from './database.js'; const { restoreE2EDatabase, setupE2EDatabase } = database; /** - * @param {import('@playwright/test').FullConfig} config - * @return {Promise} + * Set up the E2E environment. + * + * @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; diff --git a/tests/e2e/config/global-teardown.js b/tests/e2e/config/global-teardown.js index 3652d9207b0f4..0ad483955aa0b 100644 --- a/tests/e2e/config/global-teardown.js +++ b/tests/e2e/config/global-teardown.js @@ -8,6 +8,7 @@ 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 ) { diff --git a/tests/e2e/specs/install.test.js b/tests/e2e/specs/install.test.js index 5110807430361..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', ); diff --git a/tests/e2e/utils/wp-cli.js b/tests/e2e/utils/wp-cli.js index f336ad375d99e..3766260a0456a 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,6 +22,14 @@ 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 ) + ? [ '--config-file=/var/www/wp-config-e2e.php' ] + : []; + const urlArgs = args.some( ( argument ) => argument.startsWith( '--url=' ) ) + ? [] + : [ `--url=${ baseURL }` ]; + return execFileSync( process.execPath, [ @@ -25,6 +40,8 @@ export function wpCli( args, options = {} ) { 'cli', 'wp', `--path=/var/www/${ process.env.LOCAL_DIR ?? 'src' }`, + ...configArgs, + ...urlArgs, ...args, ], { 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`. From 15532303f6400d90988b2efb53faf61a09e7a7d2 Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Thu, 26 Nov 2026 23:46:49 +0530 Subject: [PATCH 6/9] Fix-E2E-CLI-config-selection --- tests/e2e/config/database.js | 3 ++- tests/e2e/config/database.test.cjs | 10 +++++++--- tests/e2e/utils/wp-cli.js | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/tests/e2e/config/database.js b/tests/e2e/config/database.js index 2da483f005129..f8adc69ddd9e2 100644 --- a/tests/e2e/config/database.js +++ b/tests/e2e/config/database.js @@ -121,13 +121,14 @@ function runWpCli( [ 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 ) }`, - `--config-file=/var/www/${ configFile }`, ], { cwd: process.cwd(), diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index d03579bab119e..47dfac12aaba3 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -182,14 +182,18 @@ test( 'isolates database setup and rejects another run in the same checkout', as commands.some( ( args ) => args.includes( 'WP_CACHE_KEY_SALT' ) && args.includes( 'set' ) && - args.some( ( arg ) => arg.includes( 'wp-config-e2e.' ) ) + 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-e2e.' ) ) + args.some( ( arg ) => + arg.includes( 'WP_CONFIG_PATH=/var/www/wp-config-e2e.' ) + ) ) ); assert.ok( @@ -202,7 +206,7 @@ test( 'isolates database setup and rejects another run in the same checkout', as commands.some( ( args ) => args.includes( 'install' ) && args.includes( '--url=http://localhost:8900' ) && - args.includes( '--config-file=/var/www/wp-config-e2e.php' ) + args.includes( 'WP_CONFIG_PATH=/var/www/wp-config-e2e.php' ) ) ); diff --git a/tests/e2e/utils/wp-cli.js b/tests/e2e/utils/wp-cli.js index 3766260a0456a..bc669beedec66 100644 --- a/tests/e2e/utils/wp-cli.js +++ b/tests/e2e/utils/wp-cli.js @@ -24,7 +24,7 @@ const { getBaseURL, isDefaultEnvironment } = database; export function wpCli( args, options = {} ) { const baseURL = getBaseURL(); const configArgs = isDefaultEnvironment( baseURL ) - ? [ '--config-file=/var/www/wp-config-e2e.php' ] + ? [ '--env', 'WP_CONFIG_PATH=/var/www/wp-config-e2e.php' ] : []; const urlArgs = args.some( ( argument ) => argument.startsWith( '--url=' ) ) ? [] From 2aa0d6cd55c4391aeebc6e945a7ab7b69dee7fea Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Fri, 27 Nov 2026 00:06:14 +0530 Subject: [PATCH 7/9] Fix E2E Host Port Routing --- tests/e2e/config/database.test.cjs | 8 ++++++++ tools/local-env/default.template | 1 + 2 files changed, 9 insertions(+) diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index 47dfac12aaba3..b299a090e5818 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -16,6 +16,14 @@ function loadDatabase() { 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 } = loadDatabase(); const originalPort = process.env.LOCAL_PORT; 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; From 4276b3bdcc4baa14eaff15d93bdc1ca014dbb20a Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Fri, 27 Nov 2026 00:15:23 +0530 Subject: [PATCH 8/9] Align E2E Utility Base URL --- tests/e2e/config/database.js | 12 ++++++++++++ tests/e2e/config/database.test.cjs | 5 ++++- tests/e2e/playwright.config.js | 6 +++--- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/tests/e2e/config/database.js b/tests/e2e/config/database.js index f8adc69ddd9e2..69e6cc93b636f 100644 --- a/tests/e2e/config/database.js +++ b/tests/e2e/config/database.js @@ -75,6 +75,17 @@ function getBaseURL() { 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. * @@ -871,5 +882,6 @@ module.exports = { getBaseURL, isDefaultEnvironment, restoreE2EDatabase, + setTestBaseURL, setupE2EDatabase, }; diff --git a/tests/e2e/config/database.test.cjs b/tests/e2e/config/database.test.cjs index b299a090e5818..37864fdf9df6a 100644 --- a/tests/e2e/config/database.test.cjs +++ b/tests/e2e/config/database.test.cjs @@ -25,7 +25,7 @@ test( 'passes the request host, including its port, to PHP', async () => { } ); test( 'uses a separate local E2E port and classifies local URLs', ( t ) => { - const { getBaseURL, isDefaultEnvironment } = loadDatabase(); + 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; @@ -51,6 +51,8 @@ test( 'uses a separate local E2E port and classifies local URLs', ( t ) => { 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 ); @@ -58,6 +60,7 @@ test( 'uses a separate local E2E port and classifies local URLs', ( t ) => { 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/ ); diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 3d2939f770219..2355b626a6813 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -8,11 +8,11 @@ import { defineConfig, devices } from '@playwright/test'; * WordPress dependencies */ const database = require( './config/database.js' ); -const baseConfig = require( '@wordpress/scripts/config/playwright.config' ); -const { getBaseURL, isDefaultEnvironment } = database; +const { isDefaultEnvironment, setTestBaseURL } = database; -const baseURL = getBaseURL(); +const baseURL = setTestBaseURL(); +const baseConfig = require( '@wordpress/scripts/config/playwright.config' ); process.env.WP_ARTIFACTS_PATH ??= path.join( process.cwd(), 'artifacts' ); process.env.STORAGE_STATE_PATH ??= path.join( From 20112bc573c21d74c1ead3c22d9fc41e50c30ddc Mon Sep 17 00:00:00 2001 From: ArkaPrabhaChowdhury Date: Fri, 27 Nov 2026 00:23:11 +0530 Subject: [PATCH 9/9] Fix E2E CLI Environment Option Order --- tests/e2e/utils/wp-cli.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/utils/wp-cli.js b/tests/e2e/utils/wp-cli.js index bc669beedec66..4500422446167 100644 --- a/tests/e2e/utils/wp-cli.js +++ b/tests/e2e/utils/wp-cli.js @@ -35,12 +35,12 @@ export function wpCli( args, options = {} ) { [ join( process.cwd(), 'tools/local-env/scripts/docker.js' ), 'exec', + ...configArgs, '--user', 'wp_php', 'cli', 'wp', `--path=/var/www/${ process.env.LOCAL_DIR ?? 'src' }`, - ...configArgs, ...urlArgs, ...args, ],