From c3a433342e68d61f43dc99074204efa02ec90049 Mon Sep 17 00:00:00 2001 From: "homeboy-ci[bot]" <266378653+homeboy-ci[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:24:13 +0000 Subject: [PATCH] feat(phpunit): support extra_themes theme dependencies in phpunit recipes --- docs/recipe-contract.md | 12 + packages/cli/src/commands/recipe-build.ts | 4 +- packages/cli/src/recipe-validation.ts | 25 +- packages/runtime-core/src/recipe-builders.ts | 72 +++++- .../src/phpunit-command-handlers.ts | 139 ++++++++++ .../src/wordpress-command-runners.ts | 2 + scripts/smoke-discovery.ts | 1 + .../phpunit-extra-themes.integration.test.ts | 65 +++++ tests/phpunit-extra-themes.test.ts | 243 ++++++++++++++++++ 9 files changed, 560 insertions(+), 3 deletions(-) create mode 100644 tests/phpunit-extra-themes.integration.test.ts create mode 100644 tests/phpunit-extra-themes.test.ts diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 7f002f2c..0c5bef36 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -985,6 +985,18 @@ created test tables and before test discovery and execution. Any dependency `plugins_loaded` callbacks registered during that load are invoked once after dependency activation. +`extra_themes` declares theme dependencies for the PHPUnit builder, using the +same shape as `inputs.extra_themes` (`source`/`sourcePath`, `slug`/`mountSlug`, +`activate`). Themes mount under `/wordpress/wp-content/themes/` and the +builder passes them to `wordpress.phpunit` as `dependency-themes-json`. In +managed bootstrap mode the `activate: true` theme becomes the active theme +(`template`/`stylesheet` options, including a child theme's parent) after +dependency plugins load, its `functions.php` (child first, then parent) is +loaded, and its `after_setup_theme` and `init` callbacks run before fixtures and +tests. Do not pass themes through `extra_plugins`: validation reports a +theme-shaped `extra_plugins` source (a `style.css` with `Theme Name:` and no +plugin entry file) and points to `extra_themes`. + Set `databaseType` to `mysql` when managed PHPUnit tests require MySQL semantics. The builder provisions a disposable MySQL service, maps its canonical `DB_*` outputs into the runtime, and writes those values into `wp-tests-config.php`. diff --git a/packages/cli/src/commands/recipe-build.ts b/packages/cli/src/commands/recipe-build.ts index 92d89238..60795275 100644 --- a/packages/cli/src/commands/recipe-build.ts +++ b/packages/cli/src/commands/recipe-build.ts @@ -1,5 +1,5 @@ import { readFile, writeFile } from "node:fs/promises" -import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core" +import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeExtraTheme, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core" interface RecipeBuildOptions { recipeType: "phpunit" | "bench" | "template" | "generic-ability-runtime-run" | "runtime-package-run" @@ -19,6 +19,7 @@ interface WordPressPhpunitBuilderOptions { mounts?: WorkspaceRecipeMount[] services?: WorkspaceRecipeRuntimeService[] extra_plugins?: WorkspaceRecipeExtraPlugin[] + extra_themes?: WorkspaceRecipeExtraTheme[] pluginSource?: string pluginSlug: string cwd?: string @@ -92,6 +93,7 @@ function buildRecipe(recipeType: RecipeBuildOptions["recipeType"], options: Word mounts: Array.isArray(phpunitOptions.mounts) ? phpunitOptions.mounts : [], services: Array.isArray(phpunitOptions.services) ? phpunitOptions.services : [], extra_plugins: Array.isArray(phpunitOptions.extra_plugins) ? phpunitOptions.extra_plugins : [], + extra_themes: Array.isArray(phpunitOptions.extra_themes) ? phpunitOptions.extra_themes : [], pluginSource: stringOrUndefined(phpunitOptions.pluginSource), pluginSlug: requiredString(phpunitOptions.pluginSlug, "pluginSlug"), cwd: stringOrUndefined(phpunitOptions.cwd), diff --git a/packages/cli/src/recipe-validation.ts b/packages/cli/src/recipe-validation.ts index 74a1d862..a491cf45 100644 --- a/packages/cli/src/recipe-validation.ts +++ b/packages/cli/src/recipe-validation.ts @@ -745,7 +745,12 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe, } if (pluginMountedSource && !localZipSource) { - await validateExistingFile(join(pluginMountedSource, pluginFile.slice(slug.length + 1)), `${path}.pluginFile`, addIssue) + const pluginEntryPath = join(pluginMountedSource, pluginFile.slice(slug.length + 1)) + if (!await isExistingFile(pluginEntryPath) && await looksLikeThemeDirectory(pluginMountedSource)) { + addIssue("missing-path", `${path}.pluginFile`, `File does not exist: ${pluginEntryPath}. The extra_plugins source ${pluginMountedSource} looks like a theme (style.css declares Theme Name:), not a plugin; declare it under inputs.extra_themes (or the phpunit builder's extra_themes option) instead of extra_plugins.`) + continue + } + await validateExistingFile(pluginEntryPath, `${path}.pluginFile`, addIssue) } } @@ -2094,6 +2099,24 @@ async function validateExistingBackendPackageSource(path: string, issuePath: str addIssue("missing-backend-package-source", issuePath, `Runtime backend package source must be an existing file or directory: ${path}`) } +async function isExistingFile(path: string): Promise { + try { + return (await stat(path)).isFile() + } catch { + return false + } +} + +/** True when a directory carries a theme style.css header (`Theme Name:`). */ +export async function looksLikeThemeDirectory(directory: string): Promise { + try { + const styleCss = await readFile(join(directory, "style.css"), "utf8") + return /^[ \t/*#@]*Theme Name\s*:/im.test(styleCss.slice(0, 8192)) + } catch { + return false + } +} + async function validateExistingFile(path: string, issuePath: string, addIssue: (code: string, path: string, message: string) => void): Promise { try { const result = await stat(path) diff --git a/packages/runtime-core/src/recipe-builders.ts b/packages/runtime-core/src/recipe-builders.ts index 64ae935f..20be6766 100644 --- a/packages/runtime-core/src/recipe-builders.ts +++ b/packages/runtime-core/src/recipe-builders.ts @@ -1,4 +1,4 @@ -import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js" +import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeExtraTheme, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js" import { commandArg, commandJsonArg, commandStringListArg } from "./command-codecs.js" export { buildRuntimePackageRunRecipe, CODEBOX_RUN_RUNTIME_PACKAGE_ABILITY, RUNTIME_PACKAGE_ARTIFACT_DECLARATION_SCHEMA, RUNTIME_PACKAGE_EXECUTION_INPUT_SCHEMA, RUNTIME_PACKAGE_EXECUTION_RESULT_SCHEMA, RUNTIME_PACKAGE_OUTPUT_PROJECTION_SCHEMA, runtimePackageExecutionInput, type RuntimePackageArtifactDeclaration, type RuntimePackageExecutionInput, type RuntimePackageOutputProjection, type RuntimePackageRunRecipeOptions } from "./runtime-package-execution.js" export { RUNTIME_PACKAGE_DIAGNOSTIC_SCHEMA, RUNTIME_PACKAGE_RESULT_SCHEMA, RUNTIME_PACKAGE_TASK_SCHEMA, normalizeRuntimePackageResult, normalizeRuntimePackageTask, validateRuntimePackageTask, type RuntimePackageDiagnostic, type RuntimePackageResult, type RuntimePackageTask } from "./runtime-package-contracts.js" @@ -25,6 +25,13 @@ export interface WordPressPhpunitRecipeOptions { mounts?: WorkspaceRecipeMount[] services?: WorkspaceRecipeRuntimeService[] extra_plugins?: WorkspaceRecipeExtraPlugin[] + /** + * Theme dependencies, same shape as recipe `inputs.extra_themes`. Themes are + * mounted under wp-content/themes/; the `activate: true` theme becomes + * the active theme for the managed PHPUnit bootstrap so its functions.php + * (and its parent's, for child themes) loads before component tests run. + */ + extra_themes?: WorkspaceRecipeExtraTheme[] pluginSource?: string pluginSlug: string cwd?: string @@ -79,6 +86,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio const autoloadFile = options.autoloadFile ?? (options.bootstrapMode === "project" ? "" : "/wp-codebox-vendor/autoload.php") const services = phpunitRuntimeServices(options.databaseType, options.services) const extraPlugins = normalizeExtraPlugins(options.extra_plugins) + const extraThemes = normalizeExtraThemes(options.extra_themes) if (options.databaseType === "mdi-native") { const nativePlugin = nativeMdiPlugin(extraPlugins) const nativeIndex = extraPlugins.findIndex((plugin) => plugin.slug === "markdown-database-integration") @@ -104,6 +112,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio }, inputs: { extra_plugins: extraPlugins, + ...(extraThemes.length > 0 ? { extra_themes: extraThemes } : {}), ...(services.length > 0 ? { services } : {}), mounts: normalizeRecipeMounts([ ...(options.pluginSource ? [{ source: options.pluginSource, target: pluginTarget } satisfies WorkspaceRecipeMount] : []), @@ -131,6 +140,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio commandArg("phpunit-xml-default", options.phpunitXml === undefined ? "1" : ""), commandStringListArg("dependency-mounts", options.dependencyMounts ?? []), commandJsonArg("dependency-plugins-json", phpunitDependencyPlugins(options.dependencyMounts ?? [], extraPlugins)), + ...(extraThemes.length > 0 ? [commandJsonArg("dependency-themes-json", phpunitDependencyThemes(extraThemes))] : []), commandJsonArg("bootstrap-files-json", options.bootstrapFiles ?? []), commandJsonArg("preload-files-json", options.preloadFiles ?? []), commandJsonArg("phpunit-args-json", options.phpunitArgs ?? []), @@ -162,6 +172,46 @@ function phpunitDependencyPlugins(mounts: readonly string[], plugins: readonly W }) } +export interface PhpunitDependencyTheme { + slug: string + path: string + activate: boolean +} + +/** + * Projects recipe extra_themes into the managed PHPUnit bootstrap contract. + * Slugs follow the recipe source contract: mountSlug, then slug, then the + * local source directory basename. + */ +export function phpunitDependencyThemes(themes: readonly WorkspaceRecipeExtraTheme[]): PhpunitDependencyTheme[] { + if (themes.filter((theme) => theme.activate === true).length > 1) { + throw new Error("buildWordPressPhpunitRecipe extra_themes permits at most one active theme") + } + const seen = new Set() + return themes.map((theme, index) => { + const slug = phpunitDependencyThemeSlug(theme, index) + if (seen.has(slug)) { + throw new Error(`buildWordPressPhpunitRecipe extra_themes slugs must be unique: ${slug}`) + } + seen.add(slug) + return { slug, path: `/wordpress/wp-content/themes/${slug}`, activate: theme.activate === true } + }) +} + +function phpunitDependencyThemeSlug(theme: WorkspaceRecipeExtraTheme, index: number): string { + const explicit = theme.mountSlug ?? theme.slug + const inferred = explicit ?? (theme.source ?? theme.sourcePath ?? "") + .replace(/[?#].*$/, "") + .replace(/[\\/]+$/g, "") + .split(/[\\/]/) + .pop() + const slug = (inferred ?? "").trim() + if (!/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) { + throw new Error(`buildWordPressPhpunitRecipe extra_themes[${index}] requires a theme directory slug (set slug or mountSlug): ${slug || ""}`) + } + return slug +} + function nativeMdiPlugin(plugins: readonly WorkspaceRecipeExtraPlugin[]): WorkspaceRecipeExtraPlugin { const candidates = plugins.filter((plugin) => plugin.slug === "markdown-database-integration") if (candidates.length > 1) { @@ -334,6 +384,26 @@ function normalizeExtraPlugins(plugins: readonly WorkspaceRecipeExtraPlugin[] = }) } +function normalizeExtraThemes(themes: readonly WorkspaceRecipeExtraTheme[] = []): WorkspaceRecipeExtraTheme[] { + const normalized = themes.map((theme, index) => { + if (!theme || typeof theme !== "object") { + throw new Error(`Recipe extra theme ${index} must be an object`) + } + if ((typeof theme.source !== "string" || !theme.source) && (typeof theme.sourcePath !== "string" || !theme.sourcePath)) { + throw new Error(`Recipe extra theme ${index} requires source`) + } + const entry: WorkspaceRecipeExtraTheme = {} + for (const key of ["source", "sourcePath", "sourceRoot", "sourceSubpath", "sourceSubdir", "originalSource", "slug", "mountSlug", "activate", "sha256", "metadata"] as const) { + if (theme[key] !== undefined) { + (entry as Record)[key] = theme[key] + } + } + return entry + }) + phpunitDependencyThemes(normalized) + return normalized +} + function blueprintWithWpConfigDefines(blueprint: unknown, defines: JsonObject): unknown { const defineKeys = Object.keys(defines) if (defineKeys.length === 0) { diff --git a/packages/runtime-playground/src/phpunit-command-handlers.ts b/packages/runtime-playground/src/phpunit-command-handlers.ts index 0eb9f13d..cdfe5f56 100644 --- a/packages/runtime-playground/src/phpunit-command-handlers.ts +++ b/packages/runtime-playground/src/phpunit-command-handlers.ts @@ -19,6 +19,8 @@ export interface PhpunitRunCodeOptions { wpConfigDefines: Record dependencyMounts: string[] dependencyPlugins?: Array<{ path: string; pluginFile: string; activate: boolean; loadAs: "plugin" | "mu-plugin" }> + /** Mounted theme dependencies; the `activate` entry becomes the active theme and its functions.php loads. */ + dependencyThemes?: PhpunitDependencyThemeOption[] bootstrapFiles: string[] preloadFiles?: string[] bootstrapMode: string @@ -36,6 +38,29 @@ export interface PhpunitRunCodeOptions { junitFile?: string } +export interface PhpunitDependencyThemeOption { + slug: string + path: string + activate: boolean +} + +const PHPUNIT_DEPENDENCY_THEME_SLUG = /^[a-z0-9][a-z0-9_-]*$/i + +/** Parses `dependency-themes-json` entries into the managed bootstrap theme contract. */ +export function parsePhpunitDependencyThemes(entries: readonly unknown[]): PhpunitDependencyThemeOption[] { + const themes = entries.map((entry) => { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error("dependency-themes-json entries must be objects") + const metadata = entry as Record + const slug = typeof metadata.slug === "string" ? metadata.slug.trim() : "" + if (!PHPUNIT_DEPENDENCY_THEME_SLUG.test(slug)) throw new Error(`dependency-themes-json entries require a theme directory slug: ${slug || ""}`) + const path = typeof metadata.path === "string" && metadata.path.trim() ? metadata.path.trim().replace(/\/+$/, "") : `/wordpress/wp-content/themes/${slug}` + if (path !== `/wordpress/wp-content/themes/${slug}`) throw new Error(`dependency-themes-json theme path must be /wordpress/wp-content/themes/${slug}: ${path}`) + return { slug, path, activate: metadata.activate === true } + }) + if (themes.filter((theme) => theme.activate).length > 1) throw new Error("dependency-themes-json permits at most one active theme") + return themes +} + export type PhpunitMultisitePreinstallCodeOptions = Pick export interface CorePhpunitRunCodeOptions { @@ -568,6 +593,7 @@ $bench_env = json_decode(${JSON.stringify(JSON.stringify(options.env))}, true); $wp_config_defines = json_decode(${JSON.stringify(JSON.stringify(options.wpConfigDefines))}, true); $dep_mounts = ${JSON.stringify(options.dependencyMounts.join("\n"))}; $dependency_plugins = json_decode(${JSON.stringify(JSON.stringify(options.dependencyPlugins ?? []))}, true); +$dependency_themes = json_decode(${JSON.stringify(JSON.stringify(options.dependencyThemes ?? []))}, true); $bootstrap_files = json_decode(${JSON.stringify(JSON.stringify(options.bootstrapFiles))}, true); $preload_files = json_decode(${JSON.stringify(JSON.stringify(options.preloadFiles ?? []))}, true); $bootstrap_mode = ${JSON.stringify(options.bootstrapMode || "managed")}; @@ -1257,6 +1283,118 @@ function pg_run_load_deps_stage(array $cfg): array { } } +function pg_theme_style_headers(string $style_css): array { + $contents = is_readable($style_css) ? (string) file_get_contents($style_css, false, null, 0, 8192) : ''; + $headers = array('name' => '', 'template' => ''); + if (preg_match('/^[ \\t\\/*#@]*Theme Name\\s*:(.*)$/mi', $contents, $match)) { + $headers['name'] = trim(preg_replace('/\\s*(?:\\*\\/|\\?>).*/', '', $match[1])); + } + if (preg_match('/^[ \\t\\/*#@]*Template\\s*:(.*)$/mi', $contents, $match)) { + $headers['template'] = trim(preg_replace('/\\s*(?:\\*\\/|\\?>).*/', '', $match[1])); + } + return $headers; +} + +function pg_resolve_dependency_theme_dir(string $theme_root, string $slug): string { + if (!preg_match('/^[a-z0-9][a-z0-9_-]*$/i', $slug)) { + throw new RuntimeException('managed PHPUnit theme dependency slug is invalid: ' . $slug); + } + $theme_dir = realpath($theme_root . '/' . $slug); + if ($theme_dir === false || !is_dir($theme_dir) || dirname($theme_dir) !== $theme_root) { + throw new RuntimeException('managed PHPUnit theme dependency is not mounted as a direct child of the WordPress themes root: ' . $theme_root . '/' . $slug); + } + $headers = pg_theme_style_headers($theme_dir . '/style.css'); + if ($headers['name'] === '') { + throw new RuntimeException('managed PHPUnit theme dependency has no style.css Theme Name header: ' . $slug); + } + return $theme_dir; +} + +/** + * Makes the declared active theme dependency the active theme and loads its + * functions.php (child first, then parent, as wp-settings.php does). The + * wp-phpunit install runs with WP_INSTALLING, so WordPress itself never loads + * theme functions during the managed bootstrap. + */ +function pg_run_load_theme_deps_stage(array $cfg): array { + pg_stage_begin('load_theme_deps'); + try { + $result = array('stylesheet' => null, 'template' => null, 'loaded' => array()); + $themes = is_array($cfg['themes'] ?? null) ? $cfg['themes'] : array(); + if (empty($themes)) { + pg_stage_ok('load_theme_deps'); + return $result; + } + $declared_root = defined('WP_CONTENT_DIR') ? WP_CONTENT_DIR . '/themes' : '/wordpress/wp-content/themes'; + $theme_root = realpath($declared_root); + if ($theme_root === false || !is_dir($theme_root)) { + throw new RuntimeException('WordPress themes root is unavailable while loading managed PHPUnit theme dependencies: ' . $declared_root); + } + $active = null; + foreach ($themes as $theme) { + if (!is_array($theme) || !is_string($theme['slug'] ?? null)) { + throw new RuntimeException('managed PHPUnit theme dependency metadata must contain a slug'); + } + pg_resolve_dependency_theme_dir($theme_root, $theme['slug']); + pg_log('THEME_DEPENDENCY_MOUNTED ' . $theme['slug']); + if (!empty($theme['activate'])) { + if ($active !== null) { + throw new RuntimeException('managed PHPUnit theme dependencies permit at most one active theme'); + } + $active = $theme['slug']; + } + } + if ($active === null) { + pg_log('NOTICE:no theme dependency declares activate=true; theme functions.php not loaded'); + pg_stage_ok('load_theme_deps'); + return $result; + } + $stylesheet_dir = pg_resolve_dependency_theme_dir($theme_root, $active); + $headers = pg_theme_style_headers($stylesheet_dir . '/style.css'); + $template = $headers['template'] !== '' ? $headers['template'] : $active; + $template_dir = $template === $active ? $stylesheet_dir : pg_resolve_dependency_theme_dir($theme_root, $template); + if ($template !== $active && pg_theme_style_headers($template_dir . '/style.css')['template'] !== '') { + throw new RuntimeException('managed PHPUnit child theme parent must be a standalone theme: ' . $template); + } + if (function_exists('update_option')) { + update_option('template', $template); + update_option('stylesheet', $active); + } + if (function_exists('wp_clean_themes_cache')) { + wp_clean_themes_cache(false); + } + if (function_exists('wp_set_template_globals')) { + wp_set_template_globals(); + } + if (function_exists('wp_get_theme')) { + $wp_theme = wp_get_theme($active); + if ($wp_theme->errors()) { + pg_log('NOTICE:theme dependency ' . $active . ' reports errors: ' . $wp_theme->errors()->get_error_message()); + } + } + pg_log('THEME_DEPENDENCY_ACTIVE ' . $active . ($template !== $active ? ' template=' . $template : '')); + $result['stylesheet'] = $active; + $result['template'] = $template; + $pre_after_setup_theme = function_exists('add_action') ? pg_snapshot_wordpress_hook_callbacks('after_setup_theme') : array(); + foreach (array_unique(array($stylesheet_dir, $template_dir)) as $theme_dir) { + $functions = $theme_dir . '/functions.php'; + if (is_file($functions) && is_readable($functions)) { + pg_log('THEME_FUNCTIONS_LOAD ' . basename($theme_dir) . '/functions.php'); + require_once $functions; + $result['loaded'][] = $functions; + } + } + if (function_exists('add_action')) { + pg_run_deferred_wordpress_hook_callbacks(pg_defer_new_wordpress_hook_callbacks('after_setup_theme', $pre_after_setup_theme), array(), 'after_setup_theme'); + } + pg_stage_ok('load_theme_deps'); + return $result; + } catch (Throwable $e) { + pg_stage_fail('load_theme_deps', $e); + exit(1); + } +} + function pg_run_load_component_stage(array $cfg): ?string { pg_stage_begin('load_component'); try { @@ -1487,6 +1625,7 @@ $reopened_ability_categories_init = pg_reopen_wordpress_action('wp_abilities_api $reopened_ability_init = pg_reopen_wordpress_action('wp_abilities_api_init'); pg_run_deferred_wordpress_hook_callbacks($deferred_install_plugins_loaded_callbacks, array(), 'plugins_loaded'); pg_run_deferred_wordpress_hook_callbacks($deferred_dependency_plugins_loaded_callbacks, array(), 'plugins_loaded'); +$theme_dependency_load = pg_run_load_theme_deps_stage(array('themes' => $dependency_themes)); $deferred_install_init_callbacks = array_merge($deferred_install_init_callbacks, $deferred_dependency_init_callbacks, pg_defer_new_wordpress_hook_callbacks('init', $pre_replayed_plugins_loaded_init_callbacks)); usort($deferred_install_init_callbacks, static function (array $left, array $right): int { return ($left['priority'] ?? 10) <=> ($right['priority'] ?? 10); diff --git a/packages/runtime-playground/src/wordpress-command-runners.ts b/packages/runtime-playground/src/wordpress-command-runners.ts index fdd9d2a0..39f9296e 100644 --- a/packages/runtime-playground/src/wordpress-command-runners.ts +++ b/packages/runtime-playground/src/wordpress-command-runners.ts @@ -29,6 +29,7 @@ import { cacheChurnObservationPhpCode, restPerformanceObservationInputFromArgs, restPerformanceObservationPhpCode, + parsePhpunitDependencyThemes, phpunitRunCode, phpunitMultisitePreinstallCode, pluginStateInputFromArgs, @@ -994,6 +995,7 @@ export async function runPhpunitCommand({ if (!pluginFile) throw new Error("dependency-plugins-json entries require pluginFile") return { path, pluginFile, activate: metadata.activate !== false, loadAs: metadata.loadAs === "mu-plugin" ? "mu-plugin" as const : "plugin" as const } }), + dependencyThemes: parsePhpunitDependencyThemes(jsonArrayArg(args, "dependency-themes-json")), bootstrapFiles: jsonArrayArg(args, "bootstrap-files-json").filter((value): value is string => typeof value === "string"), preloadFiles: jsonArrayArg(args, "preload-files-json").filter((value): value is string => typeof value === "string"), bootstrapMode, diff --git a/scripts/smoke-discovery.ts b/scripts/smoke-discovery.ts index 1e68ab1a..64cdc826 100644 --- a/scripts/smoke-discovery.ts +++ b/scripts/smoke-discovery.ts @@ -64,6 +64,7 @@ const BROWSER_FILES: readonly string[] = [ /* Files that share process handlers or Playground caches remain serial within their lane. */ const DISCOVERY_SERIAL: readonly string[] = [ "tests/bounded-recipe-plan.integration.test.ts", + "tests/phpunit-extra-themes.integration.test.ts", "tests/phpunit-runtime-rejection.test.ts", "tests/playground-readonly-mounts-integration.test.ts", "tests/playground-readonly-mounts.test.ts", diff --git a/tests/phpunit-extra-themes.integration.test.ts b/tests/phpunit-extra-themes.integration.test.ts new file mode 100644 index 00000000..28fdf9aa --- /dev/null +++ b/tests/phpunit-extra-themes.integration.test.ts @@ -0,0 +1,65 @@ +import assert from "node:assert/strict" +import { execFile } from "node:child_process" +import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { promisify } from "node:util" + +import { buildWordPressPhpunitRecipe } from "../packages/runtime-core/src/index.js" + +// End-to-end coverage for https://github.com/Automattic/wp-codebox/issues/2604: +// a plugin whose PHPUnit tests call a sibling theme's functions.php helpers runs +// green when the theme is declared through the phpunit builder's extra_themes. + +const execFileAsync = promisify(execFile) +const root = await mkdtemp(join(tmpdir(), "wp-codebox-phpunit-extra-themes-")) +const harnessFixture = join(root, "harness") +const harnessVendor = join(harnessFixture, "vendor") + +try { + await cp("tests/fixtures/phpunit-playground-harness", harnessFixture, { recursive: true }) + await execFileAsync("composer", ["install", "--no-interaction", "--prefer-dist"], { cwd: harnessFixture, timeout: 300_000, maxBuffer: 2 * 1024 * 1024 }) + const pluginDir = join(root, "theme-consumer") + const themeDir = join(root, "themes", "consumer-theme") + await mkdir(join(pluginDir, "tests"), { recursive: true }) + await mkdir(themeDir, { recursive: true }) + await writeFile(join(pluginDir, "theme-consumer.php"), "\ntests\n`) + await writeFile(join(pluginDir, "tests", "ThemeHelperTest.php"), `assertTrue(function_exists('consumer_theme_helper')); + $this->assertSame('consumer-theme-helper', consumer_theme_helper()); + $this->assertSame('consumer-theme', get_stylesheet()); + $this->assertTrue(did_action('consumer_theme_setup') > 0); + } +} +`) + await writeFile(join(themeDir, "style.css"), "/*\nTheme Name: Consumer Theme\n*/\n") + await writeFile(join(themeDir, "index.php"), " candidate.command === "wordpress.phpunit") + return step?.args?.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1) +} + +function extractPhpFunction(source: string, functionName: string): string { + const start = source.indexOf(`function ${functionName}(`) + assert.notEqual(start, -1, `expected generated PHP to declare ${functionName}`) + let depth = 0 + let sawBody = false + for (let index = start; index < source.length; index++) { + const character = source[index] + if (character === "{") { + depth++ + sawBody = true + } else if (character === "}") { + depth-- + if (sawBody && depth === 0) return source.slice(start, index + 1) + } + } + throw new Error(`could not find the end of ${functionName}`) +} + +function runCodeOptions(overrides: Partial = {}): PhpunitRunCodeOptions { + return { + pluginSlug: "theme-consumer", + cwd: "/wordpress/wp-content/plugins/theme-consumer", + autoloadFile: "/wp-codebox-vendor/autoload.php", + testsDir: "/wp-codebox-vendor/wp-phpunit/wp-phpunit", + phpunitXml: "/wordpress/wp-content/plugins/theme-consumer/phpunit.xml.dist", + phpunitXmlIsDefault: true, + selectedTestFile: "", + changedTestFiles: [], + phpunitArgs: [], + env: {}, + wpConfigDefines: {}, + dependencyMounts: [], + bootstrapFiles: [], + bootstrapMode: "managed", + projectBootstrap: "", + multisite: false, + databaseType: "sqlite", + ...overrides, + } +} + +// 1. `recipe build phpunit` accepts extra_themes and emits them into the recipe. +await withTempDir("wp-codebox-phpunit-extra-themes-build-", async (directory) => { + const optionsPath = join(directory, "options.json") + const outputPath = join(directory, "recipe.json") + await writeFile(optionsPath, JSON.stringify({ + pluginSlug: "theme-consumer", + pluginSource: "./theme-consumer", + extra_plugins: [{ source: "./helper-plugin", slug: "helper-plugin" }], + extra_themes: [ + { source: "./themes/extrachill/", activate: true }, + { source: "./themes/spare", slug: "spare-theme" }, + ], + })) + + assert.equal(await runRecipeBuildCommand(["phpunit", "--options", optionsPath, "--output", outputPath]), 0) + const recipe = JSON.parse(await readFile(outputPath, "utf8")) as WorkspaceRecipe + assertWorkspaceRecipeJsonSchema(recipe) + assert.deepEqual(recipe.inputs?.extra_themes, [ + { source: "./themes/extrachill/", activate: true }, + { source: "./themes/spare", slug: "spare-theme" }, + ]) + assert.deepEqual(JSON.parse(phpunitStepArg(recipe, "dependency-themes-json") ?? "null"), [ + { slug: "extrachill", path: "/wordpress/wp-content/themes/extrachill", activate: true }, + { slug: "spare-theme", path: "/wordpress/wp-content/themes/spare-theme", activate: false }, + ]) + assert.deepEqual(recipe.inputs?.extra_plugins, [{ source: "./helper-plugin", slug: "helper-plugin" }]) +}) + +// Recipes without theme dependencies keep their previous shape. +{ + const recipe = buildWordPressPhpunitRecipe({ pluginSlug: "theme-consumer" }) + assert.equal(recipe.inputs?.extra_themes, undefined) + assert.equal(phpunitStepArg(recipe, "dependency-themes-json"), undefined) +} + +// Builder guards mirror recipe extra_themes rules. +assert.throws(() => buildWordPressPhpunitRecipe({ pluginSlug: "x", extra_themes: [{ source: "./a", activate: true }, { source: "./b", activate: true }] }), /at most one active theme/) +assert.throws(() => buildWordPressPhpunitRecipe({ pluginSlug: "x", extra_themes: [{ source: "./a" }, { source: "./other/a" }] }), /slugs must be unique: a/) +assert.throws(() => buildWordPressPhpunitRecipe({ pluginSlug: "x", extra_themes: [{ activate: true }] }), /requires source/) +assert.throws(() => buildWordPressPhpunitRecipe({ pluginSlug: "x", extra_themes: [{ source: "https://example.test/theme.zip" }] }), /set slug or mountSlug/) +assert.deepEqual(phpunitDependencyThemes([{ source: "https://example.test/theme.zip", mountSlug: "remote-theme", activate: true }]), [ + { slug: "remote-theme", path: "/wordpress/wp-content/themes/remote-theme", activate: true }, +]) + +// 2. Validation: a theme passed as extra_plugins points to extra_themes; extra_themes validates cleanly. +await withTempDir("wp-codebox-phpunit-extra-themes-validate-", async (directory) => { + const themeDir = join(directory, "themes", "extrachill") + await mkdir(themeDir, { recursive: true }) + await writeFile(join(themeDir, "style.css"), "/*\nTheme Name: Extra Chill\n*/\n") + await writeFile(join(themeDir, "functions.php"), " issue.path === "$.inputs.extra_plugins[0].pluginFile") + assert.ok(pluginFileIssue, JSON.stringify(issues)) + assert.equal(pluginFileIssue.code, "missing-path") + assert.match(pluginFileIssue.message, /looks like a theme/) + assert.match(pluginFileIssue.message, /Theme Name:/) + assert.match(pluginFileIssue.message, /extra_themes/) + + // A plain missing plugin entry (no theme header) keeps the original message. + const notTheme = join(directory, "not-a-theme") + await mkdir(notTheme, { recursive: true }) + await writeFile(join(notTheme, "readme.txt"), "nothing\n") + const plainIssues = await validateWorkspaceRecipeSemantics(buildWordPressPhpunitRecipe({ pluginSlug: "theme-consumer", pluginSource: pluginDir, extra_plugins: [{ source: notTheme }] }), recipePath) + const plainIssue = plainIssues.find((issue) => issue.path === "$.inputs.extra_plugins[0].pluginFile") + assert.ok(plainIssue, JSON.stringify(plainIssues)) + assert.doesNotMatch(plainIssue.message, /extra_themes/) + assert.match(plainIssue.message, /^File does not exist: /) + + const declared = buildWordPressPhpunitRecipe({ pluginSlug: "theme-consumer", pluginSource: pluginDir, extra_themes: [{ source: themeDir, activate: true }] }) + assertWorkspaceRecipeJsonSchema(declared) + const declaredIssues = await validateWorkspaceRecipeSemantics(declared, recipePath) + assert.deepEqual(declaredIssues.filter((issue) => issue.path.includes("extra_themes") || issue.path.includes("extra_plugins")), []) +}) + +// 3. Runner arg parsing for dependency-themes-json. +assert.deepEqual(parsePhpunitDependencyThemes([{ slug: "extrachill", activate: true }, { slug: "base", path: "/wordpress/wp-content/themes/base/" }]), [ + { slug: "extrachill", path: "/wordpress/wp-content/themes/extrachill", activate: true }, + { slug: "base", path: "/wordpress/wp-content/themes/base", activate: false }, +]) +assert.throws(() => parsePhpunitDependencyThemes(["extrachill"]), /must be objects/) +assert.throws(() => parsePhpunitDependencyThemes([{ slug: "../escape" }]), /theme directory slug/) +assert.throws(() => parsePhpunitDependencyThemes([{ slug: "a", path: "/tmp/a" }]), /theme path must be/) +assert.throws(() => parsePhpunitDependencyThemes([{ slug: "a", activate: true }, { slug: "b", activate: true }]), /at most one active theme/) + +// 4. Managed bootstrap: generated PHP is valid, threads the theme list, and loads +// theme functions after dependency plugins but before fixtures/tests. +const dependencyThemes = [{ slug: "child-theme", path: "/wordpress/wp-content/themes/child-theme", activate: true }, { slug: "parent-theme", path: "/wordpress/wp-content/themes/parent-theme", activate: false }] +const runCode = phpunitRunCode(runCodeOptions({ dependencyThemes })) +assert.ok(runCode.includes(`$dependency_themes = json_decode(${JSON.stringify(JSON.stringify(dependencyThemes))}, true);`)) +const loadDepsAt = runCode.indexOf("$dependency_load = pg_run_load_deps_stage(") +const themeStageAt = runCode.indexOf("$theme_dependency_load = pg_run_load_theme_deps_stage(array('themes' => $dependency_themes));") +const initReplayAt = runCode.indexOf("pg_run_deferred_wordpress_hook_callbacks($deferred_install_init_callbacks, array(), 'init');") +const fixturesAt = runCode.indexOf("pg_stage_begin('load_fixtures');") +assert.ok(loadDepsAt > 0 && themeStageAt > loadDepsAt, "theme dependencies load after dependency plugins") +assert.ok(initReplayAt > themeStageAt, "theme init callbacks are captured before the deferred init replay") +assert.ok(fixturesAt > themeStageAt, "theme functions load before fixtures and component tests") +assert.ok(phpunitRunCode(runCodeOptions()).includes("$dependency_themes = json_decode(\"[]\", true);")) + +await withTempDir("wp-codebox-phpunit-extra-themes-lint-", async (directory) => { + const scriptPath = join(directory, "runner.php") + await writeFile(scriptPath, ` { + const contentDir = join(directory, "wp-content") + const parentDir = join(contentDir, "themes", "parent-theme") + const childDir = join(contentDir, "themes", "child-theme") + await mkdir(parentDir, { recursive: true }) + await mkdir(childDir, { recursive: true }) + await writeFile(join(parentDir, "style.css"), "/*\nTheme Name: Parent Theme\n*/\n") + await writeFile(join(parentDir, "functions.php"), " extractPhpFunction(runCode, name)).join("\n\n") + const harness = ` $stage, 'error' => $e->getMessage())); exit(0); } +function pg_log($message) { $GLOBALS['log'][] = $message; } +function update_option($name, $value) { $GLOBALS['options'][$name] = $value; return true; } +function add_action($hook, $callback) { $GLOBALS['hooks'][$hook][] = $callback; return true; } +function pg_snapshot_wordpress_hook_callbacks($hook) { return array('count' => count($GLOBALS['hooks'][$hook] ?? array())); } +function pg_defer_new_wordpress_hook_callbacks($hook, $before) { $all = $GLOBALS['hooks'][$hook] ?? array(); $GLOBALS['hooks'][$hook] = array_slice($all, 0, $before['count']); return array_slice($all, $before['count']); } +function pg_run_deferred_wordpress_hook_callbacks($deferred, $args, $hook) { foreach ($deferred as $callback) { $callback(); } } +${stageFunctions} +$dependency_themes = json_decode(${JSON.stringify(JSON.stringify(dependencyThemes))}, true); +$result = pg_run_load_theme_deps_stage(array('themes' => $dependency_themes)); +// Simulates a component test calling theme helpers after bootstrap. +echo json_encode(array( + 'result' => $result, + 'options' => $GLOBALS['options'], + 'load_order' => $GLOBALS['load_order'], + 'setup' => $GLOBALS['setup'], + 'log' => $GLOBALS['log'], + 'helper' => function_exists('child_theme_helper') ? child_theme_helper() : null, +)); +` + const harnessPath = join(directory, "harness.php") + await writeFile(harnessPath, harness) + const output = JSON.parse(execFileSync("php", [harnessPath], { encoding: "utf8" })) as { + failed?: string + error?: string + result: { stylesheet: string; template: string; loaded: string[] } + options: Record + load_order: string[] + setup: string[] + log: string[] + helper: string | null + } + assert.equal(output.failed, undefined, output.error) + assert.equal(output.result.stylesheet, "child-theme") + assert.equal(output.result.template, "parent-theme") + assert.deepEqual(output.options, { template: "parent-theme", stylesheet: "child-theme" }) + assert.deepEqual(output.load_order, ["child", "parent"]) + assert.deepEqual(output.setup, ["parent"]) + assert.equal(output.helper, "parent-helper+child") + assert.ok(output.log.includes("THEME_DEPENDENCY_ACTIVE child-theme template=parent-theme"), JSON.stringify(output.log)) + assert.deepEqual(output.log.filter((line) => line.startsWith("begin:") || line.startsWith("ok:")), ["begin:load_theme_deps", "ok:load_theme_deps"]) + + // An unmounted theme dependency fails the stage with a clear error. + const missing = harness.replace(JSON.stringify(JSON.stringify(dependencyThemes)), JSON.stringify(JSON.stringify([{ slug: "missing-theme", path: "/wordpress/wp-content/themes/missing-theme", activate: true }]))) + await writeFile(harnessPath, missing) + const failure = JSON.parse(execFileSync("php", [harnessPath], { encoding: "utf8" })) as { failed?: string; error?: string } + assert.equal(failure.failed, "load_theme_deps") + assert.match(failure.error ?? "", /not mounted as a direct child of the WordPress themes root/) +}) + +console.log("phpunit extra_themes tests passed")