Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
54 changes: 44 additions & 10 deletions packages/runtime-playground/src/phpunit-command-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export interface PhpunitRunCodeOptions {
junitFile?: string
}

export type PhpunitMultisitePreinstallCodeOptions = Pick<PhpunitRunCodeOptions, "testsDir" | "env" | "wpConfigDefines" | "databaseType" | "resultFile">
export type PhpunitTestInstallCodeOptions = Pick<PhpunitRunCodeOptions, "testsDir" | "env" | "wpConfigDefines" | "databaseType" | "multisite" | "resultFile">

export interface CorePhpunitRunCodeOptions {
coreRoot: string
Expand Down Expand Up @@ -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]
Expand All @@ -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, '');
Expand All @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)}));
Expand Down
9 changes: 9 additions & 0 deletions packages/runtime-playground/src/phpunit-command-semantics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RuntimeCreateSpec, "environment" | "runtimeEnv">): boolean {
return phpunitExecutionSemantics(args, runtimeSpec).bootstrapMode === "project" || requiresManagedMultisitePreinstall(args, runtimeSpec)
}
12 changes: 7 additions & 5 deletions packages/runtime-playground/src/wordpress-command-runners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
restPerformanceObservationInputFromArgs,
restPerformanceObservationPhpCode,
phpunitRunCode,
phpunitMultisitePreinstallCode,
phpunitTestInstallCode,
pluginStateInputFromArgs,
pluginStatePhpCode,
PLUGIN_PHPUNIT_RESULT_FILE,
Expand All @@ -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"
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions scripts/smoke-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down
35 changes: 33 additions & 2 deletions tests/phpunit-project-autoload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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({
Expand Down
Loading
Loading