diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 6308e75c3d3da..c0ce694b9a93f 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -21,3 +21,68 @@ Adding the label starts a separate run without another code push. An existing re Unrelated labels skip only the label-triggered workflow's `full-matrix` job and do not replace or cancel PHPUnit checks. Look for `PHPUnit Tests (full matrix)` in GitHub Actions and the PHPUnit checks on the PR. Each run tests the PR's merge commit and retains its own logs and results, so check the revision before relying on an older run. + +## Find state that tests leak + +A test or test class that changes shared state and does not restore it can make later tests pass or fail depending on the order they run in. `tests/phpunit/leaks/` holds an opt-in PHPUnit listener that snapshots state between tests and classes, and a script that reports what changed. + +It snapshots database rows, schema and `AUTO_INCREMENT` counters, temporary tables, the object cache (including the keys on memcached servers), cached options that disagree with the database, globals, static properties and variables, constants, ini settings, environment variables, other process state such as the error handler, and files under `wp-content` and the temporary directory. A process-isolated test's in-process state dies with its child process: its report shows what the child leaves in the database, files and memcached. It needs PHPUnit 9 or earlier: PHPUnit 10 removed test listeners. + +Run the tests with the leak configuration (`tests/phpunit/leaks/multisite.xml` for multisite), then compare the snapshots: + +``` +node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --filter Tests_Option +node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/diff.php tests/phpunit/build/leaks/snapshots.jsonl +``` + +The report lists what each test and class leaves behind, i.e. the state that differs before and after it. Cache entries it drops are left out: a miss reads the source again. It exits with 2 if it reports anything, 1 if the run did not finish, ran no test or snapshotted none, else 0. Each run replaces the snapshots file. Snapshots take time and space, e.g. 156 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. + +To sweep the whole suite, use the `class` scope: it snapshots at class bounds only, by default only the state that outlives the PHP process (database, files, memcached, stale cached options). `diff.php` then lists each class that leaves that state unlike the install: + +``` +node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_SCOPE=class php ./vendor/bin/phpunit -c tests/phpunit/leaks/multisite.xml +``` + +To find out why a class only fails after others, run it alone and in sequence, each with its own `WP_TESTS_LEAKS_OUT` and without `WP_TESTS_LEAKS_SCOPE`, then compare the state it starts with. Keys that differ between the two runs before any snapshotted class ran, e.g. timestamps, are run noise and left out. Both runs are read only up to its `class_start`, so they need not finish. In the sequence run another snapshotted class must run before it. `--filter` keeps file order, so use `--order-by=reverse` when the earlier class's file sorts after its: + +``` +node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www/tests/phpunit/build/leaks/alone.jsonl php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --filter Tests_Class_Name +node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www/tests/phpunit/build/leaks/sequence.jsonl php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --filter 'Tests_Earlier_Class|Tests_Class_Name' +node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/diff.php tests/phpunit/build/leaks/alone.jsonl tests/phpunit/build/leaks/sequence.jsonl Tests_Class_Name +``` + +In comparison mode, `diff.php` exits with 2 when it reports differences after filtering out run noise, or 0 when there are none. It exits with 1 if either run has no `class_start` for the target or the target was the first snapshotted class in the sequence run. + +For example, before [r65746](https://core.trac.wordpress.org/changeset/65746), two `Tests_Post_TheTitleAttribute` tests passed alone and failed after `Tests_Post_wpGetPostAutosave`: post titles were saved without kses. On a checkout before it, a sweep over the hook that should have filtered them names one class, instead of hundreds of global differences: + +``` +node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_SCOPE=class -e WP_TESTS_LEAKS_AREAS=global/wp_filter/title_save_pre php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --order-by=reverse --filter 'Tests_Post_wpGetPostAutosave|Tests_Post_TheTitleAttribute' +``` + +`diff.php` reports `Tests_Post_wpGetPostAutosave` leaving `global/wp_filter/title_save_pre` without `wp_filter_kses`: its `wpSetUpBeforeClass()` logged in an administrator, whose `unfiltered_html` removes the kses filters, and never logged out. `--order-by=reverse` runs it first. + +`tests/phpunit/leaks/rules.php` sets what is snapshotted: per scope, a list of patterns over the snapshot keys (`area/key`, e.g. `static/WP_Theme_JSON_Resolver::*`; `!` negates, the last match wins), and per test file, rules adding or dropping patterns, each saying why. A file no pattern keeps, e.g. one rule `!*`, is not snapshotted. The listener checks the file before any test runs, and stops on an unknown area, a rule missing its reason, or a path matching no file. + +The leak configurations pass the listener its settings: `rules`, the rules file from the repo root, and `scope`, `test` or `class`. Environment variables win over them when set: + +* `WP_TESTS_LEAKS_RULES`: rules file. +* `WP_TESTS_LEAKS_SCOPE`: `test` or `class`. +* `WP_TESTS_LEAKS_AREAS`: comma-separated patterns replacing the scope's defaults in the rules file; its per-file rules still apply. A pattern that kept no key all run, e.g. a typo, is listed on STDERR, and the run reads as incomplete. Takes shorthands: `all`, `persistent`, `database`, `caches`, `globals`, `statics`, `runtime`, `files`, e.g. `statics,globals` or `caches,!stale`. +* `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. + +To check the test classes a branch adds or changes: + +``` +classes=$(git diff --name-only --diff-filter=AM trunk...HEAD -- 'tests/phpunit/tests/*.php' | xargs grep -ho '^class [A-Za-z0-9_]*' | cut -d' ' -f2 | paste -sd'|' -) +node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --filter "/^($classes)::/" +node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/diff.php tests/phpunit/build/leaks/snapshots.jsonl +``` + +The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each, and that the probe rules in `rules.php` drop and skip what they say. `check-probes.php` exits with 1 if the report misses one, or lists state it must not, e.g. state that dies with an isolated child. It reads the run's setup (multisite, PHP version, persistent object cache, scope) from the snapshots file: + +``` +node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --testsuite leak-probe +node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/check-probes.php tests/phpunit/build/leaks/snapshots.jsonl +``` + +The suite runs only when named, except on PHPUnit 5, which ignores `defaultTestSuite`: run `--testsuite default` and `--testsuite restapi-autosave` there, each with its own `WP_TESTS_LEAKS_OUT`, and diff each file. With a persistent object cache, `tear_down()` flushes it, so the cached option probes leave nothing. diff --git a/tests/phpunit/leaks/bootstrap.php b/tests/phpunit/leaks/bootstrap.php new file mode 100644 index 0000000000000..c55cbe282a537 --- /dev/null +++ b/tests/phpunit/leaks/bootstrap.php @@ -0,0 +1,44 @@ + patterns that must each match a reported key. +const PER_TEST = array( + 'test Tests_Leak_Probe::test_leaks_option_cache' => array( '#^stale/runtime/1/options/alloptions/blogname$#', '#^stale/runtime/1/options/leak_probe_not_autoloaded$#' ), + 'test Tests_Leak_Probe::test_leaks_cache_after_tear_down' => array( '#^cache/leak_probe/(1:)?after_tear_down$#', '#^stale/runtime/1/options/leak_probe_cached_only$#', '#^cache/.*leak_probe:after_tear_down$#', '#^mc/.*leak_probe:after_tear_down$#', '#^stale/local/1/options/leak_probe_cached_only$#', '#^stale/memcached/1/options/leak_probe_cached_only$#' ), + 'test Tests_Leak_Probe::test_leaks_composite_key_row' => array( '#^db/\w+term_relationships/999999,1$#', '#^dbcount/\w+term_relationships$#' ), + 'test Tests_Leak_Probe::test_leaks_notoptions_cache' => array( '#^db/\w+options/leak_probe_missing$#', '#^dbcount/\w+options$#', '#^stale/runtime/1/options/notoptions/leak_probe_missing$#' ), + 'test Tests_Leak_Probe::test_leaks_network_option_cache' => array( '#^stale/runtime/1/site-options/1:site_admins$#' ), + 'test Tests_Leak_Probe::test_leaks_other_site' => array( OTHER_SITE_ROW, '#^temptable/\w+_\d+_options$#', '#^stale/runtime/(?!1/)\d+/options/alloptions/blogname$#', '#^stale/runtime/(?!1/)\d+/options/leak_probe_cached_only$#', '#^stale/local/(?!1/)\d+/options/leak_probe_cached_only$#', '#^stale/memcached/(?!1/)\d+/options/leak_probe_cached_only$#' ), + 'test Tests_Leak_Probe::test_leaks_cache_global_group' => array( '#^global/wp_object_cache/global_groups$#' ), + STATIC_TITLE => array( '#^fstatic/leak_probe_counter\(\)/\$calls$#', '#^fstatic/Tests_Leak_Probe::method_counter\(\)/\$calls$#', PARENT_STATIC, CHILD_STATIC ), + 'test Tests_Leak_Probe::test_leaks_static_property' => array( '#^static/Tests_Leak_Probe::\$leaked$#' ), + 'test Tests_Leak_Probe::test_leaks_constant' => array( '#^const/LEAK_PROBE_CONSTANT$#' ), + 'test Tests_Leak_Probe::test_leaks_auto_increment' => array( '#^autoinc/\w+posts$#' ), + 'test Tests_Leak_Probe::test_leaks_deep_global_change' => array( '#^global/leak_probe_deep/l1$#' ), + 'test Tests_Leak_Probe::test_leaks_big_array_key' => array( '#^global/leak_probe_big/2500$#' ), + 'test Tests_Leak_Probe::test_leaks_removed_global' => array( '#^global/leak_probe_gone$#' ), + 'test Tests_Leak_Probe::test_leaks_type_only_change' => array( '#^global/leak_probe_int$#' ), + 'test Tests_Leak_Probe::test_leaks_filtered_globals' => array( '#^global/leak_probe_filtered_kept$#' ), + 'test Tests_Leak_Probe::test_leaks_closure_swap' => array( '#^global/leak_probe_cb$#' ), + 'test Tests_Leak_Probe::test_leaks_wpdb_and_server' => array( '#^global/_SERVER/LEAK_PROBE$#', '#^global/wpdb/show_errors$#' ), + 'test Tests_Leak_Probe::test_leaks_process_state' => array( '#^env/LEAK_PROBE$#', '#^ini/precision$#', '#^ini/error_reporting$#', '#^proc/autoloaders$#', '#^proc/error_handler$#', '#^proc/error_reporting$#', '#^proc/exception_handler$#', '#^proc/libxml_errors$#', '#^proc/locale$#', '#^proc/mb_encoding$#', '#^proc/timezone$#', '#^proc/umask$#' ), + 'test Tests_Leak_Probe::test_leaks_files' => array( '#^file/.*/wp-content/leak-probe\.txt$#', '#^file/(?!.*/wp-content/).*/leak-probe\.txt$#', '#^file/.*/wp-content/leak-probe-link$#', '#^file/(?!.*/wp-content/).*/leak-probe-link$#', '#^file/.*/wp-content/leak-probe-dir$#', '#^file/(?!.*/wp-content/).*/leak-probe-dir$#' ), + 'test Tests_Leak_Probe::test_leaks_schema' => array( '#^schema/\w+options$#' ), + 'test Tests_Leak_Probe::test_leaks_temp_table' => array( '#^temptable/\w+leak_probe_tmp$#' ), + 'test Tests_Leak_Probe::test_leaks_permanent_table' => array( '#^schema/\w+leak_probe_permanent$#', '#^dbcount/\w+leak_probe_permanent$#' ), + 'test Tests_Leak_Probe::test_leaks_in_child' => array( '#^db/\w+links/\d+$#' ), + 'class Tests_Leak_Probe_Class_Fixture' => array( '#^proc/cwd$#', '#^proc/ob_level$#', '#^cache/leak_probe/(1:)?after_class$#', '#^cache/.*leak_probe:after_class$#', '#^mc/.*leak_probe:after_class$#' ), +); + +const CLASS_SCOPE = array( + // The global: rules.php adds it to the class scope's areas for the file. + 'class Tests_Leak_Probe' => array( '#^db/\w+links/\d+$#', '#^schema/\w+options$#', OTHER_SITE_ROW, '#^global/leak_probe_filtered_kept$#' ), + 'class Tests_Leak_Probe_Class_Fixture' => array( '#^stale/runtime/1/options/leak_probe_class_cached_only$#', '#^mc/.*leak_probe:after_class$#', '#^stale/memcached/1/options/leak_probe_class_cached_only$#' ), +); + +// Planted in the in-memory object cache, which a persistent cache's tear_down() flush clears. +const RUNTIME_CACHE_ONLY = array( + '#^stale/runtime/1/options/alloptions/blogname$#', + '#^stale/runtime/1/options/leak_probe_not_autoloaded$#', + '#^stale/runtime/1/options/notoptions/leak_probe_missing$#', + '#^stale/runtime/1/site-options/1:site_admins$#', + '#^cache/leak_probe/(1:)?after_tear_down$#', + '#^stale/runtime/1/options/leak_probe_cached_only$#', + '#^cache/leak_probe/(1:)?after_class$#', + '#^stale/runtime/1/options/leak_probe_class_cached_only$#', + '#^stale/runtime/(?!1/)\d+/options/alloptions/blogname$#', + '#^stale/runtime/(?!1/)\d+/options/leak_probe_cached_only$#', +); + +// Only a persistent cache has these: the drop-in's derived keys, the servers' keys, their stale checks. +const PERSISTENT_CACHE_ONLY = array( + '#^cache/.*leak_probe:after_tear_down$#', + '#^mc/.*leak_probe:after_tear_down$#', + '#^stale/local/1/options/leak_probe_cached_only$#', + '#^stale/memcached/1/options/leak_probe_cached_only$#', + '#^cache/.*leak_probe:after_class$#', + '#^mc/.*leak_probe:after_class$#', + '#^stale/memcached/1/options/leak_probe_class_cached_only$#', + '#^stale/local/(?!1/)\d+/options/leak_probe_cached_only$#', + '#^stale/memcached/(?!1/)\d+/options/leak_probe_cached_only$#', +); + +const MULTISITE_ONLY = array( + '#^stale/runtime/1/site-options/1:site_admins$#', + OTHER_SITE_ROW, + '#^temptable/\w+_\d+_options$#', + '#^stale/runtime/(?!1/)\d+/options/alloptions/blogname$#', + '#^stale/runtime/(?!1/)\d+/options/leak_probe_cached_only$#', + '#^stale/local/(?!1/)\d+/options/leak_probe_cached_only$#', + '#^stale/memcached/(?!1/)\d+/options/leak_probe_cached_only$#', +); + +// Report title => pattern no reported key may match: the class plants no cache leak, and its flushes drop the install's entries. +const UNEXPECTED = array( + 'class Tests_Leak_Probe' => '#^(cache|mc)/#', + // Gone with the connection the test replaced. + 'test Tests_Leak_Probe::test_reconnect_drops_temp_table' => '#^temptable/\w+leak_probe_gone$#', + // Its start is the previous test's end, reused: a wrong one reports more keys. + 'test Tests_Leak_Probe::test_leaks_constant' => '#^(?!const/LEAK_PROBE_CONSTANT$)#', + // Its start follows its class's fixture, not the previous class's last test_end. + 'test Tests_Leak_Probe_Class_Fixture::test_fixture_user_exists' => '#^db/\w+users/#', + // The previous probe's, which this test's set_up() flush drops. + 'test Tests_Leak_Probe::test_leaks_cache_after_tear_down' => '#^stale/runtime/1/options/(alloptions/blogname|leak_probe_not_autoloaded)$#', + // Dies with its child process. + 'test Tests_Leak_Probe::test_leaks_in_child' => '#^const/LEAK_PROBE_CHILD_CONSTANT$#', + // Dropped by a rules.php pattern. + 'test Tests_Leak_Probe::test_leaks_filtered_globals' => '#^global/leak_probe_filtered_dropped$#', +); + +// rules.php skips its file: no snapshot line names it. +const SKIPPED_CLASS = 'Tests_Leak_Probe_Skipped'; + +// diff.php exits with 2 when it reports a leak, as every probe run must. +const DIFF_LEAKS = 2; + +// Comparison mode refuses the run's first class: nothing ran before it. +const FIRST_CLASS = 'Tests_Leak_Probe'; + +const DIFF_REFUSED = 1; + +const DIFF_INCOMPLETE = 1; + +// Comparison mode: a key both first classes differ on is run noise, one only the class differs on is reported. +const NOISE_KEY = 'global/leak_probe_noise'; + +const INHERITED_KEY = 'global/leak_probe_inherited'; + +// Report header and changed key lines, see report() in diff.php. +const HEADER = '#^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$#'; + +const KEY_LINE = '#^ (\S.*)$#'; + +const SCOPE_CLASS = 'class'; + +// The run's setup, from its first line. +function setup( $file ) { + $handle = fopen( $file, 'r' ); + if ( false === $handle ) { + fwrite( STDERR, "Cannot read $file\n" ); + exit( 1 ); + } + + $snap = json_decode( (string) fgets( $handle ), true ); + fclose( $handle ); + + if ( ! isset( $snap['setup']['multisite'], $snap['setup']['php'], $snap['setup']['persistent_cache'] ) || ! array_key_exists( 'scope', $snap['setup'] ) ) { + fwrite( STDERR, "No run setup in $file\n" ); + exit( 1 ); + } + + return $snap['setup']; +} + +// Whether any snapshot line's id starts with the class name. +function snapshotted( $file, $class_name ) { + $handle = fopen( $file, 'r' ); + if ( false === $handle ) { + fwrite( STDERR, "Cannot read $file\n" ); + exit( 1 ); + } + + $needle = '"id":"' . $class_name; + $found = false; + $line = fgets( $handle ); + while ( false !== $line && ! $found ) { + $found = false !== strpos( $line, $needle ); + $line = fgets( $handle ); + } + fclose( $handle ); + + return $found; +} + +// diff.php's exit code and output lines, STDERR included. +function diff( array $files ) { + $args = implode( ' ', array_map( 'escapeshellarg', $files ) ); + exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . " $args 2>&1", $output, $code ); + + return array( $code, $output ); +} + +function temp_file( $content ) { + $file = tempnam( sys_get_temp_dir(), 'leak-probe-' ); + if ( false === $file || false === file_put_contents( $file, $content ) ) { + fwrite( STDERR, "Cannot write a temporary file\n" ); + exit( 1 ); + } + + return $file; +} + +function class_start( $id, $noise, $inherited ) { + $state = array( + NOISE_KEY => array( $noise, $noise ), + INHERITED_KEY => array( $inherited, $inherited ), + ); + + return json_encode( + array( + 'point' => 'class_start', + 'id' => $id, + 'state' => $state, + ) + ) . "\n"; +} + +// The run without its last line, run_end. +function cut( $file ) { + $lines = file( $file ); + if ( false === $lines ) { + fwrite( STDERR, "Cannot read $file\n" ); + exit( 1 ); + } + + return temp_file( implode( '', array_slice( $lines, 0, -1 ) ) ); +} + +if ( 2 !== $argc ) { + fwrite( STDERR, "Usage: php check-probes.php run.jsonl\n" ); + exit( 1 ); +} + +list( $code, $output ) = diff( array( $argv[1] ) ); +if ( DIFF_LEAKS !== $code ) { + fwrite( STDERR, "diff.php exited with $code, not " . DIFF_LEAKS . ".\n" ); + exit( 1 ); +} + +$reported = array(); +$title = null; +foreach ( $output as $line ) { + if ( preg_match( HEADER, $line, $m ) ) { + $title = $m[1]; + $reported[ $title ] = array(); + continue; + } + + if ( null !== $title && preg_match( KEY_LINE, $line, $m ) ) { + $reported[ $title ][] = $m[1]; + } +} + +$setup = setup( $argv[1] ); +$expected = SCOPE_CLASS === $setup['scope'] ? CLASS_SCOPE : PER_TEST; + +// The copy this PHP version does not have: reporting it would mean the listener reads the wrong one. +$other_static = $setup['php'] >= PHP_SHARED_STATICS ? CHILD_STATIC : PARENT_STATIC; +$unexpected = UNEXPECTED + array( STATIC_TITLE => $other_static ); + +// Patterns this setup cannot report: the other cache's, multisite's on single site, the other PHP's. +$skip = array_merge( + $setup['persistent_cache'] ? RUNTIME_CACHE_ONLY : PERSISTENT_CACHE_ONLY, + $setup['multisite'] ? array() : MULTISITE_ONLY, + array( $other_static ) +); + +$missed = array(); +$checked = 0; +$skipped = 0; +foreach ( $expected as $title => $patterns ) { + foreach ( $patterns as $pattern ) { + if ( in_array( $pattern, $skip, true ) ) { + ++$skipped; + continue; + } + + ++$checked; + if ( ! preg_grep( $pattern, $reported[ $title ] ?? array() ) ) { + $missed[] = "$title: $pattern"; + } + } +} + +foreach ( $unexpected as $title => $pattern ) { + foreach ( preg_grep( $pattern, $reported[ $title ] ?? array() ) as $key ) { + $missed[] = "$title: unexpected $key"; + } +} + +foreach ( $reported as $title => $keys ) { + if ( false !== strpos( $title, SKIPPED_CLASS ) ) { + $missed[] = "$title: reported, but rules.php skips its file"; + } +} + +if ( snapshotted( $argv[1], SKIPPED_CLASS ) ) { + $missed[] = SKIPPED_CLASS . ': snapshotted, but rules.php skips its file'; +} + +// The class scope writes no class_start. +if ( SCOPE_CLASS !== $setup['scope'] ) { + list( $code, $refusal ) = diff( array( $argv[1], $argv[1], FIRST_CLASS ) ); + if ( DIFF_REFUSED !== $code || ! preg_grep( '/no snapshotted class ran before it/', $refusal ) ) { + $missed[] = FIRST_CLASS . ": comparison mode exited with $code, not refused as the first class"; + } +} + +$alone = temp_file( class_start( 'First', 'a', 'same' ) . class_start( 'Target', 'a', 'same' ) ); +$seq = temp_file( class_start( 'First', 'b', 'same' ) . class_start( 'Target', 'b', 'inherited' ) ); + +list( $code, $compared ) = diff( array( $alone, $seq, 'Target' ) ); +if ( DIFF_LEAKS !== $code || ! in_array( ' ' . INHERITED_KEY, $compared, true ) || in_array( ' ' . NOISE_KEY, $compared, true ) ) { + $missed[] = "comparison mode: exited with $code, not reporting " . INHERITED_KEY . ' only'; +} + +$cut = cut( $argv[1] ); + +list( $code, $incomplete ) = diff( array( $cut ) ); +if ( DIFF_INCOMPLETE !== $code || ! preg_grep( '#^Incomplete run#', $incomplete ) ) { + $missed[] = "run cut before run_end: diff.php exited with $code, not reported incomplete"; +} + +unlink( $alone ); +unlink( $seq ); +unlink( $cut ); + +if ( $missed ) { + fwrite( STDERR, "Missed or unexpected leaks:\n " . implode( "\n ", $missed ) . "\n" ); + exit( 1 ); +} + +echo "$checked expected leaks reported, $skipped skipped for this setup.\n"; diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php new file mode 100644 index 0000000000000..70a2ff842cb90 --- /dev/null +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -0,0 +1,1278 @@ + [hash, preview], appended as one JSON line + * to WP_TESTS_LEAKS_OUT. diff.php compares snapshots. + * + * Scope "class" sweeps a whole suite cheaply: snapshots at class bounds only, and one + * "class_leaks" line per class that changes state and leaves it unlike the install. + * A leak is reported once, by the first class leaving it; later ones start with it. + * + * Settings: the listener's "rules" and "scope", or the WP_TESTS_LEAKS_RULES and + * WP_TESTS_LEAKS_SCOPE env vars, which win when set. The rules file picks the keys snapshotted + * per scope and test file, see rules.php. WP_TESTS_LEAKS_AREAS replaces its scope's defaults. + * + * Areas: + * db/table/pk row, keyed by a unique key (e.g. option_name) or the primary key + * dbcount/table row count + * autoinc/table AUTO_INCREMENT counter (ROLLBACK does not reset it) + * schema/table SHOW CREATE TABLE without the AUTO_INCREMENT clause + * temptable/name temporary tables created through $wpdb and not dropped + * cache/group/key in-memory object cache (drop-in: cache/derived key) + * mc/key keys on the memcached servers + * stale/source/blog/group/key[/option] + * cached option/network option disagreeing with the DB + * global/name[/key] globals, arrays one level deeper; $wpdb minus query noise, + * $wp_object_cache minus its entries and counters + * static/Class::$prop class static properties + * fstatic/fn()/$var static variables of functions and methods + * const/NAME user-defined constants + * ini/name, env/NAME, proc/what ini settings, environment, process state + * file/path files under wp-content and the temp dir top level + */ +class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { + + use Yoast\PHPUnitPolyfills\TestListeners\TestListenerDefaultImplementation; + + private const SKIP_GLOBALS = array( 'GLOBALS', 'timestart', 'argv', 'argc', '__composer_autoload_files', '__PHPUNIT_BOOTSTRAP' ); + + // $wpdb properties that change on every query, the listener's own included. + private const WPDB_NOISE = array( 'last_query', 'last_result', 'col_info', 'queries', 'num_queries', 'num_rows', 'rows_affected', 'insert_id', 'result', 'func_call', 'time_start', 'last_error', 'dbh', 'col_meta', 'table_charset' ); + + // $wp_object_cache entries, snapshotted by cache(), and hit counters, which every read changes. + private const CACHE_NOISE = array( 'cache', 'cache_hits', 'cache_misses' ); + + // Test tooling, PHPUnit 5's PEAR-style names (PHPUnit_, PHP_Timer, ...) included. + private const SKIP_PREFIXES = array( 'PHPUnit', 'PHP_', 'Text_Template', 'File_Iterator', 'Composer\\', 'SebastianBergmann\\', 'Doctrine\\', 'Yoast\\', __CLASS__ ); + + private const MAX_DEPTH = 12; + + private const PHP_8_1 = 80100; + + private const PREVIEW_LENGTH = 200; + + private const MISMATCH_PREVIEW_LENGTH = 90; + + private const MEMCACHED_BATCH = 500; + + private const MEMCACHED_TIMEOUT = 2; + + private const SCOPE_CLASS = 'class'; + + private const SCOPE_TEST = 'test'; + + private const SETTINGS = array( 'rules', 'scope' ); + + private const RULES = 'tests/phpunit/leaks/rules.php'; + + private const RULE_KEYS = array( 'why', 'paths', 'areas' ); + + // Snapshot method => the areas it reads. + private const COLLECTORS = array( + 'db' => array( 'db', 'dbcount', 'autoinc', 'schema', 'temptable' ), + 'cache' => array( 'cache', 'stale' ), + 'memcached' => array( 'mc', 'stale' ), + 'globals' => array( 'global' ), + 'statics' => array( 'static' ), + 'static_vars' => array( 'fstatic' ), + 'constants' => array( 'const' ), + 'process' => array( 'ini', 'env', 'proc' ), + 'files' => array( 'file' ), + ); + + // Pattern shorthands, e.g. WP_TESTS_LEAKS_AREAS=statics,globals. + private const ALIASES = array( + 'all' => array( '*/*' ), + 'persistent' => array( 'db/*', 'schema/*', 'mc/*', 'file/*', 'stale/*' ), + 'database' => array( 'db/*', 'dbcount/*', 'autoinc/*', 'schema/*', 'temptable/*' ), + 'caches' => array( 'cache/*', 'mc/*', 'stale/*' ), + 'globals' => array( 'global/*' ), + 'statics' => array( 'static/*', 'fstatic/*' ), + 'runtime' => array( 'const/*', 'ini/*', 'env/*', 'proc/*' ), + 'files' => array( 'file/*' ), + ); + + // Where rule paths are searched for, from the repo root; not fixtures or output. + private const TESTS_DIR = 'tests/phpunit'; + + private const SKIP_DIRS = array( 'data', 'build' ); + + private const JSON_FLAGS = JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES; + + // SHOW CREATE TABLE has the live counter; information_schema caches it. + private const AUTO_INCREMENT = '/ AUTO_INCREMENT=(\d+)/'; + + // The result file PHPUnit 9 hands an isolated child, see TestCase::run(). + private const PHPUNIT_TEMP_PREFIX = 'phpunit_'; + + // The listener's own environment: its settings. + private const ENV_PREFIX = 'WP_TESTS_LEAKS_'; + + private $out; + + private $scope; + + private $rules_file; + + // The scope's default patterns, each [negated, glob, whole area]. + private $patterns = array(); + + // Each [path globs, patterns]. + private $file_rules = array(); + + // Test file => plan, see plan(). + private $plans = array(); + + // WP_TESTS_LEAKS_SCOPE=class: the state at the run start and at the running class start. + private $installed = null; + + private $class_start = null; + + // Whether the last snapshot was a test_end: the next test_start reuses it. + private $ended = false; + + private $columns = array(); + + private $primary = array(); + + private $temp_tables = array(); + + // Tables db() listed, so the stale checks skip a deleted site's. + private $tables = array(); + + // The connection $temp_tables were created on. + private $connection = null; + + // Suites started and not ended: the run starts at the first and ends with it. + private $open_suites = 0; + + // Whether any class's plan kept an area: else diff.php would read the run as clean. + private $snapshotted = false; + + // Key globs that kept a key, see unmatched(). + private $matched = array(); + + // DB rows read by the stale checks, reset per snapshot. + private $rows = array(); + + /** + * @param array $settings The listener's : "rules" (path from the repo root) and "scope" ("test" or "class"). + */ + public function __construct( array $settings = array() ) { + $unknown = array_diff( array_keys( $settings ), self::SETTINGS ); + if ( $unknown ) { + $this->fail( 'Unknown settings: ' . implode( ', ', $unknown ) . '.' ); + } + + // Set and truncated by bootstrap.php. + $this->out = getenv( 'WP_TESTS_LEAKS_OUT' ); + $this->scope = $this->setting( 'SCOPE', $settings['scope'] ?? self::SCOPE_TEST ); + + if ( ! in_array( $this->scope, array( self::SCOPE_TEST, self::SCOPE_CLASS ), true ) ) { + $this->fail( 'The scope must be "' . self::SCOPE_TEST . '" or "' . self::SCOPE_CLASS . "\", not \"$this->scope\"." ); + } + + $this->rules_file = $this->absolute( $this->setting( 'RULES', $settings['rules'] ?? self::RULES ) ); + $this->load_rules(); + + // Last, so it sees the CREATE TEMPORARY TABLE rewritten by the test case's own filter. + add_filter( 'query', array( $this, 'track_temp_tables' ), PHP_INT_MAX ); + } + + // The env var if set and not empty, else the default. + private function setting( $name, $fallback ) { + $value = getenv( self::ENV_PREFIX . $name ); + + return false === $value || '' === $value ? $fallback : $value; + } + + private function absolute( $path ) { + return str_starts_with( $path, '/' ) ? $path : $this->root() . "/$path"; + } + + private function root() { + return dirname( __DIR__, 3 ); + } + + private function load_rules() { + if ( ! is_file( $this->rules_file ) ) { + $this->fail( "No rules file at $this->rules_file." ); + } + + $rules = require $this->rules_file; + $source = $this->rules_file; + if ( ! is_array( $rules ) || ! isset( $rules['areas'][ $this->scope ] ) || array_diff( array_keys( $rules ), array( 'areas', 'files' ) ) ) { + $this->fail( "$source must return an array with 'areas' per scope and, optionally, 'files'." ); + } + + $env = $this->setting( 'AREAS', '' ); + $this->patterns = '' === $env + ? $this->patterns( $rules['areas'][ $this->scope ], "$source areas $this->scope" ) + : $this->patterns( explode( ',', $env ), self::ENV_PREFIX . 'AREAS' ); + + foreach ( $rules['files'] ?? array() as $i => $rule ) { + $where = "$source files $i"; + if ( ! is_array( $rule ) || array_diff( array_keys( $rule ), self::RULE_KEYS ) || array_diff( self::RULE_KEYS, array_keys( $rule ) ) ) { + $this->fail( "$where: needs exactly 'why', 'paths' and 'areas'." ); + } + + if ( ! is_string( $rule['why'] ) || '' === trim( $rule['why'] ) ) { + $this->fail( "$where: 'why' must say why the rule exists." ); + } + + if ( ! is_array( $rule['paths'] ) || ! $rule['paths'] || array_filter( $rule['paths'], 'is_string' ) !== $rule['paths'] ) { + $this->fail( "$where: 'paths' must be a list of globs." ); + } + + $this->file_rules[] = array( $rule['paths'], $this->patterns( $rule['areas'], $where ) ); + } + } + + // Entries to [negated, glob, whole area]: aliases expanded, a bare area name as "area/*". + private function patterns( $entries, $where ) { + if ( ! is_array( $entries ) || ! $entries ) { + $this->fail( "$where: needs a list of patterns." ); + } + + $patterns = array(); + foreach ( $entries as $entry ) { + $entry = is_string( $entry ) ? trim( $entry ) : ''; + if ( '' === $entry || '!' === $entry ) { + $this->fail( "$where: empty or non-string pattern." ); + } + + $negated = '!' === $entry[0]; + $name = $negated ? substr( $entry, 1 ) : $entry; + $globs = self::ALIASES[ $name ] ?? array( str_contains( $name, '/' ) ? $name : "$name/*" ); + + foreach ( $globs as $glob ) { + list( $area, $key ) = explode( '/', $glob, 2 ); + if ( ! $this->areas_matching( $area ) ) { + $this->fail( "$where: \"$entry\" matches no area: " . implode( ', ', $this->areas() ) . '.' ); + } + + $patterns[] = array( $negated, $glob, '*' === $key ); + } + } + + return $patterns; + } + + private function areas() { + return array_values( array_unique( array_merge( ...array_values( self::COLLECTORS ) ) ) ); + } + + private function areas_matching( $glob ) { + return array_filter( + $this->areas(), + static function ( $area ) use ( $glob ) { + return fnmatch( $glob, $area, FNM_NOESCAPE ); + } + ); + } + + // A rule whose paths match no test file was left behind by a rename or removal. + private function check_paths() { + $files = array(); + $dir = new RecursiveDirectoryIterator( $this->root() . '/' . self::TESTS_DIR, FilesystemIterator::SKIP_DOTS ); + $skip = new RecursiveCallbackFilterIterator( + $dir, + static function ( $file ) { + return ! $file->isDir() || ! in_array( $file->getFilename(), self::SKIP_DIRS, true ); + } + ); + foreach ( new RecursiveIteratorIterator( $skip ) as $path => $file ) { + $files[] = $this->relative( $path ); + } + + foreach ( $this->file_rules as $i => $rule ) { + foreach ( $rule[0] as $glob ) { + $matched = array_filter( + $files, + function ( $file ) use ( $glob ) { + return $this->globbed( array( $glob ), $file ); + } + ); + if ( ! $matched ) { + $this->fail( "$this->rules_file files $i: \"$glob\" matches no file under " . self::TESTS_DIR . '.' ); + } + } + } + } + + private function relative( $path ) { + return substr( $path, strlen( $this->root() ) + 1 ); + } + + /* + * The test file's patterns, the defaults then each matching rule's, as area => true to keep + * all its keys, or its patterns, last first. Areas no pattern keeps are left out. + */ + private function plan( $class_name ) { + $file = class_exists( $class_name, false ) ? (string) ( new ReflectionClass( $class_name ) )->getFileName() : ''; + if ( isset( $this->plans[ $file ] ) ) { + return $this->plans[ $file ]; + } + + $patterns = $this->patterns; + foreach ( $this->file_rules as $rule ) { + if ( '' !== $file && $this->globbed( $rule[0], $this->relative( $file ) ) ) { + $patterns = array_merge( $patterns, $rule[1] ); + } + } + + $this->plans[ $file ] = $this->plan_for( $patterns ); + + return $this->plans[ $file ]; + } + + private function globbed( array $globs, $path ) { + foreach ( $globs as $glob ) { + if ( fnmatch( $glob, $path, FNM_NOESCAPE ) ) { + return true; + } + } + + return false; + } + + private function plan_for( array $patterns ) { + $plan = array(); + foreach ( $this->areas() as $area ) { + $last = array(); + foreach ( array_reverse( $patterns ) as $pattern ) { + if ( ! fnmatch( strstr( $pattern[1], '/', true ), $area, FNM_NOESCAPE ) ) { + continue; + } + + $last[] = $pattern; + + // Earlier patterns can't change a key it matches. + if ( $pattern[2] ) { + break; + } + } + + if ( ! in_array( false, array_column( $last, 0 ), true ) ) { + continue; + } + + $plan[ $area ] = 1 === count( $last ) && $last[0][2] ? true : $last; + } + + return $plan; + } + + // The class scope's install snapshot: every key any test file's plan keeps. + private function union_plan() { + $patterns = $this->patterns; + foreach ( $this->file_rules as $rule ) { + foreach ( $rule[1] as $pattern ) { + if ( ! $pattern[0] ) { + $patterns[] = $pattern; + } + } + } + + return $this->plan_for( $patterns ); + } + + private function filter( array $state, array $plan ) { + $kept = array(); + foreach ( $state as $key => $entry ) { + $area = $plan[ strstr( $key, '/', true ) ] ?? null; + if ( true === $area || ( $area && $this->kept( $key, $area ) ) ) { + $kept[ $key ] = $entry; + } + } + + return $kept; + } + + // The last pattern matching the key decides. + private function kept( $key, array $patterns ) { + foreach ( $patterns as $pattern ) { + if ( fnmatch( $pattern[1], $key, FNM_NOESCAPE ) ) { + $this->matched[ $pattern[1] ] = true; + return ! $pattern[0]; + } + } + + return false; + } + + public function track_temp_tables( $query ) { + $this->sync_connection(); + + if ( preg_match( '/^\s*CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)/i', $query, $m ) ) { + $this->temp_tables[ $m[1] ] = true; + } elseif ( preg_match( '/^\s*DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?(.+)$/is', $query, $m ) ) { + foreach ( preg_split( '/\s*,\s*/', trim( $m[1], " ;\n" ) ) as $name ) { + unset( $this->temp_tables[ trim( $name, '`' ) ] ); + } + } + + return $query; + } + + public function start_test_suite( $suite ) { + // Marks the run's start and end so diff.php sees a cut run. The start holds the setup check-probes.php reads. + if ( 0 === $this->open_suites++ ) { + $this->check_paths(); + $this->mark( 'run_start', array( 'setup' => $this->setup() ) ); + + // Before any class runs, those rules.php skips included. + if ( self::SCOPE_CLASS === $this->scope ) { + $this->installed = $this->state( $this->union_plan() ); + } + } + + $class_name = $suite->getName(); + if ( ! class_exists( $class_name, false ) ) { + return; + } + + $plan = $this->plan( $class_name ); + if ( ! $plan ) { + return; + } + + $this->snapshotted = true; + + if ( self::SCOPE_CLASS !== $this->scope ) { + $this->write( 'class_start', $class_name, $plan ); + return; + } + + $this->class_start = $this->state( $plan ); + } + + public function end_test_suite( $suite ) { + if ( class_exists( $suite->getName(), false ) ) { + $this->end_class( $suite->getName() ); + } + + if ( 0 !== --$this->open_suites ) { + return; + } + + // With no run_end, diff.php reports the run as incomplete. + if ( ! $this->snapshotted ) { + fwrite( STDERR, "No test file's patterns keep an area: nothing was snapshotted.\n" ); + return; + } + + $unmatched = $this->unmatched(); + foreach ( $unmatched as $glob ) { + fwrite( STDERR, "\"$glob\" kept no key: a typo, or nothing it names existed.\n" ); + } + + if ( $unmatched ) { + return; + } + + $this->mark( 'run_end' ); + } + + // Positive key globs of the plans used that kept no key all run. + private function unmatched() { + $globs = array(); + foreach ( $this->plans as $plan ) { + foreach ( array_filter( $plan, 'is_array' ) as $patterns ) { + foreach ( $patterns as $pattern ) { + if ( ! $pattern[0] && ! $pattern[2] && ! isset( $this->matched[ $pattern[1] ] ) ) { + $globs[ $pattern[1] ] = true; + } + } + } + } + + return array_keys( $globs ); + } + + private function end_class( $class_name ) { + // Class hooks run before the next test, this class's again with --repeat. + $this->ended = false; + + $plan = $this->plan( $class_name ); + if ( ! $plan ) { + return; + } + + if ( self::SCOPE_CLASS !== $this->scope ) { + $this->write( 'class_end', $class_name, $plan ); + return; + } + + $this->write_class_leaks( $class_name, $plan ); + } + + public function start_test( $test ) { + $name = $this->name( $test ); + $reuse = $this->ended; + $this->ended = false; + + $plan = $this->plan( get_class( $test ) ); + if ( self::SCOPE_CLASS === $this->scope || ! $plan ) { + return; + } + + if ( $reuse ) { + $this->append( $this->line( 'test_start', $name, array() ) + array( 'reuse' => true ) ); + return; + } + + $this->write( 'test_start', $name, $plan ); + } + + public function end_test( $test, $time ) { + $plan = $this->plan( get_class( $test ) ); + if ( self::SCOPE_CLASS !== $this->scope && $plan ) { + $this->write( 'test_end', $this->name( $test ), $plan ); + $this->ended = true; + } + } + + private function name( $test ) { + return $test instanceof PHPUnit\Framework\TestCase ? get_class( $test ) . '::' . $test->getName() : get_class( $test ); + } + + private function write( $point, $id, array $plan ) { + $this->append( $this->line( $point, $id, $this->state( $plan ) ) ); + } + + private function line( $point, $id, array $state ) { + return array( + 'point' => $point, + 'id' => $id, + 'state' => $state, + ); + } + + private function mark( $point, array $extra = array() ) { + $this->append( $this->line( $point, '', array() ) + $extra ); + } + + private function setup() { + return array( + 'multisite' => is_multisite(), + 'php' => PHP_VERSION_ID, + 'persistent_cache' => (bool) wp_using_ext_object_cache(), + 'scope' => $this->scope, + ); + } + + /* + * Persistent state the class changed and left unlike the install, e.g. `site_admins` + * ["admin"] at install, ["superadmin"] at class start, [] at class end. The line + * holds the install values as "installed" and the class end ones as "state". + */ + private function write_class_leaks( $class_name, array $plan ) { + $start = $this->class_start; + $end = $this->state( $plan ); + + $this->class_start = null; + + $installed = array(); + $left = array(); + foreach ( array_keys( $start + $end ) as $key ) { + $hash = $end[ $key ][0] ?? null; + if ( ( $start[ $key ][0] ?? null ) === $hash || ( $this->installed[ $key ][0] ?? null ) === $hash ) { + continue; + } + + if ( isset( $this->installed[ $key ] ) ) { + $installed[ $key ] = $this->installed[ $key ]; + } + if ( isset( $end[ $key ] ) ) { + $left[ $key ] = $end[ $key ]; + } + } + + if ( ! $installed && ! $left ) { + return; + } + + $this->append( $this->line( 'class_leaks', $class_name, $left ) + array( 'installed' => $installed ) ); + } + + // The keys the plan keeps, see plan(). + private function state( array $plan ) { + global $wpdb; + + /* + * A memcached run without the drop-in silently snapshots the in-memory cache instead. + * Happens when the env's php container (re)starts with LOCAL_PHP_MEMCACHED=false: + * its start command deletes src/wp-content/object-cache.php. + */ + if ( 'true' === getenv( 'LOCAL_PHP_MEMCACHED' ) && ! wp_using_ext_object_cache() ) { + $this->fail( 'LOCAL_PHP_MEMCACHED=true but no object-cache.php drop-in is active.' ); + } + + $this->rows = array(); + + // The stale checks in cache() and memcached() read it too: a dropped table would fail their reads. + if ( array_intersect_key( $plan, array_flip( array_merge( self::COLLECTORS['db'], self::COLLECTORS['cache'], self::COLLECTORS['memcached'] ) ) ) ) { + $this->list_tables(); + } + + $state = array(); + foreach ( self::COLLECTORS as $method => $areas ) { + if ( array_intersect_key( $plan, array_flip( $areas ) ) ) { + $state = array_merge( $state, $this->$method() ); + } + } + + $state = $this->filter( $state, $plan ); + + // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. + $wpdb->query( 'COMMIT' ); + + return $state; + } + + private function append( array $line ) { + if ( false === file_put_contents( $this->out, json_encode( $line, self::JSON_FLAGS ) . "\n", FILE_APPEND | LOCK_EX ) ) { + $this->fail( "Cannot write $this->out." ); + } + } + + private function fail( $message ) { + fwrite( STDERR, __CLASS__ . ": $message\n" ); + exit( 1 ); + } + + // phpcs:disable WordPress.DB.PreparedSQL -- Table and column names come from SHOW TABLES and SHOW COLUMNS. + private function list_tables() { + global $wpdb; + + /* + * Tests leave autocommit off, so a SELECT a test ran after tear_down()'s ROLLBACK left + * a REPEATABLE READ read view open that hides rows committed since, e.g. by an isolated + * child process. Snapshots run outside the tests' transactions and START TRANSACTION + * would commit anything pending anyway, so this changes nothing for the tests. + */ + $wpdb->query( 'COMMIT' ); + + $like = $wpdb->esc_like( $wpdb->base_prefix ) . '%'; + $tables = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $like ) ); + $this->check_query( 'the tables' ); + + $this->tables = array_flip( $tables ); + } + + private function db() { + global $wpdb; + + $state = array(); + + foreach ( array_keys( $this->tables ) as $table ) { + $create = (string) $wpdb->get_var( "SHOW CREATE TABLE `$table`", 1 ); + $this->check_query( $table ); + $schema = preg_replace( self::AUTO_INCREMENT, '', $create ); + + $state[ "schema/$table" ] = $this->text( $schema ); + if ( preg_match( self::AUTO_INCREMENT, $create, $m ) ) { + $state[ "autoinc/$table" ] = $this->text( $m[1] ); + } + + // Keyed by the schema, so a test's DDL refreshes them. + $meta = md5( $schema ); + if ( ! isset( $this->columns[ $meta ] ) ) { + $this->columns[ $meta ] = $wpdb->get_col( "SHOW COLUMNS FROM `$table`" ); + $this->check_query( $table ); + // Column_name is the 5th column of SHOW KEYS. + $this->primary[ $meta ] = $wpdb->get_col( "SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'", 4 ); + $this->check_query( $table ); + + /* + * A unique key wins over the auto-increment primary key, and the latter leaves the + * row value: e.g. an option deleted and re-added with the same value is no change. + */ + $unique = $wpdb->get_col( "SHOW KEYS FROM `$table` WHERE Key_name <> 'PRIMARY' AND Non_unique = 0", 4 ); + $this->check_query( $table ); + if ( $unique ) { + $this->columns[ $meta ] = array_values( array_diff( $this->columns[ $meta ], $this->primary[ $meta ] ) ); + $this->primary[ $meta ] = $unique; + } + + // Bumped by every post saved on a site, e.g. by any class creating fixture posts. + if ( $table === $wpdb->blogs ) { + $this->columns[ $meta ] = array_values( array_diff( $this->columns[ $meta ], array( 'last_updated' ) ) ); + } + } + + $cols = $this->columns[ $meta ]; + if ( ! $cols ) { + continue; + } + + // No primary key: key by the whole row, duplicates get a #n suffix below. + $pk = $this->primary[ $meta ] ? $this->primary[ $meta ] : $cols; + $rows = $wpdb->get_results( 'SELECT ' . $this->concat( $pk ) . ' AS k, ' . $this->concat( $cols ) . " AS v FROM `$table`", ARRAY_N ); + $this->check_query( $table ); + + foreach ( (array) $rows as $row ) { + $key = "db/$table/" . str_replace( "\x1f", ',', $row[0] ); + for ( $n = 2; isset( $state[ $key ] ); $n++ ) { + $key = preg_replace( '/#\d+$/', '', $key ) . "#$n"; + } + $state[ $key ] = array( md5( $row[1] ), substr( $row[1], 0, self::PREVIEW_LENGTH ) ); + } + $state[ "dbcount/$table" ] = $this->text( (string) count( (array) $rows ) ); + } + + $this->sync_connection(); + foreach ( array_keys( $this->temp_tables ) as $name ) { + $state[ "temptable/$name" ] = $this->text( 'exists' ); + } + + return $state; + } + + // A failed read would snapshot as missing data. + private function check_query( $what ) { + global $wpdb; + + if ( $wpdb->last_error ) { + $this->fail( "Cannot read $what: $wpdb->last_error" ); + } + } + + // A new connection, e.g. from WP_UnitTestCase_Base::set_up_before_class(), has none of the old one's temporary tables. + private function sync_connection() { + global $wpdb; + + $connection = is_object( $wpdb->dbh ) ? spl_object_id( $wpdb->dbh ) : null; + if ( $connection !== $this->connection ) { + $this->connection = $connection; + $this->temp_tables = array(); + } + } + + // The columns joined by 0x1f, NULL as 0x00. + private function concat( array $columns ) { + $columns = array_map( + static function ( $column ) { + return "IFNULL(`$column`,0x00)"; + }, + $columns + ); + + return 'CONCAT_WS(0x1f,' . implode( ',', $columns ) . ')'; + } + // phpcs:enable + + // In-memory object cache entries; for memcached the drop-in's local copy, keyed by derived key. + private function cache() { + global $wp_object_cache; + + $state = array(); + if ( ! is_object( $wp_object_cache ) || ! property_exists( $wp_object_cache, 'cache' ) ) { + return $state; + } + + $cache = $this->read( new ReflectionProperty( $wp_object_cache, 'cache' ), $wp_object_cache ); + + if ( isset( $wp_object_cache->m ) ) { + foreach ( (array) $cache as $derived => $value ) { + $state[ "cache/$derived" ] = $this->entry( $value ); + $state += $this->stale_derived( 'local', $derived, $value ); + } + + return $state; + } + + $global_groups = $this->read( new ReflectionProperty( $wp_object_cache, 'global_groups' ), $wp_object_cache ); + + foreach ( (array) $cache as $group => $entries ) { + foreach ( (array) $entries as $id => $value ) { + $state[ "cache/$group/$id" ] = $this->entry( $value ); + + // Multisite prefixes non-global keys with ":". + $blog = 1; + $key = (string) $id; + if ( is_multisite() && ! isset( $global_groups[ $group ] ) && preg_match( '/^(\d+):(.*)$/s', $key, $m ) ) { + $blog = (int) $m[1]; + $key = $m[2]; + } + + $state += $this->stale( 'runtime', $blog, $group, $key, $value ); + } + } + + return $state; + } + + /* + * Keys stored on the memcached servers, not just the drop-in's local copy. + * Lists them with `lru_crawler metadump all` (memcached >= 1.4.31), then reads + * the values through the drop-in's own client so they come back unserialized. + * Flushed items may still be listed; getMulti() skips them. + */ + private function memcached() { + global $wp_object_cache; + + $state = array(); + if ( ! is_object( $wp_object_cache ) || ! isset( $wp_object_cache->m ) || ! $wp_object_cache->m instanceof Memcached ) { + return $state; + } + + $keys = array(); + foreach ( $wp_object_cache->m->getServerList() as $server ) { + $errno = 0; + $errstr = ''; + $address = "{$server['host']}:{$server['port']}"; + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Reported below. + $socket = @fsockopen( $server['host'], $server['port'], $errno, $errstr, self::MEMCACHED_TIMEOUT ); + if ( false === $socket ) { + $this->fail( "Cannot reach memcached at $address: $errstr" ); + } + + stream_set_timeout( $socket, self::MEMCACHED_TIMEOUT ); + fwrite( $socket, "lru_crawler metadump all\r\n" ); + + // memcached 1.6+ acknowledges the command before the keys. + $line = fgets( $socket ); + if ( "OK\r\n" === $line ) { + $line = fgets( $socket ); + } + + while ( false !== $line && preg_match( '/^key=(\S+)/', $line, $m ) ) { + $keys[] = rawurldecode( $m[1] ); + $line = fgets( $socket ); + } + fclose( $socket ); + + // Anything else, e.g. ERROR, BUSY or a timeout, would drop keys. + if ( "END\r\n" !== $line ) { + $this->fail( "lru_crawler metadump on $address failed: " . json_encode( $line ) ); + } + } + + foreach ( array_chunk( array_unique( $keys ), self::MEMCACHED_BATCH ) as $chunk ) { + $values = $wp_object_cache->m->getMulti( $chunk ); + if ( false === $values && Memcached::RES_NOTFOUND !== $wp_object_cache->m->getResultCode() ) { + $this->fail( 'Memcached::getMulti() failed: ' . $wp_object_cache->m->getResultMessage() ); + } + + foreach ( (array) $values as $key => $value ) { + $state[ "mc/$key" ] = $this->entry( $value ); + $state += $this->stale_derived( 'memcached', $key, $value ); + } + } + + return $state; + } + + /* + * Splits a drop-in key built by WP_Object_Cache::buildKey() and runs the stale check: + * multisite: ":options:", "site-options::" (global, no prefix) + * single site: ":options:", "
site-options:" + */ + private function stale_derived( $source, $derived, $value ) { + global $table_prefix; + + $prefix = preg_quote( $table_prefix, '/' ); + if ( ! preg_match( "/^(?:(\\d+):|{$prefix}:?)?(options|site-options):(.*)$/s", $derived, $m ) ) { + return array(); + } + + return $this->stale( $source, $m[1] ? (int) $m[1] : 1, $m[2], $m[3], $value ); + } + + // Cached options and network options that disagree with their DB rows, e.g. after a ROLLBACK. + private function stale( $source, $blog, $group, $key, $value ) { + $label = "stale/$source/$blog/$group/$key"; + + if ( 'options' === $group ) { + $rows = $this->option_rows( $blog ); + $name = $key; + } elseif ( 'site-options' === $group && is_multisite() && preg_match( '/^(\d+):(.+)$/s', $key, $m ) ) { + $rows = $this->sitemeta_rows( (int) $m[1] ); + $name = $m[2]; + } else { + return array(); + } + + if ( null === $rows ) { + return array(); + } + + $out = array(); + + if ( 'alloptions' === $name && is_array( $value ) ) { + foreach ( $value as $option => $cached ) { + if ( ! $this->same( $rows[ $option ] ?? null, $cached ) ) { + $out[ "$label/$option" ] = $this->mismatch( $cached, $rows[ $option ] ?? null ); + } + } + return $out; + } + + if ( 'notoptions' === $name && is_array( $value ) ) { + foreach ( array_keys( $value ) as $option ) { + if ( isset( $rows[ $option ] ) ) { + $out[ "$label/$option" ] = $this->mismatch( '(cached as missing)', $rows[ $option ] ); + } + } + return $out; + } + + if ( ! $this->same( $rows[ $name ] ?? null, $value ) ) { + $out[ $label ] = $this->mismatch( $value, $rows[ $name ] ?? null ); + } + + return $out; + } + + private function same( $raw, $cached ) { + if ( null === $raw ) { + return false; + } + + // get_option() caches the raw string, get_network_option() the unserialized value, e.g. ints as strings. + return $raw === $cached || maybe_unserialize( $raw ) == $cached; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual + } + + private function mismatch( $cached, $raw ) { + $cached = is_scalar( $cached ) ? (string) $cached : (string) json_encode( $cached, self::JSON_FLAGS ); + $raw = null === $raw ? '(no row)' : substr( $raw, 0, self::MISMATCH_PREVIEW_LENGTH ); + + return $this->text( 'cache=' . substr( $cached, 0, self::MISMATCH_PREVIEW_LENGTH ) . ' db=' . $raw ); + } + + private function option_rows( $blog ) { + global $wpdb; + + // A site created in a test has temporary tables, which SHOW TABLES leaves out. + $table = $wpdb->get_blog_prefix( $blog ) . 'options'; + if ( ! isset( $this->tables[ $table ] ) && ! isset( $this->temp_tables[ $table ] ) ) { + return null; + } + + if ( ! isset( $this->rows[ "options:$blog" ] ) ) { + $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT option_name, option_value FROM %i', $table ), OBJECT_K ); + $this->check_query( $table ); + + $this->rows[ "options:$blog" ] = wp_list_pluck( (array) $rows, 'option_value' ); + } + + return $this->rows[ "options:$blog" ]; + } + + private function sitemeta_rows( $network ) { + global $wpdb; + + if ( ! isset( $this->rows[ "sitemeta:$network" ] ) ) { + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} WHERE site_id = %d", $network ) ); + $this->check_query( $wpdb->sitemeta ); + + $this->rows[ "sitemeta:$network" ] = wp_list_pluck( (array) $rows, 'meta_value', 'meta_key' ); + } + + return $this->rows[ "sitemeta:$network" ]; + } + + // Globals; arrays one level deeper so diffs name the changed key. + private function globals() { + $state = array(); + + foreach ( $GLOBALS as $name => $value ) { + if ( in_array( $name, self::SKIP_GLOBALS, true ) ) { + continue; + } + + if ( $value instanceof wpdb ) { + $value = array_diff_key( $this->props( $value ), array_flip( self::WPDB_NOISE ) ); + } + + if ( 'wp_object_cache' === $name && is_object( $value ) ) { + $value = array_diff_key( $this->props( $value ), array_flip( self::CACHE_NOISE ) ); + } + + if ( is_array( $value ) && $value ) { + // The listener's own queries run the `query` filter too. + if ( 'wp_filters' === $name ) { + unset( $value['query'] ); + } + + foreach ( $value as $key => $item ) { + // The listener's own settings in $_ENV and $_SERVER. + if ( ! str_starts_with( (string) $key, self::ENV_PREFIX ) ) { + $state[ "global/$name/$key" ] = $this->entry( $item ); + } + } + continue; + } + + $state[ "global/$name" ] = $this->entry( $value ); + } + + return $state; + } + + private function skipped( $name ) { + foreach ( self::SKIP_PREFIXES as $prefix ) { + if ( str_starts_with( $name, $prefix ) ) { + return true; + } + } + + return false; + } + + // Static properties of user-defined classes (WP core + test framework). + private function statics() { + $state = array(); + + foreach ( get_declared_classes() as $class_name ) { + $ref = new ReflectionClass( $class_name ); + if ( $ref->isInternal() || $this->skipped( $class_name ) ) { + continue; + } + + foreach ( $ref->getProperties( ReflectionProperty::IS_STATIC ) as $prop ) { + if ( $prop->getDeclaringClass()->getName() !== $class_name ) { + continue; + } + + $state[ "static/$class_name::\${$prop->getName()}" ] = $this->entry( $this->read( $prop ) ); + } + } + + return $state; + } + + // `static $x` variables inside user functions and methods. + private function static_vars() { + $state = array(); + $functions = array(); + + foreach ( get_defined_functions()['user'] as $function ) { + $functions[ "$function()" ] = new ReflectionFunction( $function ); + } + + foreach ( get_declared_classes() as $class_name ) { + $ref = new ReflectionClass( $class_name ); + if ( $ref->isInternal() || $this->skipped( $class_name ) ) { + continue; + } + + foreach ( $ref->getMethods() as $method ) { + $inherited = $method->getDeclaringClass()->getName() !== $class_name; + + /* + * Before PHP 8.1, each subclass has its own copy of an inherited method's static variables. + * A test class's copies are the framework's, e.g. factory()'s. + */ + if ( $inherited && ( PHP_VERSION_ID >= self::PHP_8_1 || $ref->isSubclassOf( 'PHPUnit\Framework\TestCase' ) ) ) { + continue; + } + + $functions[ "$class_name::{$method->getName()}()" ] = $method; + } + } + + foreach ( $functions as $label => $ref ) { + foreach ( $ref->getStaticVariables() as $var => $value ) { + $state[ "fstatic/$label/\$$var" ] = $this->entry( $value ); + } + } + + return $state; + } + + private function constants() { + $state = array(); + + foreach ( get_defined_constants( true )['user'] ?? array() as $name => $value ) { + $state[ "const/$name" ] = $this->entry( $value ); + } + + return $state; + } + + // PHP process state a test can change and not restore. + private function process() { + $state = array(); + + foreach ( ini_get_all( null, false ) as $name => $value ) { + $state[ "ini/$name" ] = $this->text( (string) $value ); + } + + foreach ( getenv() as $name => $value ) { + if ( ! str_starts_with( $name, self::ENV_PREFIX ) ) { + $state[ "env/$name" ] = $this->text( (string) $value ); + } + } + + // Reading the current handlers means swapping them out and back. + $error_handler = set_error_handler( null ); + restore_error_handler(); + $exception_handler = set_exception_handler( null ); + restore_exception_handler(); + + $process = array( + 'error_reporting' => error_reporting(), + 'ob_level' => ob_get_level(), + 'locale' => setlocale( LC_ALL, 0 ), + 'timezone' => date_default_timezone_get(), + 'cwd' => getcwd(), + 'umask' => umask(), + 'mb_encoding' => function_exists( 'mb_internal_encoding' ) ? mb_internal_encoding() : null, + 'error_handler' => $error_handler, + 'exception_handler' => $exception_handler, + 'autoloaders' => array_map( array( $this, 'callback' ), spl_autoload_functions() ), + 'libxml_errors' => libxml_use_internal_errors(), + ); + + foreach ( $process as $what => $value ) { + $state[ "proc/$what" ] = $this->entry( $value ); + } + + return $state; + } + + // Files under wp-content (uploads, fonts, languages, ...) and the temp dir's top level. + private function files() { + $state = array(); + + if ( defined( 'WP_CONTENT_DIR' ) && is_dir( WP_CONTENT_DIR ) ) { + $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( WP_CONTENT_DIR, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST ); + // Absolute paths: their leading "/" is the separator. + foreach ( $iterator as $path => $file ) { + $state[ 'file' . $path ] = $this->file( $file ); + } + } + + foreach ( new FilesystemIterator( sys_get_temp_dir() ) as $path => $file ) { + if ( ! str_starts_with( $file->getFilename(), self::PHPUNIT_TEMP_PREFIX ) ) { + $state[ 'file' . $path ] = $this->file( $file ); + } + } + + // The listener's own output, e.g. with WP_TESTS_LEAKS_OUT in the temp dir. + $own = realpath( $this->out ); + if ( false !== $own ) { + unset( $state[ 'file' . $own ] ); + } + + return $state; + } + + // A method callback by class and name: e.g. Composer's ClassLoader changes with every lookup. + private function callback( $callback ) { + return is_array( $callback ) && is_object( $callback[0] ) ? get_class( $callback[0] ) . '::' . $callback[1] : $callback; + } + + private function file( SplFileInfo $file ) { + // Before the target's metadata, which a dangling link has none of. + if ( $file->isLink() ) { + return $this->text( 'link ' . $file->getLinkTarget() ); + } + + return $this->text( $file->isDir() ? 'dir' : $file->getSize() . ' ' . $file->getMTime() ); + } + + // Private members need setAccessible() before PHP 8.1, which deprecates it in 8.5. + private function read( ReflectionProperty $prop, $instance = null ) { + if ( PHP_VERSION_ID < self::PHP_8_1 ) { + $prop->setAccessible( true ); + } + + return $prop->isInitialized( $instance ) ? $prop->getValue( $instance ) : '(uninitialized)'; + } + + private function props( $instance ) { + $props = array(); + foreach ( (array) $instance as $k => $v ) { + $props[ preg_replace( '/^\0.+\0/', '', $k ) ] = $v; + } + + return $props; + } + + private function text( $text ) { + return array( md5( $text ), substr( $text, 0, self::PREVIEW_LENGTH ) ); + } + + private function entry( $value ) { + $seen = array(); + $norm = $this->normalize( $value, 0, $seen ); + $text = is_string( $norm ) ? $norm : (string) json_encode( $norm, self::JSON_FLAGS ); + + // Not the JSON: it hashes 1 and "1" alike, and invalid UTF-8 as U+FFFD. + return array( md5( serialize( $norm ) ), substr( $text, 0, self::PREVIEW_LENGTH ) ); + } + + /* + * Serializable view of a value: closures by definition site and bound object, + * resources by type, cycles cut, depth capped at MAX_DEPTH. + */ + private function normalize( $value, $depth, array &$seen ) { + if ( $depth > self::MAX_DEPTH ) { + return '(deep)'; + } + + if ( is_resource( $value ) ) { + return '(resource ' . get_resource_type( $value ) . ')'; + } + + if ( $value instanceof Closure ) { + $ref = new ReflectionFunction( $value ); + $bound = $ref->getClosureThis(); + + return array( + '@closure' => $ref->getFileName() . ':' . $ref->getStartLine(), + 'this' => $bound ? get_class( $bound ) . '#' . spl_object_id( $bound ) : null, + 'use' => $this->normalize( $ref->getStaticVariables(), $depth + 1, $seen ), + ); + } + + if ( is_array( $value ) ) { + $out = array(); + foreach ( $value as $k => $v ) { + $out[ $k ] = $this->normalize( $v, $depth + 1, $seen ); + } + return $out; + } + + // The listener is in $wp_filter through its query filter; its own state is not the test's. + if ( $value instanceof self ) { + return '(' . __CLASS__ . ')'; + } + + if ( is_object( $value ) ) { + $id = spl_object_id( $value ); + if ( isset( $seen[ $id ] ) ) { + return '(cycle ' . get_class( $value ) . ')'; + } + $seen[ $id ] = true; + + $props = (array) $value; + if ( $value instanceof wpdb ) { + $props = array_diff_key( $this->props( $value ), array_flip( self::WPDB_NOISE ) ); + } + + $out = array( '@class' => get_class( $value ) ); + foreach ( $props as $k => $v ) { + $out[ str_replace( "\0", '', $k ) ] = $this->normalize( $v, $depth + 1, $seen ); + } + return $out; + } + + if ( is_float( $value ) && ! is_finite( $value ) ) { + return (string) $value; + } + + return $value; + } +} diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php new file mode 100644 index 0000000000000..17b89047ddba7 --- /dev/null +++ b/tests/phpunit/leaks/diff.php @@ -0,0 +1,174 @@ + $value ) { + if ( $value[0] !== $first_b[ $key ][0] ) { + $noise[ $key ] = true; + } + } + + $lines = compare( array_diff_key( $a, $noise ), array_diff_key( $b, $noise ) ); + exit( report( "{$argv[3]} class_start: {$argv[1]} -> {$argv[2]}, " . count( $noise ) . ' run noise keys ignored', $lines ) ? CHANGES_FOUND : 0 ); +} + +if ( 2 !== $argc ) { + fwrite( STDERR, USAGE ); + exit( 1 ); +} + +$snaps = load( $argv[1] ); +$count = 0; +$orphans = 0; +$open = array(); +$changes = false; +$ended = null; +foreach ( $snaps as $snap ) { + ++$count; + if ( 'class_leaks' === $snap['point'] ) { + $changes = report( "class {$snap['id']} leaves, unlike the install", compare( $snap['installed'], $snap['state'] ) ) || $changes; + continue; + } + + list( $kind, $edge ) = explode( '_', $snap['point'] ); + $slot = $kind . '|' . $snap['id']; + + // A reused start is the last test_end; with none, its end is an orphan. + if ( 'start' === $edge ) { + $state = empty( $snap['reuse'] ) ? $snap['state'] : $ended; + if ( null !== $state ) { + $open[ $slot ] = $state; + } + continue; + } + + if ( 'test' === $kind ) { + $ended = $snap['state']; + } + + if ( ! isset( $open[ $slot ] ) ) { + ++$orphans; + continue; + } + + $changes = report( "$kind {$snap['id']} leaves", compare( $open[ $slot ], $snap['state'] ) ) || $changes; + unset( $open[ $slot ] ); +} + +// A run that crashed, or is still running, leaves cut lines and starts with no end, the run_start included. +$unreadable = $snaps->getReturn(); +if ( ! $count || $unreadable || $orphans || $open ) { + fwrite( STDERR, "Incomplete run: $count snapshots, $unreadable unreadable lines, " . count( $open ) . " starts with no end, $orphans ends with no start.\n" ); + exit( 1 ); +} + +exit( $changes ? CHANGES_FOUND : 0 ); diff --git a/tests/phpunit/leaks/multisite.xml b/tests/phpunit/leaks/multisite.xml new file mode 100644 index 0000000000000..0507e10860c26 --- /dev/null +++ b/tests/phpunit/leaks/multisite.xml @@ -0,0 +1,60 @@ + + + + + + + + + + ../tests + ../tests/rest-api/rest-autosaves-controller.php + + + + ../tests/rest-api/rest-autosaves-controller.php + + + + probe + + + + + ajax + ms-files + ms-excluded + external-http + oembed-headers + html-api-web-platform-tests + + + + + + + + + + tests/phpunit/leaks/rules.php + + test + + + + + diff --git a/tests/phpunit/leaks/phpunit.xml b/tests/phpunit/leaks/phpunit.xml new file mode 100644 index 0000000000000..23e1a61d06fbb --- /dev/null +++ b/tests/phpunit/leaks/phpunit.xml @@ -0,0 +1,58 @@ + + + + + + ../tests + ../tests/rest-api/rest-autosaves-controller.php + + + + ../tests/rest-api/rest-autosaves-controller.php + + + + probe + + + + + ajax + ms-files + ms-required + external-http + html-api-web-platform-tests + + + + + + + + + + tests/phpunit/leaks/rules.php + + test + + + + + + + + diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php new file mode 100644 index 0000000000000..fc70ef66f4131 --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -0,0 +1,324 @@ +category->create(); + $cat_b = $factory->category->create(); + self::$post_id = $factory->post->create( array( 'post_category' => array( $cat_a, $cat_b ) ) ); + + $GLOBALS['leak_probe_big'] = range( 0, 2999 ); + $GLOBALS['leak_probe_int'] = 1; + $GLOBALS['leak_probe_gone'] = 'original'; + $GLOBALS['leak_probe_cb'] = function () { + return 'original'; + }; + $GLOBALS['leak_probe_deep'] = array( 'l1' => array( 'l2' => array( 'l3' => array( 'l4' => array( 'l5' => array( 'l6' => array( 'l7' => array( 'l8' => array( 'l9' => 'original' ) ) ) ) ) ) ) ) ); + } + + // Leaves the site test_leaks_other_site() commits: the class leaks it. + public static function wpTearDownAfterClass() { + self::remove_leftovers(); + } + + private static function remove_leftovers() { + global $wpdb; + + // Outside a test, CREATE and DROP TABLE are not rewritten to temporary ones. + $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $wpdb->prefix . self::PERMANENT_TABLE ) ); + + foreach ( self::file_dirs() as $dir ) { + // A leftover link makes symlink() create its target. + foreach ( array( self::FILE, self::LINK, self::LINK_TARGET ) as $name ) { + if ( is_link( "$dir/$name" ) || is_file( "$dir/$name" ) ) { + unlink( "$dir/$name" ); + } + } + + if ( is_dir( "$dir/" . self::DIR ) && ! is_link( "$dir/" . self::DIR ) ) { + rmdir( "$dir/" . self::DIR ); + } + } + } + + private static function file_dirs() { + return array( WP_CONTENT_DIR, sys_get_temp_dir() ); + } + + public function tear_down() { + parent::tear_down(); + + // After the framework's flush, as a test's own tear_down() can, so a persistent cache keeps it. + if ( 'test_leaks_cache_after_tear_down' === $this->getName() ) { + $this->assertTrue( wp_cache_set( 'after_tear_down', 'leaked', 'leak_probe' ) ); + // An option only the cache has. + $this->assertTrue( wp_cache_set( 'leak_probe_cached_only', 'leaked', 'options' ) ); + } + + if ( 'test_leaks_other_site' === $this->getName() && self::$site_id ) { + switch_to_blog( self::$site_id ); + $this->assertTrue( wp_cache_set( 'leak_probe_cached_only', 'leaked', 'options' ) ); + restore_current_blog(); + } + } + + public function test_term_relationships_fixture() { + $this->assertCount( 2, wp_get_post_categories( self::$post_id ) ); + } + + public function test_leaks_option_cache() { + update_option( 'blogname', 'leaked blogname' ); + update_option( 'leak_probe_not_autoloaded', 'leaked', false ); + + $this->assertSame( 'leaked blogname', get_option( 'blogname' ) ); + } + + public function test_leaks_cache_after_tear_down() { + $this->assertTrue( true ); + } + + public function test_leaks_composite_key_row() { + global $wpdb; + $inserted = $wpdb->insert( + $wpdb->term_relationships, + array( + 'object_id' => self::ORPHAN_OBJECT_ID, + 'term_taxonomy_id' => 1, + ) + ); + $this->assertSame( 1, $inserted ); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); + } + + public function test_leaks_notoptions_cache() { + get_option( 'leak_probe_missing' ); + + // Commit a row the notoptions cache still says is missing. + global $wpdb; + $inserted = $wpdb->insert( + $wpdb->options, + array( + 'option_name' => 'leak_probe_missing', + 'option_value' => 'now exists', + 'autoload' => 'off', + ) + ); + $this->assertSame( 1, $inserted ); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); + + $this->assertFalse( get_option( 'leak_probe_missing' ) ); + } + + public function test_leaks_network_option_cache() { + if ( ! is_multisite() ) { + $this->markTestSkipped( 'Network options only cache separately on multisite.' ); + } + + update_site_option( 'site_admins', array( 'leak-probe-admin' ) ); + + $this->assertSame( array( 'leak-probe-admin' ), get_site_option( 'site_admins' ) ); + } + + public function test_leaks_other_site() { + if ( ! is_multisite() ) { + $this->markTestSkipped( 'Only multisite has other sites.' ); + } + + global $wpdb; + + // Its tables are temporary: the test case rewrites CREATE TABLE. + self::$site_id = self::factory()->blog->create(); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); + + // Rolled back by tear_down(), not in the cache. + switch_to_blog( self::$site_id ); + update_option( 'blogname', 'leaked blogname' ); + restore_current_blog(); + + $this->assertSame( 'leaked blogname', get_blog_option( self::$site_id, 'blogname' ) ); + } + + public function test_leaks_cache_global_group() { + wp_cache_add_global_groups( 'leak_probe_group' ); + $this->assertTrue( true ); + } + + public function test_leaks_function_static_var() { + $this->assertSame( 1, leak_probe_counter() ); + $this->assertSame( 1, self::method_counter() ); + $this->assertSame( 1, Leak_Probe_Counter_Child::count() ); + } + + private static function method_counter() { + static $calls = 0; + return ++$calls; + } + + public function test_leaks_static_property() { + self::$leaked = 'leaked'; + $this->assertTrue( true ); + } + + public function test_leaks_constant() { + define( 'LEAK_PROBE_CONSTANT', 'leaked' ); + $this->assertTrue( defined( 'LEAK_PROBE_CONSTANT' ) ); + } + + public function test_leaks_auto_increment() { + $this->assertIsInt( self::factory()->post->create() ); + } + + public function test_leaks_deep_global_change() { + $GLOBALS['leak_probe_deep']['l1']['l2']['l3']['l4']['l5']['l6']['l7']['l8']['l9'] = 'leaked'; + $this->assertTrue( true ); + } + + public function test_leaks_big_array_key() { + $GLOBALS['leak_probe_big'][2500] = 'leaked'; + $this->assertTrue( true ); + } + + public function test_leaks_removed_global() { + unset( $GLOBALS['leak_probe_gone'] ); + $this->assertArrayNotHasKey( 'leak_probe_gone', $GLOBALS ); + } + + public function test_leaks_type_only_change() { + $GLOBALS['leak_probe_int'] = '1'; + $this->assertTrue( true ); + } + + // rules.php drops leak_probe_filtered_*, then keeps leak_probe_filtered_kept. + public function test_leaks_filtered_globals() { + $GLOBALS['leak_probe_filtered_dropped'] = 'leaked'; + $GLOBALS['leak_probe_filtered_kept'] = 'leaked'; + $this->assertTrue( true ); + } + + public function test_leaks_closure_swap() { + $GLOBALS['leak_probe_cb'] = function () { + return 'original'; + }; + $this->assertTrue( true ); + } + + public function test_leaks_wpdb_and_server() { + global $wpdb; + $wpdb->hide_errors(); + $_SERVER['LEAK_PROBE'] = 'leaked'; + $this->assertTrue( true ); + } + + public function test_leaks_process_state() { + ini_set( 'precision', '10' ); + error_reporting( E_ALL & ~E_USER_NOTICE ); + date_default_timezone_set( 'Europe/Rome' ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions -- The leak this test plants. + setlocale( LC_ALL, 'C.UTF-8' ); + putenv( 'LEAK_PROBE=leaked' ); + umask( 0077 ); + mb_internal_encoding( 'ISO-8859-1' ); + libxml_use_internal_errors( true ); + spl_autoload_register( function ( $class_name ) {} ); + set_exception_handler( function ( $e ) {} ); + set_error_handler( function () {} ); + $this->assertTrue( true ); + } + + public function test_leaks_files() { + foreach ( self::file_dirs() as $dir ) { + $this->assertNotFalse( file_put_contents( "$dir/" . self::FILE, 'leaked' ) ); + // Dangling: a link has no target metadata to read. + $this->assertTrue( symlink( "$dir/" . self::LINK_TARGET, "$dir/" . self::LINK ) ); + $this->assertTrue( mkdir( "$dir/" . self::DIR ) ); + } + } + + public function test_leaks_schema() { + global $wpdb; + $this->assertTrue( $wpdb->query( "ALTER TABLE {$wpdb->options} ADD INDEX leak_probe (autoload)" ) ); + } + + public function test_leaks_temp_table() { + global $wpdb; + $this->assertTrue( $wpdb->query( "CREATE TABLE {$wpdb->prefix}leak_probe_tmp (id int)" ) ); + } + + public function test_reconnect_drops_temp_table() { + global $wpdb; + $this->assertTrue( $wpdb->query( "CREATE TABLE {$wpdb->prefix}leak_probe_gone (id int)" ) ); + + // As each class's set_up_before_class() does: the new connection has no temporary tables. + $this->assertTrue( $wpdb->db_connect() ); + } + + public function test_leaks_permanent_table() { + global $wpdb; + + // As Tests_DB_dbDelta does. + remove_filter( 'query', array( $this, '_create_temporary_tables' ) ); + $this->assertTrue( $wpdb->query( $wpdb->prepare( 'CREATE TABLE %i (id int)', $wpdb->prefix . self::PERMANENT_TABLE ) ) ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_leaks_in_child() { + // In-process state, which dies with the child: must not be reported. + define( 'LEAK_PROBE_CHILD_CONSTANT', 'leaked' ); + + // Committed to a table no class cleanup resets, so the parent sees it. + global $wpdb; + $inserted = $wpdb->insert( + $wpdb->links, + array( + 'link_url' => 'https://leak-probe-child.example', + 'link_name' => 'leak_probe_child_row', + ) + ); + $this->assertSame( 1, $inserted ); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); + } +} diff --git a/tests/phpunit/leaks/probe/leakProbeClassFixture.php b/tests/phpunit/leaks/probe/leakProbeClassFixture.php new file mode 100644 index 0000000000000..dce461a454f7a --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbeClassFixture.php @@ -0,0 +1,34 @@ +user->create( array( 'user_login' => self::ADMIN ) ); + + if ( is_multisite() ) { + update_site_option( 'site_admins', array( self::ADMIN ) ); + } + } + + public static function tear_down_after_class() { + parent::tear_down_after_class(); + + // After the framework's flush, as a class's own tear_down_after_class() can, so a persistent cache keeps it. + wp_cache_set( 'after_class', 'leaked', 'leak_probe' ); + wp_cache_set( 'leak_probe_class_cached_only', 'leaked', 'options' ); + + // PHPUnit restores both after each test, not after class hooks. + chdir( sys_get_temp_dir() ); + ob_start(); + } + + public function test_fixture_user_exists() { + $this->assertInstanceOf( WP_User::class, get_user_by( 'login', self::ADMIN ) ); + } +} diff --git a/tests/phpunit/leaks/probe/leakProbeSkipped.php b/tests/phpunit/leaks/probe/leakProbeSkipped.php new file mode 100644 index 0000000000000..aa7a9fa2f8fac --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbeSkipped.php @@ -0,0 +1,14 @@ +query( 'COMMIT' ); + $this->assertTrue( true ); + } +} diff --git a/tests/phpunit/leaks/rules.php b/tests/phpunit/leaks/rules.php new file mode 100644 index 0000000000000..ca954613e9c11 --- /dev/null +++ b/tests/phpunit/leaks/rules.php @@ -0,0 +1,66 @@ + array( + 'test' => array( + 'db/*', + 'dbcount/*', + 'autoinc/*', + 'schema/*', + 'temptable/*', + 'cache/*', + 'mc/*', + 'stale/*', + 'global/*', + 'static/*', + 'fstatic/*', + 'const/*', + 'ini/*', + 'env/*', + 'proc/*', + 'file/*', + ), + /* + * What the next class inherits. Not row counts, they repeat the db rows, nor AUTO_INCREMENT + * counters, which nearly every class's fixtures bump, nor temporary tables: a child's own + * connection can't see them. + */ + 'class' => array( + 'db/*', + 'schema/*', + 'mc/*', + 'file/*', + 'stale/*', + ), + ), + 'files' => array( + array( + 'why' => 'Leak probe: a later pattern keeps a key an earlier one drops, see check-probes.php.', + 'paths' => array( + 'tests/phpunit/leaks/probe/leakProbe.php', + ), + 'areas' => array( + '!global/leak_probe_filtered_*', + 'global/leak_probe_filtered_kept', + ), + ), + array( + 'why' => 'Leak probe: a file no pattern keeps is not snapshotted, see check-probes.php.', + 'paths' => array( + 'tests/phpunit/leaks/probe/leakProbeSkipped.php', + ), + 'areas' => array( + '!*', + ), + ), + ), +);