From 68d9497a8e4731d4698b4acf2705ba33a68dab20 Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Fri, 4 Dec 2026 00:18:02 +0000 Subject: [PATCH] fix(phpunit): reset project-mode database to core's test-install state --- docs/recipe-contract.md | 8 ++ .../src/phpunit-command-handlers.ts | 54 ++++++++--- .../src/phpunit-command-semantics.ts | 9 ++ .../src/wordpress-command-runners.ts | 12 +-- scripts/smoke-discovery.ts | 1 + tests/phpunit-project-autoload.test.ts | 35 +++++++- ...-project-install-state.integration.test.ts | 90 +++++++++++++++++++ 7 files changed, 192 insertions(+), 17 deletions(-) create mode 100644 tests/playground-phpunit-project-install-state.integration.test.ts diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 0603330c..b0a2bfc4 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -1042,6 +1042,14 @@ runners. In project bootstrap mode, the runner detects the PHPUnit version loade by the project's autoloader. PHPUnit 9.6, 10, 11, and 12 use the same recipe arguments and structured result format. +Before a project-mode PHPUnit run, the runner executes `testsDir`'s +`includes/install.php` in a separate request against `wptests_` tables, the step +core's `includes/bootstrap.php` would run as a shell command. The project +bootstrap then loads with `WP_TESTS_SKIP_INSTALL=1`, so suites start from core's +test install state: plain permalinks (`permalink_structure` is `''`), flushed +rewrite rules, and the `example.org` test site. If `testsDir` has no +`includes/install.php`, the run uses the existing Playground site instead. + ```json { "pluginSlug": "woocommerce", diff --git a/packages/runtime-playground/src/phpunit-command-handlers.ts b/packages/runtime-playground/src/phpunit-command-handlers.ts index f6223600..66448a15 100644 --- a/packages/runtime-playground/src/phpunit-command-handlers.ts +++ b/packages/runtime-playground/src/phpunit-command-handlers.ts @@ -38,7 +38,7 @@ export interface PhpunitRunCodeOptions { junitFile?: string } -export type PhpunitMultisitePreinstallCodeOptions = Pick +export type PhpunitTestInstallCodeOptions = Pick export interface CorePhpunitRunCodeOptions { coreRoot: string @@ -481,7 +481,16 @@ CONFIG; }` } -export function phpunitMultisitePreinstallCode(options: PhpunitMultisitePreinstallCodeOptions): string { +/** + * Runs wp-phpunit's own includes/install.php in a separate Playground request. + * + * This is the in-sandbox equivalent of the \`system( php install.php ... )\` call in + * core's tests/phpunit/includes/bootstrap.php, which Playground cannot spawn. The + * following PHPUnit request then boots with WP_TESTS_SKIP_INSTALL=1 against the + * database state core's test install leaves (plain permalinks, test user, default + * theme, and the network tables for multisite). + */ +export function phpunitTestInstallCode(options: PhpunitTestInstallCodeOptions): string { const wpConfigDefines = { ...options.wpConfigDefines } for (const name of ["MULTISITE", "SUBDOMAIN_INSTALL", "DOMAIN_CURRENT_SITE", "PATH_CURRENT_SITE", "SITE_ID_CURRENT_SITE", "BLOG_ID_CURRENT_SITE", "WPMU_PLUGIN_DIR"]) { delete wpConfigDefines[name] @@ -496,6 +505,7 @@ $bench_env = json_decode(${JSON.stringify(JSON.stringify(options.env))}, true); $wp_config_defines = json_decode(${JSON.stringify(JSON.stringify(wpConfigDefines))}, true); $database_type = ${JSON.stringify(options.databaseType)}; $result_file = ${JSON.stringify(options.resultFile ?? PLUGIN_PHPUNIT_RESULT_FILE)}; +$multisite = ${JSON.stringify(options.multisite)}; $preinstall_complete = false; @file_put_contents($result_file, ''); @@ -504,6 +514,11 @@ function pg_preinstall_log(string $marker): void { @file_put_contents($result_file, 'PREINSTALL:' . $marker . "\n", FILE_APPEND); } pg_preinstall_log('start'); +if (!is_readable($tests_dir . '/includes/install.php')) { + // Without the WordPress test library there is no core test install to run. + pg_preinstall_log('installer-unavailable:' . $tests_dir); + return; +} register_shutdown_function(static function () use (&$preinstall_complete, $result_file): void { if ($preinstall_complete) { return; @@ -521,21 +536,29 @@ ${managedPhpunitConfigWriterPhp()} pg_apply_env($bench_env); pg_preinstall_log('environment-applied'); if (!is_dir('/tmp/wp-codebox-preinstall-mu-plugins') && !mkdir('/tmp/wp-codebox-preinstall-mu-plugins', 0700, true) && !is_dir('/tmp/wp-codebox-preinstall-mu-plugins')) { - throw new RuntimeException('Could not create isolated multisite preinstall mu-plugin directory.'); + throw new RuntimeException('Could not create isolated PHPUnit test install mu-plugin directory.'); } pg_preinstall_log('mu-plugin-directory-ready'); $config_path = pg_write_managed_test_config($wp_config_defines, 'wptests_', $database_type); pg_preinstall_log('config-written'); -if (!defined('WP_TESTS_MULTISITE')) { +if ($multisite && !defined('WP_TESTS_MULTISITE')) { define('WP_TESTS_MULTISITE', true); } -$argv = array('install.php', $config_path, 'run_ms_tests', 'no_core_tests'); +$argv = array('install.php', $config_path, $multisite ? 'run_ms_tests' : 'no_ms_tests', 'no_core_tests'); $_SERVER['argv'] = $argv; $_SERVER['argc'] = count($argv); try { pg_preinstall_log('before-installer-include'); require $tests_dir . '/includes/install.php'; - pg_preinstall_log('installer-blogs:' . implode(',', array_map('strval', (array) $wpdb->get_col("SELECT blog_id FROM {\$wpdb->blogs} ORDER BY blog_id")))); + // Core's single-site branch deletes permalink_structure while its multisite branch + // stores ''. Store '' in both and flush the rewrite rules wp_install() generated for + // the temporary pretty structure, so suites see plain permalinks either way. + $GLOBALS['wp_rewrite']->set_permalink_structure(''); + flush_rewrite_rules(false); + pg_preinstall_log('permalink-structure:' . var_export(get_option('permalink_structure'), true)); + if ($multisite) { + pg_preinstall_log('installer-blogs:' . implode(',', array_map('strval', (array) $wpdb->get_col("SELECT blog_id FROM {\$wpdb->blogs} ORDER BY blog_id")))); + } $preinstall_complete = true; pg_preinstall_log('installer-complete'); } catch (Throwable $error) { @@ -1067,11 +1090,19 @@ function pg_prepare_project_bootstrap_environment(string $config_path): void { } } -function pg_skip_project_bootstrap_shell_install(): void { +function pg_project_test_install_available(string $tests_dir): bool { + return is_readable(rtrim($tests_dir, '/') . '/includes/install.php'); +} + +function pg_skip_project_bootstrap_shell_install(bool $test_install_available): void { putenv('WP_TESTS_SKIP_INSTALL=1'); $_ENV['WP_TESTS_SKIP_INSTALL'] = '1'; $_SERVER['WP_TESTS_SKIP_INSTALL'] = '1'; - pg_log('NOTICE:using existing Playground install; project bootstrap shell install skipped'); + if ($test_install_available) { + pg_log('NOTICE:core test install ran in a separate request; project bootstrap shell install skipped'); + } else { + pg_log('NOTICE:WordPress test library installer unavailable; using existing Playground install; project bootstrap shell install skipped'); + } } function pg_run_project_bootstrap_stage(array $cfg): string { @@ -1445,10 +1476,13 @@ if ($autoload_file_role === '' && $bootstrap_mode === 'project' && $project_auto } $harness_autoload_file = $legacy_project_autoload_file !== '' ? '/wp-codebox-vendor/autoload.php' : $autoload_file; -$config_path = pg_run_boot_stage(array('extra_defines' => $wp_config_defines, 'table_prefix' => $bootstrap_mode === 'project' ? 'wp_' : 'wptests_', 'autoload_file' => $harness_autoload_file, 'autoload_required' => $bootstrap_mode !== 'project' || $harness_autoload_file !== '', 'database_type' => $database_type)); +// Project mode boots the tables written by the separate core test install request. +// Only a project without the WordPress test library falls back to the Playground site. +$project_test_install_available = $bootstrap_mode === 'project' && pg_project_test_install_available($tests_dir); +$config_path = pg_run_boot_stage(array('extra_defines' => $wp_config_defines, 'table_prefix' => $bootstrap_mode === 'project' && !$project_test_install_available ? 'wp_' : 'wptests_', 'autoload_file' => $harness_autoload_file, 'autoload_required' => $bootstrap_mode !== 'project' || $harness_autoload_file !== '', 'database_type' => $database_type)); if ($bootstrap_mode === 'project') { pg_prepare_project_bootstrap_environment($config_path); - pg_skip_project_bootstrap_shell_install(); + pg_skip_project_bootstrap_shell_install($project_test_install_available); // Match vendor/bin/phpunit: load the explicit Composer autoloader before bootstrap. pg_run_project_autoload_stage($project_autoload_file); $phpunit_child_bootstrap = pg_run_project_bootstrap_stage(array('project_bootstrap' => $project_bootstrap, 'phpunit_xml' => ${JSON.stringify(options.phpunitXml)}, 'phpunit_xml_is_default' => ${JSON.stringify(options.phpunitXmlIsDefault)})); diff --git a/packages/runtime-playground/src/phpunit-command-semantics.ts b/packages/runtime-playground/src/phpunit-command-semantics.ts index f3b42cf5..77294aa8 100644 --- a/packages/runtime-playground/src/phpunit-command-semantics.ts +++ b/packages/runtime-playground/src/phpunit-command-semantics.ts @@ -29,3 +29,12 @@ export function requiresManagedMultisitePreinstall(args: string[], runtimeSpec: || semantics.databaseType === "mdi-native" ) } + +/** + * Whether wordpress.phpunit runs wp-phpunit's install.php in a separate request + * before the PHPUnit request. Project mode always does, because core's bootstrap + * would shell out to install.php and Playground cannot spawn that process. + */ +export function requiresSeparatePhpunitTestInstall(args: string[], runtimeSpec: Pick): boolean { + return phpunitExecutionSemantics(args, runtimeSpec).bootstrapMode === "project" || requiresManagedMultisitePreinstall(args, runtimeSpec) +} diff --git a/packages/runtime-playground/src/wordpress-command-runners.ts b/packages/runtime-playground/src/wordpress-command-runners.ts index fdd9d2a0..07285f76 100644 --- a/packages/runtime-playground/src/wordpress-command-runners.ts +++ b/packages/runtime-playground/src/wordpress-command-runners.ts @@ -30,7 +30,7 @@ import { restPerformanceObservationInputFromArgs, restPerformanceObservationPhpCode, phpunitRunCode, - phpunitMultisitePreinstallCode, + phpunitTestInstallCode, pluginStateInputFromArgs, pluginStatePhpCode, PLUGIN_PHPUNIT_RESULT_FILE, @@ -54,7 +54,7 @@ import { bootstrapAbilityPhpCode, bootstrapPhpCode, phpCodeFromArgs, splitLeadin import { assertPlaygroundResponseOk, attachPlaygroundDiagnostics, completedPlaygroundCommandError, playgroundCommandDiagnosticText, type PlaygroundRunResponse } from "./playground-command-errors.js" import type { PlaygroundCliServer } from "./preview-server.js" import { clearPluginPhpunitJunitResult, persistCorePhpunitResult, persistPluginPhpunitCompletedResult, persistPluginPhpunitJunitResult, persistPluginPhpunitResult, persistVfsDiagnosticFileToHost, phpunitJunitCaptureDiagnostic, readCorePhpunitDiagnostic, readPluginPhpunitCompletedResult, readPluginPhpunitDiagnostic, readPluginPhpunitDiscoveryResult } from "./runtime-diagnostics.js" -import { phpunitExecutionSemantics, requiresManagedMultisitePreinstall } from "./phpunit-command-semantics.js" +import { phpunitExecutionSemantics, requiresManagedMultisitePreinstall, requiresSeparatePhpunitTestInstall } from "./phpunit-command-semantics.js" import { parsePhpunitOutput } from "./phpunit-test-results.js" import { runRuntimeExternalHttpLoad, waitForRuntimePreviewReady, type RuntimeExternalHttpLoadResult } from "./external-http-load.js" import type { RuntimeWpCliBridge } from "./runtime-wp-cli-bridge.js" @@ -966,6 +966,7 @@ export async function runPhpunitCommand({ const autoloadFile = argValue(args, "autoload-file")?.trim() || (bootstrapMode === "project" ? "" : "/wp-codebox-vendor/autoload.php") const autoloadFileRole = argValue(args, "autoload-file-role")?.trim() === "harness" ? "harness" : undefined const managedMultisitePreinstalled = !explicitCode && !discoveryOnly && requiresManagedMultisitePreinstall(args, runtimeSpec) + const separateTestInstall = !explicitCode && !discoveryOnly && requiresSeparatePhpunitTestInstall(args, runtimeSpec) const resultFile = processIdentity ? `/tmp/wp-codebox-phpunit-result-${processIdentity}.txt` : PLUGIN_PHPUNIT_RESULT_FILE const diagnosticHostFile = `/wordpress/wp-content/plugins/${pluginSlug}/.pg-test-result${processIdentity ? `-${processIdentity}` : ""}.txt` const code = explicitCode ? await phpCodeFromArgs(args, "wordpress.phpunit", false) : phpunitRunCode({ @@ -1010,16 +1011,17 @@ export async function runPhpunitCommand({ let response: PlaygroundRunResponse try { const bootstrapArgs = explicitCode ? args : [...args, "bootstrap=runtime-only"] - if (managedMultisitePreinstalled) { - const preinstallCode = phpunitMultisitePreinstallCode({ + if (separateTestInstall) { + const preinstallCode = phpunitTestInstallCode({ testsDir: argValue(args, "tests-dir")?.trim() || "/wp-codebox-vendor/wp-phpunit/wp-phpunit", env: jsonObjectArg(args, "env-json"), wpConfigDefines: jsonObjectArg(args, "wp-config-defines-json"), databaseType, + multisite, resultFile, }) const preinstallResponse = await runPlaygroundCommand("wordpress.phpunit", server, { code: bootstrapPhpCode(runtimeSpec, preinstallCode, ["recipe-active-plugins=none", ...bootstrapArgs]) }) - assertPlaygroundResponseOk("wordpress.phpunit multisite preinstall", preinstallResponse) + assertPlaygroundResponseOk(multisite ? "wordpress.phpunit multisite preinstall" : "wordpress.phpunit test install", preinstallResponse) } response = await runPlaygroundCommand("wordpress.phpunit", server, { code: bootstrapPhpCode(runtimeSpec, code, bootstrapArgs, undefined, resultFile) }) } catch (error) { diff --git a/scripts/smoke-discovery.ts b/scripts/smoke-discovery.ts index 70fc8fbe..e81bbbfb 100644 --- a/scripts/smoke-discovery.ts +++ b/scripts/smoke-discovery.ts @@ -38,6 +38,7 @@ const INTEGRATION_FILES: readonly string[] = [ "tests/execute-native-agent-task-playground-e2e.test.ts", "tests/playground-custom-archive-cache-process.test.ts", "tests/playground-phpunit-modern.integration.test.ts", + "tests/playground-phpunit-project-install-state.integration.test.ts", "tests/playground-readonly-mounts.test.ts", "tests/runtime-sources-playground-integration.test.ts", ] diff --git a/tests/phpunit-project-autoload.test.ts b/tests/phpunit-project-autoload.test.ts index 72fb83b6..8effe404 100644 --- a/tests/phpunit-project-autoload.test.ts +++ b/tests/phpunit-project-autoload.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path" import { buildWordPressPhpunitRecipe } from "../packages/runtime-core/src/recipe-builders.js" import { playgroundWpConfigConstants } from "../packages/runtime-playground/src/blueprint.js" -import { corePhpunitRunCode, phpunitMultisitePreinstallCode, phpunitRunCode } from "../packages/runtime-playground/src/phpunit-command-handlers.js" +import { corePhpunitRunCode, phpunitTestInstallCode, phpunitRunCode } from "../packages/runtime-playground/src/phpunit-command-handlers.js" import { runPhpunitCommand } from "../packages/runtime-playground/src/wordpress-command-runners.js" import { phpunitExecutionSemantics, requiresManagedMultisitePreinstall } from "../packages/runtime-playground/src/phpunit-command-semantics.js" import { recipePolicy } from "../packages/cli/src/recipe-validation.js" @@ -745,11 +745,12 @@ assert.equal(requiresManagedMultisitePreinstall(["database-type=mdi-native", "mu assert.equal(requiresManagedMultisitePreinstall(["multisite=false"], { environment: { kind: "wordpress", name: "test", version: "latest", databaseSetup: "external" }, runtimeEnv: { DB_HOST: "db" } }), false) assert.equal(requiresManagedMultisitePreinstall(["database-type=mdi-native", "multisite=yes", "bootstrap-mode=project"], { environment: { kind: "wordpress", name: "test", version: "latest", databaseSetup: "custom-drop-in" } }), false) -const preinstallCode = phpunitMultisitePreinstallCode({ +const preinstallCode = phpunitTestInstallCode({ testsDir: "/wp-codebox-vendor/wp-phpunit/wp-phpunit", env: {}, wpConfigDefines: { ...wpConfigDefines, MULTISITE: true, DOMAIN_CURRENT_SITE: "example.org" }, databaseType: "mysql", + multisite: true, resultFile: "/tmp/preinstall-result.txt", }) assert.ok(preinstallCode.includes("'run_ms_tests'"), "multisite preinstall selects wp-phpunit's network installer") @@ -810,6 +811,36 @@ assert.ok(nativeMultisiteInvocations[0].includes("'run_ms_tests'")) assert.ok(nativeMultisiteInvocations[0].includes("'MARKDOWN_DB_BACKEND' => 'mdi-native'")) assert.ok(nativeMultisiteInvocations[1].includes("$managed_multisite_preinstalled = true")) +const singleSiteInstallCode = phpunitTestInstallCode({ + testsDir: "/wordpress/wp-content/plugins/demo-plugin/vendor/wp-phpunit/wp-phpunit", + env: {}, + wpConfigDefines: {}, + databaseType: "sqlite", + multisite: false, + resultFile: "/tmp/preinstall-result.txt", +}) +assert.ok(singleSiteInstallCode.includes("$multisite = false;"), "single-site test install runs core's installer without the network") +assert.ok(singleSiteInstallCode.includes("installer-unavailable:"), "test install is skipped when the WordPress test library is absent") + +const projectInvocations: string[] = [] +await runPhpunitCommand({ + artifactRoot: mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-project-install-")), + mounts: [], + runPlaygroundCommand: async (_command, _server, input) => { + projectInvocations.push(decodedBootstrapWrapper(input.code)) + return { text: "ok", exitCode: 0 } + }, + runtimeSpec: phpunitRuntimeSpec, + server: { playground: {} } as never, + spec: { command: "wordpress.phpunit", args: ["plugin-slug=demo-plugin", "bootstrap-mode=project", "tests-dir=/wordpress/wp-content/plugins/demo-plugin/vendor/wp-phpunit/wp-phpunit"] }, +}) +assert.equal(projectInvocations.length, 2, "project mode runs core's test install in a separate request before PHPUnit") +assert.ok(projectInvocations[0].includes("require $tests_dir . '/includes/install.php'"), "project mode reuses wp-phpunit's own installer") +assert.ok(projectInvocations[0].includes("$multisite = false;")) +assert.ok(projectInvocations[0].includes("pg_write_managed_test_config($wp_config_defines, 'wptests_', $database_type)"), "project test install writes the wptests_ tables") +assert.ok(projectInvocations[1].includes("pg_skip_project_bootstrap_shell_install($project_test_install_available)"), "the PHPUnit request skips the shell install core's bootstrap would spawn") +assert.ok(projectInvocations[1].includes("$bootstrap_mode === 'project' && !$project_test_install_available ? 'wp_' : 'wptests_'"), "project mode boots the installed test tables") + const failedPreinstallInvocations: string[] = [] await assert.rejects( runPhpunitCommand({ diff --git a/tests/playground-phpunit-project-install-state.integration.test.ts b/tests/playground-phpunit-project-install-state.integration.test.ts new file mode 100644 index 00000000..f9d12b0d --- /dev/null +++ b/tests/playground-phpunit-project-install-state.integration.test.ts @@ -0,0 +1,90 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { test } from "node:test" + +// Project-mode suites must start from the database state that core's +// tests/phpunit/includes/install.php leaves behind, not from Playground's +// pretty-permalink site install. +test("project-mode PHPUnit starts from core's test install state", (t) => { + const root = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-project-install-")) + t.after(() => rmSync(root, { recursive: true, force: true })) + const slug = "project-install-state" + const plugin = join(root, slug) + const sandboxPlugin = `/wordpress/wp-content/plugins/${slug}` + mkdirSync(join(plugin, "tests"), { recursive: true }) + writeFileSync(join(plugin, "composer.json"), JSON.stringify({ + require: { "phpunit/phpunit": "^9.6", "wp-phpunit/wp-phpunit": "^6.8", "yoast/phpunit-polyfills": "^4.0" }, + config: { platform: { php: "8.3.0" } }, + })) + const install = spawnSync("composer", ["install", "--no-interaction", "--prefer-dist"], { cwd: plugin, encoding: "utf8", timeout: 300_000 }) + if (install.error?.code === "ENOENT") return t.skip("Composer is unavailable") + assert.ifError(install.error) + const installOutput = install.stdout + install.stderr + if (install.status !== 0 && /curl error (?:5|6|7|28|35|60)\b|network is unreachable|could not resolve host|connection timed out/i.test(installOutput)) { + return t.skip("Composer network access is unavailable") + } + assert.equal(install.status, 0, installOutput) + + writeFileSync(join(plugin, `${slug}.php`), " get_option('permalink_structure'), + 'using_permalinks' => $GLOBALS['wp_rewrite']->using_permalinks(), + 'rewrite_rules' => get_option('rewrite_rules'), +); +`) + writeFileSync(join(plugin, "phpunit.xml.dist"), ` + tests + +`) + writeFileSync(join(plugin, "tests", "InstallStateTest.php"), ` spawnSync(process.execPath, ["packages/cli/dist/index.js", ...args], { + encoding: "utf8", timeout: 300_000, maxBuffer: 8 * 1024 * 1024, + }) + const build = cli("recipe", "build", "phpunit", "--options", options, "--output", recipe) + assert.ifError(build.error) + assert.equal(build.status, 0, build.stderr) + const result = cli("recipe-run", "--recipe", recipe, "--artifacts", artifacts, "--json") + assert.ifError(result.error) + const output = result.stdout + result.stderr + assert.equal(result.status, 0, output) + const latest = JSON.parse(readFileSync(join(artifacts, "latest-runtime.json"), "utf8")) + const directory = join(artifacts, latest.paths.runtimeDirectory, "files/phpunit") + const completed = readFileSync(join(directory, ".wp-codebox-result.txt"), "utf8") + const summary = JSON.parse(completed.match(/^WP_CODEBOX_PHPUNIT_RESULT:(.+)$/m)?.[1] ?? "null") + assert.ok(summary, output) + assert.deepEqual([summary.status, summary.total, summary.failures, summary.errors], ["passed", 1, 0, 0], output) +})