diff --git a/packages/runtime-playground/src/phpunit-modern-runner.ts b/packages/runtime-playground/src/phpunit-modern-runner.ts index c9a6b97d..7f3fd8c3 100644 --- a/packages/runtime-playground/src/phpunit-modern-runner.ts +++ b/packages/runtime-playground/src/phpunit-modern-runner.ts @@ -68,7 +68,18 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, }); $bootstrap_code = '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)) { @@ -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; @@ -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', @@ -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)); diff --git a/patches/@wp-playground+cli+3.1.46.patch b/patches/@wp-playground+cli+3.1.46.patch index 6c0950a1..7cacb358 100644 --- a/patches/@wp-playground+cli+3.1.46.patch +++ b/patches/@wp-playground+cli+3.1.46.patch @@ -19,19 +19,25 @@ index e22c476..ed7c114 100644 trace: this.args.experimentalTrace === !0, extensions: Ve(this.args), diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.cjs b/node_modules/@wp-playground/cli/worker-thread-v1.cjs -index 4c193ec..ea12e09 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v1.cjs +++ b/node_modules/@wp-playground/cli/worker-thread-v1.cjs @@ -1,3 +1,3 @@ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@php-wasm/node"),b=require("@php-wasm/progress"),n=require("@php-wasm/universal"),q=require("@php-wasm/util"),I=require("@wp-playground/common"),u=require("@wp-playground/wordpress"),W=require("tls"),P=require("worker_threads"),i=require("./run-cli-D2-Klk3s.cjs"),k=require("@php-wasm/logger");function H(r,e,...t){console.log(performance.now().toFixed(6).padStart(15,"0"),r.toString().padStart(16,"0"),q.sprintf(e,...t))}class w extends n.PHPWorker{constructor(e){super(void 0,e),this.bootedRequestHandler=!1,this.bootedWordPress=!1}async useFileLockManager(e){this.fileLockManager=await n.consumeAPISync(e)}async bootWordPress(e,t){if(this.bootedWordPress)throw new Error("WordPress already booted");this.bootedWordPress=!0;const{siteUrl:s,phpVersion:o,wordpressInstallMode:m,wordPressZip:c,sqliteIntegrationPluginZip:d,dataSqlPath:y,constants:f}=e;try{await u.bootWordPress(this.__internal_getRequestHandler(),{siteUrl:s,phpVersion:o,wordpressInstallMode:m,wordPressZip:c!==void 0?new File([c],"wordpress.zip"):void 0,sqliteIntegrationPluginZip:d!==void 0?new File([d],"sqlite-integration-plugin.zip"):void 0,createFiles:{"/internal/shared/ca-bundle.crt":W.rootCertificates.join(` -`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);return s.useFileLockManager(e),await s.bootRequestHandler({...r,processId:t.processId}),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; -+`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);return s.useFileLockManager(e),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; ++`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);const channel=new P.MessageChannel;return await n.exposeSyncAPI(Object.fromEntries(["lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", "releaseLocksForProcess", "releaseLocksOnFdClose"].map(method => [method, (...args) => e[method](...args)])),channel.port1),await s.useFileLockManager(channel.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{channel.port1.close();try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; //# sourceMappingURL=worker-thread-v1.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/@wp-playground/cli/worker-thread-v1.js -index 93b7099..a7b02ad 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v1.js +++ b/node_modules/@wp-playground/cli/worker-thread-v1.js -@@ -125,6 +125,7 @@ function V(r, e) { +@@ -1,6 +1,6 @@ + import { loadNodeRuntime as w } from "@php-wasm/node"; + import { EmscriptenDownloadMonitor as f } from "@php-wasm/progress"; +-import { exposeAPI as y, PHPWorker as b, consumeAPISync as g, consumeAPI as h, releaseApiProxy as I, sandboxedSpawnHandlerFactory as W } from "@php-wasm/universal"; ++import { exposeAPI as y, PHPWorker as b, consumeAPISync as g, consumeAPI as h, releaseApiProxy as I, sandboxedSpawnHandlerFactory as W, exposeSyncAPI as exposeLockManager } from "@php-wasm/universal"; + import { sprintf as H } from "@php-wasm/util"; + import { RecommendedPHPVersion as k } from "@wp-playground/common"; + import { bootWordPress as R, bootRequestHandler as q } from "@wp-playground/wordpress"; +@@ -125,6 +125,7 @@ { fileLockManager: e, emscriptenOptions: { @@ -39,16 +45,29 @@ index 93b7099..a7b02ad 100644 processId: r.processId, trace: r.trace ? x : void 0, nativeInternalDirPath: r.nativeInternalDirPath -@@ -141,7 +142,7 @@ async function C(r, e) { - return o.useFileLockManager(e), await o.bootRequestHandler({ +@@ -138,12 +139,19 @@ + const t = await M("v1"), o = h( + t.phpPort + ); +- return o.useFileLockManager(e), await o.bootRequestHandler({ ++ const channel = new _(); ++ await exposeLockManager(Object.fromEntries([ ++ "lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", ++ "releaseLocksForProcess", "releaseLocksOnFdClose" ++ ].map((method) => [method, (...args) => e[method](...args)])), channel.port1); ++ await o.useFileLockManager(channel.port2); ++ return await o.bootRequestHandler({ ...r, processId: t.processId - }), { + }), await o.mountAfterWordPressInstall(r.mountsAfterWpInstall), { php: o, reap: () => { ++ channel.port1.close(); try { -@@ -157,6 +158,8 @@ async function C(r, e) { + o.dispose(); + } catch { +@@ -157,6 +165,8 @@ } process.on("unhandledRejection", (r) => { S.error("Unhandled rejection:", r); @@ -58,20 +77,18 @@ index 93b7099..a7b02ad 100644 const i = new _(), [c, p] = y( new F(new f()), diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.cjs b/node_modules/@wp-playground/cli/worker-thread-v2.cjs -index 0a1477e..55e5f09 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v2.cjs +++ b/node_modules/@wp-playground/cli/worker-thread-v2.cjs @@ -1,4 +1,4 @@ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("@php-wasm/node"),q=require("@php-wasm/progress"),o=require("@php-wasm/universal"),W=require("@php-wasm/util"),H=require("@wp-playground/common"),p=require("@wp-playground/wordpress"),h=require("tls"),c=require("worker_threads"),i=require("./run-cli-D2-Klk3s.cjs"),R=require("@php-wasm/logger");function _(r,e,...t){console.log(performance.now().toFixed(6).padStart(15,"0"),r.toString().padStart(16,"0"),W.sprintf(e,...t))}function P(r){return{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:r?"1":"0",disable_functions:r?"":"fsockopen,pfsockopen,curl_init,curl_exec,curl_multi_exec,mail"}}class f extends o.PHPWorker{constructor(e){super(void 0,e),this.bootedRequestHandler=!1,this.bootedWordPress=!1}async useFileLockManager(e){this.fileLockManager=await o.consumeAPISync(e)}async bootWordPress(e,t){if(this.bootedWordPress)throw new Error("WordPress already booted");this.bootedWordPress=!0;const{siteUrl:s,phpVersion:n,wordpressInstallMode:g,wordPressZip:d,networking:y=!0,sqliteIntegrationPluginZip:u,dataSqlPath:I,constants:b}=e;try{await p.bootWordPress(this.__internal_getRequestHandler(),{siteUrl:s,phpVersion:n,wordpressInstallMode:g,wordPressZip:d!==void 0?new File([d],"wordpress.zip"):void 0,sqliteIntegrationPluginZip:u!==void 0?new File([u],"sqlite-integration-plugin.zip"):void 0,createFiles:{"/internal/shared/ca-bundle.crt":h.rootCertificates.join(` `)},phpIniEntries:P(y),dataSqlPath:I,constants:b});const a=o.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[o.releaseApiProxy](),w()}catch(a){throw m(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await p.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createFiles:{"/internal/shared/ca-bundle.crt":h.rootCertificates.join(` -`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(e,n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; -+`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(e,n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; ++`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(Object.fromEntries(["lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", "releaseLocksForProcess", "releaseLocksOnFdClose"].map(method => [method, (...args) => e[method](...args)])),n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{n.port1.close();try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; //# sourceMappingURL=worker-thread-v2.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.js b/node_modules/@wp-playground/cli/worker-thread-v2.js -index fb79a59..6af079f 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v2.js +++ b/node_modules/@wp-playground/cli/worker-thread-v2.js -@@ -136,6 +136,7 @@ function V(r, e) { +@@ -136,6 +136,7 @@ { fileLockManager: e, emscriptenOptions: { @@ -79,16 +96,23 @@ index fb79a59..6af079f 100644 processId: r.processId, trace: r.trace ? C : void 0, nativeInternalDirPath: r.nativeInternalDirPath -@@ -152,7 +153,7 @@ async function j(r, e) { - return await q(e, o.port1), await n.useFileLockManager(o.port2), await n.bootRequestHandler({ +@@ -149,12 +150,13 @@ + const t = await F("v2"), n = P( + t.phpPort + ), o = new m(); +- return await q(e, o.port1), await n.useFileLockManager(o.port2), await n.bootRequestHandler({ ++ return await q(Object.fromEntries(["lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", "releaseLocksForProcess", "releaseLocksOnFdClose"].map(method => [method, (...args) => e[method](...args)])), o.port1), await n.useFileLockManager(o.port2), await n.bootRequestHandler({ ...r, processId: t.processId - }), { + }), await n.mountAfterWordPressInstall(r.mountsAfterWpInstall), { php: n, reap: () => { ++ o.port1.close(); try { -@@ -168,6 +169,8 @@ async function j(r, e) { + n.dispose(); + } catch { +@@ -168,6 +170,8 @@ } process.on("unhandledRejection", (r) => { E.error("Unhandled rejection:", r); diff --git a/patches/README.md b/patches/README.md index 9a60fc59..09f1fd28 100644 --- a/patches/README.md +++ b/patches/README.md @@ -12,7 +12,10 @@ after the Playground CLI ships the same worker terminalization behavior. The same patch also applies post-install mounts to sandboxed CLI subprocesses. Spawned workers boot a request handler but do not install WordPress themselves, so without this change they miss the plugin and Composer mounts used by the -parent. Remove this part when upstream attaches those mounts to child workers. +parent. The patch also gives each child its own connection to the parent's +file-lock manager. This lets an isolated WordPress bootstrap open the shared +SQLite database without timing out on file-lock requests. Remove these changes +when upstream handles both mounts and file-lock forwarding for child workers. The manual `build-php-wasm-mysqli-poll-overlay.yml` workflow carries the C-level `select()` wrapper and Asyncify imports from WordPress Playground PR diff --git a/tests/playground-phpunit-isolation.integration.test.ts b/tests/playground-phpunit-isolation.integration.test.ts index a824501c..87c0aef1 100644 --- a/tests/playground-phpunit-isolation.integration.test.ts +++ b/tests/playground-phpunit-isolation.integration.test.ts @@ -6,13 +6,14 @@ import { join } from "node:path" import { test } from "node:test" for (const major of [9, 10, 11, 12]) { - test(`PHPUnit ${major} runs an isolated test between regular tests`, (t) => { + test(`PHPUnit ${major} runs isolated tests between regular tests`, async (t) => { const root = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-isolation-")) t.after(() => rmSync(root, { recursive: true, force: true })) const slug = "isolation-fixture" const plugin = join(root, slug) const sandboxPlugin = `/wordpress/wp-content/plugins/${slug}` const managed = major === 9 + const fullBootstrap = major === 12 const phpVersion = major === 12 ? "8.4" : "8.3" const harness = join(root, "harness") mkdirSync(join(plugin, "tests"), { recursive: true }) @@ -20,7 +21,11 @@ for (const major of [9, 10, 11, 12]) { cpSync("tests/fixtures/phpunit-playground-harness", harness, { recursive: true }) } else { writeFileSync(join(plugin, "composer.json"), JSON.stringify({ - require: { "phpunit/phpunit": `^${major}`, "wp-phpunit/wp-phpunit": "^6.8" }, + require: { + "phpunit/phpunit": `^${major}`, + "wp-phpunit/wp-phpunit": "^6.8", + ...(fullBootstrap ? { "yoast/phpunit-polyfills": "^4.0" } : {}), + }, config: { platform: { php: `${phpVersion}.0` } }, })) } @@ -36,7 +41,16 @@ for (const major of [9, 10, 11, 12]) { assert.equal(install.status, 0, installOutput) writeFileSync(join(plugin, `${slug}.php`), " tests @@ -51,14 +65,17 @@ final class IsolationTest extends PHPUnit\\Framework\\TestCase { } ${managed ? "/** @runInSeparateProcess\n * @preserveGlobalState disabled\n */" : "#[PHPUnit\\Framework\\Attributes\\RunInSeparateProcess]\n #[PHPUnit\\Framework\\Attributes\\PreserveGlobalState(false)]"} - public function testIsolated(): void { + ${fullBootstrap ? "#[PHPUnit\\Framework\\Attributes\\DataProvider('cases')]" : ""} + public function testIsolated(${fullBootstrap ? "$case" : ""}): void { if (defined('ISOLATION_PARENT_ONLY') || file_get_contents(sys_get_temp_dir() . '/isolation-parent') !== 'parent') { self::fail('The worker must have fresh PHP state and share the parent filesystem'); } ${managed ? "require_once dirname(PHPUNIT_COMPOSER_INSTALL) . '/wp-phpunit/wp-phpunit/includes/functions.php';" : ""} - self::assertTrue(function_exists('tests_add_filter')); + ${fullBootstrap ? "self::assertNotEmpty(get_option('siteurl'));\n self::assertTrue(defined('ISOLATION_PROJECT_BOOTSTRAPPED'));" : "self::assertTrue(function_exists('tests_add_filter'));"} } + ${fullBootstrap ? "public static function cases(): array { return ['first' => [1], 'second' => [2]]; }" : ""} + public function testAfter(): void { self::assertTrue(defined('ISOLATION_PARENT_ONLY')); } @@ -90,14 +107,57 @@ final class IsolationTest extends PHPUnit\\Framework\\TestCase { 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) - assert.equal(result.status, 0, result.stderr || result.stdout) - 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.deepEqual([summary.status, summary.total, summary.assertions, summary.errors, summary.failures], ["passed", 3, 3, 0, 0]) + function runFixture(artifactDir: string, exitCode: number, expected: [string, number, number, number, number]) { + const result = cli("recipe-run", "--recipe", recipe, "--artifacts", artifactDir, "--json") + assert.ifError(result.error) + const output = result.stdout + result.stderr + assert.equal(result.status, exitCode, output) + const latest = JSON.parse(readFileSync(join(artifactDir, "latest-runtime.json"), "utf8")) + const directory = join(artifactDir, 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.assertions, summary.errors, summary.failures], expected, output) + return output + } + + runFixture(artifacts, 0, fullBootstrap ? ["passed", 4, 6, 0, 0] : ["passed", 3, 3, 0, 0]) + + if (!managed) { + const isolatedStart = fullBootstrap ? "public function testIsolated($case): void {" : "public function testIsolated(): void {" + const conditional = fullBootstrap ? "if ($case === 1) " : "" + for (const [kind, exitCode] of [ + ["fatal", fullBootstrap ? 2 : 255], + ["empty", 0], + ] as const) { + await t.test(`reports the ${kind} child and still runs the following tests`, () => { + if (kind === "fatal") { + // Bypass PHPUnit's recoverable error handler to exercise a PHP fatal. + const fatal = `fwrite(STDOUT, 'child stdout'); + fwrite(STDERR, 'child stderr: ' . str_repeat('x', 20000)); + set_error_handler(static fn () => false); + trigger_error('deliberate isolation fatal', E_USER_ERROR);` + writeFileSync(testFile, testCode.replace(isolatedStart, `${isolatedStart}\n ${conditional}{ ${fatal} }`)) + } else { + // End the child before PHPUnit runs the test or emits its own shutdown message. + writeFileSync(testFile, testCode.replace("