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
4 changes: 3 additions & 1 deletion docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
29 changes: 29 additions & 0 deletions packages/runtime-playground/src/phpunit-command-handlers.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down
119 changes: 119 additions & 0 deletions packages/runtime-playground/src/phpunit-modern-runner.ts
Original file line number Diff line number Diff line change
@@ -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, '<?php') === false) {
throw new RuntimeException('Unable to write PHPUnit Application bootstrap override');
}
array_push($argv, '--bootstrap', $bootstrap_file);
if (!$listing && isset($args['filter'])) {
$argv[] = '--filter=' . $args['filter'];
}
if (!empty($args['testdox'])) {
$argv[] = '--testdox';
}
if (!empty($args['verbose'])) {
array_push($argv, '--display-incomplete', '--display-skipped');
}
if ($listing) {
array_push($argv, '--list-tests-xml', $list_file);
} elseif (!empty($args['junitLogfile'])) {
array_push($argv, '--log-junit', $args['junitLogfile']);
}
// Discovery already honored --testsuite, excludes and file scoping. Pass
// its exact files, not the original XML suite or an unscoped directory.
if (count($files) > 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);
}`
}
1 change: 1 addition & 0 deletions scripts/smoke-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down
1 change: 1 addition & 0 deletions tests/phpunit-project-autoload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
`)
Expand Down
108 changes: 108 additions & 0 deletions tests/playground-phpunit-modern.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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`), "<?php\n/** Plugin Name: PHPUnit 11 Fixture */\n")
writeFileSync(join(plugin, "bootstrap.php"), `<?php
require __DIR__ . '/vendor/autoload.php';
require getenv('WP_TESTS_DIR') . '/includes/functions.php';
`)
writeFileSync(join(plugin, "phpunit.xml.dist"), `<phpunit bootstrap="bootstrap.php">
<testsuites><testsuite name="fixture"><directory>tests</directory></testsuite></testsuites>
</phpunit>
`)
writeFileSync(join(plugin, "tests", "PassingTest.php"), `<?php
final class PassingTest extends PHPUnit\\Framework\\TestCase {
public function testPass(): void {
self::assertTrue(function_exists('tests_add_filter'));
}
}
`)
writeFileSync(join(plugin, "tests", "FailingTest.php"), `<?php
final class FailingTest extends PHPUnit\\Framework\\TestCase {
public function testFail(): void {
self::assertTrue(false);
}
}
`)

function runRecipe(name: string, options: { phpunitArgs?: string[]; changedTestFiles?: string[]; selectedTestFile?: string }, expectedExit: number) {
const optionsPath = join(root, `${name}-options.json`)
const recipe = join(root, `${name}.json`)
const artifacts = join(root, `${name}-artifacts`)
writeFileSync(optionsPath, JSON.stringify({
pluginSlug,
pluginSource: plugin,
bootstrapMode: "project",
phpVersion: "8.3",
testsDir: `/wordpress/wp-content/plugins/${pluginSlug}/vendor/wp-phpunit/wp-phpunit`,
...options,
}))
const build = run(process.execPath, [cli, "recipe", "build", "phpunit", "--options", optionsPath, "--output", recipe])
assert.ifError(build.error)
assert.equal(build.status, 0, build.stderr)
const result = run(process.execPath, [cli, "recipe-run", "--recipe", recipe, "--artifacts", artifacts, "--json"])
assert.ifError(result.error)
assert.equal(result.status, expectedExit, result.stderr)
const latest = JSON.parse(readFileSync(join(artifacts, "latest-runtime.json"), "utf8"))
const directory = join(artifacts, latest.paths.runtimeDirectory, "files", "phpunit")
const diagnostics = readFileSync(join(directory, ".pg-test-result.txt"), "utf8")
assert.match(diagnostics, /^STAGE_OK:run_tests$/m, diagnostics)
assert.doesNotMatch(diagnostics, /^STAGE_FAIL:/m)
return { diagnostics, stdout: result.stdout, directory }
}

const mixed = runRecipe("mixed", {}, 1)
assert.match(mixed.diagnostics, /^SOME TESTS FAILED$/m)
assert.match(mixed.diagnostics, /^TESTS: 2 ASSERTIONS: 2 FAILURES: 1 ERRORS: 0$/m)
assert.match(readFileSync(join(mixed.directory, ".wp-codebox-junit.xml"), "utf8"), /<failure\b/)

const passing = runRecipe("passing", { phpunitArgs: ["--filter", "testPass", "--no-testdox"] }, 0)
assert.match(passing.diagnostics, /^ALL TESTS PASSED$/m)
assert.match(passing.diagnostics, /^TESTS: 1 ASSERTIONS: 1 FAILURES: 0 ERRORS: 0$/m)

const selected = runRecipe("selected", { selectedTestFile: "PassingTest.php" }, 0)
assert.match(selected.diagnostics, /^TESTS: 1 ASSERTIONS: 1 FAILURES: 0 ERRORS: 0$/m)

const changed = runRecipe("changed", {
changedTestFiles: ["tests/PassingTest.php"],
phpunitArgs: ["--testsuite=fixture"],
}, 0)
assert.match(changed.diagnostics, /^SCOPED_TEST_FILES requested=1 matched=1$/m)
assert.match(changed.diagnostics, /^TESTS: 1 ASSERTIONS: 1 FAILURES: 0 ERRORS: 0$/m)

const listing = runRecipe("listing", { phpunitArgs: ["--list-tests"] }, 0)
assert.match(listing.diagnostics, /^TESTS: 2 ASSERTIONS: 0 FAILURES: 0 ERRORS: 0$/m)
assert.match(listing.stdout, /PassingTest::testPass/)
assert.match(listing.stdout, /FailingTest::testFail/)
})
Loading