diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 3e165946..61596796 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -1001,7 +1001,9 @@ that service; WP Codebox never substitutes SQLite for it. Omitting `databaseType` preserves the default SQLite behavior. Use `recipe build phpunit` when generating recipes for plugin CI or offloaded lab -runners: +runners. In project bootstrap mode, the runner detects the PHPUnit version loaded +by the project's autoloader. PHPUnit 9.6, 10, 11, and 12 use the same recipe +arguments and structured result format. ```json { diff --git a/packages/runtime-playground/src/phpunit-command-handlers.ts b/packages/runtime-playground/src/phpunit-command-handlers.ts index 0eb9f13d..65485ae3 100644 --- a/packages/runtime-playground/src/phpunit-command-handlers.ts +++ b/packages/runtime-playground/src/phpunit-command-handlers.ts @@ -1,4 +1,5 @@ import { posix } from "node:path" +import { phpunitModernRunnerPhp } from "./phpunit-modern-runner.js" import { phpEnvAssignmentFunction, phpWpConfigDefineAppenderFunction } from "./php-snippets.js" export interface PhpunitRunCodeOptions { @@ -1628,7 +1629,22 @@ try { exit(1); } +${phpunitModernRunnerPhp("pg")} + pg_stage_begin('load_tests'); +if (pg_uses_modern_phpunit()) { + // Application owns test loading for PHPUnit 10+. + pg_stage_ok('load_tests'); + 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)}); + } catch (Throwable $e) { + pg_log_mdi_native_diagnostic(); + pg_stage_fail('run_tests', $e); + exit(1); + } +} try { $suite = method_exists('PHPUnit\\Framework\\TestSuite', 'empty') ? PHPUnit\\Framework\\TestSuite::empty('WP Codebox PHPUnit Tests') @@ -1944,7 +1960,20 @@ try { exit(1); } +${phpunitModernRunnerPhp("core_pg")} + core_pg_stage_begin('load_tests'); +if (core_pg_uses_modern_phpunit()) { + core_pg_stage_ok('load_tests'); + core_pg_stage_begin('run_tests'); + core_pg_log('RUNNING ' . count($test_files) . ' TEST FILES'); + try { + core_pg_run_modern_phpunit($test_files, core_pg_phpunit_args($argv ?? array()), $phpunit_xml, ${JSON.stringify(options.phpunitXmlIsDefault)}); + } catch (Throwable $e) { + core_pg_stage_fail('run_tests', $e); + exit(1); + } +} try { $suite = method_exists('PHPUnit\\Framework\\TestSuite', 'empty') ? PHPUnit\\Framework\\TestSuite::empty('WP Codebox WordPress Core Tests') diff --git a/packages/runtime-playground/src/phpunit-modern-runner.ts b/packages/runtime-playground/src/phpunit-modern-runner.ts new file mode 100644 index 00000000..07f06e28 --- /dev/null +++ b/packages/runtime-playground/src/phpunit-modern-runner.ts @@ -0,0 +1,119 @@ +// PHPUnit 10+ owns suite construction, filtering, execution and result collection. +export function phpunitModernRunnerPhp(prefix: "pg" | "core_pg"): string { + return `function ${prefix}_uses_modern_phpunit(): bool { + 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 { + if (empty($files)) { + // An empty changed-file scope must not fall back to the full XML suite. + ${prefix}_log('ALL TESTS PASSED'); + ${prefix}_log('TESTS: 0 ASSERTIONS: 0 FAILURES: 0 ERRORS: 0'); + ${prefix}_stage_ok('run_tests'); + exit(0); + } + + if ($implicit_config && !is_readable($config) && basename($config) === 'phpunit.xml.dist') { + $config = dirname($config) . '/phpunit.xml'; + } + $argv = array('phpunit', '--colors=never', '--do-not-cache-result', '--no-extensions', '--no-logging'); + if (is_readable($config)) { + array_push($argv, '--configuration', $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. + $scratch = '/tmp/wp-codebox-phpunit-app-' . bin2hex(random_bytes(16)); + if (!mkdir($scratch, 0700)) { + throw new RuntimeException('Unable to allocate PHPUnit Application scratch directory'); + } + $listing = !empty($args['listTests']); + $bootstrap_file = $scratch . '/bootstrap.php'; + $list_file = $scratch . '/list.xml'; + $staging_dir = $scratch . '/tests'; + $application_running = false; + register_shutdown_function(static function () use (&$application_running, $listing, $scratch, $bootstrap_file, $list_file, $staging_dir): void { + $list = $listing && is_file($list_file) ? @simplexml_load_file($list_file) : false; + @unlink($bootstrap_file); + @unlink($list_file); + if (is_dir($staging_dir)) { + foreach (glob($staging_dir . '/*', GLOB_ONLYDIR) ?: array() as $dir) { + foreach (glob($dir . '/*.php') ?: array() as $link) { + unlink($link); + } + rmdir($dir); + } + rmdir($staging_dir); + } + rmdir($scratch); + if (!$application_running) { + return; + } + // Application calls exit() itself for --list-tests-xml and startup errors. + if ($list !== false && !PHPUnit\\TestRunner\\TestResult\\Facade::result()->hasTestTriggeredPhpunitErrorEvents()) { + $methods = $list->xpath('//*[local-name()="testMethod" or local-name()="testCaseMethod"]'); + foreach ($methods as $method) { + // Early PHPUnit 10 XML has the name but no id attribute. + echo (isset($method['id']) ? (string) $method['id'] : (string) $method->xpath('..')[0]['name'] . '::' . (string) $method['name']) . PHP_EOL; + } + ${prefix}_log('ALL TESTS PASSED'); + ${prefix}_log('TESTS: ' . count($methods) . ' ASSERTIONS: 0 FAILURES: 0 ERRORS: 0'); + ${prefix}_stage_ok('run_tests'); + return; + } + ${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, ' 1 && version_compare(PHPUnit\\Runner\\Version::id(), '10.4.0', '<')) { + // PHPUnit 10.0–10.3 accept only one positional path. Symlinks keep the + // original __DIR__ and basename when PHPUnit resolves each test file. + if (!mkdir($staging_dir, 0700)) { + throw new RuntimeException('Unable to create PHPUnit test selection directory'); + } + foreach ($files as $index => $file) { + $dir = $staging_dir . '/' . $index; + if (!mkdir($dir, 0700) || !symlink($file, $dir . '/' . basename($file))) { + throw new RuntimeException('Unable to stage PHPUnit test file: ' . $file); + } + } + array_push($argv, '--test-suffix', '.php', $staging_dir); + } else { + $argv = array_merge($argv, $files); + } + $GLOBALS['argv'] = $_SERVER['argv'] = $argv; + $GLOBALS['argc'] = $_SERVER['argc'] = count($argv); + $application_running = true; + try { + (new PHPUnit\\TextUI\\Application())->run($argv); + } finally { + $application_running = false; + } + $result = PHPUnit\\TestRunner\\TestResult\\Facade::result(); + ${prefix === "pg" ? "pg_log_mdi_native_diagnostic();" : ""} + ${prefix}_log($result->wasSuccessful() ? 'ALL TESTS PASSED' : 'SOME TESTS FAILED'); + ${prefix}_log('TESTS: ' . $result->numberOfTestsRun() . ' ASSERTIONS: ' . $result->numberOfAssertions() . ' FAILURES: ' . $result->numberOfTestFailedEvents() . ' ERRORS: ' . $result->numberOfTestErroredEvents()); + ${prefix}_stage_ok('run_tests'); + exit($result->wasSuccessful() ? 0 : 1); +}` +} diff --git a/scripts/smoke-discovery.ts b/scripts/smoke-discovery.ts index 1e68ab1a..70fc8fbe 100644 --- a/scripts/smoke-discovery.ts +++ b/scripts/smoke-discovery.ts @@ -37,6 +37,7 @@ const INTEGRATION_FILES: readonly string[] = [ "scripts/doctor-command-smoke.ts", "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-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 6e05aae1..a69b9b3c 100644 --- a/tests/phpunit-project-autoload.test.ts +++ b/tests/phpunit-project-autoload.test.ts @@ -465,6 +465,7 @@ function ${stagePrefix}_stage_fail($stage, \\Throwable $e) { } function ${stagePrefix}_log($message) {} ${stagePrefix === "core_pg" ? "function core_pg_phpunit_args($args) { return getenv('LIST_TESTS') ? array('listTests' => true) : array(); }" : ""} +${extractPhpFunction(source, `${stagePrefix}_uses_modern_phpunit`)} ${generatedHarnessTail} } `) diff --git a/tests/playground-phpunit-modern.integration.test.ts b/tests/playground-phpunit-modern.integration.test.ts new file mode 100644 index 00000000..8620ec97 --- /dev/null +++ b/tests/playground-phpunit-modern.integration.test.ts @@ -0,0 +1,108 @@ +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" + +const pluginSlug = "modern-phpunit" +const cli = "packages/cli/dist/index.js" + +function run(command: string, args: string[], cwd?: string) { + return spawnSync(command, args, { cwd, encoding: "utf8", timeout: 300_000, maxBuffer: 8 * 1024 * 1024 }) +} + +test("project recipes run and list tests with Composer-installed PHPUnit 11", (t) => { + const root = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-modern-")) + t.after(() => rmSync(root, { recursive: true, force: true })) + const plugin = join(root, pluginSlug) + mkdirSync(join(plugin, "tests"), { recursive: true }) + writeFileSync(join(plugin, "composer.json"), JSON.stringify({ + require: { "phpunit/phpunit": "^11", "wp-phpunit/wp-phpunit": "^6.8" }, + config: { platform: { php: "8.3.0" } }, + })) + const install = run("composer", ["install", "--no-interaction", "--prefer-dist"], plugin) + if (install.error?.code === "ENOENT") { + return t.skip("Composer is unavailable; cannot install the real PHPUnit 11 fixture") + } + const installOutput = install.stdout + install.stderr + if (install.status !== 0 && /curl error (?:5|6|7|28|35|60)\b|network is unreachable|network disabled|could not resolve host|connection timed out/i.test(installOutput)) { + return t.skip("Composer network access is unavailable; cannot install the real PHPUnit 11 fixture") + } + assert.ifError(install.error) + assert.equal(install.status, 0, installOutput) + + writeFileSync(join(plugin, `${pluginSlug}.php`), " + tests + +`) + writeFileSync(join(plugin, "tests", "PassingTest.php"), `