diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 392591456..bf157326c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -265,3 +265,88 @@ jobs: name: playwright-artifacts path: artifacts/ retention-days: 7 + + # The same suite against WordPress Playground (PHP compiled to WebAssembly) + # instead of wp-env, so no Docker images, containers or MariaDB. Runs next + # to the wp-env job while the two are compared; see + # tests/e2e/playground/server.mjs. + e2e-playground: + name: E2E (Playwright, Playground) + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # Same reason as the e2e job: `npm ci` runs Composer in postinstall. + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Get Composer cache directory + id: composer-cache + run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT" + + - name: Cache Composer + uses: actions/cache@v4 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-e2e-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer-e2e- + + - name: Install dependencies + run: npm ci + + - name: Get Playwright version + id: playwright-version + run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT" + + - name: Cache Playwright browsers + id: playwright-cache + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }} + + # Playground keeps the downloaded WordPress zip and wp-cli.phar here. + # The key follows the core version in .wp-env.ci.json. + - name: Cache Playground downloads + uses: actions/cache@v4 + with: + path: ~/.wordpress-playground + key: ${{ runner.os }}-wp-playground-${{ hashFiles('.wp-env.ci.json', 'package-lock.json') }} + restore-keys: | + ${{ runner.os }}-wp-playground- + + - name: Install browsers, build assets + env: + PLAYWRIGHT_CACHE_HIT: ${{ steps.playwright-cache.outputs.cache-hit }} + run: | + if [ "$PLAYWRIGHT_CACHE_HIT" = "true" ]; then + npx playwright install-deps chromium + else + npx playwright install --with-deps chromium + fi + + npm run build + + # Starts Playground, runs both Playwright passes, stops Playground. + - name: Run E2E tests + env: + CLOUDINARY_E2E_URL: ${{ secrets.CLOUDINARY_E2E_URL }} + run: npm run test:e2e:playground + + - name: Upload Playwright artifacts + if: failure() + uses: actions/upload-artifact@v4 + with: + name: playwright-artifacts-playground + path: artifacts/ + retention-days: 7 diff --git a/README.md b/README.md index 5c3a10b65..4703e5aae 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,20 @@ The suite runs against the HTTPS tests site. Start it through the npm scripts, w WP_BASE_URL=http://localhost:8889 npm run test:e2e ``` +### Running the tests without Docker (WordPress Playground) + +```bash +npm run test:e2e:playground +``` + +This starts the site in [WordPress Playground](https://wordpress.github.io/wordpress-playground/) (PHP compiled to WebAssembly, SQLite instead of MariaDB), runs the suite against it on `http://localhost:8889`, and stops it. The parallel and `@serial` passes each get a fresh site; see `tests/e2e/playground/run-e2e.sh` for why. It needs no Docker and no `npm run env:start`. Stop wp-env first, because both use port 8889. WordPress core, the PHP version and the `wp-config.php` constants come from `.wp-env.ci.json`. Pass Playwright arguments to run a part of the suite: + +```bash +npm run test:e2e:playground -- tests/e2e/plugin.spec.js +``` + +The specs call WP-CLI through `tests/e2e/utils/wizard.js`. With Playground, that helper sends the commands to a small bridge in `tests/e2e/playground/server.mjs` instead of `docker exec`. The Playground log is in `artifacts/playground.log`. + ### Wizard test credentials `tests/e2e/wizard-setup.spec.js` exercises the live Cloudinary connection flow, so it needs a real connection string. Provide one of two ways: diff --git a/package-lock.json b/package-lock.json index 5f0912866..638ff4c54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,6 +39,7 @@ "@wordpress/hooks": "^5.0.0", "@wordpress/i18n": "^7.0.0", "@wordpress/scripts": "^37.1.0", + "@wp-playground/cli": "^3.1.61", "copy-webpack-plugin": "^14.0.0", "css-loader": "^7.1.5", "css-minimizer-webpack-plugin": "^8.0.0", diff --git a/package.json b/package.json index a244b6bb0..da2677c26 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "test:e2e:parallel": "./.wp-env/scripts/run-e2e.sh --grep-invert @serial", "test:e2e:serial": "./.wp-env/scripts/run-e2e.sh --grep @serial --workers=1", "test:e2e:debug": "./.wp-env/scripts/run-e2e.sh --ui", + "test:e2e:playground": "./tests/e2e/playground/run-e2e.sh", "test:unit": "wp-env run tests-cli --env-cwd=\"wp-content/plugins/$(basename \"$PWD\")\" vendor/bin/phpunit" }, "lint-staged": { @@ -87,6 +88,7 @@ "@wordpress/hooks": "^5.0.0", "@wordpress/i18n": "^7.0.0", "@wordpress/scripts": "^37.1.0", + "@wp-playground/cli": "^3.1.61", "copy-webpack-plugin": "^14.0.0", "css-loader": "^7.1.5", "css-minimizer-webpack-plugin": "^8.0.0", diff --git a/tests/e2e/cloudinary-gallery-delivery.spec.js b/tests/e2e/cloudinary-gallery-delivery.spec.js index b5bf6bedd..17633c587 100644 --- a/tests/e2e/cloudinary-gallery-delivery.spec.js +++ b/tests/e2e/cloudinary-gallery-delivery.spec.js @@ -190,6 +190,15 @@ test.describe( 'Cloudinary Gallery block delivery', { tag: '@serial' }, () => { } ) => { await admin.editPost( created.postId ); + // editPost() returns before the editor has parsed the post content, + // so wait for the block to reach the store before reading it. + await page.waitForFunction( () => + window.wp?.data + ?.select( 'core/block-editor' ) + .getBlocks() + .some( ( b ) => b.name === 'cloudinary/gallery' ) + ); + // Select the block through the data store. Clicking it in the canvas // would hit the widget's own buttons inside the block. const clientId = await page.evaluate( () => { diff --git a/tests/e2e/cloudinary-video-delivery.spec.js b/tests/e2e/cloudinary-video-delivery.spec.js index 45efe4504..84ca9f164 100644 --- a/tests/e2e/cloudinary-video-delivery.spec.js +++ b/tests/e2e/cloudinary-video-delivery.spec.js @@ -65,6 +65,13 @@ function setVideoPlayer( value ) { 'update_option("cloudinary_media_display", array_merge((array) get_option("cloudinary_media_display", array()), array("video_player" => "' + value + '")));'; + + // Playground has no container; the helper applies its own timeout. + if ( process.env.WP_E2E_RUNTIME === 'playground' ) { + wpCli( [ 'eval', `'${ php }'` ] ); + return; + } + const cmd = [ 'docker', 'exec', diff --git a/tests/e2e/playground/run-e2e.sh b/tests/e2e/playground/run-e2e.sh new file mode 100755 index 000000000..8a62b24d2 --- /dev/null +++ b/tests/e2e/playground/run-e2e.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# Run the e2e suite against WordPress Playground instead of wp-env. +# +# Starts tests/e2e/playground/server.mjs in the background, waits until its +# WP-CLI bridge answers, runs Playwright, then stops the server. The +# Playground log is written to artifacts/playground.log. +# +# Without arguments, runs the passes of `npm run test:e2e`, each against a +# fresh site: +# +# - The parallel pass, 6 PHP workers. +# - The @serial pass without the storage-modes spec, 6 PHP workers. +# - The storage-modes spec, 1 PHP worker. It checks local files after a +# sync, and with more than one worker a deleted file can still look present +# to another worker (see the `workers` comment in server.mjs). Other specs +# stay on 6 workers, because with 1 the block editor saves too slowly on CI +# runners. +# +# With arguments, starts one site with 1 PHP worker and passes the arguments +# to Playwright, e.g. a single spec file. +# +# Usage: tests/e2e/playground/run-e2e.sh [playwright args] + +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +cd "$PROJECT_DIR" + +export WP_E2E_RUNTIME=playground +export WP_PLAYGROUND_PORT="${WP_PLAYGROUND_PORT:-8889}" +export WP_PLAYGROUND_CLI_PORT="${WP_PLAYGROUND_CLI_PORT:-8890}" +export WP_BASE_URL="http://localhost:${WP_PLAYGROUND_PORT}" + +LOG_FILE="$PROJECT_DIR/artifacts/playground.log" +mkdir -p "$(dirname "$LOG_FILE")" +: > "$LOG_FILE" + +server_pid="" + +stop_server() { + if [ -n "$server_pid" ]; then + kill "$server_pid" 2> /dev/null || true + wait "$server_pid" 2> /dev/null || true + server_pid="" + fi +} +trap stop_server EXIT + +# Starts a fresh site and waits until the WP-CLI bridge, which starts +# listening only after WordPress has booted, is up. +# +# $1: number of PHP workers. +start_server() { + local start_line + start_line=$(($(wc -l < "$LOG_FILE") + 1)) + + WP_PLAYGROUND_WORKERS="$1" node tests/e2e/playground/server.mjs >> "$LOG_FILE" 2>&1 & + server_pid=$! + + for _ in $(seq 1 180); do + if ! kill -0 "$server_pid" 2> /dev/null; then + echo "Playground exited during startup:" >&2 + tail -n "+$start_line" "$LOG_FILE" >&2 + exit 1 + fi + if tail -n "+$start_line" "$LOG_FILE" | grep -q "Playground ready"; then + tail -n "+$start_line" "$LOG_FILE" | grep "Playground ready" + return + fi + sleep 1 + done + + echo "Playground did not start within 180s:" >&2 + tail -n "+$start_line" "$LOG_FILE" >&2 + exit 1 +} + +if [ "$#" -gt 0 ]; then + start_server 1 + ./.wp-env/scripts/run-e2e.sh "$@" + exit +fi + +STORAGE_SPEC="tests/e2e/cloudinary-storage-modes.spec.js" + +# Unlike `npm run test:e2e`, run every pass even when one fails, so one CI +# run reports every failure. Exit non-zero if any failed. +status=0 + +start_server 6 +npm run --silent test:e2e:parallel || status=1 +stop_server + +start_server 6 +./.wp-env/scripts/run-e2e.sh --grep @serial --workers=1 \ + --grep-invert "Cloudinary storage modes" || status=1 +stop_server + +start_server 1 +./.wp-env/scripts/run-e2e.sh "$STORAGE_SPEC" --workers=1 || status=1 +stop_server + +exit "$status" diff --git a/tests/e2e/playground/server.mjs b/tests/e2e/playground/server.mjs new file mode 100644 index 000000000..333408887 --- /dev/null +++ b/tests/e2e/playground/server.mjs @@ -0,0 +1,211 @@ +/** + * Boots the e2e WordPress site in WordPress Playground (PHP compiled to + * WebAssembly), as a Docker-free alternative to wp-env. + * + * Two servers are started: + * + * - The WordPress site, on WP_PLAYGROUND_PORT (default 8889, the same port + * wp-env's tests site uses, so WP_BASE_URL does not change). + * - A WP-CLI bridge on WP_PLAYGROUND_CLI_PORT (default 8890), bound to + * 127.0.0.1. Playground has no container to `docker exec` into, so + * tests/e2e/utils/wizard.js sends WP-CLI commands here instead. See + * ./wp-cli-client.js. + * + * WordPress core, the PHP version and the wp-config constants are read from + * .wp-env.ci.json so both runtimes test the same thing. + * + * Usage: node tests/e2e/playground/server.mjs + */ + +import { runCLI } from '@wp-playground/cli'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const PROJECT_DIR = path.resolve( + path.dirname( fileURLToPath( import.meta.url ) ), + '../../..' +); +const PLUGIN_SLUG = path.basename( PROJECT_DIR ); +const PORT = Number( process.env.WP_PLAYGROUND_PORT || 8889 ); +const CLI_PORT = Number( process.env.WP_PLAYGROUND_CLI_PORT || 8890 ); +const SITE_URL = `http://localhost:${ PORT }`; +const WP_CLI_PHAR = '/tmp/wp-cli.phar'; + +const wpEnvConfig = JSON.parse( + fs.readFileSync( path.join( PROJECT_DIR, '.wp-env.ci.json' ), 'utf8' ) +); +const testsEnv = wpEnvConfig.env?.tests ?? {}; + +const startedAt = Date.now(); + +const server = await runCLI( { + command: 'server', + port: PORT, + 'site-url': SITE_URL, + php: testsEnv.phpVersion || wpEnvConfig.phpVersion || '8.2', + wp: wpEnvConfig.core || 'latest', + // Each PHP worker keeps its own cached view of the mounted filesystem. + // With @wp-playground/cli 3.1.61, a file that one worker deletes can still + // look present to another: file_exists() is true but filesize() fails + // with "stat failed". Specs that check local files must use 1 worker; + // run-e2e.sh sets this per Playwright pass. + workers: Number( process.env.WP_PLAYGROUND_WORKERS || 6 ), + mount: [ + { + hostPath: PROJECT_DIR, + vfsPath: `/wordpress/wp-content/plugins/${ PLUGIN_SLUG }`, + }, + { + hostPath: path.join( PROJECT_DIR, '.wp-env/mu-plugins' ), + vfsPath: '/wordpress/wp-content/mu-plugins', + }, + ], + blueprint: { + extraLibraries: [ 'wp-cli' ], + steps: [ + { + step: 'defineWpConfigConsts', + consts: { + ...( wpEnvConfig.config || {} ), + ...( testsEnv.config || {} ), + }, + }, + { + step: 'activatePlugin', + pluginPath: `/wordpress/wp-content/plugins/${ PLUGIN_SLUG }`, + }, + ], + }, +} ); + +/** + * Runs one WP-CLI command inside Playground. + * + * Everything happens in a single PHP request, so it runs on one Playground + * worker. That matters for `evalFile`: each worker has its own /tmp, so a file + * written there by a separate call might not be visible to the worker that + * runs the command. + * + * @param {Object} payload + * @param {string[]} payload.args WP-CLI arguments after `wp`. + * @param {string} [payload.worker] Playwright worker marker, see tests/e2e/fixtures.js. + * @param {string} [payload.evalFile] PHP source for `wp eval-file`. The file path is appended to `args`. + * @return {Promise<{exitCode: number, stdout: string, stderr: string}>} Result. + */ +async function runWpCli( { args, worker, evalFile } ) { + const argv = [ ...args ]; + let evalPath = ''; + + if ( typeof evalFile === 'string' ) { + evalPath = `/tmp/cld-e2e-eval-${ Date.now() }-${ Math.random() + .toString( 36 ) + .slice( 2 ) }.php`; + argv.push( evalPath ); + } + + // Playground runs PHP as a web SAPI, which prints warnings as HTML on + // stdout. Under the real CLI SAPI they go to stderr as plain text, and + // specs that JSON.parse() the output depend on that. + const php = ` { + if ( req.method !== 'POST' || req.url !== '/wp-cli' ) { + res.writeHead( 404 ).end(); + return; + } + + let body = ''; + req.on( 'data', ( chunk ) => ( body += chunk ) ); + req.on( 'end', async () => { + try { + const result = await runWpCli( JSON.parse( body ) ); + res.writeHead( 200, { 'content-type': 'application/json' } ); + res.end( JSON.stringify( result ) ); + } catch ( error ) { + res.writeHead( 500, { 'content-type': 'application/json' } ); + res.end( + JSON.stringify( { + exitCode: 1, + stdout: '', + stderr: String( error?.stack || error ), + } ) + ); + } + } ); +} ); + +cliServer.listen( CLI_PORT, '127.0.0.1', () => { + console.log( + `Playground ready in ${ Math.round( + ( Date.now() - startedAt ) / 1000 + ) }s: site ${ SITE_URL }, WP-CLI bridge http://127.0.0.1:${ CLI_PORT }` + ); +} ); + +async function shutdown() { + cliServer.close(); + await server[ Symbol.asyncDispose ](); + process.exit( 0 ); +} + +process.on( 'SIGINT', shutdown ); +process.on( 'SIGTERM', shutdown ); diff --git a/tests/e2e/playground/wp-cli-client.js b/tests/e2e/playground/wp-cli-client.js new file mode 100644 index 000000000..78ef9ca2e --- /dev/null +++ b/tests/e2e/playground/wp-cli-client.js @@ -0,0 +1,48 @@ +/** + * Sends one WP-CLI command to the bridge in ./server.mjs and prints the result. + * + * Run as a child process by tests/e2e/utils/wizard.js. The e2e helpers are + * synchronous (they used `execSync( 'docker exec ...' )`), and running this + * script through `execFileSync` keeps them that way without changing every + * call site. + * + * Reads the JSON request from stdin, writes the command's stdout to stdout and + * its stderr to stderr, and exits with the command's exit code. + */ + +const http = require( 'http' ); + +const CLI_PORT = Number( process.env.WP_PLAYGROUND_CLI_PORT || 8890 ); + +let body = ''; +process.stdin.on( 'data', ( chunk ) => ( body += chunk ) ); +process.stdin.on( 'end', () => { + const req = http.request( + { + host: '127.0.0.1', + port: CLI_PORT, + path: '/wp-cli', + method: 'POST', + headers: { 'content-type': 'application/json' }, + }, + ( res ) => { + let raw = ''; + res.on( 'data', ( chunk ) => ( raw += chunk ) ); + res.on( 'end', () => { + const result = JSON.parse( raw ); + process.stdout.write( result.stdout ); + process.stderr.write( result.stderr ); + process.exitCode = result.exitCode; + } ); + } + ); + + req.on( 'error', ( error ) => { + process.stderr.write( + `Could not reach the Playground WP-CLI bridge on port ${ CLI_PORT }. Start it with \`npm run env:playground\`.\n${ error.message }\n` + ); + process.exitCode = 1; + } ); + + req.end( body ); +} ); diff --git a/tests/e2e/utils/wizard.js b/tests/e2e/utils/wizard.js index ebcc98c0e..9dd992559 100644 --- a/tests/e2e/utils/wizard.js +++ b/tests/e2e/utils/wizard.js @@ -10,9 +10,13 @@ * latter routes through `got` → `api.wordpress.org` at startup and * times out on macOS due to an IPv6 resolution issue. `docker exec` * goes straight to the running container. + * + * When WP_E2E_RUNTIME=playground, the site runs in WordPress Playground + * (tests/e2e/playground/server.mjs) and there is no container. Commands go to + * that server's WP-CLI bridge instead; see runPlaygroundCli(). */ -const { execSync } = require( 'child_process' ); +const { execFileSync, execSync } = require( 'child_process' ); const fs = require( 'fs' ); const os = require( 'os' ); const path = require( 'path' ); @@ -21,8 +25,102 @@ const CONNECT_OPTION = 'cloudinary_connect'; const SIGNATURE_OPTION = 'cloudinary_connection_signature'; const STATUS_OPTION = 'cloudinary_status'; +const IS_PLAYGROUND = process.env.WP_E2E_RUNTIME === 'playground'; + +const PLAYGROUND_CLIENT = path.join( + __dirname, + '../playground/wp-cli-client.js' +); + let cachedCliContainer = null; +/** + * Splits a shell command line into arguments, the way a POSIX shell would for + * the quoting the specs use: single quotes are literal, double quotes allow + * backslash escapes, and whitespace outside quotes separates arguments. + * + * Callers build arguments for `docker exec` through a shell, so they quote + * values such as `'{"plan":"free"}'`. Splitting the joined command line again + * gives Playground the same argv the shell would have produced. + * + * @param {string} line Command line. + * @return {string[]} Arguments. + */ +function splitShellWords( line ) { + const words = []; + let current = ''; + let inWord = false; + let quote = null; + + for ( let i = 0; i < line.length; i++ ) { + const char = line[ i ]; + + if ( quote === "'" ) { + if ( char === "'" ) { + quote = null; + } else { + current += char; + } + } else if ( quote === '"' ) { + if ( char === '"' ) { + quote = null; + } else if ( char === '\\' && /["\\$`]/.test( line[ i + 1 ] ) ) { + current += line[ ++i ]; + } else { + current += char; + } + } else if ( char === "'" || char === '"' ) { + quote = char; + inWord = true; + } else if ( char === '\\' && i + 1 < line.length ) { + current += line[ ++i ]; + inWord = true; + } else if ( /\s/.test( char ) ) { + if ( inWord ) { + words.push( current ); + current = ''; + inWord = false; + } + } else { + current += char; + inWord = true; + } + } + + if ( inWord ) { + words.push( current ); + } + + return words; +} + +/** + * Runs a WP-CLI command through the Playground server's WP-CLI bridge. + * + * The bridge client runs as a child process so this stays synchronous, like + * the `docker exec` path. A failed command throws, as execSync does. + * + * @param {string[]} args Shell-quoted WP-CLI arguments after `wp`. + * @param {string} [evalFile] PHP source to run with `wp eval-file`. + * @return {string} stdout, trimmed. + */ +function runPlaygroundCli( args, evalFile ) { + const request = { + args: splitShellWords( args.join( ' ' ) ), + worker: process.env.CLD_E2E_WORKER, + evalFile, + }; + + return execFileSync( process.execPath, [ PLAYGROUND_CLIENT ], { + input: JSON.stringify( request ), + encoding: 'utf8', + stdio: [ 'pipe', 'pipe', 'pipe' ], + // Same reason as the docker path in cloudinary-video-delivery.spec.js: + // a synchronous call cannot be interrupted by Playwright's timeout. + timeout: 120_000, + } ).trim(); +} + /** * Find the wp-env CLI container name dynamically. * @@ -79,6 +177,10 @@ function workerEnvFlags() { * @return {string} stdout, trimmed. */ function wpCli( args ) { + if ( IS_PLAYGROUND ) { + return runPlaygroundCli( args ); + } + const container = getCliContainer(); const cmd = [ 'docker', @@ -108,6 +210,13 @@ function wpCli( args ) { * @return {string} stdout, trimmed. */ function wpEvalFile( phpCode ) { + if ( IS_PLAYGROUND ) { + return runPlaygroundCli( + [ 'eval-file' ], + `