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
13 changes: 12 additions & 1 deletion packages/runtime-playground/src/phpunit-modern-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,18 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config,
});
$bootstrap_code = '<?php';
${prefix === "pg" ? `if ($child_bootstrap !== '') {
$bootstrap_code .= ' require_once ' . var_export($child_bootstrap, true) . ';';
// PHPUnit can start a child without preserved globals. Seed the same
// project test environment before that child loads the WP test library.
$bootstrap_code .= ' if (!function_exists("pg_skip_project_bootstrap_shell_install")) {';
foreach (array('WP_TESTS_DIR', 'WP_TESTS_CONFIG_FILE_PATH', 'WP_PHPUNIT__TESTS_CONFIG', 'WP_TESTS_SKIP_INSTALL', 'WP_MULTISITE') as $name) {
$value = getenv($name);
if ($value !== false) {
$key = var_export($name, true);
$bootstrap_code .= ' $_SERVER[' . $key . '] = $_ENV[' . $key . '] = ' . var_export($value, true) . ';'
. ' putenv(' . var_export($name . '=' . $value, true) . ');';
}
}
$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) {
Expand Down
97 changes: 91 additions & 6 deletions packages/runtime-playground/src/phpunit-process-isolation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// 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) {
function pg_phpunit_proc_open($job, ?string $script, $command, array $descriptors, &$pipes, ?string $cwd, ?array $env, ?string &$staged_script, bool $isolation_test) {
// 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) === '') {
Expand All @@ -13,7 +13,7 @@ function pg_phpunit_proc_open($job, ?string $script, $command, array $descriptor
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) {
if ($script === null || file_put_contents($script, $isolation_test ? pg_phpunit_capture_fatals($code, $script . '.fatal') : $code) === false) {
throw new RuntimeException('Unable to stage the PHPUnit isolation job');
}
if (is_string($command)) {
Expand All @@ -31,6 +31,64 @@ function pg_phpunit_proc_open($job, ?string $script, $command, array $descriptor
return $process;
}

function pg_phpunit_capture_fatals(string $code, string $fatal_file): string {
// PHPUnit 12 can redirect error_log to a child-only temporary file and
// replace the exit status from its shutdown handler. Record the PHP fatal
// before that handler runs, without changing the result or output streams.
$capture = 'register_shutdown_function(static function (): void {'
. ' $error = error_get_last();'
. ' if ($error !== null && ($error["type"] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR))) {'
. ' @file_put_contents(' . var_export($fatal_file, true) . ', "PHP fatal: " . substr($error["message"], 0, 768) . " in " . substr($error["file"], -160) . ":" . $error["line"]);'
. ' } });';
// PHPUnit templates start with an opening tag and, in 10+, strict_types.
return preg_replace_callback('/^<\?php\s+(?:declare\s*\(strict_types=1\);)?/',
static fn (array $match): string => $match[0] . "\n" . $capture . "\n", $code, 1);
}

function pg_phpunit_finish_child($process, ?string $staged_script, string &$stderr): int {
$exit_code = proc_close($process);
if ($staged_script !== null) {
$fatal_file = $staged_script . '.fatal';
if (is_file($fatal_file)) {
$fatal = file_get_contents($fatal_file);
if ($fatal !== false) {
$stderr .= "\n" . $fatal;
}
unlink($fatal_file);
}
unlink($staged_script);
}
return $exit_code;
}

function pg_phpunit_child_diagnostic(string $result, string $stdout, string $stderr, ?int $exit_code, ?string $spawn_error): string {
if ($result !== '' && $stderr === '' && $exit_code === 0 && $spawn_error === null) {
return '';
}

$excerpt = static function (string $output): string {
// Keep the beginning and the end: a fatal can follow a noisy bootstrap.
if (strlen($output) > 2048) {
$output = substr($output, 0, 1024) . "\n[output truncated]\n" . substr($output, -1024);
}
return trim($output) !== '' ? trim($output) : '(empty)';
};
if ($spawn_error !== null) {
$reason = $spawn_error;
} elseif ($result === '') {
// Before PHPUnit 12.3, progress and result collectors match the native
// wording and expect a Finished event. Rephrase it on those releases
// so they count this as a normal error on an unprepared test.
$reason = version_compare(PHPUnit\Runner\Version::id(), '12.3.0', '>=')
? 'Test was run in child process and ended unexpectedly'
: 'Test was run in a child process and ended unexpectedly';
} else {
$reason = 'PHPUnit isolation child failed';
}
return $reason . ' (exit code ' . ($exit_code ?? 'unavailable') . ")\n"
. 'stdout: ' . $excerpt($stdout) . "\nstderr: " . $excerpt($stderr);
}

function pg_set_phpunit_composer_install(): void {
if (defined('PHPUNIT_COMPOSER_INSTALL')) {
return;
Expand Down Expand Up @@ -62,6 +120,7 @@ function pg_register_phpunit_process_adapter(): void {
$adapter ??= static function (string $class): void {
if (!in_array($class, array(
'PHPUnit\Framework\TestCase',
'PHPUnit\Util\PHP\AbstractPhpProcess',
'PHPUnit\Util\PHP\DefaultPhpProcess',
'PHPUnit\Util\PHP\JobRunner',
'SebastianBergmann\Environment\Runtime',
Expand Down Expand Up @@ -105,19 +164,45 @@ SNAPSHOT
// 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\AbstractPhpProcess') {
// Only isolation tests need diagnostics. PHPUnit also uses these
// runners for PHPT jobs, where stdout/stderr must stay untouched.
// Feed failures through the native stderr branch: it emits an
// error without a Finished event for the unprepared test.
$job_call = $modern ? '$this->run($job)' : '$this->runJob($job)';
$stdout = $modern ? '$result->stdout()' : "\$_result['stdout']";
$stderr = $modern ? '$result->stderr()' : "\$_result['stderr']";
$source = str_replace($job_call . ';', $modern
? '$this->run($job, $pg_exit_code, $pg_spawn_error, true);'
: '$this->runJob($job, [], $pg_exit_code, $pg_spawn_error, true);', $source);
// Early PHPUnit 10 carries the serialized result on stdout.
$result = str_contains($source, '$processResult =') ? '$processResult' : $stdout;
$diagnostic = '\pg_phpunit_child_diagnostic(' . $result . ', ' . $stdout . ', ' . $stderr . ', $pg_exit_code, $pg_spawn_error)';
$source = str_replace("\n " . $stderr, "\n " . $diagnostic, $source);
}
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.
// Pass exit status alongside PHPUnit's unmodified result object.
$status = ', ?int &$pg_exit_code = null, ?string &$pg_spawn_error = null, bool $pg_isolation_test = false';
$forward_status = ', $pg_exit_code, $pg_spawn_error, $pg_isolation_test';
$run = $modern ? 'function run(Job $job' : 'function runJob(string $job, array $settings = []';
$run_process = $modern ? 'function runProcess(Job $job, ?string $temporaryFile' : 'function runProcess(string $job, array $settings';
$call = $modern ? 'return $this->runProcess($job, $temporaryFile' : 'return $this->runProcess($job, $settings';
$source = str_replace(
array($run . ')', $run_process . ')', $call . ');'),
array($run . $status . ')', $run_process . $status . ')', $call . $forward_status . ');'),
$source
);
$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) {'
. rtrim($match[1], " \r\n,") . ', $pg_staged_script, $pg_isolation_test); } catch (\Throwable $e) {'
. ' $pg_spawn_error = $e->getMessage();'
. ' 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);
$source = str_replace('proc_close($process);', '$pg_exit_code = \pg_phpunit_finish_child($process, $pg_staged_script, $stderr);', $source);
}
}
eval(substr($source, 5));
Expand Down
Loading
Loading