-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathphpunit-command-handlers.ts
More file actions
1785 lines (1666 loc) · 73.8 KB
/
Copy pathphpunit-command-handlers.ts
File metadata and controls
1785 lines (1666 loc) · 73.8 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { phpEnvAssignmentFunction, phpWpConfigDefineAppenderFunction } from "./php-snippets.js"
export interface PhpunitRunCodeOptions {
pluginSlug: string
cwd: string
autoloadFile: string
autoloadFileRole?: "harness"
projectAutoloadFile?: string
testsDir: string
testRoot?: string
phpunitXml: string
phpunitXmlIsDefault: boolean
selectedTestFile: string
changedTestFiles: string[]
phpunitArgs: string[]
env: Record<string, unknown>
wpConfigDefines: Record<string, unknown>
dependencyMounts: string[]
bootstrapFiles: string[]
preloadFiles?: string[]
bootstrapMode: string
projectBootstrap: string
multisite: boolean
preinstalledMultisite?: boolean
databaseType: "sqlite" | "mysql"
/**
* Sandbox-internal, writable path for the structured diagnostics log. Defaults
* to a /tmp path so diagnostics survive read-only plugin mounts and a mid-install
* die() or exit().
*/
resultFile?: string
}
export type PhpunitMultisitePreinstallCodeOptions = Pick<PhpunitRunCodeOptions, "testsDir" | "env" | "wpConfigDefines" | "databaseType" | "resultFile">
export interface CorePhpunitRunCodeOptions {
coreRoot: string
testsDir: string
phpunitXml: string
phpunitXmlIsDefault: boolean
selectedTestFile: string
changedTestFiles: string[]
autoloadFile: string
wpConfigDefines: Record<string, unknown>
multisite: boolean
/**
* Sandbox-internal, writable path for the structured diagnostics log. Defaults
* to a /tmp path so diagnostics survive read-only core mounts and a mid-require
* die() in WordPress core's bootstrap.php (see issue #314).
*/
resultFile?: string
}
export const CORE_PHPUNIT_RESULT_FILE = "/tmp/wp-codebox-core-phpunit-result.txt"
export const PLUGIN_PHPUNIT_RESULT_FILE = "/tmp/wp-codebox-phpunit-result.txt"
interface PhpunitConfigDiscoveryPhpOptions {
functionName: string
logFunction: string
loadedConfigMessage: string
fallbackXmlDist: boolean
restrictDirectoriesToTests: boolean
basePathExpression: string
uniqueReturnValues: boolean
replaceDefaultMatchers: boolean
allowMissingImplicitConfig: boolean
}
interface PhpunitChangedTestFilterPhpOptions {
relativeFunctionName: string
filterFunctionName: string
logFunction: string
rootParameterName: string
testsPathFallback: boolean
}
function phpunitConfigDiscoveryPhp(options: PhpunitConfigDiscoveryPhpOptions): string {
const fallbackXmlDist = options.fallbackXmlDist ? `
if (!is_readable($xml_path) && basename($xml_path) === 'phpunit.xml.dist') {
$alternate = dirname($xml_path) . '/phpunit.xml';
if (is_readable($alternate)) {
$xml_path = $alternate;
}
}` : ""
const missingImplicitConfig = options.allowMissingImplicitConfig ? `
if (!is_readable($xml_path)) {
${options.logFunction}('NOTICE:using managed PHPUnit discovery defaults; no implicit config found at ' . $xml_path);
return $return_values();
}` : ""
const directoryRestriction = options.restrictDirectoriesToTests ? `
$normalized = trim(str_replace('\\\\', '/', $raw), '/');
if ($raw === '' || ($normalized !== 'tests' && strpos($normalized, 'tests/') !== 0)) {
continue;
}` : `
if ($raw === '') {
continue;
}`
const returnValues = options.uniqueReturnValues
? "array(array_values(array_unique($directories)), array_values(array_unique($suffixes)), array_values(array_unique($prefixes)), $excludes, array_values(array_unique($files)))"
: "array($directories, $suffixes, $prefixes, $excludes, $files)"
const suffixAssignment = options.replaceDefaultMatchers ? "$suffixes = $config_suffixes;" : "$suffixes = array_merge($suffixes, $config_suffixes);"
const prefixAssignment = options.replaceDefaultMatchers ? "$prefixes = $config_prefixes;" : "$prefixes = array_merge($prefixes, $config_prefixes);"
return `function ${options.functionName}($xml_path, $test_dir_default) {
$directories = array($test_dir_default);
$suffixes = array('Test.php');
$prefixes = array('test-');
$excludes = array();
$files = array();
$return_values = static function() use (&$directories, &$suffixes, &$prefixes, &$excludes, &$files) {
return ${returnValues};
};${fallbackXmlDist}${missingImplicitConfig}
if (!is_readable($xml_path)) {
throw new RuntimeException('PHPUnit config is not readable: ' . $xml_path);
}
$prev = libxml_use_internal_errors(true);
$xml = @simplexml_load_file($xml_path);
$errors = libxml_get_errors();
libxml_clear_errors();
libxml_use_internal_errors($prev);
if ($xml === false) {
$first = $errors ? trim($errors[0]->message) : 'unknown';
throw new RuntimeException('PHPUnit config could not be parsed at ' . $xml_path . ': ' . $first);
}
$base = ${options.basePathExpression};
$config_dirs = array();
$config_suffixes = array();
$config_prefixes = array();
foreach ($xml->xpath('//testsuite/directory') ?: array() as $dir) {
$raw = trim((string) $dir);${directoryRestriction}
$config_dirs[] = $raw[0] === '/' ? rtrim($raw, '/') : rtrim($base . '/' . $raw, '/');
foreach (explode(',', (string) ($dir['suffix'] ?? '')) as $suffix) {
$suffix = trim($suffix);
if ($suffix !== '') {
$config_suffixes[] = $suffix;
}
}
foreach (explode(',', (string) ($dir['prefix'] ?? '')) as $prefix) {
$prefix = trim($prefix);
if ($prefix !== '') {
$config_prefixes[] = $prefix;
}
}
}
foreach ($xml->xpath('//testsuite/exclude') ?: array() as $exclude) {
$raw = trim((string) $exclude);
if ($raw !== '') {
$excludes[] = $raw[0] === '/' ? rtrim($raw, '/') : rtrim($base . '/' . $raw, '/');
}
}
foreach ($xml->xpath('//testsuite/file') ?: array() as $file) {
$raw = trim((string) $file);
if ($raw !== '') {
$files[] = $raw[0] === '/' ? $raw : $base . '/' . $raw;
}
}
if (!empty($config_dirs)) {
$directories = $config_dirs;
${options.logFunction}('${options.loadedConfigMessage}' . $xml_path);
}
if (!empty($config_suffixes)) {
${suffixAssignment}
}
if (!empty($config_prefixes)) {
${prefixAssignment}
}
return $return_values();
}`
}
function phpunitDiscoveryPhp(functionName: string, logFunction: string): string {
return `function ${functionName}(array $directories, array $suffixes, array $prefixes, array $excludes, array $files = array()) {
$found = array();
foreach ($files as $file) {
if (!is_string($file) || $file === '') {
throw new RuntimeException('configured PHPUnit test file is invalid');
}
if (!is_file($file) || !is_readable($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'php') {
throw new RuntimeException('configured PHPUnit test file is not a readable PHP file: ' . $file);
}
foreach ($excludes as $exclude) {
if (strpos($file, $exclude) === 0) {
continue 2;
}
}
$found[] = $file;
}
foreach ($directories as $dir) {
if (!is_dir($dir) || !is_readable($dir)) {
throw new RuntimeException('configured PHPUnit test directory is not a readable directory: ' . $dir);
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($iterator as $file) {
if (!$file->isFile() || $file->getExtension() !== 'php') {
continue;
}
$path = $file->getPathname();
foreach ($excludes as $exclude) {
if (strpos($path, $exclude) === 0) {
continue 2;
}
}
$base = $file->getBasename();
$matches = false;
foreach ($suffixes as $suffix) {
if ($suffix !== '' && substr($base, -strlen($suffix)) === $suffix) {
$matches = true;
break;
}
}
if (!$matches) {
foreach ($prefixes as $prefix) {
if ($prefix !== '' && strpos($base, $prefix) === 0) {
$matches = true;
break;
}
}
}
if ($matches) {
$found[] = $path;
}
}
}
sort($found);
return array_values(array_unique($found));
}`
}
function phpunitChangedTestFilterPhp(options: PhpunitChangedTestFilterPhpOptions): string {
const testsPathFallback = options.testsPathFallback ? ` elseif (strpos($path, '/tests/') !== false) {
$path = substr($path, strpos($path, '/tests/') + 1);
}` : ""
return `function ${options.filterFunctionName}(array $test_files, string $changed_files_json, string $${options.rootParameterName}): array {
$decoded = json_decode($changed_files_json, true);
if (!is_array($decoded) || empty($decoded)) {
return $test_files;
}
$wanted = array();
foreach ($decoded as $entry) {
if (!is_scalar($entry)) {
continue;
}
$normalized = ${options.relativeFunctionName}((string) $entry, $${options.rootParameterName});
if ($normalized !== '') {
$wanted[$normalized] = true;
}
}
$filtered = array();
foreach ($test_files as $file) {
if (isset($wanted[${options.relativeFunctionName}((string) $file, $${options.rootParameterName})])) {
$filtered[] = $file;
}
}
${options.logFunction}('SCOPED_TEST_FILES requested=' . count($wanted) . ' matched=' . count($filtered));
return $filtered;
}
function ${options.relativeFunctionName}(string $path, string $${options.rootParameterName}): string {
$path = trim(str_replace('\\\\', '/', $path));
$${options.rootParameterName} = rtrim(str_replace('\\\\', '/', $${options.rootParameterName}), '/');
if (strpos($path, $${options.rootParameterName} . '/') === 0) {
$path = substr($path, strlen($${options.rootParameterName}) + 1);
}${testsPathFallback}
while (strpos($path, './') === 0) {
$path = substr($path, 2);
}
return ltrim($path, '/');
}`
}
function phpunitArgsPhp(functionName: string, logFunction: string): string {
return `function ${functionName}_private_cache_result_file() {
$path = false;
try {
$candidate = '/tmp/wp-codebox-phpunit-' . bin2hex(random_bytes(24)) . '.cache';
$handle = @fopen($candidate, 'x');
if ($handle !== false) {
fclose($handle);
$path = $candidate;
}
} catch (Throwable $e) {
// tempnam() asks the operating system to allocate a unique file when
// cryptographic randomness is unavailable.
}
if ($path === false) {
$path = tempnam('/tmp', 'wp-codebox-phpunit-');
}
if ($path === false) {
throw new RuntimeException('Unable to allocate a private PHPUnit result cache file.');
}
if (!@chmod($path, 0600)) {
@unlink($path);
throw new RuntimeException('Unable to restrict the private PHPUnit result cache file permissions.');
}
// fileperms() is meaningful on the POSIX filesystems used by Playground.
// Fail closed rather than passing a cache file with broader permissions.
$mode = @fileperms($path);
if ($mode !== false && (($mode & 0777) !== 0600)) {
@unlink($path);
throw new RuntimeException('Private PHPUnit result cache file permissions are not 0600.');
}
register_shutdown_function(static function () use ($path): void {
@unlink($path);
});
return $path;
}
function ${functionName}(array $argv) {
$arguments = array('colors' => 'never', 'testdox' => true, 'verbose' => false, 'cacheResult' => false, 'cacheResultFile' => ${functionName}_private_cache_result_file(), 'extensions' => array());
$args = array_slice($argv, 1);
for ($i = 0; $i < count($args); $i++) {
$arg = $args[$i];
if ($arg === '--filter' && isset($args[$i + 1])) {
$arguments['filter'] = $args[++$i];
${logFunction}('NOTICE:phpunit filter applied: ' . $arguments['filter']);
continue;
}
if (strpos($arg, '--filter=') === 0) {
$arguments['filter'] = substr($arg, strlen('--filter='));
${logFunction}('NOTICE:phpunit filter applied: ' . $arguments['filter']);
continue;
}
if ($arg === '--list-tests') {
$arguments['listTests'] = true;
continue;
}
if ($arg === '--no-testdox') {
$arguments['testdox'] = false;
continue;
}
if ($arg === '--verbose' || $arg === '-v') {
$arguments['verbose'] = true;
continue;
}
}
return $arguments;
}`
}
function managedPhpunitConfigWriterPhp(): string {
return `function pg_write_managed_test_config(array $extra_defines, string $table_prefix, string $database_type): string {
$config_path = '/tmp/wp-tests-config.php';
$config = "<?php\n";
pg_append_wp_config_defines($config, $extra_defines);
$config .= '$table_prefix = ' . var_export($table_prefix, true) . ";\n";
if ($database_type === 'mysql') {
$db_host = getenv('DB_HOST');
if (!is_string($db_host) || $db_host === '') {
throw new RuntimeException('Managed PHPUnit requires DB_HOST when database-type=mysql; declare a MySQL runtime service with canonical DB_* outputs.');
}
$db_port = getenv('DB_PORT');
if (is_string($db_port) && $db_port !== '') {
$db_host .= ':' . $db_port;
}
foreach (array(
'DB_NAME' => getenv('DB_NAME') ?: 'runtime',
'DB_USER' => getenv('DB_USER') ?: 'runtime',
'DB_PASSWORD' => getenv('DB_PASSWORD') ?: '',
'DB_HOST' => $db_host,
) as $name => $value) {
$config .= 'define(' . var_export($name, true) . ', ' . var_export($value, true) . ");\n";
}
} else {
$config .= <<<'CONFIG'
define('DB_NAME', ':memory:');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
CONFIG;
}
$config .= <<<'CONFIG'
define('DB_CHARSET', 'utf8');
define('WP_TESTS_DOMAIN', 'example.org');
define('WP_TESTS_EMAIL', 'admin@example.org');
define('WP_TESTS_TITLE', 'Test Blog');
define('WP_PHP_BINARY', 'php');
define('ABSPATH', '/wordpress/');
define('FS_CHMOD_FILE', 0644);
define('FS_CHMOD_DIR', 0755);
define('FS_METHOD', 'direct');
CONFIG;
file_put_contents($config_path, $config);
return $config_path;
}`
}
export function phpunitMultisitePreinstallCode(options: PhpunitMultisitePreinstallCodeOptions): string {
const wpConfigDefines = { ...options.wpConfigDefines }
for (const name of ["MULTISITE", "SUBDOMAIN_INSTALL", "DOMAIN_CURRENT_SITE", "PATH_CURRENT_SITE", "SITE_ID_CURRENT_SITE", "BLOG_ID_CURRENT_SITE"]) {
delete wpConfigDefines[name]
}
return `error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
$tests_dir = ${JSON.stringify(options.testsDir)};
$bench_env = json_decode(${JSON.stringify(JSON.stringify(options.env))}, true);
$wp_config_defines = json_decode(${JSON.stringify(JSON.stringify(wpConfigDefines))}, true);
$database_type = ${JSON.stringify(options.databaseType)};
$result_file = ${JSON.stringify(options.resultFile ?? PLUGIN_PHPUNIT_RESULT_FILE)};
$preinstall_complete = false;
@file_put_contents($result_file, '');
register_shutdown_function(static function () use (&$preinstall_complete, $result_file): void {
if ($preinstall_complete) {
return;
}
$failure = error_get_last();
if (is_array($failure) && in_array($failure['type'] ?? 0, array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR), true)) {
@file_put_contents($result_file, 'STAGE_FATAL:preinstall:' . (string) ($failure['message'] ?? '') . ' at ' . (string) ($failure['file'] ?? '') . ':' . (int) ($failure['line'] ?? 0) . "\n", FILE_APPEND);
}
});
${phpEnvAssignmentFunction("pg_apply_env", "json_encode", "error_log('Skipping invalid environment key: ' . var_export($name, true));")}
${phpWpConfigDefineAppenderFunction("pg_append_wp_config_defines", "error_log('Skipping invalid wp_config_defines key: ' . var_export($name, true));")}
${managedPhpunitConfigWriterPhp()}
pg_apply_env($bench_env);
$config_path = pg_write_managed_test_config($wp_config_defines, 'wptests_', $database_type);
if (!defined('WP_TESTS_MULTISITE')) {
define('WP_TESTS_MULTISITE', true);
}
$argv = array('install.php', $config_path, 'run_ms_tests', 'no_core_tests');
$_SERVER['argv'] = $argv;
$_SERVER['argc'] = count($argv);
try {
require $tests_dir . '/includes/install.php';
$preinstall_complete = true;
} catch (Throwable $error) {
@file_put_contents($result_file, 'STAGE_FAIL:preinstall:' . get_class($error) . ': ' . $error->getMessage() . ' at ' . $error->getFile() . ':' . $error->getLine() . "\n", FILE_APPEND);
throw $error;
}`
}
export function phpunitRunCode(options: PhpunitRunCodeOptions): string {
return `error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
$plugin_slug = ${JSON.stringify(options.pluginSlug)};
$plugin_path = '/wordpress/wp-content/plugins/' . $plugin_slug;
$runtime_cwd = ${JSON.stringify(options.cwd || `/wordpress/wp-content/plugins/${options.pluginSlug}`)};
$result_file = ${JSON.stringify(options.resultFile ?? PLUGIN_PHPUNIT_RESULT_FILE)};
$current_stage = 'preboot';
$pg_stage_output_buffering = false;
$autoload_file = ${JSON.stringify(options.autoloadFile)};
$autoload_file_role = ${JSON.stringify(options.autoloadFileRole ?? "")};
$project_autoload_file = ${JSON.stringify(options.projectAutoloadFile ?? "")};
$tests_dir = ${JSON.stringify(options.testsDir)};
$test_root = ${JSON.stringify(options.testRoot || `/wordpress/wp-content/plugins/${options.pluginSlug}/tests`)};
$selected_test_file = ${JSON.stringify(options.selectedTestFile)};
$changed_test_files_raw = ${JSON.stringify(JSON.stringify(options.changedTestFiles))};
$changed_test_scope = ${JSON.stringify(options.changedTestFiles.length > 0)};
$phpunit_args_raw = json_decode(${JSON.stringify(JSON.stringify(options.phpunitArgs))}, true);
$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"))};
$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")};
$project_bootstrap = ${JSON.stringify(options.projectBootstrap)};
$multisite = ${JSON.stringify(options.multisite)};
$preinstalled_multisite = ${JSON.stringify(options.preinstalledMultisite ?? false)};
$database_type = ${JSON.stringify(options.databaseType)};
function pg_build_phpunit_argv($raw): array {
$phpunit_argv = array('phpunit');
if (is_array($raw)) {
foreach ($raw as $arg) {
if (is_scalar($arg)) {
$phpunit_argv[] = (string) $arg;
}
}
}
return $phpunit_argv;
}
@file_put_contents($result_file, '');
function pg_log($msg) {
global $result_file;
if (!in_array('file', stream_get_wrappers(), true)) {
@stream_wrapper_restore('file');
}
file_put_contents($result_file, $msg . "\n", FILE_APPEND);
}
function pg_resolve_selected_test_file($selected_test_file, $test_dir, $runtime_cwd, $plugin_path) {
if ($selected_test_file === '') {
return '';
}
if ($selected_test_file[0] === '/') {
return $selected_test_file;
}
$relative = ltrim($selected_test_file, '/');
$candidates = array(
rtrim($test_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $relative,
rtrim($runtime_cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $relative,
rtrim($plugin_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $relative,
);
$tests_real = realpath($test_dir);
foreach (array_unique($candidates) as $candidate) {
$candidate_real = realpath($candidate);
if ($candidate_real !== false && $tests_real !== false && strpos($candidate_real, rtrim($tests_real, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) === 0 && is_file($candidate_real)) {
return $candidate_real;
}
}
return $candidates[0];
}
${phpEnvAssignmentFunction("pg_apply_env", "json_encode", "pg_log('NOTICE: skipping invalid bench_env key: ' . var_export($name, true));")}
${phpWpConfigDefineAppenderFunction("pg_append_wp_config_defines", "pg_log('NOTICE: skipping invalid wp_config_defines key: ' . var_export($name, true));")}
${managedPhpunitConfigWriterPhp()}
function pg_diagnostic_context(): string {
global $current_stage;
$hook = function_exists('current_filter') ? current_filter() : null;
if (!is_string($hook) || $hook === '') {
$hook = 'none';
}
$installing = function_exists('wp_installing') && wp_installing() ? 'true' : 'false';
return 'stage=' . ($current_stage ?: 'unknown') . ' hook=' . $hook . ' wp_installing=' . $installing;
}
function &pg_stage_timings_ref(): array {
static $timings = array('_starts_ns' => array(), '_durations_ms' => array());
return $timings;
}
function pg_stage_begin($stage) {
global $current_stage;
$current_stage = $stage;
$timings = &pg_stage_timings_ref();
$timings['_starts_ns'][$stage] = hrtime(true);
pg_log('STAGE_BEGIN:' . $stage);
}
function pg_stage_ok($stage) {
$timings = &pg_stage_timings_ref();
if (isset($timings['_starts_ns'][$stage])) {
$timings['_durations_ms'][$stage] = (hrtime(true) - $timings['_starts_ns'][$stage]) / 1000000;
}
pg_log('STAGE_OK:' . $stage);
}
function pg_stage_fail($stage, Throwable $e) {
pg_log('STAGE_FAIL:' . $stage . ':' . get_class($e) . ': ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine());
pg_log('TRACE:');
foreach (explode("\n", $e->getTraceAsString()) as $line) {
pg_log(' ' . $line);
}
}
function pg_install_diagnostics_handlers() {
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
return false;
}
$labels = array(E_WARNING => 'WARNING', E_NOTICE => 'NOTICE', E_DEPRECATED => 'DEPRECATED', E_USER_WARNING => 'USER_WARNING', E_USER_NOTICE => 'USER_NOTICE', E_USER_DEPRECATED => 'USER_DEPRECATED', E_STRICT => 'STRICT');
pg_log('NOTICE:' . ($labels[$severity] ?? ('E_' . $severity)) . ': ' . $message . ' at ' . $file . ':' . $line . ' context=' . pg_diagnostic_context());
return false;
});
register_shutdown_function(function () {
global $current_stage, $pg_stage_output_buffering;
if (!empty($pg_stage_output_buffering)) {
$buffered = '';
while (ob_get_level() > 0) {
$chunk = ob_get_clean();
if ($chunk !== false) {
$buffered = $chunk . $buffered;
}
}
$buffered = trim($buffered);
if ($buffered !== '') {
pg_log('STAGE_DIE:' . $current_stage . ':' . $buffered);
}
}
$error = error_get_last();
if ($error && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR), true)) {
pg_log('STAGE_FATAL:' . $current_stage . ':' . $error['message'] . ' at ' . $error['file'] . ':' . $error['line']);
}
});
}
function pg_snapshot_wordpress_hook_callbacks(string $hook_name): array {
global $wp_filter;
$snapshot = array();
if (!isset($wp_filter[$hook_name]) || !isset($wp_filter[$hook_name]->callbacks)) {
return $snapshot;
}
foreach ($wp_filter[$hook_name]->callbacks as $priority => $callbacks) {
foreach (array_keys($callbacks) as $callback_id) {
$snapshot[$priority . ':' . $callback_id] = true;
}
}
return $snapshot;
}
function pg_remove_new_wordpress_hook_callbacks(string $hook_name, array $before): void {
global $wp_filter;
if (!isset($wp_filter[$hook_name]) || !isset($wp_filter[$hook_name]->callbacks)) {
return;
}
$callbacks_by_priority = $wp_filter[$hook_name]->callbacks;
foreach ($callbacks_by_priority as $priority => $callbacks) {
foreach (array_keys($callbacks) as $callback_id) {
if (!isset($before[$priority . ':' . $callback_id])) {
$callback = $callbacks[$callback_id];
if (isset($callback['function'])) remove_action($hook_name, $callback['function'], (int) $priority);
}
}
}
}
function pg_defer_new_wordpress_hook_callbacks(string $hook_name, array $before): array {
global $wp_filter;
$deferred = array();
if (!isset($wp_filter[$hook_name]) || !isset($wp_filter[$hook_name]->callbacks)) {
return $deferred;
}
$callbacks_by_priority = $wp_filter[$hook_name]->callbacks;
foreach ($callbacks_by_priority as $priority => $callbacks) {
foreach ($callbacks as $callback_id => $callback) {
if (isset($before[$priority . ':' . $callback_id])) {
continue;
}
if (isset($callback['function']) && remove_action($hook_name, $callback['function'], (int) $priority)) {
$deferred[] = array('priority' => (int) $priority, 'callback' => $callback);
}
}
}
usort($deferred, static function (array $left, array $right): int { return $left['priority'] <=> $right['priority']; });
return $deferred;
}
function pg_run_deferred_wordpress_hook_callbacks(array $deferred, array $args = array(), ?string $hook_name = null): void {
global $wp_filter, $wp_current_filter;
$pushed_hook = false;
$original_hook = null;
$replay_hook = null;
if (is_string($hook_name) && $hook_name !== '') {
if (!is_array($wp_current_filter)) {
$wp_current_filter = array();
}
$wp_current_filter[] = $hook_name;
$pushed_hook = true;
$original_hook = $wp_filter[$hook_name] ?? null;
$replay_hook = new WP_Hook();
$wp_filter[$hook_name] = $replay_hook;
foreach ($deferred as $entry) {
$callback = $entry['callback'] ?? null;
if (!is_array($callback) || !isset($callback['function'])) {
continue;
}
$priority = isset($entry['priority']) ? (int) $entry['priority'] : 10;
$accepted_args = isset($callback['accepted_args']) ? (int) $callback['accepted_args'] : count($args);
add_filter($hook_name, $callback['function'], $priority, $accepted_args);
}
}
try {
if ($replay_hook instanceof WP_Hook) {
$replay_hook->do_action($args);
return;
}
foreach ($deferred as $entry) {
$callback = $entry['callback'] ?? null;
if (!is_array($callback) || !isset($callback['function'])) {
continue;
}
$accepted_args = isset($callback['accepted_args']) ? (int) $callback['accepted_args'] : count($args);
call_user_func_array($callback['function'], array_slice($args, 0, $accepted_args));
}
} finally {
if ($replay_hook instanceof WP_Hook && is_string($hook_name)) {
$retained_callbacks = $replay_hook->callbacks;
if ($original_hook instanceof WP_Hook) {
$wp_filter[$hook_name] = $original_hook;
} else {
unset($wp_filter[$hook_name]);
}
foreach ($retained_callbacks as $priority => $callbacks) {
foreach ($callbacks as $callback) {
if (isset($callback['function'])) {
add_filter($hook_name, $callback['function'], (int) $priority, (int) ($callback['accepted_args'] ?? 0));
}
}
}
}
if ($pushed_hook) {
array_pop($wp_current_filter);
}
}
}
function pg_reopen_wordpress_action(string $hook_name): bool {
global $wp_actions;
if (!function_exists('did_action') || did_action($hook_name) === 0) {
return false;
}
if (!is_array($wp_actions)) {
$wp_actions = array();
}
$wp_actions[$hook_name] = 0;
pg_log('NOTICE:reopened WordPress action after install: ' . $hook_name);
return true;
}
function pg_fire_reopened_wordpress_action(string $hook_name, bool $reopened): void {
if ($reopened && function_exists('do_action')) {
do_action($hook_name);
}
}
function pg_fire_runtime_abilities_ready(): void {
if (!function_exists('do_action')) {
return;
}
do_action('contained_runtime_abilities_ready');
if (function_exists('did_action')) {
pg_log('NOTICE:runtime ability lifecycle ready: wp_abilities_api_categories_init=' . did_action('wp_abilities_api_categories_init') . '; wp_abilities_api_init=' . did_action('wp_abilities_api_init') . '; contained_runtime_abilities_ready=' . did_action('contained_runtime_abilities_ready'));
}
}
function pg_preload_wp_cli_namespaced_functions(string $autoload_file): void {
if ($autoload_file === '') {
return;
}
$vendor_dir = dirname($autoload_file);
$wp_cli_root = $vendor_dir . '/wp-cli/wp-cli';
if (!defined('WP_CLI_ROOT')) {
define('WP_CLI_ROOT', $wp_cli_root);
}
if (!defined('WP_CLI_VENDOR_DIR')) {
define('WP_CLI_VENDOR_DIR', $vendor_dir);
}
if (!defined('WP_CLI_VERSION') && is_readable($wp_cli_root . '/VERSION')) {
define('WP_CLI_VERSION', trim(file_get_contents($wp_cli_root . '/VERSION')));
}
if (!defined('WP_CLI_START_MICROTIME')) {
define('WP_CLI_START_MICROTIME', microtime(true));
}
if (!function_exists('WP_CLI\\Utils\\parse_str_to_argv') && is_readable($wp_cli_root . '/php/utils.php')) {
require_once $wp_cli_root . '/php/utils.php';
}
if (!function_exists('WP_CLI\\Dispatcher\\get_path') && is_readable($wp_cli_root . '/php/dispatcher.php')) {
require_once $wp_cli_root . '/php/dispatcher.php';
}
if (!function_exists('WP_CLI\\Utils\\get_upgrader') && is_readable($wp_cli_root . '/php/utils-wp.php')) {
require_once $wp_cli_root . '/php/utils-wp.php';
}
}
function pg_run_boot_stage(array $cfg = []): ?string {
global $autoload_file;
pg_stage_begin('boot');
try {
$harness_autoload = trim((string) ($cfg['autoload_file'] ?? $autoload_file));
$autoload_required = !empty($cfg['autoload_required']);
$extra_defines = $cfg['extra_defines'] ?? array();
$table_prefix = isset($cfg['table_prefix']) && is_string($cfg['table_prefix']) && $cfg['table_prefix'] !== '' ? $cfg['table_prefix'] : 'wptests_';
$database_type = (string) ($cfg['database_type'] ?? 'sqlite');
$config_path = pg_write_managed_test_config($extra_defines, $table_prefix, $database_type);
if ($harness_autoload !== '' && is_readable($harness_autoload)) {
pg_preload_wp_cli_namespaced_functions($harness_autoload);
require_once $harness_autoload;
} elseif ($autoload_required || $harness_autoload !== '') {
throw new RuntimeException('configured PHPUnit harness autoload file is not readable: ' . $harness_autoload . '; mount the WP Codebox PHPUnit harness or clear autoload-file when using bootstrap-mode=project with a project bootstrap that loads PHPUnit.');
} else {
pg_log('NOTICE:project bootstrap mode continuing without configured PHPUnit harness autoload');
}
pg_stage_ok('boot');
return $config_path;
} catch (Throwable $e) {
pg_stage_fail('boot', $e);
exit(1);
}
}
function pg_run_preinstalled_multisite_stage(array $cfg): void {
pg_stage_begin('install');
try {
$config_path = (string) ($cfg['config_path'] ?? '');
$tests_dir = (string) ($cfg['tests_dir'] ?? '');
if ($config_path === '' || !is_readable($config_path)) {
throw new RuntimeException('managed multisite config is not readable: ' . $config_path);
}
if ($tests_dir === '' || !is_readable($tests_dir . '/includes/functions.php')) {
throw new RuntimeException('managed multisite test library is not readable: ' . $tests_dir);
}
if (!defined('WP_INSTALLING')) {
define('WP_INSTALLING', true);
}
if (!defined('DISABLE_WP_CRON')) {
define('DISABLE_WP_CRON', true);
}
require_once $config_path;
require_once $tests_dir . '/includes/functions.php';
tests_reset__SERVER();
$GLOBALS['PHP_SELF'] = '/index.php';
$_SERVER['PHP_SELF'] = '/index.php';
tests_add_filter('wp_die_handler', '_wp_die_handler_filter_exit');
require_once ABSPATH . 'wp-settings.php';
pg_stage_ok('install');
} catch (Throwable $e) {
pg_stage_fail('install', $e);
exit(1);
}
}
function pg_resolve_runtime_cwd(string $cwd, string $plugin_path): string {
$cwd = trim(str_replace('\\\\', '/', $cwd));
if ($cwd === '') {
return $plugin_path;
}
if ($cwd[0] !== '/') {
$cwd = rtrim($plugin_path, '/') . '/' . ltrim($cwd, '/');
}
$real = realpath($cwd);
if ($real === false || !is_dir($real)) {
throw new RuntimeException('cwd is not a readable sandbox directory: ' . $cwd);
}
return $real;
}
function pg_resolve_test_root(string $root, string $plugin_path): string {
$root = trim(str_replace('\\\\', '/', $root));
if ($root === '') {
$root = $plugin_path . '/tests';
} elseif ($root[0] !== '/') {
$root = rtrim($plugin_path, '/') . '/' . ltrim($root, '/');
}
$real = realpath($root);
if ($real === false || !is_dir($real)) {
throw new RuntimeException('test root is not a readable sandbox directory: ' . $root);
}
return $real;
}
function pg_manifest_component_entry(string $plugin_slug): ?array {
$manifest = $GLOBALS['contained_runtime_component_manifest'] ?? null;
if (!is_array($manifest)) {
$json = defined('CONTAINED_RUNTIME_COMPONENT_MANIFEST_JSON') ? CONTAINED_RUNTIME_COMPONENT_MANIFEST_JSON : '';
$decoded = is_string($json) && $json !== '' ? json_decode($json, true) : null;
$manifest = is_array($decoded) ? $decoded : null;
}
if (!is_array($manifest)) {
return null;
}
foreach (array('components', 'providers') as $section) {
foreach (is_array($manifest[$section] ?? null) ? $manifest[$section] : array() as $entry) {
if (is_array($entry) && (string) ($entry['slug'] ?? '') === $plugin_slug) {
return $entry;
}
}
}
return null;
}
function pg_manifest_component_plugin_file(string $plugin_slug, string $plugin_path): ?string {
$entry = pg_manifest_component_entry($plugin_slug);
if ($entry === null) {
return null;
}
$entrypoint = trim(str_replace('\\\\', '/', (string) ($entry['entrypoint'] ?? $entry['pluginFile'] ?? '')));
if ($entrypoint === '' || str_starts_with($entrypoint, '/') || str_contains($entrypoint, '..') || !str_ends_with($entrypoint, '.php')) {
throw new RuntimeException('manifest contains unsafe component entrypoint for slug ' . $plugin_slug);
}
if (!str_starts_with($entrypoint, $plugin_slug . '/')) {
throw new RuntimeException('manifest component entrypoint must be relative to the mounted plugin slug: ' . $entrypoint);
}
$relative = substr($entrypoint, strlen($plugin_slug) + 1);
$file = rtrim($plugin_path, '/') . '/' . $relative;
$real = realpath($file);
$plugin_real = realpath($plugin_path);
if ($real === false || $plugin_real === false || strpos($real, rtrim($plugin_real, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) !== 0 || !is_file($real) || !is_readable($real)) {
throw new RuntimeException('manifest component entrypoint is not readable under mounted plugin path: ' . $entrypoint);
}
return $real;
}
function pg_plugin_real_path(string $relative_path, string $kind): ?string {
global $plugin_path;
$relative_path = trim(str_replace('\\\\', '/', $relative_path));
if ($relative_path === '' || strpos($relative_path, '..') !== false || strpos($relative_path, "\0") !== false) {
pg_log('NOTICE:invalid ' . $kind . ' path: ' . var_export($relative_path, true));
return null;
}
$path = $plugin_path . '/' . ltrim($relative_path, '/');
$real = realpath($path);
$plugin_real = realpath($plugin_path);
if ($real === false || $plugin_real === false || strpos($real, rtrim($plugin_real, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) !== 0 || !is_file($real)) {
pg_log('NOTICE:' . $kind . ' file not found under plugin path: ' . $relative_path);
return null;
}
return $real;
}
function pg_project_bootstrap_from_config(string &$xml_path, bool $xml_is_default): string {
if ($xml_is_default && !is_readable($xml_path) && basename($xml_path) === 'phpunit.xml.dist') {
$alternate = dirname($xml_path) . '/phpunit.xml';
if (is_readable($alternate)) {
$xml_path = $alternate;
}
}
if (!is_readable($xml_path)) {
return '';
}
$prev = libxml_use_internal_errors(true);
$xml = @simplexml_load_file($xml_path);
libxml_clear_errors();
libxml_use_internal_errors($prev);
if ($xml === false) {
return '';
}
return trim((string) ($xml['bootstrap'] ?? ''));
}
function pg_project_bootstrap_real_path(string $bootstrap, string $xml_path, bool $from_config): ?string {
if ($from_config) {
$xml_real = realpath($xml_path);
if ($xml_real === false) {
return null;
}
$base_dir = dirname($xml_real);
$candidate = $bootstrap !== '' && $bootstrap[0] === '/' ? $bootstrap : $base_dir . '/' . $bootstrap;
$real = realpath($candidate);
$base_real = realpath($base_dir);
if ($real === false || $base_real === false || !is_file($real) || !is_readable($real)) {
return null;
}
$base_parent = dirname($base_real);
if ($real !== $base_parent && strpos($real, rtrim($base_parent, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) !== 0) {
return null;
}
return $real;
}
return pg_plugin_real_path($bootstrap, 'project bootstrap');
}
function pg_prepare_project_bootstrap_environment(string $config_path): void {
global $tests_dir;
$tests_dir = rtrim($tests_dir, '/');
foreach (array(
'WP_TESTS_DIR' => $tests_dir,
'WP_TESTS_CONFIG_FILE_PATH' => $config_path,
'WP_PHPUNIT__TESTS_CONFIG' => $config_path,
) as $name => $value) {
putenv($name . '=' . $value);
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
function pg_skip_project_bootstrap_shell_install(): void {
putenv('WP_TESTS_SKIP_INSTALL=1');
$_ENV['WP_TESTS_SKIP_INSTALL'] = '1';
$_SERVER['WP_TESTS_SKIP_INSTALL'] = '1';
pg_log('NOTICE:using existing Playground install; project bootstrap shell install skipped');
}
function pg_run_project_bootstrap_stage(array $cfg): void {
global $pg_stage_output_buffering;
pg_stage_begin('project_bootstrap');
try {
$bootstrap = trim((string) ($cfg['project_bootstrap'] ?? ''));
$phpunit_xml = (string) ($cfg['phpunit_xml'] ?? '');
$phpunit_xml_is_default = !empty($cfg['phpunit_xml_is_default']);
$from_config = false;
if ($bootstrap === '') {
$bootstrap = pg_project_bootstrap_from_config($phpunit_xml, $phpunit_xml_is_default);
$from_config = $bootstrap !== '';
}
$bootstrap_real = pg_project_bootstrap_real_path($bootstrap, $phpunit_xml, $from_config);
if ($bootstrap_real === null) {
throw new RuntimeException('project bootstrap not found; pass project-bootstrap=<relative path> or declare phpunit bootstrap');
}
pg_log('PROJECT_BOOTSTRAP:' . $bootstrap);
$pg_stage_output_buffering = true;
ob_start();
require_once $bootstrap_real;
while (ob_get_level() > 0) {
@ob_end_clean();
}
$pg_stage_output_buffering = false;
pg_stage_ok('project_bootstrap');
} catch (Throwable $e) {
$pg_stage_output_buffering = false;