-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathphpunit-project-autoload.test.ts
More file actions
472 lines (428 loc) · 24.5 KB
/
Copy pathphpunit-project-autoload.test.ts
File metadata and controls
472 lines (428 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import assert from "node:assert/strict"
import { execFileSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { buildWordPressPhpunitRecipe } from "../packages/runtime-core/src/recipe-builders.js"
import { corePhpunitRunCode, phpunitRunCode } from "../packages/runtime-playground/src/phpunit-command-handlers.js"
import { runPhpunitCommand } from "../packages/runtime-playground/src/wordpress-command-runners.js"
import { recipePolicy } from "../packages/cli/src/recipe-validation.js"
import { recipeExtraPluginSourceSubpath } from "../packages/cli/src/recipe-sources.js"
import { recipeInputMountPathMap, rewriteInputMountPathArgs } from "../packages/cli/src/commands/recipe-runtime-setup.js"
const woocommerceAutoload = "/wordpress/wp-content/plugins/woocommerce/vendor/autoload_packages.php"
const phpunitRuntimeSpec = {
runtimeEnv: { TC_MYSQL_PORT: "3306" },
} as never
function phpunitRecipeArgs(options: Omit<Parameters<typeof buildWordPressPhpunitRecipe>[0], "pluginSlug">): string[] {
return buildWordPressPhpunitRecipe({ pluginSlug: "demo-plugin", ...options }).workflow.steps[0].args
}
const projectRecipeWithoutAutoload = phpunitRecipeArgs({ bootstrapMode: "project" })
assert.ok(projectRecipeWithoutAutoload.includes("autoload-file="))
assert.ok(!projectRecipeWithoutAutoload.some((arg) => arg === "autoload-file-role=harness"), "project mode without an autoload file must not require the harness")
const managedRecipe = phpunitRecipeArgs({})
assert.ok(managedRecipe.includes("autoload-file=/wp-codebox-vendor/autoload.php"))
assert.ok(managedRecipe.includes("autoload-file-role=harness"))
const explicitAutoloadRecipe = phpunitRecipeArgs({
bootstrapMode: "project",
autoloadFile: "/wp-codebox-vendor/autoload.php",
projectAutoloadFile: "/workspace/project/vendor/autoload.php",
})
assert.ok(explicitAutoloadRecipe.includes("autoload-file=/wp-codebox-vendor/autoload.php"))
assert.ok(explicitAutoloadRecipe.includes("autoload-file-role=harness"))
assert.ok(explicitAutoloadRecipe.includes("project-autoload-file=/workspace/project/vendor/autoload.php"))
function extractPhpFunction(source: string, functionName: string): string {
const start = source.indexOf(`function ${functionName}(`)
assert.notEqual(start, -1)
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 extract PHP function ${functionName}`)
}
function phpString(value: string): string {
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`
}
function assertPhpunitParseConfigFallbacksReturnFiveTuple(source: string, functionName: string, logFunctionName: string): void {
const tempDir = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-config-"))
const malformedXml = join(tempDir, "phpunit.xml.dist")
const scriptPath = join(tempDir, "assert-phpunit-config.php")
writeFileSync(malformedXml, "<phpunit><testsuites>")
const parseConfigFunction = extractPhpFunction(source, functionName)
writeFileSync(scriptPath, `<?php
function ${logFunctionName}($message) {}
${parseConfigFunction}
function assert_phpunit_config_tuple($tuple, $label) {
if (!is_array($tuple) || count($tuple) !== 5) {
throw new RuntimeException($label . ' returned ' . gettype($tuple) . ' with ' . (is_array($tuple) ? count($tuple) : 'n/a') . ' values');
}
if (!is_array($tuple[4])) {
throw new RuntimeException($label . ' returned non-array configured files');
}
}
assert_phpunit_config_tuple(${functionName}(${phpString(join(tempDir, "missing.xml.dist"))}, ${phpString(join(tempDir, "tests"))}), 'missing config');
assert_phpunit_config_tuple(${functionName}(${phpString(malformedXml)}, ${phpString(join(tempDir, "tests"))}), 'parse failure');
echo "ok\n";
`)
assert.equal(execFileSync("php", [scriptPath], { encoding: "utf8" }), "ok\n")
}
function assertSelectedTestFileResolution(source: string): void {
const tempDir = mkdtempSync(join(tmpdir(), "wp-codebox-selected-test-file-"))
const pluginRoot = join(tempDir, "demo-plugin")
const testRoot = join(pluginRoot, "tests")
const nestedTestDir = join(testRoot, "Feature")
const selectedTestFile = join(nestedTestDir, "ExampleTest.php")
const scriptPath = join(tempDir, "assert-selected-test-file.php")
mkdirSync(nestedTestDir, { recursive: true })
writeFileSync(selectedTestFile, "<?php // test\n")
const selectedTestFileReal = realpathSync(selectedTestFile)
const resolverFunction = extractPhpFunction(source, "pg_resolve_selected_test_file")
writeFileSync(scriptPath, `<?php
${resolverFunction}
$plugin_root = ${phpString(pluginRoot)};
$test_root = ${phpString(testRoot)};
$selected_test_file = ${phpString(selectedTestFile)};
$cases = array(
'relative-to-test-root' => pg_resolve_selected_test_file('Feature/ExampleTest.php', $test_root, $plugin_root, $plugin_root),
'relative-to-runtime-root' => pg_resolve_selected_test_file('tests/Feature/ExampleTest.php', $test_root, $plugin_root, $plugin_root),
'absolute-runtime-path' => pg_resolve_selected_test_file($selected_test_file, $test_root, $plugin_root, $plugin_root),
);
echo json_encode($cases);
`)
assert.deepEqual(JSON.parse(execFileSync("php", [scriptPath], { encoding: "utf8" })), {
"relative-to-test-root": selectedTestFileReal,
"relative-to-runtime-root": selectedTestFileReal,
"absolute-runtime-path": selectedTestFile,
})
}
function assertProjectBootstrapHarnessGuard(source: string): void {
const tempDir = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-harness-guard-"))
const stubFile = join(tempDir, "phpunit-testsuite-stub.php")
const scriptPath = join(tempDir, "assert-harness-guard.php")
writeFileSync(stubFile, `<?php
namespace PHPUnit\\Framework;
class TestSuite {}
`)
const ensureFn = extractPhpFunction(source, "pg_ensure_phpunit_harness_loaded")
writeFileSync(scriptPath, `<?php
function pg_log($msg) {}
function pg_stage_begin($stage) {}
function pg_stage_ok($stage) {}
function pg_stage_fail($stage, Throwable $e) {}
${ensureFn}
if (class_exists('PHPUnit\\Framework\\TestSuite', false)) {
throw new RuntimeException('precondition failed: PHPUnit\\Framework\\TestSuite must not be preloaded in the test environment');
}
$reached_testsuite = false;
$boundary_message = '';
try {
pg_ensure_phpunit_harness_loaded();
$reached_testsuite = true;
} catch (RuntimeException $e) {
$boundary_message = $e->getMessage();
} catch (Throwable $e) {
throw new RuntimeException('REGRESSION: guard threw non-RuntimeException: ' . get_class($e) . ': ' . $e->getMessage());
}
if ($reached_testsuite) {
throw new RuntimeException('REGRESSION: harness guard did not fail when PHPUnit was unavailable; TestSuite construction would be reached');
}
foreach (array('PHPUnit\\Framework\\TestSuite', 'bootstrap-mode=project', 'project-autoload-file', 'autoload-file=/wp-codebox-vendor/autoload.php') as $needle) {
if (strpos($boundary_message, $needle) === false) {
throw new RuntimeException('REGRESSION: boundary error missing actionable hint: ' . $needle . '; message=' . $boundary_message);
}
}
spl_autoload_register(function ($class) {
if ($class !== 'PHPUnit\\Framework\\TestSuite') {
return;
}
require_once ${phpString(realpathSync(stubFile))};
});
try {
pg_ensure_phpunit_harness_loaded();
} catch (Throwable $e) {
throw new RuntimeException('REGRESSION: harness guard failed even though a project autoloader provides PHPUnit: ' . $e->getMessage());
}
echo "BOUNDARY_OK\n";
`)
assert.equal(execFileSync("php", [scriptPath], { encoding: "utf8" }), "BOUNDARY_OK\n")
}
const recipe = buildWordPressPhpunitRecipe({
pluginSlug: "woocommerce",
extra_plugins: [{
source: "/workspace/woocommerce",
sourceRoot: "/workspace/woocommerce",
sourceSubpath: "plugins/woocommerce",
slug: "woocommerce",
pluginFile: "woocommerce/woocommerce.php",
activate: false,
}],
bootstrapMode: "project",
projectBootstrap: "tests/legacy/bootstrap.php",
projectAutoloadFile: woocommerceAutoload,
cwd: "/home/example/public_html",
testRoot: "/home/example/public_html/bin/tests/phpunit",
phpunitXml: "/home/example/public_html/bin/tests/phpunit/phpunit.xml.dist",
mounts: [
{ source: "/workspace/wp-codebox-vendor", target: "/wp-codebox-vendor", mode: "readonly" },
{ source: "/workspace/project-tests", target: "/home/example/public_html/bin/tests", mode: "readonly" },
],
})
assert.deepEqual(recipe.inputs.extra_plugins, [{
source: "/workspace/woocommerce",
sourceRoot: "/workspace/woocommerce",
sourceSubpath: "plugins/woocommerce",
slug: "woocommerce",
pluginFile: "woocommerce/woocommerce.php",
activate: false,
}])
assert.equal(recipeExtraPluginSourceSubpath(recipe.inputs.extra_plugins[0], "/tmp"), "plugins/woocommerce")
assert.equal(recipePolicy(recipe).commands.includes("wordpress.run-php"), true)
assert.deepEqual(recipe.inputs.mounts?.filter((mount) => mount.target === "/wp-codebox-vendor" || mount.target === "/home/example/public_html/bin/tests"), [
{ source: "/workspace/wp-codebox-vendor", target: "/wp-codebox-vendor", mode: "readonly" },
{ source: "/workspace/project-tests", target: "/home/example/public_html/bin/tests", mode: "readonly" },
])
assert.deepEqual(recipe.workflow.steps[0].args.filter((arg) => arg.includes("autoload-file=")), [
"autoload-file=",
`project-autoload-file=${woocommerceAutoload}`,
])
assert.ok(!recipe.workflow.steps[0].args.includes("autoload-file-role=harness"), "project mode without an explicit autoload file preserves project-owned harness setup")
assert.deepEqual(rewriteInputMountPathArgs(recipe.workflow.steps[0].args, recipeInputMountPathMap(recipe)).filter((arg) => arg.includes("autoload-file=")), [
"autoload-file=",
`project-autoload-file=${woocommerceAutoload}`,
])
assert.ok(!rewriteInputMountPathArgs(recipe.workflow.steps[0].args, recipeInputMountPathMap(recipe)).includes("autoload-file-role=harness"), "CLI path canonicalization preserves absent harness autoload intent")
assert.ok(recipe.workflow.steps[0].args.includes("cwd=/home/example/public_html"))
assert.ok(recipe.workflow.steps[0].args.includes("test-root=/home/example/public_html/bin/tests/phpunit"))
assert.ok(recipe.workflow.steps[0].args.includes("phpunit-xml=/home/example/public_html/bin/tests/phpunit/phpunit.xml.dist"))
const projectModeCode = phpunitRunCode({
pluginSlug: "woocommerce",
cwd: "/wordpress/wp-content/plugins/woocommerce",
autoloadFile: woocommerceAutoload,
testsDir: "/wp-codebox-vendor/wp-phpunit/wp-phpunit",
testRoot: "/home/example/public_html/bin/tests/phpunit",
phpunitXml: "/wordpress/wp-content/plugins/woocommerce/phpunit.xml.dist",
selectedTestFile: "",
changedTestFiles: [],
phpunitArgs: ["--list-tests"],
env: {},
wpConfigDefines: {},
dependencyMounts: [],
bootstrapFiles: [],
bootstrapMode: "project",
projectBootstrap: "tests/legacy/bootstrap.php",
multisite: false,
})
const bootIndex = projectModeCode.indexOf("$config_path = pg_run_boot_stage")
const projectBootstrapIndex = projectModeCode.indexOf("pg_run_project_bootstrap_stage", bootIndex)
const projectAutoloadIndex = projectModeCode.indexOf("pg_run_project_autoload_stage", projectBootstrapIndex)
const phpunitArgvIndex = projectModeCode.indexOf("$_SERVER['argv'] = $phpunit_argv;")
assert.ok(bootIndex > 0)
assert.ok(phpunitArgvIndex > 0 && phpunitArgvIndex < projectBootstrapIndex, "project bootstrap must receive forwarded PHPUnit arguments")
assert.ok(projectBootstrapIndex > bootIndex)
assert.ok(projectAutoloadIndex > projectBootstrapIndex)
assert.ok(projectModeCode.includes("'autoload_required' => $bootstrap_mode !== 'project' || $harness_autoload_file !== ''"))
assert.ok(projectModeCode.includes("$legacy_project_autoload_file = $autoload_file"))
assert.ok(projectModeCode.includes('$autoload_file_role = "";'), "direct callers without an explicit role retain the legacy compatibility path")
assert.ok(projectModeCode.includes("if ($autoload_file_role === '' && $bootstrap_mode === 'project'"))
assert.ok(projectModeCode.includes("configured PHPUnit harness autoload file is not readable"))
assert.ok(projectModeCode.includes("NOTICE:project bootstrap mode continuing without configured PHPUnit harness autoload"))
assert.ok(projectModeCode.includes("$test_root = \"/home/example/public_html/bin/tests/phpunit\";"))
assert.ok(projectModeCode.includes("pg_resolve_test_root"))
assert.ok(projectModeCode.includes("pg_resolve_selected_test_file"))
assert.ok(projectModeCode.includes("function pg_project_bootstrap_real_path"))
assert.ok(projectModeCode.includes("$base_dir = dirname($xml_real);"))
assert.ok(projectModeCode.includes("$bootstrap_real = pg_project_bootstrap_real_path($bootstrap, $phpunit_xml, $from_config);"))
assert.ok(projectModeCode.includes("foreach ($xml->xpath('//testsuite/file') ?: array() as $file)"))
assert.ok(projectModeCode.includes("list($directories, $suffixes, $prefixes, $excludes, $configured_files) = wp_codebox_phpunit_parse_config"))
assert.ok(projectModeCode.includes("$test_files = wp_codebox_phpunit_discover($directories, $suffixes, $prefixes, $excludes, $configured_files);"))
assert.ok(projectModeCode.includes("' files=' . count($configured_files)"))
assert.equal(projectModeCode.match(/return array\(\$directories, \$suffixes, \$prefixes, \$excludes\);/g)?.length ?? 0, 0)
assert.equal(projectModeCode.match(/return \$return_values\(\);/g)?.length, 3)
assertPhpunitParseConfigFallbacksReturnFiveTuple(projectModeCode, "wp_codebox_phpunit_parse_config", "pg_log")
assertSelectedTestFileResolution(projectModeCode)
assert.ok(projectModeCode.includes("function pg_ensure_phpunit_harness_loaded(): void"))
assert.ok(projectModeCode.includes("PHPUnit harness is not initialized"))
assert.ok(projectModeCode.includes("pg_stage_begin('verify_harness')"))
const verifyHarnessIndex = projectModeCode.indexOf("pg_stage_begin('verify_harness')")
const projectModeTestsuiteIndex = projectModeCode.indexOf("$suite = new PHPUnit\\Framework\\TestSuite(")
assert.ok(verifyHarnessIndex > 0, "verify_harness stage must be present")
assert.ok(projectModeTestsuiteIndex > verifyHarnessIndex, "harness verification must precede TestSuite construction")
assertProjectBootstrapHarnessGuard(projectModeCode)
const canonicalHarnessProjectModeCode = phpunitRunCode({
pluginSlug: "woocommerce",
cwd: "/wordpress/wp-content/plugins/woocommerce",
autoloadFile: "/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/autoload.php",
autoloadFileRole: "harness",
projectAutoloadFile: woocommerceAutoload,
testsDir: "/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/wp-phpunit/wp-phpunit",
testRoot: "/home/example/public_html/bin/tests/phpunit",
phpunitXml: "/wordpress/wp-content/plugins/woocommerce/phpunit.xml.dist",
selectedTestFile: "",
changedTestFiles: [],
phpunitArgs: [],
env: {},
wpConfigDefines: {},
dependencyMounts: [],
bootstrapFiles: [],
bootstrapMode: "project",
projectBootstrap: "tests/legacy/bootstrap.php",
multisite: false,
})
assert.ok(canonicalHarnessProjectModeCode.includes('$autoload_file_role = "harness";'))
assert.ok(canonicalHarnessProjectModeCode.includes('$harness_autoload_file = $legacy_project_autoload_file !== \'\' ? \'/wp-codebox-vendor/autoload.php\' : $autoload_file;'))
const canonicalHarnessResolution = canonicalHarnessProjectModeCode.match(/\$legacy_project_autoload_file = '';[\s\S]*?\$harness_autoload_file = [^;]+;/)?.[0]
assert.ok(canonicalHarnessResolution, "generated project-mode code must resolve harness autoload intent")
const canonicalHarnessProbe = join(mkdtempSync(join(tmpdir(), "wp-codebox-canonical-harness-")), "probe.php")
writeFileSync(canonicalHarnessProbe, `<?php
$bootstrap_mode = 'project';
$autoload_file = '/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/autoload.php';
$autoload_file_role = 'harness';
$project_autoload_file = ${phpString(woocommerceAutoload)};
${canonicalHarnessResolution}
echo json_encode(array($legacy_project_autoload_file, $harness_autoload_file));
`)
assert.deepEqual(JSON.parse(execFileSync("php", [canonicalHarnessProbe], { encoding: "utf8" })), ["", "/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/autoload.php"], "a canonical staged harness path remains the harness in project mode")
let capturedCanonicalHarnessCode = ""
await runPhpunitCommand({
artifactRoot: mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-artifacts-")),
mounts: [],
runPlaygroundCommand: async (_command, _server, input) => {
capturedCanonicalHarnessCode = input.code
return { text: "ok", exitCode: 0 }
},
runtimeSpec: phpunitRuntimeSpec,
server: { playground: {} } as never,
spec: {
command: "wordpress.phpunit",
args: [
"plugin-slug=ai-provider-for-openai",
"bootstrap-mode=project",
"autoload-file=/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/autoload.php",
"autoload-file-role=harness",
"phpunit-xml=phpunit.xml.dist",
"test-file=tests/unit/Models/OpenAiEmbeddingGenerationModelTest.php",
],
},
})
assert.ok(capturedCanonicalHarnessCode.includes('$autoload_file = "/tmp/wp-codebox-inputs/0-wp-codebox-vendor-73845ca47d2f/autoload.php";'))
assert.ok(capturedCanonicalHarnessCode.includes('$autoload_file_role = "harness";'))
assert.ok(capturedCanonicalHarnessCode.includes('putenv("TC_MYSQL_PORT=3306");'), "runtime service environment is passed to the PHP executed by wordpress.phpunit")
assert.ok(capturedCanonicalHarnessCode.indexOf('putenv("TC_MYSQL_PORT=3306");') < capturedCanonicalHarnessCode.indexOf("require_once '/wordpress/wp-load.php';"), "runtime environment is available to project bootstrap code")
let capturedExplicitCode = ""
await runPhpunitCommand({
artifactRoot: mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-artifacts-")),
mounts: [],
runPlaygroundCommand: async (_command, _server, input) => {
capturedExplicitCode = input.code
return { text: "ok", exitCode: 0 }
},
runtimeSpec: phpunitRuntimeSpec,
server: { playground: {} } as never,
spec: {
command: "wordpress.phpunit",
args: ["code=<?php declare(strict_types=1); echo getenv('TC_MYSQL_PORT');", "env-json={\"TC_MYSQL_PORT\":\"3307\"}"],
},
})
assert.equal((capturedExplicitCode.match(/declare\(strict_types=1\);/g) ?? []).length, 1, "explicit PHP is normalized once at the runtime bootstrap boundary")
assert.ok(capturedExplicitCode.includes("echo getenv('TC_MYSQL_PORT');"), "explicit PHPUnit code receives the same runtime bootstrap")
assert.ok(capturedExplicitCode.indexOf('putenv("TC_MYSQL_PORT=3306");') < capturedExplicitCode.lastIndexOf("TC_MYSQL_PORT"), "explicit env-json handling remains after runtime environment bootstrap")
const coreModeCode = corePhpunitRunCode({
coreRoot: "/wordpress",
testsDir: "/wordpress/tests/phpunit",
phpunitXml: "/wordpress/phpunit.xml.dist",
selectedTestFile: "",
changedTestFiles: [],
autoloadFile: "/wp-codebox-vendor/autoload.php",
wpConfigDefines: {},
multisite: false,
})
assert.ok(coreModeCode.includes("list($directories, $suffixes, $prefixes, $excludes, $configured_files) = core_pg_parse_phpunit_config"))
assert.ok(coreModeCode.includes("$test_files = core_pg_discover_tests($directories, $suffixes, $prefixes, $excludes, $configured_files);"))
assert.equal(coreModeCode.match(/return array\(\$directories, \$suffixes, \$prefixes, \$excludes\);/g)?.length ?? 0, 0)
assert.equal(coreModeCode.match(/return \$return_values\(\);/g)?.length, 3)
assertPhpunitParseConfigFallbacksReturnFiveTuple(coreModeCode, "core_pg_parse_phpunit_config", "core_pg_log")
const managedModeCode = phpunitRunCode({
pluginSlug: "demo-plugin",
cwd: "/wordpress/wp-content/plugins/demo-plugin",
autoloadFile: "/wp-codebox-vendor/autoload.php",
testsDir: "/wp-codebox-vendor/wp-phpunit/wp-phpunit",
phpunitXml: "/wordpress/wp-content/plugins/demo-plugin/phpunit.xml.dist",
selectedTestFile: "",
changedTestFiles: [],
phpunitArgs: [],
env: {},
wpConfigDefines: {},
dependencyMounts: [],
bootstrapFiles: [],
bootstrapMode: "managed",
projectBootstrap: "",
multisite: false,
})
assert.ok(managedModeCode.includes("configured PHPUnit harness autoload file is not readable"))
assert.ok(managedModeCode.includes("'cacheResult' => false"))
const installStageIndex = managedModeCode.indexOf("pg_run_install_stage(array(")
const dependencyLoadStageIndex = managedModeCode.indexOf("$loaded_dep_files = pg_run_load_deps_stage", installStageIndex)
const activationStageIndex = managedModeCode.indexOf("pg_run_activation_stage", dependencyLoadStageIndex)
const dependencyPluginsLoadedSnapshotIndex = managedModeCode.indexOf("$pre_dependency_plugins_loaded_callbacks = pg_snapshot_wordpress_hook_callbacks('plugins_loaded');", installStageIndex)
const dependencyPluginsLoadedDeferIndex = managedModeCode.indexOf("$deferred_dependency_plugins_loaded_callbacks = pg_defer_new_wordpress_hook_callbacks('plugins_loaded', $pre_dependency_plugins_loaded_callbacks);", dependencyLoadStageIndex)
const dependencyPluginsLoadedReplayIndex = managedModeCode.indexOf("pg_run_deferred_wordpress_hook_callbacks($deferred_dependency_plugins_loaded_callbacks, array(), 'plugins_loaded');", activationStageIndex)
assert.ok(installStageIndex > 0)
assert.ok(dependencyPluginsLoadedSnapshotIndex > installStageIndex && dependencyPluginsLoadedSnapshotIndex < dependencyLoadStageIndex, "dependency plugins_loaded callbacks must be scoped to dependency loading")
assert.ok(dependencyLoadStageIndex > installStageIndex, "dependency plugins must load after managed PHPUnit installation")
assert.ok(dependencyPluginsLoadedDeferIndex > dependencyLoadStageIndex && dependencyPluginsLoadedDeferIndex < activationStageIndex, "dependency plugins_loaded callbacks must defer until activation completes")
assert.ok(activationStageIndex > dependencyLoadStageIndex, "dependency plugins must activate after loading and before tests execute")
assert.ok(dependencyPluginsLoadedReplayIndex > activationStageIndex, "dependency plugins_loaded callbacks must run once after activation")
const dependencyRecipe = buildWordPressPhpunitRecipe({
pluginSlug: "demo-plugin",
extra_plugins: [{
source: "/workspace/dependency",
slug: "dependency",
pluginFile: "dependency/dependency.php",
activate: false,
}],
dependencyMounts: ["/wordpress/wp-content/plugins/dependency"],
})
assert.deepEqual(dependencyRecipe.inputs.extra_plugins, [{
source: "/workspace/dependency",
slug: "dependency",
pluginFile: "dependency/dependency.php",
activate: false,
}])
assert.ok(dependencyRecipe.workflow.steps[0].args.includes("dependency-mounts=/wordpress/wp-content/plugins/dependency"))
const phpunitCacheAllocator = extractPhpFunction(managedModeCode, "wp_codebox_phpunit_args_private_cache_result_file")
const phpunitArgsFunction = extractPhpFunction(managedModeCode, "wp_codebox_phpunit_args")
const phpunitArgsProbe = join(mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-cache-args-")), "probe.php")
writeFileSync(phpunitArgsProbe, `<?php
function pg_log($message) {}
${phpunitCacheAllocator}
${phpunitArgsFunction}
echo json_encode(array(
'first' => wp_codebox_phpunit_args(array('phpunit', '--filter', 'OnlyTest', '--cache-result-file=/wordpress/ignored.cache')),
'second' => wp_codebox_phpunit_args(array('phpunit', '--cache-result-file', 'ignored.cache')),
'firstMode' => fileperms(wp_codebox_phpunit_args(array('phpunit'))['cacheResultFile']) & 0777,
));
`)
const phpunitArgs = JSON.parse(execFileSync("php", [phpunitArgsProbe], { encoding: "utf8" })) as {
first: Record<string, unknown>
second: Record<string, unknown>
firstMode: number
}
for (const argumentSet of [phpunitArgs.first, phpunitArgs.second]) {
assert.equal(argumentSet.cacheResult, false, "PHPUnit result caching must start disabled")
assert.match(String(argumentSet.cacheResultFile), /^\/tmp\/wp-codebox-phpunit-[a-f0-9]{48}\.cache$/, "cache file must be privately allocated under /tmp")
}
assert.equal(phpunitArgs.first.filter, "OnlyTest", "unrecognized caller cache options must not affect supported PHPUnit options")
assert.notEqual(phpunitArgs.first.cacheResultFile, phpunitArgs.second.cacheResultFile, "each PHPUnit invocation must receive an unpredictable cache path")
assert.equal(phpunitArgs.firstMode, 0o600, "the internal cache file must be private to the sandbox process")
assert.equal(existsSync(String(phpunitArgs.first.cacheResultFile)), false, "the internal cache must be removed at PHP shutdown")
assert.equal(existsSync(String(phpunitArgs.second.cacheResultFile)), false, "each allocated cache file must be cleaned up")
console.log("phpunit project autoload ok")