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
22 changes: 16 additions & 6 deletions packages/runtime-playground/src/phpunit-command-handlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { posix } from "node:path"
import { phpunitModernRunnerPhp } from "./phpunit-modern-runner.js"
import { phpunitProcessIsolationPhp } from "./phpunit-process-isolation.js"
import { phpEnvAssignmentFunction, phpWpConfigDefineAppenderFunction } from "./php-snippets.js"

export interface PhpunitRunCodeOptions {
Expand Down Expand Up @@ -70,6 +71,7 @@ interface PhpunitConfigDiscoveryPhpOptions {
uniqueReturnValues: boolean
replaceDefaultMatchers: boolean
allowMissingImplicitConfig: boolean
includeProcessIsolation?: boolean
}

interface PhpunitChangedTestFilterPhpOptions {
Expand Down Expand Up @@ -113,7 +115,7 @@ function phpunitConfigDiscoveryPhp(options: PhpunitConfigDiscoveryPhpOptions): s
const suffixAssignment = options.replaceDefaultMatchers ? "$suffixes = $config_suffixes;" : "$suffixes = array_merge($suffixes, $config_suffixes);"
const prefixAssignment = options.replaceDefaultMatchers ? "$prefixes = $config_prefixes;" : "$prefixes = array_merge($prefixes, $config_prefixes);"

return `function ${options.functionName}($xml_path, $test_dir_default, array $selected_testsuites = array()) {
return `function ${options.functionName}($xml_path, $test_dir_default, array $selected_testsuites = array()${options.includeProcessIsolation ? ", &$process_isolation = false" : ""}) {
$directories = array($test_dir_default);
$suffixes = array('Test.php');
$prefixes = array('test-');
Expand Down Expand Up @@ -197,7 +199,7 @@ function phpunitConfigDiscoveryPhp(options: PhpunitConfigDiscoveryPhpOptions): s
if (!empty($config_prefixes)) {
${prefixAssignment}
}
return $return_values();
${options.includeProcessIsolation ? "$process_isolation = in_array((string) ($xml['processIsolation'] ?? ''), array('true', '1'), true);\n " : ""}return $return_values();
}`
}

Expand Down Expand Up @@ -898,6 +900,7 @@ function pg_run_boot_stage(array $cfg = []): ?string {
if ($harness_autoload !== '' && is_readable($harness_autoload)) {
pg_preload_wp_cli_namespaced_functions($harness_autoload);
require_once $harness_autoload;
pg_register_phpunit_process_adapter();
} elseif ($autoload_required || $harness_autoload !== '') {
throw new RuntimeException('configured PHPUnit harness autoload file is not readable: ' . $harness_autoload . '; mount the WP Codebox PHPUnit harness or clear autoload-file when using bootstrap-mode=project with a project bootstrap that loads PHPUnit.');
} else {
Expand Down Expand Up @@ -1071,7 +1074,7 @@ function pg_skip_project_bootstrap_shell_install(): void {
pg_log('NOTICE:using existing Playground install; project bootstrap shell install skipped');
}

function pg_run_project_bootstrap_stage(array $cfg): void {
function pg_run_project_bootstrap_stage(array $cfg): string {
global $pg_stage_output_buffering;
pg_stage_begin('project_bootstrap');
try {
Expand All @@ -1096,6 +1099,7 @@ function pg_run_project_bootstrap_stage(array $cfg): void {
}
$pg_stage_output_buffering = false;
pg_stage_ok('project_bootstrap');
return $bootstrap_real;
} catch (Throwable $e) {
$pg_stage_output_buffering = false;
pg_stage_fail('project_bootstrap', $e);
Expand Down Expand Up @@ -1434,6 +1438,7 @@ if ($multisite) {
$_ENV['WP_MULTISITE'] = '1';
}

${phpunitProcessIsolationPhp}
$legacy_project_autoload_file = '';
if ($autoload_file_role === '' && $bootstrap_mode === 'project' && $project_autoload_file === '' && $autoload_file !== '' && $autoload_file !== '/wp-codebox-vendor/autoload.php') {
$legacy_project_autoload_file = $autoload_file;
Expand All @@ -1446,7 +1451,7 @@ if ($bootstrap_mode === 'project') {
pg_skip_project_bootstrap_shell_install();
// Match vendor/bin/phpunit: load the explicit Composer autoloader before bootstrap.
pg_run_project_autoload_stage($project_autoload_file);
pg_run_project_bootstrap_stage(array('project_bootstrap' => $project_bootstrap, 'phpunit_xml' => ${JSON.stringify(options.phpunitXml)}, 'phpunit_xml_is_default' => ${JSON.stringify(options.phpunitXmlIsDefault)}));
$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)}));
// A legacy autoload-file reclassified as a project autoloader still runs after bootstrap.
pg_run_project_autoload_stage($legacy_project_autoload_file);
} else {
Expand Down Expand Up @@ -1572,6 +1577,10 @@ try {
pg_stage_begin('verify_harness');
try {
pg_ensure_phpunit_harness_loaded();
pg_register_phpunit_process_adapter();
if (!pg_uses_modern_phpunit()) {
pg_set_phpunit_composer_install();
}
pg_stage_ok('verify_harness');
} catch (Throwable $e) {
pg_stage_fail('verify_harness', $e);
Expand All @@ -1588,6 +1597,7 @@ ${phpunitConfigDiscoveryPhp({
uniqueReturnValues: false,
replaceDefaultMatchers: true,
allowMissingImplicitConfig: options.phpunitXmlIsDefault,
includeProcessIsolation: true,
})}

${phpunitDiscoveryPhp("wp_codebox_phpunit_discover", "pg_log")}
Expand All @@ -1598,7 +1608,7 @@ try {
if (!is_dir($test_dir)) {
throw new RuntimeException('configured PHPUnit test root is not a readable directory: ' . $test_dir);
}
list($directories, $suffixes, $prefixes, $excludes, $configured_files) = wp_codebox_phpunit_parse_config(${JSON.stringify(options.phpunitXml)}, $test_dir, $selected_testsuites);
list($directories, $suffixes, $prefixes, $excludes, $configured_files) = wp_codebox_phpunit_parse_config(${JSON.stringify(options.phpunitXml)}, $test_dir, $selected_testsuites, $phpunit_args['processIsolation']);
$test_files = wp_codebox_phpunit_discover($directories, $suffixes, $prefixes, $excludes, $configured_files);
// The third argument must be the same base <directory>/<file> entries in phpunit.xml were
// resolved against (dirname($xml_path), phpunitConfigDiscoveryPhp's basePathExpression
Expand Down Expand Up @@ -1641,7 +1651,7 @@ if (pg_uses_modern_phpunit()) {
pg_stage_begin('run_tests');
pg_log('RUNNING ' . count($test_files) . ' TEST FILES');
try {
pg_run_modern_phpunit($test_files, $phpunit_args, ${JSON.stringify(options.phpunitXml)}, ${JSON.stringify(options.phpunitXmlIsDefault)});
pg_run_modern_phpunit($test_files, $phpunit_args, ${JSON.stringify(options.phpunitXml)}, ${JSON.stringify(options.phpunitXmlIsDefault)}, $phpunit_child_bootstrap ?? '');
} catch (Throwable $e) {
pg_log_mdi_native_diagnostic();
pg_stage_fail('run_tests', $e);
Expand Down
14 changes: 10 additions & 4 deletions packages/runtime-playground/src/phpunit-modern-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export function phpunitModernRunnerPhp(prefix: "pg" | "core_pg"): string {
return method_exists('PHPUnit\\Runner\\Version', 'id') && (int) PHPUnit\\Runner\\Version::id() >= 10;
}

function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, bool $implicit_config): void {
function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, bool $implicit_config, string $child_bootstrap = ''): void {
if (empty($files)) {
// An empty changed-file scope must not fall back to the full XML suite.
${prefix}_log('ALL TESTS PASSED');
Expand All @@ -22,8 +22,9 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config,
} else {
$argv[] = '--no-configuration';
}
// WordPress bootstrap has already run, possibly with an explicit override.
// Use a private empty file instead of re-running the bootstrap from XML.
// Give fresh isolation workers the project bootstrap without re-running it
// in the parent. Set the Composer entry point here, after Application's
// preload phase, so it does not bypass the subprocess adapter.
$scratch = '/tmp/wp-codebox-phpunit-app-' . bin2hex(random_bytes(16));
if (!mkdir($scratch, 0700)) {
throw new RuntimeException('Unable to allocate PHPUnit Application scratch directory');
Expand Down Expand Up @@ -65,7 +66,12 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config,
${prefix}_stage_fail('run_tests', new RuntimeException('PHPUnit Application exited before reporting a result; see PHPUnit output'));
exit(1);
});
if (file_put_contents($bootstrap_file, '<?php') === false) {
$bootstrap_code = '<?php';
${prefix === "pg" ? `if ($child_bootstrap !== '') {
$bootstrap_code .= ' require_once ' . var_export($child_bootstrap, true) . ';';
}
$bootstrap_code .= ' if (function_exists("pg_set_phpunit_composer_install")) { pg_set_phpunit_composer_install(); }';` : ""}
if (file_put_contents($bootstrap_file, $bootstrap_code) === false) {
throw new RuntimeException('Unable to write PHPUnit Application bootstrap override');
}
array_push($argv, '--bootstrap', $bootstrap_file);
Expand Down
129 changes: 129 additions & 0 deletions packages/runtime-playground/src/phpunit-process-isolation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// The PHP-WASM request SAPI calls itself "cli", but leaves PHP_BINARY empty.
// Adapt only PHPUnit's subprocess classes, without writing into mounted vendor trees.
export const phpunitProcessIsolationPhp = String.raw`
function pg_phpunit_proc_open($job, ?string $script, $command, array $descriptors, &$pipes, ?string $cwd, ?array $env, ?string &$staged_script) {
// Playground CLI mounts /tmp in both workers. Its sandboxed spawn handler
// runs scripts but does not forward stdin to PHP's CLI SAPI.
if (is_array($command) && ($command[0] ?? null) === '') {
$command[0] = WP_CODEBOX_PHPUNIT_BINARY;
}
if (!function_exists('proc_open')) {
throw new RuntimeException('PHPUnit process isolation requires proc_open, which is disabled');
}
if ($script === null) {
$code = is_string($job) ? $job : $job->code();
$script = $staged_script = tempnam(sys_get_temp_dir(), 'phpunit-job-') ?: null;
if ($script === null || file_put_contents($script, $code) === false) {
throw new RuntimeException('Unable to stage the PHPUnit isolation job');
}
if (is_string($command)) {
// Insert before optional script arguments or stderr redirection.
$command = preg_replace('/(?= -- | 2>&1$|$)/', ' -f ' . escapeshellarg($script), $command, 1);
} else {
$arguments = array_search('--', $command, true);
array_splice($command, $arguments === false ? count($command) : $arguments, 0, array('-f', $script));
}
}
$process = @proc_open($command, $descriptors, $pipes, $cwd ?? (getcwd() ?: null), array_replace(getenv(), $env ?? array()));
if (!is_resource($process)) {
throw new RuntimeException('Playground could not open the PHPUnit isolation worker');
}
return $process;
}

function pg_set_phpunit_composer_install(): void {
if (defined('PHPUNIT_COMPOSER_INSTALL')) {
return;
}
foreach (spl_autoload_functions() as $loader) {
if (is_array($loader) && $loader[0] instanceof Composer\Autoload\ClassLoader && $loader[0]->findFile(PHPUnit\Runner\Version::class)) {
foreach (Composer\Autoload\ClassLoader::getRegisteredLoaders() as $vendor => $registered) {
if ($registered === $loader[0]) {
define('PHPUNIT_COMPOSER_INSTALL', $vendor . '/autoload.php');
return;
}
}
}
}
}

function pg_register_phpunit_process_adapter(): void {
if (PHP_BINARY !== '' || PHP_SAPI !== 'cli') {
return;
}
if (!defined('WP_CODEBOX_PHPUNIT_BINARY')) {
define('WP_CODEBOX_PHPUNIT_BINARY', '/internal/shared/bin/php');
}
static $adapter = null;
if ($adapter !== null) {
// Composer prepends new loaders; restore our priority without duplicates.
spl_autoload_unregister($adapter);
}
$adapter ??= static function (string $class): void {
if (!in_array($class, array(
'PHPUnit\Framework\TestCase',
'PHPUnit\Util\PHP\DefaultPhpProcess',
'PHPUnit\Util\PHP\JobRunner',
'SebastianBergmann\Environment\Runtime',
'PHPUnit\Util\PHP\ExtensionSettings',
), true)) {
return;
}
foreach (spl_autoload_functions() as $loader) {
if (!is_array($loader) || !$loader[0] instanceof Composer\Autoload\ClassLoader) {
continue;
}
$file = $loader[0]->findFile($class);
if (!$file || !is_readable($file)) {
continue;
}
$source = file_get_contents($file);
if ($source === false || !str_starts_with($source, '<?php')) {
continue;
}
// PHPUnit 9 snapshots WordPress globals before opening a subprocess.
// A live database connection cannot be serialized: report the error on
// this test rather than disabling preservation or aborting the suite.
if ($class === 'PHPUnit\Framework\TestCase') {
$snapshot = '$globals = GlobalState::getGlobalsAsString();';
if (!str_contains($source, $snapshot)) {
return;
}
$source = str_replace('__DIR__', var_export(dirname($file), true), $source);
$source = str_replace($snapshot, <<<'SNAPSHOT'
try {
$globals = GlobalState::getGlobalsAsString();
} catch (\Throwable $e) {
$result->startTest($this);
$result->addError($this, new \RuntimeException('Unable to preserve PHPUnit isolation globals: ' . $e->getMessage(), 0, $e), 0.0);
$result->endTest($this, 0.0);
return $result;
}
SNAPSHOT
, $source);
}
// Newer sebastian/environment also uses PHP_BINARY to probe CLI INI defaults.
$source = str_replace('use const PHP_BINARY;', 'use const WP_CODEBOX_PHPUNIT_BINARY as PHP_BINARY;', $source);
$modern = $class === 'PHPUnit\Util\PHP\JobRunner';
if ($modern || $class === 'PHPUnit\Util\PHP\DefaultPhpProcess') {
$script = $modern ? '$temporaryFile' : '$this->tempFile';
$error = $modern ? "new Result('', \$e->getMessage())" : "['stdout' => '', 'stderr' => \$e->getMessage()]";
// Feed spawn errors into PHPUnit's existing child-result processor,
// which reports stderr as a test error rather than aborting the suite.
$source = preg_replace_callback('/\$process = proc_open\((.*?)\n \);/s',
static function (array $match) use ($script, $error): string {
return '$pg_staged_script = null; try { $process = \pg_phpunit_proc_open($job, ' . $script . ','
. rtrim($match[1], " \r\n,") . ', $pg_staged_script); } catch (\Throwable $e) {'
. ' if ($pg_staged_script !== null) { @unlink($pg_staged_script); } return ' . $error . '; }';
}, $source, 1, $adapted);
if ($adapted) {
$source = str_replace('proc_close($process);', 'proc_close($process); if ($pg_staged_script !== null) { @unlink($pg_staged_script); }', $source);
}
}
eval(substr($source, 5));
return;
}
};
spl_autoload_register($adapter, true, true);
}
`
28 changes: 28 additions & 0 deletions packages/runtime-playground/src/programmatic-playground-runner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as PHPWasmNode from "@php-wasm/node"
import * as PHPWasmUniversal from "@php-wasm/universal"
import { compileBlueprint } from "@wp-playground/blueprints"
import { bootWordPressAndRequestHandler } from "@wp-playground/wordpress"
import type { MountSpec, RuntimeCreateSpec } from "@automattic/wp-codebox-core"
Expand All @@ -16,9 +17,17 @@ const { createNodeFsMountHandler, loadNodeRuntime } = PHPWasmNode as unknown as
loadNodeRuntime(phpVersion: AllPHPVersion, options?: { followSymlinks?: boolean; emscriptenOptions?: { processId?: number }; extensions?: Array<string | { source: { format: "manifest"; manifestUrl: string } }> }): Promise<number>
}

const { PHP, proxyFileSystem, sandboxedSpawnHandlerFactory } = PHPWasmUniversal as unknown as {
PHP: new (runtimeId: number) => ProgrammaticPHP & { exit(): void }
proxyFileSystem(parent: ProgrammaticPHP, child: ProgrammaticPHP, paths: string[]): Promise<void>
sandboxedSpawnHandlerFactory(getChild: () => Promise<{ php: ProgrammaticPHP; reap(): void }>): unknown
}

type AllPHPVersion = "8.5" | "8.4" | "8.3" | "8.2" | "8.1" | "8.0" | "7.4" | "5.2"

interface ProgrammaticPHP {
isDir(path: string): boolean
listFiles(path: string, options: { prependPath: boolean }): string[]
fileExists(path: string): boolean
mkdir(path: string): void
mount(vfsPath: string, mountHandler: unknown): Promise<unknown>
Expand Down Expand Up @@ -57,13 +66,31 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec,
const postinstallMounts = mounts.filter((mount) => mount.phase !== "pre-install")
const wpConfig = databaseBootstrapWpConfig(spec)
const wordPressZip = await wordpressArchiveFile(options)
let spawningPhp: ProgrammaticPHP
const requestHandler = await bootWordPressAndRequestHandler({
createPhpRuntime: () => loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++)),
maxPhpInstances: 1,
phpVersion,
siteUrl: playgroundRuntimeSiteUrl(spec) ?? "http://127.0.0.1",
documentRoot: "/wordpress",
sapiName: "cli",
spawnHandler: () => sandboxedSpawnHandlerFactory(async () => {
// The request handler has one slot, already occupied by the parent.
// A child needs its own PHP runtime, but must see the parent's VFS.
const parent = spawningPhp
const child = new PHP(await loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++)))
try {
await proxyFileSystem(parent, child, [
"/internal/shared",
...parent.listFiles("/", { prependPath: true }).filter((path) =>
!["/internal", "/dev", "/proc", "/request"].includes(path) && parent.isDir(path)),
])
return { php: child, reap: () => child.exit() }
} catch (error) {
child.exit()
throw error
}
}),
wordpressInstallMode: options.wordpressInstallMode ?? "install-from-existing-files",
...(wordPressZip ? { wordPressZip } : {}),
constants: playgroundWpConfigConstants(spec.environment.blueprint),
Expand All @@ -77,6 +104,7 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec,
},
async onPHPInstanceCreated(php: unknown) {
const programmaticPhp = php as ProgrammaticPHP
spawningPhp = programmaticPhp
if (options.wordpressDirectory) {
await mountHostDirectory(programmaticPhp, "/wordpress", options.wordpressDirectory)
}
Expand Down
Loading
Loading