From 55e5d7eed80ac6fb18c2278fd52a979b40fb3555 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Fri, 20 Nov 2026 18:06:21 +0100 Subject: [PATCH 01/18] Build/Test Tools: Add a test state leak finder Tests that change shared state and don't restore it make other tests pass or fail depending on run order. Add an opt-in PHPUnit listener that snapshots state before and after each test and class, and a script that reports what changed. It covers database rows, schema, AUTO_INCREMENT counters and temporary tables, the object cache including memcached keys, cached options that disagree with the database, globals, static properties and variables, constants, ini and env settings, process state, and files under wp-content and the temp dir. Process-isolated children are snapshotted too. A class-scope mode sweeps the whole suite for state that outlives the process. Runs on PHPUnit 5.7 to 9, which have test listeners. On PHPUnit 10+ the leak bootstrap exits with a message. A leak-probe test suite plants one leak per area to check the listener sees each. --- tests/phpunit/README.md | 35 + tests/phpunit/leaks/bootstrap.php | 35 + .../leaks/class-wp-phpunit-leak-listener.php | 950 ++++++++++++++++++ tests/phpunit/leaks/diff.php | 119 +++ tests/phpunit/leaks/multisite.xml | 50 + tests/phpunit/leaks/phpunit.xml | 48 + tests/phpunit/leaks/probe/leakProbe.php | 181 ++++ .../leaks/probe/leakProbeClassFixture.php | 22 + 8 files changed, 1440 insertions(+) create mode 100644 tests/phpunit/leaks/bootstrap.php create mode 100644 tests/phpunit/leaks/class-wp-phpunit-leak-listener.php create mode 100644 tests/phpunit/leaks/diff.php create mode 100644 tests/phpunit/leaks/multisite.xml create mode 100644 tests/phpunit/leaks/phpunit.xml create mode 100644 tests/phpunit/leaks/probe/leakProbe.php create mode 100644 tests/phpunit/leaks/probe/leakProbeClassFixture.php diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 6308e75c3d3da..f321e32b4c7f9 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -21,3 +21,38 @@ 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 child process is snapshotted too, if the test has `@preserveGlobalState disabled` as core's do. 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. It exits with 1 if the run did not finish or ran no test. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. + +To sweep the whole suite, snapshot only the state that outlives the PHP process (database, files, memcached, stale cached options) at class bounds. `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: + +``` +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 php php tests/phpunit/leaks/diff.php tests/phpunit/build/leaks/alone.jsonl tests/phpunit/build/leaks/sequence.jsonl Tests_Class_Name +``` + +Environment variables: + +* `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. +* `WP_TESTS_LEAKS_SCOPE`: `class` for the whole-suite sweep. + +The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each: `--testsuite leak-probe`. It runs only when named, except on PHPUnit 5, which ignores `defaultTestSuite`: run `--testsuite default`, then `--testsuite restapi-autosave` there. 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..8b6e1d8d722a2 --- /dev/null +++ b/tests/phpunit/leaks/bootstrap.php @@ -0,0 +1,35 @@ +watch_child(); +} 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..f63baddad584d --- /dev/null +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -0,0 +1,950 @@ + [hash, preview], appended as one JSON line + * to WP_TESTS_LEAKS_OUT. diff.php compares snapshots. + * + * WP_TESTS_LEAKS_SCOPE=class sweeps a whole suite cheaply: persistent areas only, at class + * bounds only, and writes one "class_leaks" line per class that changes them and leaves + * them unlike the install. That is what the next class, and every isolated child, inherits. + * A leak is reported once, by the first class leaving it; later ones start with it. + * + * 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 + * 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; + + const SKIP_GLOBALS = array( 'GLOBALS', 'wp_object_cache', 'timestart', 'argv', 'argc', '__composer_autoload_files', '__PHPUNIT_BOOTSTRAP' ); + + // $wpdb properties that change on every query, the listener's own included. + 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' ); + + // Test tooling, PHPUnit 5's PEAR-style names (PHPUnit_, PHP_Timer, ...) included. + const SKIP_PREFIXES = array( 'PHPUnit', 'PHP_', 'Text_Template', 'File_Iterator', 'Composer\\', 'SebastianBergmann\\', 'Doctrine\\', 'Yoast\\', __CLASS__ ); + + const MAX_DEPTH = 12; + + const PREVIEW_LENGTH = 200; + + const MISMATCH_PREVIEW_LENGTH = 90; + + const MEMCACHED_BATCH = 500; + + const MEMCACHED_TIMEOUT = 2; + + const SCOPE_CLASS = 'class'; + + const JSON_FLAGS = JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + + // SHOW CREATE TABLE has the live counter; information_schema caches it. + const AUTO_INCREMENT = '/ AUTO_INCREMENT=(\d+)/'; + + // The result file PHPUnit 9 hands an isolated child, see TestCase::run(). + const PHPUNIT_TEMP_PREFIX = 'phpunit_'; + + // An isolated child's test_end runs at shutdown: output buffers are closed, the shutdown action ran. + const CHILD_SHUTDOWN_NOISE = array( 'proc|ob_level', 'global|wp_actions|shutdown' ); + + // The listener's own environment: its settings, and the test name handed to an isolated child. + const ENV_PREFIX = 'WP_TESTS_LEAKS_'; + + const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; + + /* + * Areas that outlive the PHP process, so isolated children and later runs inherit them. + * Not row counts, they repeat the db rows, nor temporary tables: a child's own connection + * can't see them. + */ + const PERSISTENT = '/^(db|schema|mc|file|stale)\|/'; + + private $out; + + private $scope; + + private $child = false; + + // WP_TESTS_LEAKS_SCOPE=class: the state at the first class start and at the running class start. + private $installed = null; + + private $class_start = null; + + 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; + + // DB rows read by the stale checks, reset per snapshot. + private $rows = array(); + + public function __construct() { + // Set and truncated by bootstrap.php. + $this->out = getenv( 'WP_TESTS_LEAKS_OUT' ); + $this->scope = getenv( 'WP_TESTS_LEAKS_SCOPE' ); + + if ( $this->scope && self::SCOPE_CLASS !== $this->scope ) { + $this->fail( 'WP_TESTS_LEAKS_SCOPE must be "' . self::SCOPE_CLASS . '" or unset.' ); + } + + // 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 ); + } + + /** + * Snapshots this process-isolated child process, from now to its shutdown. + */ + public function watch_child() { + if ( self::SCOPE_CLASS === $this->scope ) { + return; + } + + $this->child = true; + $id = getenv( self::ENV_TEST ); + + $this->write( 'test_start', $id ); + register_shutdown_function( + function () use ( $id ) { + global $wpdb; + + // A child that died mid-test left its transaction open: the snapshot's COMMIT would keep it. + $wpdb->query( 'ROLLBACK' ); + $this->write( 'test_end', $id ); + } + ); + } + + 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. + if ( 0 === $this->open_suites++ ) { + $this->mark( 'run_start' ); + } + + if ( ! class_exists( $suite->getName(), false ) ) { + return; + } + + if ( self::SCOPE_CLASS !== $this->scope ) { + $this->write( 'class_start', $suite->getName() ); + return; + } + + $this->class_start = $this->state(); + $this->installed = $this->installed ?? $this->class_start; + } + + public function end_test_suite( $suite ) { + if ( class_exists( $suite->getName(), false ) ) { + $this->end_class( $suite->getName() ); + } + + if ( 0 === --$this->open_suites ) { + $this->mark( 'run_end' ); + } + } + + private function end_class( $class_name ) { + if ( self::SCOPE_CLASS !== $this->scope ) { + $this->write( 'class_end', $class_name ); + return; + } + + $this->write_class_leaks( $class_name ); + } + + public function start_test( $test ) { + if ( self::SCOPE_CLASS === $this->scope ) { + return; + } + + $name = $this->name( $test ); + $this->write( 'test_start', $name ); + + // An isolated child inherits the environment. + putenv( self::ENV_TEST . '=' . $name ); + } + + public function end_test( $test, $time ) { + if ( self::SCOPE_CLASS !== $this->scope ) { + $this->write( 'test_end', $this->name( $test ) ); + } + } + + private function name( $test ) { + return $test instanceof PHPUnit\Framework\TestCase ? get_class( $test ) . '::' . $test->getName() : get_class( $test ); + } + + private function write( $point, $id, ?array $state = null ) { + $this->append( + array( + 'pid' => getmypid(), + 'child' => $this->child, + 'point' => $point, + 'id' => $id, + 'state' => $state ?? $this->state(), + ) + ); + } + + private function mark( $point ) { + $this->write( $point, '', array() ); + } + + /* + * 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 ) { + $start = $this->class_start; + $end = $this->state(); + + $this->class_start = null; + + $installed = array(); + $left = array(); + foreach ( array_unique( array_merge( array_keys( $start ), array_keys( $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( + array( + 'pid' => getmypid(), + 'point' => 'class_leaks', + 'id' => $class_name, + 'installed' => $installed, + 'state' => $left, + ) + ); + } + + // The snapshot for the scope. + private function state() { + 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(); + + $state = self::SCOPE_CLASS === $this->scope ? $this->persistent() : $this->everything(); + + // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. + $wpdb->query( 'COMMIT' ); + + return $state; + } + + private function persistent() { + return array_filter( + array_merge( $this->db(), $this->cache(), $this->memcached(), $this->files() ), + static function ( $key ) { + return preg_match( self::PERSISTENT, $key ); + }, + ARRAY_FILTER_USE_KEY + ); + } + + private function everything() { + $state = array_merge( + $this->db(), + $this->cache(), + $this->memcached(), + $this->globals(), + $this->statics(), + $this->static_vars(), + $this->constants(), + $this->process(), + $this->files() + ); + + return $this->child ? array_diff_key( $state, array_flip( self::CHILD_SHUTDOWN_NOISE ) ) : $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 db() { + global $wpdb; + + $state = array(); + + /* + * Tests leave autocommit off, so an earlier snapshot's SELECT 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' ); + + // Read before cache() in persistent() and everything(). + $this->tables = array_flip( $tables ); + + foreach ( $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; + + $table = $wpdb->get_blog_prefix( $blog ) . 'options'; + if ( ! isset( $this->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 ( 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 >= 80100 || $ref->isSubclassOf( 'PHPUnit\Framework\TestCase' ) ) ) { + continue; + } + + $functions[ "$class_name::{$method->getName()}()" ] = $inherited ? new ReflectionMethod( $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 ); + 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 ); + } + } + + 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 < 80100 ) { + $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 : json_encode( $norm, self::JSON_FLAGS ); + + return $this->text( (string) $text ); + } + + /* + * 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..1179b7353ef0d --- /dev/null +++ b/tests/phpunit/leaks/diff.php @@ -0,0 +1,119 @@ + {$argv[2]}", compare( class_start( load( $argv[1] ), $argv[3] ), class_start( load( $argv[2] ), $argv[3] ) ) ); + exit( 0 ); +} + +if ( 2 !== $argc ) { + fwrite( STDERR, USAGE ); + exit( 1 ); +} + +$snaps = load( $argv[1] ); +$count = 0; +$orphans = 0; +$open = array(); +foreach ( $snaps as $snap ) { + ++$count; + if ( 'class_leaks' === $snap['point'] ) { + report( "class {$snap['id']} leaves, unlike the install", compare( $snap['installed'], $snap['state'] ) ); + continue; + } + + list( $kind, $edge ) = explode( '_', $snap['point'] ); + $slot = $snap['pid'] . '|' . $kind . '|' . $snap['id']; + + if ( 'start' === $edge ) { + $open[ $slot ] = $snap['state']; + continue; + } + + if ( ! isset( $open[ $slot ] ) ) { + ++$orphans; + continue; + } + + $where = empty( $snap['child'] ) ? '' : ' (isolated child)'; + report( "$kind {$snap['id']}$where leaves", compare( $open[ $slot ], $snap['state'] ) ); + 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 ); +} diff --git a/tests/phpunit/leaks/multisite.xml b/tests/phpunit/leaks/multisite.xml new file mode 100644 index 0000000000000..85a7bc1a3ca84 --- /dev/null +++ b/tests/phpunit/leaks/multisite.xml @@ -0,0 +1,50 @@ + + + + + + + + + + ../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 + + + + + + + diff --git a/tests/phpunit/leaks/phpunit.xml b/tests/phpunit/leaks/phpunit.xml new file mode 100644 index 0000000000000..e63b0ec6b4e5b --- /dev/null +++ b/tests/phpunit/leaks/phpunit.xml @@ -0,0 +1,48 @@ + + + + + + ../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 + + + + + + + + + + diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php new file mode 100644 index 0000000000000..2f318da569e2b --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -0,0 +1,181 @@ +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_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' ) ) ) ) ) ) ) ) ); + } + + public static function wpTearDownAfterClass() { + foreach ( array( WP_CONTENT_DIR . '/', sys_get_temp_dir() . '/' ) as $dir ) { + if ( file_exists( $dir . self::FILE ) ) { + unlink( $dir . self::FILE ); + } + } + } + + 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_notoptions_cache() { + get_option( 'leak_probe_missing' ); + + // Commit a row the notoptions cache still says is missing. + global $wpdb; + $wpdb->insert( + $wpdb->options, + array( + 'option_name' => 'leak_probe_missing', + 'option_value' => 'now exists', + 'autoload' => 'off', + ) + ); + $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_function_static_var() { + $this->assertSame( 1, leak_probe_counter() ); + $this->assertSame( 1, self::method_counter() ); + } + + 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_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() { + file_put_contents( WP_CONTENT_DIR . '/' . self::FILE, 'leaked' ); + file_put_contents( sys_get_temp_dir() . '/' . self::FILE, 'leaked' ); + $this->assertTrue( true ); + } + + public function test_leaks_schema() { + global $wpdb; + $wpdb->query( "ALTER TABLE {$wpdb->options} ADD INDEX leak_probe (autoload)" ); + $this->assertTrue( true ); + } + + public function test_leaks_temp_table() { + global $wpdb; + $wpdb->query( "CREATE TABLE {$wpdb->prefix}leak_probe_tmp (id int)" ); + $this->assertTrue( true ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_leaks_in_child() { + define( 'LEAK_PROBE_CHILD_CONSTANT', 'leaked' ); + leak_probe_counter(); + + // Committed to a table no class cleanup resets, so the parent sees it too. + global $wpdb; + $wpdb->insert( + $wpdb->links, + array( + 'link_url' => 'https://leak-probe-child.example', + 'link_name' => 'leak_probe_child_row', + ) + ); + $wpdb->query( 'COMMIT' ); + $this->assertTrue( true ); + } +} diff --git a/tests/phpunit/leaks/probe/leakProbeClassFixture.php b/tests/phpunit/leaks/probe/leakProbeClassFixture.php new file mode 100644 index 0000000000000..6d9963a61bc10 --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbeClassFixture.php @@ -0,0 +1,22 @@ +user->create( array( 'user_login' => self::ADMIN ) ); + + if ( is_multisite() ) { + update_site_option( 'site_admins', array( self::ADMIN ) ); + } + } + + public function test_fixture_user_exists() { + $this->assertInstanceOf( WP_User::class, get_user_by( 'login', self::ADMIN ) ); + } +} From 67e6377042b88bcfc86eebe4c3fe3185ae30baab Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Mon, 23 Nov 2026 17:40:23 +0100 Subject: [PATCH 02/18] Build/Test Tools: Snapshot object cache settings Snapshot $wp_object_cache minus its entries and hit counters, so a test adding global or non-persistent groups shows as a leak; a probe covers it. Skip the listener's own output file in the file snapshot, and add the in-sequence run to the README's alone/sequence comparison. --- tests/phpunit/README.md | 1 + .../leaks/class-wp-phpunit-leak-listener.php | 20 ++++++++++++++++--- tests/phpunit/leaks/probe/leakProbe.php | 5 +++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index f321e32b4c7f9..8cb3456890aac 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -47,6 +47,7 @@ To find out why a class only fails after others, run it alone and in sequence, e ``` 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 ``` diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index f63baddad584d..4792b5164903a 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -26,7 +26,8 @@ * 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 + * 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 @@ -37,11 +38,14 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { use Yoast\PHPUnitPolyfills\TestListeners\TestListenerDefaultImplementation; - const SKIP_GLOBALS = array( 'GLOBALS', 'wp_object_cache', 'timestart', 'argv', 'argc', '__composer_autoload_files', '__PHPUNIT_BOOTSTRAP' ); + 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. 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' ); + // $wp_object_cache entries, snapshotted by cache(), and hit counters, which every read changes. + const CACHE_NOISE = array( 'cache', 'cache_hits', 'cache_misses' ); + // Test tooling, PHPUnit 5's PEAR-style names (PHPUnit_, PHP_Timer, ...) included. const SKIP_PREFIXES = array( 'PHPUnit', 'PHP_', 'Text_Template', 'File_Iterator', 'Composer\\', 'SebastianBergmann\\', 'Doctrine\\', 'Yoast\\', __CLASS__ ); @@ -678,6 +682,10 @@ private function globals() { $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 ) { @@ -757,7 +765,7 @@ private function static_vars() { continue; } - $functions[ "$class_name::{$method->getName()}()" ] = $inherited ? new ReflectionMethod( $class_name, $method->getName() ) : $method; + $functions[ "$class_name::{$method->getName()}()" ] = $method; } } @@ -838,6 +846,12 @@ private function files() { } } + // 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; } diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index 2f318da569e2b..3b45c59f6c0c4 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -77,6 +77,11 @@ public function test_leaks_network_option_cache() { $this->assertSame( array( 'leak-probe-admin' ), get_site_option( 'site_admins' ) ); } + 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() ); From c789b67fc48428ae237f786bcd440f4c60e7c3a9 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Tue, 24 Nov 2026 09:40:40 +0100 Subject: [PATCH 03/18] Build/Test Tools: Check leak probes and cut noise The probe suite passed whether or not the listener saw the planted leaks. check-probes.php now fails when a probe's expected key is missing from the diff.php report, or when an isolated child reports in-process state. Probe queries assert their results, and a new probe covers type-only changes. Isolated children snapshot only state that outlives them, so their reports no longer list globals that die with the process. The alone-vs-sequence diff drops keys that already differ before any class ran, so identical runs report nothing. Also hash serialized values so 1 and "1" differ, ignore $wpdb->table_charset, keep bootstrap's variable out of the globals, make listener constants private, and fix the PHPUnit 5 README steps. --- tests/phpunit/README.md | 13 +- tests/phpunit/leaks/bootstrap.php | 3 + tests/phpunit/leaks/check-probes.php | 142 ++++++++++++++++++ .../leaks/class-wp-phpunit-leak-listener.php | 77 +++++----- tests/phpunit/leaks/diff.php | 34 ++++- tests/phpunit/leaks/probe/leakProbe.php | 25 +-- 6 files changed, 238 insertions(+), 56 deletions(-) create mode 100644 tests/phpunit/leaks/check-probes.php diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 8cb3456890aac..cfb56c8c66233 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -26,7 +26,7 @@ Look for `PHPUnit Tests (full matrix)` in GitHub Actions and the PHPUnit checks 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 child process is snapshotted too, if the test has `@preserveGlobalState disabled` as core's do. It needs PHPUnit 9 or earlier: PHPUnit 10 removed test listeners. +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 child process is snapshotted too, if the test has `@preserveGlobalState disabled` as core's do: only the state that outlives it (database, files, memcached, stale memcached options). 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: @@ -43,7 +43,7 @@ To sweep the whole suite, snapshot only the state that outlives the PHP process 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: +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 class ran, e.g. timestamps, are run noise and left out: ``` 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 @@ -56,4 +56,11 @@ Environment variables: * `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. * `WP_TESTS_LEAKS_SCOPE`: `class` for the whole-suite sweep. -The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each: `--testsuite leak-probe`. It runs only when named, except on PHPUnit 5, which ignores `defaultTestSuite`: run `--testsuite default`, then `--testsuite restapi-autosave` there. With a persistent object cache, `tear_down()` flushes it, so the cached option probes leave nothing. +The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `check-probes.php` exits with 1 if the report misses one, or if an isolated child reports state that dies with it; pass it the same `WP_TESTS_LEAKS_SCOPE`, if any, as the run: + +``` +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 index 8b6e1d8d722a2..2b524fd2a390d 100644 --- a/tests/phpunit/leaks/bootstrap.php +++ b/tests/phpunit/leaks/bootstrap.php @@ -24,6 +24,9 @@ fwrite( STDERR, "Cannot write $leaks_out.\n" ); exit( 1 ); } + + // Else the listener snapshots it as a global. + unset( $leaks_out ); } require dirname( __DIR__ ) . '/includes/bootstrap.php'; diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php new file mode 100644 index 0000000000000..ccd35980cee00 --- /dev/null +++ b/tests/phpunit/leaks/check-probes.php @@ -0,0 +1,142 @@ + 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_notoptions_cache' => array( '/^db\|\w+options\|leak_probe_missing$/', '/^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_cache_global_group' => array( '/^global\|wp_object_cache\|global_groups$/' ), + 'test Tests_Leak_Probe::test_leaks_function_static_var' => array( '/^fstatic\|leak_probe_counter\(\)\|\$calls$/', '/^fstatic\|Tests_Leak_Probe::method_counter\(\)\|\$calls$/' ), + '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_type_only_change' => array( '/^global\|leak_probe_int$/' ), + '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$/' ), + '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_in_child (isolated child)' => array( '/^db\|\w+links\|\d+$/' ), +); + +const CLASS_SCOPE = array( + 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/' ), +); + +// 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$/', +); + +const MULTISITE_ONLY = array( '/^stale\|runtime\|1\|site-options\|1:site_admins$/' ); + +// An isolated child's report holds only these, see OUTLIVES_PROCESS in the listener. +const CHILD_AREAS = '/^(db|schema|mc|file|stale\|memcached)\|/'; + +const CHILD_SUFFIX = ' (isolated child)'; + +// Report header and changed key lines, see report() in diff.php. +const HEADER = '/^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$/'; + +const KEY_LINE = '/^ (\S.*)$/'; + +// The keys of the run's first non-empty snapshot. +function first_keys( $file ) { + $handle = fopen( $file, 'r' ); + if ( false === $handle ) { + fwrite( STDERR, "Cannot read $file\n" ); + exit( 1 ); + } + + $line = fgets( $handle ); + while ( false !== $line ) { + $snap = json_decode( $line, true ); + if ( ! empty( $snap['state'] ) ) { + fclose( $handle ); + return array_keys( $snap['state'] ); + } + + $line = fgets( $handle ); + } + + fclose( $handle ); + fwrite( STDERR, "No snapshot in $file\n" ); + exit( 1 ); +} + +if ( 2 !== $argc ) { + fwrite( STDERR, "Usage: php check-probes.php run.jsonl\n" ); + exit( 1 ); +} + +exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . ' ' . escapeshellarg( $argv[1] ), $output, $code ); +if ( 0 !== $code ) { + fwrite( STDERR, "diff.php failed with $code.\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]; + } +} + +$multisite = (bool) preg_grep( '/^schema\|\w+blogs$/', first_keys( $argv[1] ) ); +$runtime_cache = 'true' !== getenv( 'LOCAL_PHP_MEMCACHED' ); +$expected = 'class' === getenv( 'WP_TESTS_LEAKS_SCOPE' ) ? CLASS_SCOPE : PER_TEST; + +$missed = array(); +$checked = 0; +$skipped = 0; +foreach ( $expected as $title => $patterns ) { + foreach ( $patterns as $pattern ) { + if ( ( ! $multisite && in_array( $pattern, MULTISITE_ONLY, true ) ) || ( ! $runtime_cache && in_array( $pattern, RUNTIME_CACHE_ONLY, true ) ) ) { + ++$skipped; + continue; + } + + ++$checked; + if ( ! preg_grep( $pattern, $reported[ $title ] ?? array() ) ) { + $missed[] = "$title: $pattern"; + } + } +} + +foreach ( $reported as $title => $keys ) { + if ( ! str_ends_with( $title, CHILD_SUFFIX ) ) { + continue; + } + + foreach ( preg_grep( CHILD_AREAS, $keys, PREG_GREP_INVERT ) as $key ) { + $missed[] = "$title: unexpected $key"; + } +} + +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 index 4792b5164903a..ca013a503480e 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -6,7 +6,7 @@ * class_start (before setUpBeforeClass), test_start (before setUp), * test_end (after tearDown), class_end (after tearDownAfterClass). * In a process-isolated test's child process, test_start and test_end wrap the whole - * child, class hooks included. + * child, class hooks included, and snapshot only the areas that outlive it. * * Each snapshot is a flat map "area|key" => [hash, preview], appended as one JSON line * to WP_TESTS_LEAKS_OUT. diff.php compares snapshots. @@ -38,51 +38,51 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { use Yoast\PHPUnitPolyfills\TestListeners\TestListenerDefaultImplementation; - const SKIP_GLOBALS = array( 'GLOBALS', 'timestart', 'argv', 'argc', '__composer_autoload_files', '__PHPUNIT_BOOTSTRAP' ); + 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. - 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' ); + 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. - const CACHE_NOISE = array( 'cache', 'cache_hits', 'cache_misses' ); + private const CACHE_NOISE = array( 'cache', 'cache_hits', 'cache_misses' ); // Test tooling, PHPUnit 5's PEAR-style names (PHPUnit_, PHP_Timer, ...) included. - const SKIP_PREFIXES = array( 'PHPUnit', 'PHP_', 'Text_Template', 'File_Iterator', 'Composer\\', 'SebastianBergmann\\', 'Doctrine\\', 'Yoast\\', __CLASS__ ); + private const SKIP_PREFIXES = array( 'PHPUnit', 'PHP_', 'Text_Template', 'File_Iterator', 'Composer\\', 'SebastianBergmann\\', 'Doctrine\\', 'Yoast\\', __CLASS__ ); - const MAX_DEPTH = 12; + private const MAX_DEPTH = 12; - const PREVIEW_LENGTH = 200; + private const PREVIEW_LENGTH = 200; - const MISMATCH_PREVIEW_LENGTH = 90; + private const MISMATCH_PREVIEW_LENGTH = 90; - const MEMCACHED_BATCH = 500; + private const MEMCACHED_BATCH = 500; - const MEMCACHED_TIMEOUT = 2; + private const MEMCACHED_TIMEOUT = 2; - const SCOPE_CLASS = 'class'; + private const SCOPE_CLASS = 'class'; - const JSON_FLAGS = JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + private const JSON_FLAGS = JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; // SHOW CREATE TABLE has the live counter; information_schema caches it. - const AUTO_INCREMENT = '/ AUTO_INCREMENT=(\d+)/'; + private const AUTO_INCREMENT = '/ AUTO_INCREMENT=(\d+)/'; // The result file PHPUnit 9 hands an isolated child, see TestCase::run(). - const PHPUNIT_TEMP_PREFIX = 'phpunit_'; - - // An isolated child's test_end runs at shutdown: output buffers are closed, the shutdown action ran. - const CHILD_SHUTDOWN_NOISE = array( 'proc|ob_level', 'global|wp_actions|shutdown' ); + private const PHPUNIT_TEMP_PREFIX = 'phpunit_'; // The listener's own environment: its settings, and the test name handed to an isolated child. - const ENV_PREFIX = 'WP_TESTS_LEAKS_'; + private const ENV_PREFIX = 'WP_TESTS_LEAKS_'; - const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; + private const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; /* - * Areas that outlive the PHP process, so isolated children and later runs inherit them. - * Not row counts, they repeat the db rows, nor temporary tables: a child's own connection - * can't see them. + * Areas 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. */ - const PERSISTENT = '/^(db|schema|mc|file|stale)\|/'; + private const PERSISTENT = '/^(db|schema|mc|file|stale)\|/'; + + // Those an isolated child leaves its parent and later runs: not the in-process caches' stale|runtime and stale|local. + private const OUTLIVES_PROCESS = '/^(db|schema|mc|file|stale\|memcached)\|/'; private $out; @@ -296,7 +296,13 @@ private function state() { $this->rows = array(); - $state = self::SCOPE_CLASS === $this->scope ? $this->persistent() : $this->everything(); + if ( $this->child ) { + $state = $this->persistent( self::OUTLIVES_PROCESS ); + } elseif ( self::SCOPE_CLASS === $this->scope ) { + $state = $this->persistent( self::PERSISTENT ); + } else { + $state = $this->everything(); + } // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. $wpdb->query( 'COMMIT' ); @@ -304,18 +310,18 @@ private function state() { return $state; } - private function persistent() { + private function persistent( $areas ) { return array_filter( array_merge( $this->db(), $this->cache(), $this->memcached(), $this->files() ), - static function ( $key ) { - return preg_match( self::PERSISTENT, $key ); + static function ( $key ) use ( $areas ) { + return preg_match( $areas, $key ); }, ARRAY_FILTER_USE_KEY ); } private function everything() { - $state = array_merge( + return array_merge( $this->db(), $this->cache(), $this->memcached(), @@ -326,8 +332,6 @@ private function everything() { $this->process(), $this->files() ); - - return $this->child ? array_diff_key( $state, array_flip( self::CHILD_SHUTDOWN_NOISE ) ) : $state; } private function append( array $line ) { @@ -348,10 +352,10 @@ private function db() { $state = array(); /* - * Tests leave autocommit off, so an earlier snapshot's SELECT 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. + * 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' ); @@ -894,9 +898,10 @@ private function text( $text ) { private function entry( $value ) { $seen = array(); $norm = $this->normalize( $value, 0, $seen ); - $text = is_string( $norm ) ? $norm : json_encode( $norm, self::JSON_FLAGS ); + $text = is_string( $norm ) ? $norm : (string) json_encode( $norm, self::JSON_FLAGS ); - return $this->text( (string) $text ); + // 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 ) ); } /* diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 1179b7353ef0d..79291697b2dd1 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -6,7 +6,9 @@ * (test_start vs test_end, class_start vs class_end). * WP_TESTS_LEAKS_SCOPE=class runs: install vs class end. * php diff.php alone.jsonl seq.jsonl ID State the class ID inherits: its class_start - * in run A vs run B. + * in run A vs run B, minus run noise (timestamps, + * env, install rows): keys whose first class_start, + * before any class ran, already differs. */ const USAGE = "Usage: php diff.php run.jsonl\n php diff.php a.jsonl b.jsonl ClassName\n"; @@ -61,19 +63,37 @@ function report( $title, array $lines ) { echo "== $title (" . count( $lines ) . " changed)\n" . implode( "\n", $lines ) . "\n\n"; } -function class_start( $snaps, $id ) { - foreach ( $snaps as $snap ) { - if ( 'class_start' === $snap['point'] && $snap['id'] === $id ) { - return $snap['state']; +// The first class_start and the class ID's. +function class_starts( $file, $id ) { + $first = null; + foreach ( load( $file ) as $snap ) { + if ( 'class_start' !== $snap['point'] ) { + continue; + } + + $first = $first ?? $snap['state']; + if ( $snap['id'] === $id ) { + return array( $first, $snap['state'] ); } } - fwrite( STDERR, "No class_start for $id\n" ); + fwrite( STDERR, "No class_start for $id in $file\n" ); exit( 1 ); } if ( 4 === $argc ) { - report( "{$argv[3]} class_start: {$argv[1]} -> {$argv[2]}", compare( class_start( load( $argv[1] ), $argv[3] ), class_start( load( $argv[2] ), $argv[3] ) ) ); + list( $first_a, $a ) = class_starts( $argv[1], $argv[3] ); + list( $first_b, $b ) = class_starts( $argv[2], $argv[3] ); + + $noise = array_diff_key( $first_a, $first_b ) + array_diff_key( $first_b, $first_a ); + foreach ( array_intersect_key( $first_a, $first_b ) as $key => $value ) { + if ( $value[0] !== $first_b[ $key ][0] ) { + $noise[ $key ] = true; + } + } + + $lines = compare( array_diff_key( $a, $noise ), array_diff_key( $b, $noise ) ); + report( "{$argv[3]} class_start: {$argv[1]} -> {$argv[2]}, " . count( $noise ) . ' run noise keys ignored', $lines ); exit( 0 ); } diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index 3b45c59f6c0c4..0a1a65c9e66f0 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -24,6 +24,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { 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_cb'] = function () { return 'original'; }; @@ -54,7 +55,7 @@ public function test_leaks_notoptions_cache() { // Commit a row the notoptions cache still says is missing. global $wpdb; - $wpdb->insert( + $inserted = $wpdb->insert( $wpdb->options, array( 'option_name' => 'leak_probe_missing', @@ -62,7 +63,8 @@ public function test_leaks_notoptions_cache() { 'autoload' => 'off', ) ); - $wpdb->query( 'COMMIT' ); + $this->assertSame( 1, $inserted ); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); $this->assertFalse( get_option( 'leak_probe_missing' ) ); } @@ -116,6 +118,11 @@ public function test_leaks_big_array_key() { $this->assertTrue( true ); } + public function test_leaks_type_only_change() { + $GLOBALS['leak_probe_int'] = '1'; + $this->assertTrue( true ); + } + public function test_leaks_closure_swap() { $GLOBALS['leak_probe_cb'] = function () { return 'original'; @@ -153,14 +160,12 @@ public function test_leaks_files() { public function test_leaks_schema() { global $wpdb; - $wpdb->query( "ALTER TABLE {$wpdb->options} ADD INDEX leak_probe (autoload)" ); - $this->assertTrue( true ); + $this->assertTrue( $wpdb->query( "ALTER TABLE {$wpdb->options} ADD INDEX leak_probe (autoload)" ) ); } public function test_leaks_temp_table() { global $wpdb; - $wpdb->query( "CREATE TABLE {$wpdb->prefix}leak_probe_tmp (id int)" ); - $this->assertTrue( true ); + $this->assertTrue( $wpdb->query( "CREATE TABLE {$wpdb->prefix}leak_probe_tmp (id int)" ) ); } /** @@ -168,19 +173,19 @@ public function test_leaks_temp_table() { * @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' ); - leak_probe_counter(); // Committed to a table no class cleanup resets, so the parent sees it too. global $wpdb; - $wpdb->insert( + $inserted = $wpdb->insert( $wpdb->links, array( 'link_url' => 'https://leak-probe-child.example', 'link_name' => 'leak_probe_child_row', ) ); - $wpdb->query( 'COMMIT' ); - $this->assertTrue( true ); + $this->assertSame( 1, $inserted ); + $this->assertNotFalse( $wpdb->query( 'COMMIT' ) ); } } From bc0f6f0da1986e90d23b032593b9a6f7072727cf Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Tue, 24 Nov 2026 10:02:56 +0100 Subject: [PATCH 04/18] Build/Test Tools: Probe each leak area, skip cache drops Add leak probes for cache writes after the framework's flushes (runtime, drop-in and memcached keys, stale options), a composite-key row, a dangling symlink, a directory, and class-level cwd and output buffer changes, which PHPUnit restores per test. Clean up an interrupted run's probe files before the class runs. diff.php skips cache entries a test drops: a miss reads the source again. The framework's flushes made every first class report the install's cache entries. check-probes.php fails on cache keys under the class that plants none, and skips the expectations of the cache not in use. --- tests/phpunit/README.md | 4 +- tests/phpunit/leaks/check-probes.php | 41 ++++++++++-- tests/phpunit/leaks/diff.php | 7 ++ tests/phpunit/leaks/probe/leakProbe.php | 66 +++++++++++++++++-- .../leaks/probe/leakProbeClassFixture.php | 12 ++++ 5 files changed, 118 insertions(+), 12 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index cfb56c8c66233..f0098497caa90 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -35,7 +35,7 @@ node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c te 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. It exits with 1 if the run did not finish or ran no test. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. +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 1 if the run did not finish or ran no test. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. To sweep the whole suite, snapshot only the state that outlives the PHP process (database, files, memcached, stale cached options) at class bounds. `diff.php` then lists each class that leaves that state unlike the install: @@ -56,7 +56,7 @@ Environment variables: * `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. * `WP_TESTS_LEAKS_SCOPE`: `class` for the whole-suite sweep. -The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `check-probes.php` exits with 1 if the report misses one, or if an isolated child reports state that dies with it; pass it the same `WP_TESTS_LEAKS_SCOPE`, if any, as the run: +The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `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. Run it with the same `LOCAL_PHP_MEMCACHED` and `WP_TESTS_LEAKS_SCOPE` as the tests: ``` node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --testsuite leak-probe diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index ccd35980cee00..9540e1e18c343 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -4,14 +4,16 @@ * * php check-probes.php run.jsonl * - * Set WP_TESTS_LEAKS_SCOPE as for the run. Exits with 1 on a missed leak, in-process state an - * isolated child reports, or a failed diff.php. + * Set LOCAL_PHP_MEMCACHED and WP_TESTS_LEAKS_SCOPE as for the run. Exits with 1 on a missed leak, a key + * a probe must not report, or a failed diff.php. */ // Report title => 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_notoptions_cache' => array( '/^db\|\w+options\|leak_probe_missing$/', '/^stale\|runtime\|1\|options\|notoptions\|leak_probe_missing$/' ), + '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_cache_global_group' => array( '/^global\|wp_object_cache\|global_groups$/' ), 'test Tests_Leak_Probe::test_leaks_function_static_var' => array( '/^fstatic\|leak_probe_counter\(\)\|\$calls$/', '/^fstatic\|Tests_Leak_Probe::method_counter\(\)\|\$calls$/' ), @@ -24,14 +26,16 @@ '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$/' ), + '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-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_in_child (isolated 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( - 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/' ), + 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/' ), + '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. @@ -40,6 +44,21 @@ '/^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$/', +); + +// 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$/', ); const MULTISITE_ONLY = array( '/^stale\|runtime\|1\|site-options\|1:site_admins$/' ); @@ -49,6 +68,9 @@ const CHILD_SUFFIX = ' (isolated child)'; +// 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)\|/' ); + // Report header and changed key lines, see report() in diff.php. const HEADER = '/^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$/'; @@ -112,7 +134,8 @@ function first_keys( $file ) { $skipped = 0; foreach ( $expected as $title => $patterns ) { foreach ( $patterns as $pattern ) { - if ( ( ! $multisite && in_array( $pattern, MULTISITE_ONLY, true ) ) || ( ! $runtime_cache && in_array( $pattern, RUNTIME_CACHE_ONLY, true ) ) ) { + $other_cache = $runtime_cache ? PERSISTENT_CACHE_ONLY : RUNTIME_CACHE_ONLY; + if ( ( ! $multisite && in_array( $pattern, MULTISITE_ONLY, true ) ) || in_array( $pattern, $other_cache, true ) ) { ++$skipped; continue; } @@ -124,6 +147,12 @@ function first_keys( $file ) { } } +foreach ( UNEXPECTED as $title => $pattern ) { + foreach ( preg_grep( $pattern, $reported[ $title ] ?? array() ) as $key ) { + $missed[] = "$title: unexpected $key"; + } +} + foreach ( $reported as $title => $keys ) { if ( ! str_ends_with( $title, CHILD_SUFFIX ) ) { continue; diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 79291697b2dd1..88ea8bfb7bc0d 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -13,6 +13,9 @@ const USAGE = "Usage: php diff.php run.jsonl\n php diff.php a.jsonl b.jsonl ClassName\n"; +// A dropped cache entry is a miss, which reads the source again: not a leak, e.g. the test framework's flushes. +const CACHE_AREAS = '/^(cache|mc)\|/'; + // Yields one snapshot at a time: a full run's file can exceed the memory limit. Returns the unreadable line count. function load( $file ) { $handle = fopen( $file, 'r' ); @@ -48,6 +51,10 @@ function compare( array $a, array $b ) { continue; } + if ( ! $after && preg_match( CACHE_AREAS, $key ) ) { + continue; + } + $lines[] = sprintf( " %s\n before: %s\n after: %s", $key, $before ? $before[1] : '(absent)', $after ? $after[1] : '(absent)' ); } sort( $lines ); diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index 0a1a65c9e66f0..ec12802a72736 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -13,11 +13,23 @@ class Tests_Leak_Probe extends WP_UnitTestCase { const FILE = 'leak-probe.txt'; + const LINK = 'leak-probe-link'; + + const DIR = 'leak-probe-dir'; + + const LINK_TARGET = 'leak-probe-missing'; + + // A term_relationships row no fixture creates: object_id, term_taxonomy_id. + const ORPHAN_OBJECT_ID = 999999; + public static $post_id; public static $leaked = 'original'; public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { + // An interrupted run's leftovers would make the file probes fail or go unreported. + self::remove_files(); + // Two term_relationships rows sharing object_id: the composite primary key case. $cat_a = $factory->category->create(); $cat_b = $factory->category->create(); @@ -32,11 +44,38 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { } public static function wpTearDownAfterClass() { - foreach ( array( WP_CONTENT_DIR . '/', sys_get_temp_dir() . '/' ) as $dir ) { - if ( file_exists( $dir . self::FILE ) ) { - unlink( $dir . self::FILE ); + self::remove_files(); + } + + private static function remove_files() { + $paths = array( + WP_CONTENT_DIR . '/' . self::FILE, + sys_get_temp_dir() . '/' . self::FILE, + WP_CONTENT_DIR . '/' . self::LINK, + // A leftover link makes symlink() create its target. + WP_CONTENT_DIR . '/' . self::LINK_TARGET, + ); + foreach ( $paths as $path ) { + if ( is_link( $path ) || is_file( $path ) ) { + unlink( $path ); } } + + $dir = WP_CONTENT_DIR . '/' . self::DIR; + if ( is_dir( $dir ) && ! is_link( $dir ) ) { + rmdir( $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' ) ); + } } public function test_term_relationships_fixture() { @@ -50,6 +89,23 @@ public function test_leaks_option_cache() { $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' ); @@ -155,7 +211,9 @@ public function test_leaks_process_state() { public function test_leaks_files() { file_put_contents( WP_CONTENT_DIR . '/' . self::FILE, 'leaked' ); file_put_contents( sys_get_temp_dir() . '/' . self::FILE, 'leaked' ); - $this->assertTrue( true ); + // Dangling: a link has no target metadata to read. + $this->assertTrue( symlink( WP_CONTENT_DIR . '/' . self::LINK_TARGET, WP_CONTENT_DIR . '/' . self::LINK ) ); + $this->assertTrue( mkdir( WP_CONTENT_DIR . '/' . self::DIR ) ); } public function test_leaks_schema() { diff --git a/tests/phpunit/leaks/probe/leakProbeClassFixture.php b/tests/phpunit/leaks/probe/leakProbeClassFixture.php index 6d9963a61bc10..dce461a454f7a 100644 --- a/tests/phpunit/leaks/probe/leakProbeClassFixture.php +++ b/tests/phpunit/leaks/probe/leakProbeClassFixture.php @@ -16,6 +16,18 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { } } + 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 ) ); } From 37017b4168efd93450e07602e919cea940461aa5 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Tue, 24 Nov 2026 10:24:08 +0100 Subject: [PATCH 05/18] Build/Test Tools: Probe other sites, tables, statics Add leak probes for a site a test commits and its stale cached options, links and directories in the temp dir, a temporary table dropped by a reconnect, a permanent table, and an inherited method's static variable, which before PHP 8.1 each subclass copies. A site created in a test has temporary tables, which SHOW TABLES leaves out: the stale option checks now read tracked temporary tables too. The listener records the run's setup (multisite, PHP version, persistent cache, scope) in run_start. check-probes.php reads it instead of the environment and the first snapshot's keys, which in class scope hold only changed keys, so multisite checks were skipped. diff.php prints previews on one line: a multi-line schema read as keys. check-probes.php no longer needs PHP 8's str_ends_with(). --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/check-probes.php | 90 ++++++++++----- .../leaks/class-wp-phpunit-leak-listener.php | 24 ++-- tests/phpunit/leaks/diff.php | 7 +- tests/phpunit/leaks/probe/leakProbe.php | 106 ++++++++++++++---- 5 files changed, 171 insertions(+), 58 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index f0098497caa90..c84ef04c5d9e5 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -56,7 +56,7 @@ Environment variables: * `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. * `WP_TESTS_LEAKS_SCOPE`: `class` for the whole-suite sweep. -The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `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. Run it with the same `LOCAL_PHP_MEMCACHED` and `WP_TESTS_LEAKS_SCOPE` as the tests: +The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `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 diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 9540e1e18c343..83ed10fabf3bf 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -4,10 +4,21 @@ * * php check-probes.php run.jsonl * - * Set LOCAL_PHP_MEMCACHED and WP_TESTS_LEAKS_SCOPE as for the run. Exits with 1 on a missed leak, a key - * a probe must not report, or a failed diff.php. + * Exits with 1 on a missed leak, a key a probe must not report, or a failed diff.php. */ +// Not site 1's. +const OTHER_SITE_ROW = '/^db\|\w+blogs\|(?!1$)\d+$/'; + +// Before PHP 8.1, a subclass has its own copy of an inherited method's static variables. +const PARENT_STATIC = '/^fstatic\|Leak_Probe_Counter::count\(\)\|\$calls$/'; + +const CHILD_STATIC = '/^fstatic\|Leak_Probe_Counter_Child::count\(\)\|\$calls$/'; + +const STATIC_TITLE = 'test Tests_Leak_Probe::test_leaks_function_static_var'; + +const PHP_SHARED_STATICS = 80100; + // Report title => 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$/' ), @@ -15,8 +26,9 @@ '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$/' ), - 'test Tests_Leak_Probe::test_leaks_function_static_var' => array( '/^fstatic\|leak_probe_counter\(\)\|\$calls$/', '/^fstatic\|Tests_Leak_Probe::method_counter\(\)\|\$calls$/' ), + 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$/' ), @@ -26,15 +38,16 @@ '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-dir$/' ), + '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 (isolated 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( - 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/' ), + 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/', OTHER_SITE_ROW ), '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$/' ), ); @@ -48,6 +61,8 @@ '/^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. @@ -59,9 +74,19 @@ '/^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$/' ); +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$/', +); // An isolated child's report holds only these, see OUTLIVES_PROCESS in the listener. const CHILD_AREAS = '/^(db|schema|mc|file|stale\|memcached)\|/'; @@ -69,35 +94,36 @@ const CHILD_SUFFIX = ' (isolated child)'; // 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)\|/' ); +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$/', +); // Report header and changed key lines, see report() in diff.php. const HEADER = '/^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$/'; const KEY_LINE = '/^ (\S.*)$/'; -// The keys of the run's first non-empty snapshot. -function first_keys( $file ) { +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 ); } - $line = fgets( $handle ); - while ( false !== $line ) { - $snap = json_decode( $line, true ); - if ( ! empty( $snap['state'] ) ) { - fclose( $handle ); - return array_keys( $snap['state'] ); - } + $snap = json_decode( (string) fgets( $handle ), true ); + fclose( $handle ); - $line = fgets( $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 ); } - fclose( $handle ); - fwrite( STDERR, "No snapshot in $file\n" ); - exit( 1 ); + return $snap['setup']; } if ( 2 !== $argc ) { @@ -125,17 +151,26 @@ function first_keys( $file ) { } } -$multisite = (bool) preg_grep( '/^schema\|\w+blogs$/', first_keys( $argv[1] ) ); -$runtime_cache = 'true' !== getenv( 'LOCAL_PHP_MEMCACHED' ); -$expected = 'class' === getenv( 'WP_TESTS_LEAKS_SCOPE' ) ? CLASS_SCOPE : PER_TEST; +$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 ) { - $other_cache = $runtime_cache ? PERSISTENT_CACHE_ONLY : RUNTIME_CACHE_ONLY; - if ( ( ! $multisite && in_array( $pattern, MULTISITE_ONLY, true ) ) || in_array( $pattern, $other_cache, true ) ) { + if ( in_array( $pattern, $skip, true ) ) { ++$skipped; continue; } @@ -147,14 +182,15 @@ function first_keys( $file ) { } } -foreach ( UNEXPECTED as $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 ( ! str_ends_with( $title, CHILD_SUFFIX ) ) { + // No str_ends_with() before PHP 8. + if ( substr( $title, -strlen( CHILD_SUFFIX ) ) !== CHILD_SUFFIX ) { continue; } diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index ca013a503480e..7672b7f8244c7 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -164,9 +164,9 @@ public function track_temp_tables( $query ) { } public function start_test_suite( $suite ) { - // Marks the run's start and end so diff.php sees a cut run. + // 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->mark( 'run_start' ); + $this->mark( 'run_start', array( 'setup' => $this->setup() ) ); } if ( ! class_exists( $suite->getName(), false ) ) { @@ -223,7 +223,7 @@ private function name( $test ) { return $test instanceof PHPUnit\Framework\TestCase ? get_class( $test ) . '::' . $test->getName() : get_class( $test ); } - private function write( $point, $id, ?array $state = null ) { + private function write( $point, $id, ?array $state = null, array $extra = array() ) { $this->append( array( 'pid' => getmypid(), @@ -231,12 +231,21 @@ private function write( $point, $id, ?array $state = null ) { 'point' => $point, 'id' => $id, 'state' => $state ?? $this->state(), - ) + ) + $extra ); } - private function mark( $point ) { - $this->write( $point, '', array() ); + private function mark( $point, array $extra = array() ) { + $this->write( $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, + ); } /* @@ -645,8 +654,9 @@ private function mismatch( $cached, $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 ] ) ) { + if ( ! isset( $this->tables[ $table ] ) && ! isset( $this->temp_tables[ $table ] ) ) { return null; } diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 88ea8bfb7bc0d..a17bab747b106 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -55,13 +55,18 @@ function compare( array $a, array $b ) { continue; } - $lines[] = sprintf( " %s\n before: %s\n after: %s", $key, $before ? $before[1] : '(absent)', $after ? $after[1] : '(absent)' ); + $lines[] = sprintf( " %s\n before: %s\n after: %s", $key, preview( $before ), preview( $after ) ); } sort( $lines ); return $lines; } +// One line: a multi-line value, e.g. a schema, would read as more keys. +function preview( $entry ) { + return $entry ? preg_replace( '/\s*\n\s*/', ' ', $entry[1] ) : '(absent)'; +} + function report( $title, array $lines ) { if ( ! $lines ) { return; diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index ec12802a72736..1254f1e2398c4 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -9,6 +9,16 @@ function leak_probe_counter() { return ++$calls; } +class Leak_Probe_Counter { + public static function count() { + static $calls = 0; + return ++$calls; + } +} + +// Before PHP 8.1, has its own copy of count()'s static variable. +class Leak_Probe_Counter_Child extends Leak_Probe_Counter {} + class Tests_Leak_Probe extends WP_UnitTestCase { const FILE = 'leak-probe.txt'; @@ -22,13 +32,17 @@ class Tests_Leak_Probe extends WP_UnitTestCase { // A term_relationships row no fixture creates: object_id, term_taxonomy_id. const ORPHAN_OBJECT_ID = 999999; + const PERMANENT_TABLE = 'leak_probe_permanent'; + public static $post_id; + private static $site_id; + public static $leaked = 'original'; public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { - // An interrupted run's leftovers would make the file probes fail or go unreported. - self::remove_files(); + // An interrupted run's leftovers would make the probes fail or go unreported. + self::remove_leftovers(); // Two term_relationships rows sharing object_id: the composite primary key case. $cat_a = $factory->category->create(); @@ -43,30 +57,35 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { $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_files(); + self::remove_leftovers(); } - private static function remove_files() { - $paths = array( - WP_CONTENT_DIR . '/' . self::FILE, - sys_get_temp_dir() . '/' . self::FILE, - WP_CONTENT_DIR . '/' . self::LINK, + 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. - WP_CONTENT_DIR . '/' . self::LINK_TARGET, - ); - foreach ( $paths as $path ) { - if ( is_link( $path ) || is_file( $path ) ) { - unlink( $path ); + foreach ( array( self::FILE, self::LINK, self::LINK_TARGET ) as $name ) { + if ( is_link( "$dir/$name" ) || is_file( "$dir/$name" ) ) { + unlink( "$dir/$name" ); + } } - } - $dir = WP_CONTENT_DIR . '/' . self::DIR; - if ( is_dir( $dir ) && ! is_link( $dir ) ) { - rmdir( $dir ); + 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(); @@ -76,6 +95,12 @@ public function tear_down() { // 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() { @@ -135,6 +160,25 @@ public function test_leaks_network_option_cache() { $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 ); @@ -143,6 +187,7 @@ public function test_leaks_cache_global_group() { 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() { @@ -209,11 +254,12 @@ public function test_leaks_process_state() { } public function test_leaks_files() { - file_put_contents( WP_CONTENT_DIR . '/' . self::FILE, 'leaked' ); - file_put_contents( sys_get_temp_dir() . '/' . self::FILE, 'leaked' ); - // Dangling: a link has no target metadata to read. - $this->assertTrue( symlink( WP_CONTENT_DIR . '/' . self::LINK_TARGET, WP_CONTENT_DIR . '/' . self::LINK ) ); - $this->assertTrue( mkdir( WP_CONTENT_DIR . '/' . self::DIR ) ); + 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() { @@ -226,6 +272,22 @@ public function test_leaks_temp_table() { $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 From 2cebb5dc9c764ea579aa208136efeb5c788ad86d Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Tue, 24 Nov 2026 11:04:22 +0100 Subject: [PATCH 06/18] Build/Test Tools: Configure leak areas per test file Snapshotting every area for every test is slow and noisy, and some files leak on purpose. Add a rules file that picks the snapshot keys per scope and per test file, with fnmatch() patterns, negation and a required reason per rule. The listener validates it before any test runs and skips collectors no pattern needs. The leak configurations pass the rules file and scope as listener arguments; WP_TESTS_LEAKS_RULES, WP_TESTS_LEAKS_SCOPE and WP_TESTS_LEAKS_AREAS override them. diff.php exits with 2 when it reports changes, so CI can fail on leaks. --- tests/phpunit/README.md | 22 +- tests/phpunit/leaks/check-probes.php | 54 ++- .../leaks/class-wp-phpunit-leak-listener.php | 452 ++++++++++++++---- tests/phpunit/leaks/diff.php | 19 +- tests/phpunit/leaks/multisite.xml | 12 +- tests/phpunit/leaks/phpunit.xml | 12 +- tests/phpunit/leaks/probe/leakProbe.php | 7 + .../phpunit/leaks/probe/leakProbeSkipped.php | 14 + tests/phpunit/leaks/rules.php | 66 +++ 9 files changed, 561 insertions(+), 97 deletions(-) create mode 100644 tests/phpunit/leaks/probe/leakProbeSkipped.php create mode 100644 tests/phpunit/leaks/rules.php diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index c84ef04c5d9e5..7f3d9c4b4932a 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -35,9 +35,9 @@ node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c te 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 1 if the run did not finish or ran no test. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. +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 or ran no test, else 0. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. -To sweep the whole suite, snapshot only the state that outlives the PHP process (database, files, memcached, stale cached options) at class bounds. `diff.php` then lists each class that leaves that state unlike the install: +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 @@ -51,12 +51,24 @@ node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www 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 ``` -Environment variables: +`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. Takes shorthands: `all`, `persistent`, `db`, `cache`, `globals`, `statics`, `runtime`, `files`, e.g. `statics,globals` or `cache,!stale`. * `WP_TESTS_LEAKS_OUT`: snapshots file, default `tests/phpunit/build/leaks/snapshots.jsonl`. -* `WP_TESTS_LEAKS_SCOPE`: `class` for the whole-suite sweep. -The `leak-probe` test suite leaks one kind of state per test, to check the listener sees each. `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: +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 diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 83ed10fabf3bf..ecd29371f9a42 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -35,6 +35,7 @@ '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_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$/' ), @@ -47,7 +48,8 @@ ); const CLASS_SCOPE = array( - 'class Tests_Leak_Probe' => array( '/^db\|\w+links\|\d+$/', '/^schema\|\w+options$/', OTHER_SITE_ROW ), + // 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$/' ), ); @@ -95,11 +97,21 @@ // 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)\|/', + '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$/', + // 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, and no report blames its leak on another. +const SKIPPED_CLASS = 'Tests_Leak_Probe_Skipped'; + +const SKIPPED_LEAK = '/leak_probe_skipped/'; + +// diff.php exits with 2 when it reports a leak, as every probe run must. +const DIFF_LEAKS = 2; + // Report header and changed key lines, see report() in diff.php. const HEADER = '/^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$/'; @@ -126,14 +138,34 @@ function setup( $file ) { 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; +} + if ( 2 !== $argc ) { fwrite( STDERR, "Usage: php check-probes.php run.jsonl\n" ); exit( 1 ); } exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . ' ' . escapeshellarg( $argv[1] ), $output, $code ); -if ( 0 !== $code ) { - fwrite( STDERR, "diff.php failed with $code.\n" ); +if ( DIFF_LEAKS !== $code ) { + fwrite( STDERR, "diff.php exited with $code, not " . DIFF_LEAKS . ".\n" ); exit( 1 ); } @@ -199,6 +231,20 @@ function setup( $file ) { } } +foreach ( $reported as $title => $keys ) { + if ( false !== strpos( $title, SKIPPED_CLASS ) ) { + $missed[] = "$title: reported, but rules.php skips its file"; + } + + foreach ( preg_grep( SKIPPED_LEAK, $keys ) as $key ) { + $missed[] = "$title: unexpected $key"; + } +} + +if ( snapshotted( $argv[1], SKIPPED_CLASS ) ) { + $missed[] = SKIPPED_CLASS . ': snapshotted, but rules.php skips its file'; +} + if ( $missed ) { fwrite( STDERR, "Missed or unexpected leaks:\n " . implode( "\n ", $missed ) . "\n" ); exit( 1 ); diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index 7672b7f8244c7..7c30333877abd 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -11,11 +11,14 @@ * Each snapshot is a flat map "area|key" => [hash, preview], appended as one JSON line * to WP_TESTS_LEAKS_OUT. diff.php compares snapshots. * - * WP_TESTS_LEAKS_SCOPE=class sweeps a whole suite cheaply: persistent areas only, at class - * bounds only, and writes one "class_leaks" line per class that changes them and leaves - * them unlike the install. That is what the next class, and every isolated child, inherits. + * 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 @@ -61,6 +64,44 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { 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|*' ), + 'db' => array( 'db|*', 'dbcount|*', 'autoinc|*', 'schema|*', 'temptable|*' ), + 'cache' => 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; // SHOW CREATE TABLE has the live counter; information_schema caches it. @@ -74,20 +115,26 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; - /* - * Areas 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. - */ - private const PERSISTENT = '/^(db|schema|mc|file|stale)\|/'; - // Those an isolated child leaves its parent and later runs: not the in-process caches' stale|runtime and stale|local. private const OUTLIVES_PROCESS = '/^(db|schema|mc|file|stale\|memcached)\|/'; + private const CHILD_AREAS = array( 'db', 'schema', 'mc', 'file', 'stale' ); + 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(); + private $child = false; // WP_TESTS_LEAKS_SCOPE=class: the state at the first class start and at the running class start. @@ -113,38 +160,275 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // DB rows read by the stale checks, reset per snapshot. private $rows = array(); - public function __construct() { + /** + * @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 = getenv( 'WP_TESTS_LEAKS_SCOPE' ); + $this->scope = $this->setting( 'SCOPE', $settings['scope'] ?? self::SCOPE_TEST ); - if ( $this->scope && self::SCOPE_CLASS !== $this->scope ) { - $this->fail( 'WP_TESTS_LEAKS_SCOPE must be "' . self::SCOPE_CLASS . '" or unset.' ); + 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(); + + // An isolated child inherits the environment, not the listener's arguments. + putenv( self::ENV_PREFIX . "SCOPE=$this->scope" ); + putenv( self::ENV_PREFIX . "RULES=$this->rules_file" ); + // 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 ) ) { + return ! $pattern[0]; + } + } + + return false; + } + /** * Snapshots this process-isolated child process, from now to its shutdown. */ public function watch_child() { - if ( self::SCOPE_CLASS === $this->scope ) { + $id = getenv( self::ENV_TEST ); + $plan = array_intersect_key( $this->plan( (string) strstr( $id, '::', true ) ), array_flip( self::CHILD_AREAS ) ); + if ( self::SCOPE_CLASS === $this->scope || ! $plan ) { return; } $this->child = true; - $id = getenv( self::ENV_TEST ); - $this->write( 'test_start', $id ); + $this->write( 'test_start', $id, $plan ); register_shutdown_function( - function () use ( $id ) { + function () use ( $id, $plan ) { global $wpdb; // A child that died mid-test left its transaction open: the snapshot's COMMIT would keep it. $wpdb->query( 'ROLLBACK' ); - $this->write( 'test_end', $id ); + $this->write( 'test_end', $id, $plan ); } ); } @@ -166,20 +450,32 @@ public function track_temp_tables( $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() ) ); } - if ( ! class_exists( $suite->getName(), false ) ) { + $class_name = $suite->getName(); + if ( ! class_exists( $class_name, false ) ) { + return; + } + + $plan = $this->plan( $class_name ); + if ( ! $plan ) { return; } if ( self::SCOPE_CLASS !== $this->scope ) { - $this->write( 'class_start', $suite->getName() ); + $this->write( 'class_start', $class_name, $plan ); return; } - $this->class_start = $this->state(); - $this->installed = $this->installed ?? $this->class_start; + if ( null === $this->installed ) { + $this->installed = $this->state( $this->union_plan() ); + $this->class_start = $this->filter( $this->installed, $plan ); + return; + } + + $this->class_start = $this->state( $plan ); } public function end_test_suite( $suite ) { @@ -193,29 +489,35 @@ public function end_test_suite( $suite ) { } private function end_class( $class_name ) { + $plan = $this->plan( $class_name ); + if ( ! $plan ) { + return; + } + if ( self::SCOPE_CLASS !== $this->scope ) { - $this->write( 'class_end', $class_name ); + $this->write( 'class_end', $class_name, $plan ); return; } - $this->write_class_leaks( $class_name ); + $this->write_class_leaks( $class_name, $plan ); } public function start_test( $test ) { - if ( self::SCOPE_CLASS === $this->scope ) { - return; - } - $name = $this->name( $test ); - $this->write( 'test_start', $name ); // An isolated child inherits the environment. putenv( self::ENV_TEST . '=' . $name ); + + $plan = $this->plan( get_class( $test ) ); + if ( self::SCOPE_CLASS !== $this->scope && $plan ) { + $this->write( 'test_start', $name, $plan ); + } } public function end_test( $test, $time ) { - if ( self::SCOPE_CLASS !== $this->scope ) { - $this->write( 'test_end', $this->name( $test ) ); + $plan = $this->plan( get_class( $test ) ); + if ( self::SCOPE_CLASS !== $this->scope && $plan ) { + $this->write( 'test_end', $this->name( $test ), $plan ); } } @@ -223,20 +525,22 @@ private function name( $test ) { return $test instanceof PHPUnit\Framework\TestCase ? get_class( $test ) . '::' . $test->getName() : get_class( $test ); } - private function write( $point, $id, ?array $state = null, array $extra = array() ) { - $this->append( - array( - 'pid' => getmypid(), - 'child' => $this->child, - 'point' => $point, - 'id' => $id, - 'state' => $state ?? $this->state(), - ) + $extra + 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( + 'pid' => getmypid(), + 'child' => $this->child, + 'point' => $point, + 'id' => $id, + 'state' => $state, ); } private function mark( $point, array $extra = array() ) { - $this->write( $point, '', array(), $extra ); + $this->append( $this->line( $point, '', array() ) + $extra ); } private function setup() { @@ -253,9 +557,9 @@ private function setup() { * ["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 ) { + private function write_class_leaks( $class_name, array $plan ) { $start = $this->class_start; - $end = $this->state(); + $end = $this->state( $plan ); $this->class_start = null; @@ -290,8 +594,8 @@ private function write_class_leaks( $class_name ) { ); } - // The snapshot for the scope. - private function state() { + // The keys the plan keeps, see plan(). + private function state( array $plan ) { global $wpdb; /* @@ -305,12 +609,21 @@ private function state() { $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 ); if ( $this->child ) { - $state = $this->persistent( self::OUTLIVES_PROCESS ); - } elseif ( self::SCOPE_CLASS === $this->scope ) { - $state = $this->persistent( self::PERSISTENT ); - } else { - $state = $this->everything(); + $state = array_intersect_key( $state, array_flip( preg_grep( self::OUTLIVES_PROCESS, array_keys( $state ) ) ) ); } // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. @@ -319,30 +632,6 @@ private function state() { return $state; } - private function persistent( $areas ) { - return array_filter( - array_merge( $this->db(), $this->cache(), $this->memcached(), $this->files() ), - static function ( $key ) use ( $areas ) { - return preg_match( $areas, $key ); - }, - ARRAY_FILTER_USE_KEY - ); - } - - private function everything() { - return array_merge( - $this->db(), - $this->cache(), - $this->memcached(), - $this->globals(), - $this->statics(), - $this->static_vars(), - $this->constants(), - $this->process(), - $this->files() - ); - } - 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." ); @@ -355,11 +644,9 @@ private function fail( $message ) { } // phpcs:disable WordPress.DB.PreparedSQL -- Table and column names come from SHOW TABLES and SHOW COLUMNS. - private function db() { + private function list_tables() { global $wpdb; - $state = array(); - /* * 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 @@ -372,10 +659,15 @@ private function db() { $tables = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $like ) ); $this->check_query( 'the tables' ); - // Read before cache() in persistent() and everything(). $this->tables = array_flip( $tables ); + } + + private function db() { + global $wpdb; + + $state = array(); - foreach ( $tables as $table ) { + 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 ); diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index a17bab747b106..b2e11a606770a 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -11,6 +11,8 @@ * before any class ran, already differs. */ +const CHANGES_FOUND = 2; + const USAGE = "Usage: php diff.php run.jsonl\n php diff.php a.jsonl b.jsonl ClassName\n"; // A dropped cache entry is a miss, which reads the source again: not a leak, e.g. the test framework's flushes. @@ -67,12 +69,15 @@ function preview( $entry ) { return $entry ? preg_replace( '/\s*\n\s*/', ' ', $entry[1] ) : '(absent)'; } +// Returns whether it reported anything. function report( $title, array $lines ) { if ( ! $lines ) { - return; + return false; } echo "== $title (" . count( $lines ) . " changed)\n" . implode( "\n", $lines ) . "\n\n"; + + return true; } // The first class_start and the class ID's. @@ -105,8 +110,7 @@ function class_starts( $file, $id ) { } $lines = compare( array_diff_key( $a, $noise ), array_diff_key( $b, $noise ) ); - report( "{$argv[3]} class_start: {$argv[1]} -> {$argv[2]}, " . count( $noise ) . ' run noise keys ignored', $lines ); - exit( 0 ); + exit( report( "{$argv[3]} class_start: {$argv[1]} -> {$argv[2]}, " . count( $noise ) . ' run noise keys ignored', $lines ) ? CHANGES_FOUND : 0 ); } if ( 2 !== $argc ) { @@ -118,10 +122,11 @@ function class_starts( $file, $id ) { $count = 0; $orphans = 0; $open = array(); +$changes = false; foreach ( $snaps as $snap ) { ++$count; if ( 'class_leaks' === $snap['point'] ) { - report( "class {$snap['id']} leaves, unlike the install", compare( $snap['installed'], $snap['state'] ) ); + $changes = report( "class {$snap['id']} leaves, unlike the install", compare( $snap['installed'], $snap['state'] ) ) || $changes; continue; } @@ -138,8 +143,8 @@ function class_starts( $file, $id ) { continue; } - $where = empty( $snap['child'] ) ? '' : ' (isolated child)'; - report( "$kind {$snap['id']}$where leaves", compare( $open[ $slot ], $snap['state'] ) ); + $where = empty( $snap['child'] ) ? '' : ' (isolated child)'; + $changes = report( "$kind {$snap['id']}$where leaves", compare( $open[ $slot ], $snap['state'] ) ) || $changes; unset( $open[ $slot ] ); } @@ -149,3 +154,5 @@ function class_starts( $file, $id ) { 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 index 85a7bc1a3ca84..0507e10860c26 100644 --- a/tests/phpunit/leaks/multisite.xml +++ b/tests/phpunit/leaks/multisite.xml @@ -45,6 +45,16 @@ - + + + + + + tests/phpunit/leaks/rules.php + + test + + + diff --git a/tests/phpunit/leaks/phpunit.xml b/tests/phpunit/leaks/phpunit.xml index e63b0ec6b4e5b..23e1a61d06fbb 100644 --- a/tests/phpunit/leaks/phpunit.xml +++ b/tests/phpunit/leaks/phpunit.xml @@ -40,7 +40,17 @@ - + + + + + + tests/phpunit/leaks/rules.php + + test + + + diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index 1254f1e2398c4..dab6ec9c57177 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -224,6 +224,13 @@ public function test_leaks_type_only_change() { $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'; 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..573f64a9eec50 --- /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( + '!*', + ), + ), + ), +); From 3effe7d9e6a6596b9a14d01b24da8d756387fd86 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Tue, 24 Nov 2026 11:31:37 +0100 Subject: [PATCH 07/18] Build/Test Tools: Fix leak rules in children, baseline Isolated children planned before their test file loaded, so per-file rules never applied; the parent now passes the file in WP_TESTS_LEAKS_FILE. The class-scope install baseline is taken at run start, not after classes rules.php skips. Two-run diff.php counts as noise only keys both runs hold with different values. A relative WP_TESTS_LEAKS_OUT survives a test's chdir(). A run that snapshots nothing writes no run_end, so diff.php exits 1. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/bootstrap.php | 23 ++++++-- .../leaks/class-wp-phpunit-leak-listener.php | 59 +++++++++++-------- tests/phpunit/leaks/diff.php | 9 +-- .../leaks/probe/leakProbeChildSkipped.php | 16 +++++ tests/phpunit/leaks/rules.php | 4 +- 6 files changed, 78 insertions(+), 35 deletions(-) create mode 100644 tests/phpunit/leaks/probe/leakProbeChildSkipped.php diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 7f3d9c4b4932a..27452c72a7c34 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -35,7 +35,7 @@ node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c te 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 or ran no test, else 0. Each run replaces the snapshots file. Snapshots take time and space, e.g. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. +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. 421 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: diff --git a/tests/phpunit/leaks/bootstrap.php b/tests/phpunit/leaks/bootstrap.php index 2b524fd2a390d..b8d224b8abe59 100644 --- a/tests/phpunit/leaks/bootstrap.php +++ b/tests/phpunit/leaks/bootstrap.php @@ -9,13 +9,24 @@ exit( 1 ); } -if ( ! getenv( 'WP_TESTS_LEAKS_OUT' ) ) { - putenv( 'WP_TESTS_LEAKS_OUT=' . dirname( __DIR__ ) . '/build/leaks/snapshots.jsonl' ); +$leaks_out = getenv( 'WP_TESTS_LEAKS_OUT' ); +if ( ! $leaks_out ) { + $leaks_out = dirname( __DIR__ ) . '/build/leaks/snapshots.jsonl'; +} elseif ( '/' !== $leaks_out[0] ) { + // Tests can chdir(), e.g. Tests_Leak_Probe_Class_Fixture. + $leaks_cwd = getcwd(); + if ( false === $leaks_cwd ) { + fwrite( STDERR, "Cannot resolve WP_TESTS_LEAKS_OUT $leaks_out: no working directory.\n" ); + exit( 1 ); + } + + $leaks_out = "$leaks_cwd/$leaks_out"; } +putenv( "WP_TESTS_LEAKS_OUT=$leaks_out" ); + // Before the core bootstrap, which can exit: a failed run, or one matching no test, must not leave the last run's snapshots. if ( ! isset( $GLOBALS['__PHPUNIT_BOOTSTRAP'] ) ) { - $leaks_out = getenv( 'WP_TESTS_LEAKS_OUT' ); if ( ! is_dir( dirname( $leaks_out ) ) ) { mkdir( dirname( $leaks_out ), 0777, true ); } @@ -24,11 +35,11 @@ fwrite( STDERR, "Cannot write $leaks_out.\n" ); exit( 1 ); } - - // Else the listener snapshots it as a global. - unset( $leaks_out ); } +// Else the listener snapshots them as globals. +unset( $leaks_out, $leaks_cwd ); + require dirname( __DIR__ ) . '/includes/bootstrap.php'; require_once __DIR__ . '/class-wp-phpunit-leak-listener.php'; diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index 7c30333877abd..d4ffaa8cbfa3a 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -54,6 +54,8 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private const MAX_DEPTH = 12; + private const PHP_8_1 = 80100; + private const PREVIEW_LENGTH = 200; private const MISMATCH_PREVIEW_LENGTH = 90; @@ -115,6 +117,9 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; + // The child loads the test file after the bootstrap, where it plans. + private const ENV_FILE = 'WP_TESTS_LEAKS_FILE'; + // Those an isolated child leaves its parent and later runs: not the in-process caches' stale|runtime and stale|local. private const OUTLIVES_PROCESS = '/^(db|schema|mc|file|stale\|memcached)\|/'; @@ -137,7 +142,7 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private $child = false; - // WP_TESTS_LEAKS_SCOPE=class: the state at the first class start and at the running class start. + // WP_TESTS_LEAKS_SCOPE=class: the state at the run start and at the running class start. private $installed = null; private $class_start = null; @@ -157,6 +162,9 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // 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; + // DB rows read by the stale checks, reset per snapshot. private $rows = array(); @@ -318,7 +326,10 @@ private function relative( $path ) { * 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() : ''; + return $this->file_plan( class_exists( $class_name, false ) ? (string) ( new ReflectionClass( $class_name ) )->getFileName() : '' ); + } + + private function file_plan( $file ) { if ( isset( $this->plans[ $file ] ) ) { return $this->plans[ $file ]; } @@ -414,7 +425,7 @@ private function kept( $key, array $patterns ) { */ public function watch_child() { $id = getenv( self::ENV_TEST ); - $plan = array_intersect_key( $this->plan( (string) strstr( $id, '::', true ) ), array_flip( self::CHILD_AREAS ) ); + $plan = array_intersect_key( $this->file_plan( (string) getenv( self::ENV_FILE ) ), array_flip( self::CHILD_AREAS ) ); if ( self::SCOPE_CLASS === $this->scope || ! $plan ) { return; } @@ -452,6 +463,11 @@ public function start_test_suite( $suite ) { 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(); @@ -464,17 +480,13 @@ public function start_test_suite( $suite ) { return; } + $this->snapshotted = true; + if ( self::SCOPE_CLASS !== $this->scope ) { $this->write( 'class_start', $class_name, $plan ); return; } - if ( null === $this->installed ) { - $this->installed = $this->state( $this->union_plan() ); - $this->class_start = $this->filter( $this->installed, $plan ); - return; - } - $this->class_start = $this->state( $plan ); } @@ -483,9 +495,17 @@ public function end_test_suite( $suite ) { $this->end_class( $suite->getName() ); } - if ( 0 === --$this->open_suites ) { - $this->mark( 'run_end' ); + 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; } + + $this->mark( 'run_end' ); } private function end_class( $class_name ) { @@ -507,6 +527,7 @@ public function start_test( $test ) { // An isolated child inherits the environment. putenv( self::ENV_TEST . '=' . $name ); + putenv( self::ENV_FILE . '=' . ( new ReflectionClass( $test ) )->getFileName() ); $plan = $this->plan( get_class( $test ) ); if ( self::SCOPE_CLASS !== $this->scope && $plan ) { @@ -565,7 +586,7 @@ private function write_class_leaks( $class_name, array $plan ) { $installed = array(); $left = array(); - foreach ( array_unique( array_merge( array_keys( $start ), array_keys( $end ) ) ) as $key ) { + 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; @@ -583,15 +604,7 @@ private function write_class_leaks( $class_name, array $plan ) { return; } - $this->append( - array( - 'pid' => getmypid(), - 'point' => 'class_leaks', - 'id' => $class_name, - 'installed' => $installed, - 'state' => $left, - ) - ); + $this->append( $this->line( 'class_leaks', $class_name, $left ) + array( 'installed' => $installed ) ); } // The keys the plan keeps, see plan(). @@ -1067,7 +1080,7 @@ private function static_vars() { * 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 >= 80100 || $ref->isSubclassOf( 'PHPUnit\Framework\TestCase' ) ) ) { + if ( $inherited && ( PHP_VERSION_ID >= self::PHP_8_1 || $ref->isSubclassOf( 'PHPUnit\Framework\TestCase' ) ) ) { continue; } @@ -1177,7 +1190,7 @@ private function file( SplFileInfo $file ) { // 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 < 80100 ) { + if ( PHP_VERSION_ID < self::PHP_8_1 ) { $prop->setAccessible( true ); } diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index b2e11a606770a..05505b841c9bd 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -7,8 +7,9 @@ * WP_TESTS_LEAKS_SCOPE=class runs: install vs class end. * php diff.php alone.jsonl seq.jsonl ID State the class ID inherits: its class_start * in run A vs run B, minus run noise (timestamps, - * env, install rows): keys whose first class_start, - * before any class ran, already differs. + * env, install rows): keys both first class_starts, + * before any class ran, hold with different values. + * A key only one holds is its first class's rules. */ const CHANGES_FOUND = 2; @@ -46,7 +47,7 @@ function load( $file ) { function compare( array $a, array $b ) { $lines = array(); - foreach ( array_unique( array_merge( array_keys( $a ), array_keys( $b ) ) ) as $key ) { + foreach ( array_keys( $a + $b ) as $key ) { $before = $a[ $key ] ?? null; $after = $b[ $key ] ?? null; if ( $before && $after && $before[0] === $after[0] ) { @@ -102,7 +103,7 @@ function class_starts( $file, $id ) { list( $first_a, $a ) = class_starts( $argv[1], $argv[3] ); list( $first_b, $b ) = class_starts( $argv[2], $argv[3] ); - $noise = array_diff_key( $first_a, $first_b ) + array_diff_key( $first_b, $first_a ); + $noise = array(); foreach ( array_intersect_key( $first_a, $first_b ) as $key => $value ) { if ( $value[0] !== $first_b[ $key ][0] ) { $noise[ $key ] = true; diff --git a/tests/phpunit/leaks/probe/leakProbeChildSkipped.php b/tests/phpunit/leaks/probe/leakProbeChildSkipped.php new file mode 100644 index 0000000000000..cbd4d0419d294 --- /dev/null +++ b/tests/phpunit/leaks/probe/leakProbeChildSkipped.php @@ -0,0 +1,16 @@ +assertTrue( true ); + } +} diff --git a/tests/phpunit/leaks/rules.php b/tests/phpunit/leaks/rules.php index 573f64a9eec50..bfe2665103975 100644 --- a/tests/phpunit/leaks/rules.php +++ b/tests/phpunit/leaks/rules.php @@ -3,7 +3,8 @@ * What WP_PHPUnit_Leak_Listener snapshots, see tests/phpunit/README.md. * * Patterns are fnmatch() globs over snapshot keys, "area|key", without escapes. "!" negates. - * The last pattern matching a key decides. A bare area name means all its keys, e.g. "mc". + * The last pattern matching a key decides. A bare area name means all its keys, e.g. "mc", + * except the WP_TESTS_LEAKS_AREAS shorthands, e.g. "db" and "cache", which span more areas. * * 'areas' holds each scope's defaults; WP_TESTS_LEAKS_AREAS replaces them. A test file's * patterns are its scope's defaults, then the 'areas' of each 'files' rule whose 'paths' @@ -57,6 +58,7 @@ 'why' => 'Leak probe: a file no pattern keeps is not snapshotted, see check-probes.php.', 'paths' => array( 'tests/phpunit/leaks/probe/leakProbeSkipped.php', + 'tests/phpunit/leaks/probe/leakProbeChildSkipped.php', ), 'areas' => array( '!*', From 8b5f70ce9030e8621e92f4540f926fe59f0d12f0 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 09:51:36 +0100 Subject: [PATCH 08/18] Build/Test Tools: Rename leak shorthands off area names The db and cache shorthands shared names with the db and cache areas, so a !cache rule also dropped mc and stale, and !db dropped dbcount, autoinc, schema and temptable. Rename them database and caches, as globals, statics and files already avoid their areas. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/class-wp-phpunit-leak-listener.php | 4 ++-- tests/phpunit/leaks/rules.php | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 27452c72a7c34..6842c02b88959 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -57,7 +57,7 @@ The leak configurations pass the listener its settings: `rules`, the rules file * `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. Takes shorthands: `all`, `persistent`, `db`, `cache`, `globals`, `statics`, `runtime`, `files`, e.g. `statics,globals` or `cache,!stale`. +* `WP_TESTS_LEAKS_AREAS`: comma-separated patterns replacing the scope's defaults in the rules file; its per-file rules still apply. 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: diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index d4ffaa8cbfa3a..22f05c070619b 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -91,8 +91,8 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private const ALIASES = array( 'all' => array( '*|*' ), 'persistent' => array( 'db|*', 'schema|*', 'mc|*', 'file|*', 'stale|*' ), - 'db' => array( 'db|*', 'dbcount|*', 'autoinc|*', 'schema|*', 'temptable|*' ), - 'cache' => array( 'cache|*', 'mc|*', '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|*' ), diff --git a/tests/phpunit/leaks/rules.php b/tests/phpunit/leaks/rules.php index bfe2665103975..3972af3c11d7b 100644 --- a/tests/phpunit/leaks/rules.php +++ b/tests/phpunit/leaks/rules.php @@ -3,8 +3,7 @@ * What WP_PHPUnit_Leak_Listener snapshots, see tests/phpunit/README.md. * * Patterns are fnmatch() globs over snapshot keys, "area|key", without escapes. "!" negates. - * The last pattern matching a key decides. A bare area name means all its keys, e.g. "mc", - * except the WP_TESTS_LEAKS_AREAS shorthands, e.g. "db" and "cache", which span more areas. + * The last pattern matching a key decides. A bare area name means all its keys, e.g. "mc". * * 'areas' holds each scope's defaults; WP_TESTS_LEAKS_AREAS replaces them. A test file's * patterns are its scope's defaults, then the 'areas' of each 'files' rule whose 'paths' From bcb90aa9525c4429fced4dc0fad48fc60fe024b8 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 10:14:11 +0100 Subject: [PATCH 09/18] Build/Test Tools: Reuse the last test end as test start Nothing runs between a test's end and the next test's start in the same class, so the listener no longer snapshots there: it writes a reuse marker, and diff.php starts the test from the pid's last test_end. Halves snapshot time and file size: 1.54 GB to 779 MB and 3:14 to 1:48 on four core classes, same report. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/check-probes.php | 2 ++ .../leaks/class-wp-phpunit-leak-listener.php | 23 ++++++++++++++++--- tests/phpunit/leaks/diff.php | 11 ++++++++- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 6842c02b88959..bc35b69f20a77 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -35,7 +35,7 @@ node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c te 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. 421 MB for `Tests_Multisite_Site`: run one class or group per-test, not the whole suite. +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: diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index ecd29371f9a42..065db8382af4f 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -100,6 +100,8 @@ '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 other constants. + 'test Tests_Leak_Probe::test_leaks_constant' => '/^const\|(?!LEAK_PROBE_CONSTANT$)/', // Dropped by a rules.php pattern. 'test Tests_Leak_Probe::test_leaks_filtered_globals' => '/^global\|leak_probe_filtered_dropped$/', ); diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index 22f05c070619b..ea6c80747040e 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -5,6 +5,8 @@ * Snapshots WordPress and PHP process state at: * class_start (before setUpBeforeClass), test_start (before setUp), * test_end (after tearDown), class_end (after tearDownAfterClass). + * A test_start right after its class's previous test_end holds no state and "reuse": true, + * as nothing runs between them. * In a process-isolated test's child process, test_start and test_end wrap the whole * child, class hooks included, and snapshot only the areas that outlive it. * @@ -147,6 +149,9 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private $class_start = null; + // The class of the last test_end, until the next test starts. + private $ended = null; + private $columns = array(); private $primary = array(); @@ -529,16 +534,28 @@ public function start_test( $test ) { putenv( self::ENV_TEST . '=' . $name ); putenv( self::ENV_FILE . '=' . ( new ReflectionClass( $test ) )->getFileName() ); - $plan = $this->plan( get_class( $test ) ); - if ( self::SCOPE_CLASS !== $this->scope && $plan ) { - $this->write( 'test_start', $name, $plan ); + $class = get_class( $test ); + $reuse = $class === $this->ended; + $this->ended = null; + + $plan = $this->plan( $class ); + 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 = get_class( $test ); } } diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 05505b841c9bd..fb5abdac80a18 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -124,6 +124,7 @@ function class_starts( $file, $id ) { $orphans = 0; $open = array(); $changes = false; +$ended = array(); foreach ( $snaps as $snap ) { ++$count; if ( 'class_leaks' === $snap['point'] ) { @@ -134,11 +135,19 @@ function class_starts( $file, $id ) { list( $kind, $edge ) = explode( '_', $snap['point'] ); $slot = $snap['pid'] . '|' . $kind . '|' . $snap['id']; + // A reused start is the pid's last test_end; with none, its end is an orphan. if ( 'start' === $edge ) { - $open[ $slot ] = $snap['state']; + $state = empty( $snap['reuse'] ) ? $snap['state'] : ( $ended[ $snap['pid'] ] ?? null ); + if ( null !== $state ) { + $open[ $slot ] = $state; + } continue; } + if ( 'test' === $kind && empty( $snap['child'] ) ) { + $ended[ $snap['pid'] ] = $snap['state']; + } + if ( ! isset( $open[ $slot ] ) ) { ++$orphans; continue; From f01e90020e8865cc76f400ee0d1f56f7e42dec3e Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 10:19:40 +0100 Subject: [PATCH 10/18] Build/Test Tools: Add a leak harness worked example Shows how narrowing WP_TESTS_LEAKS_AREAS to the hook a failing assertion depends on finds the class behind the r65746 test-order failure. --- tests/phpunit/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index bc35b69f20a77..640c9b8e525e9 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -51,6 +51,14 @@ node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www 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 ``` +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. 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: From f9241fac27b93a0d8fd0d07b51b9b3277fa5b87c Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 10:46:44 +0100 Subject: [PATCH 11/18] Build/Test Tools: Refuse a leak comparison with no prior class When the class compared is the first in the sequence run, every difference counts as run noise, so diff.php printed nothing and exited 0, which reads as no order dependency. Exit 1 instead, and document that comparison mode reads runs only up to the class start, and that --filter keeps file order. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/diff.php | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 640c9b8e525e9..3f780958f1ac2 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -43,7 +43,7 @@ To sweep the whole suite, use the `class` scope: it snapshots at class bounds on 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 class ran, e.g. timestamps, are run noise and left out: +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 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 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 diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index fb5abdac80a18..d4b055afe3539 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -81,7 +81,7 @@ function report( $title, array $lines ) { return true; } -// The first class_start and the class ID's. +// The first class_start's state and id, and the class ID's state. function class_starts( $file, $id ) { $first = null; foreach ( load( $file ) as $snap ) { @@ -89,9 +89,9 @@ function class_starts( $file, $id ) { continue; } - $first = $first ?? $snap['state']; + $first = $first ?? $snap; if ( $snap['id'] === $id ) { - return array( $first, $snap['state'] ); + return array( $first['state'], $first['id'], $snap['state'] ); } } @@ -100,8 +100,14 @@ function class_starts( $file, $id ) { } if ( 4 === $argc ) { - list( $first_a, $a ) = class_starts( $argv[1], $argv[3] ); - list( $first_b, $b ) = class_starts( $argv[2], $argv[3] ); + list( $first_a, , $a ) = class_starts( $argv[1], $argv[3] ); + list( $first_b, $first_id, $b ) = class_starts( $argv[2], $argv[3] ); + + // Its own start would be all noise: nothing to report. + if ( $argv[3] === $first_id ) { + fwrite( STDERR, "{$argv[3]} is the first class in {$argv[2]}: nothing ran before it.\n" ); + exit( 1 ); + } $noise = array(); foreach ( array_intersect_key( $first_a, $first_b ) as $key => $value ) { From 2906d2041f1718a822277d0fcf089f9149abc206 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 10:57:38 +0100 Subject: [PATCH 12/18] Build/Test Tools: Skip stale entries a leak test drops A stale cached option the previous test left is gone after the next test's set_up() cache flush, so diff.php blamed it on that test as 'after: (absent)'. A stale entry gone means the cache agrees with the database again: not a leak, like a dropped cache entry. --- tests/phpunit/leaks/check-probes.php | 2 ++ tests/phpunit/leaks/diff.php | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 065db8382af4f..38d5a796de2f7 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -102,6 +102,8 @@ '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 other constants. 'test Tests_Leak_Probe::test_leaks_constant' => '/^const\|(?!LEAK_PROBE_CONSTANT$)/', + // 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)$/', // Dropped by a rules.php pattern. 'test Tests_Leak_Probe::test_leaks_filtered_globals' => '/^global\|leak_probe_filtered_dropped$/', ); diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index d4b055afe3539..60cfcb035600d 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -16,8 +16,9 @@ const USAGE = "Usage: php diff.php run.jsonl\n php diff.php a.jsonl b.jsonl ClassName\n"; -// A dropped cache entry is a miss, which reads the source again: not a leak, e.g. the test framework's flushes. -const CACHE_AREAS = '/^(cache|mc)\|/'; +// A dropped cache entry is a miss, which reads the source again, and a stale one gone agrees with it: not a leak, +// e.g. the test framework's flushes. +const CACHE_AREAS = '/^(cache|mc|stale)\|/'; // Yields one snapshot at a time: a full run's file can exceed the memory limit. Returns the unreadable line count. function load( $file ) { From 9a029c21afe446757e362467fb5222bb50d847b8 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 11:10:35 +0100 Subject: [PATCH 13/18] Build/Test Tools: Drop the isolated child snapshots PHPUnit 9 calls the parent listener's startTest and endTest around an isolated test's child process, and the parent's end snapshot sees what the child committed: the database, files and memcached. The child's own snapshot, limited to those areas, reported a subset of the parent's, so remove it and the environment it needed. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/bootstrap.php | 5 -- tests/phpunit/leaks/check-probes.php | 20 +------ .../leaks/class-wp-phpunit-leak-listener.php | 55 +------------------ tests/phpunit/leaks/diff.php | 5 +- tests/phpunit/leaks/probe/leakProbe.php | 2 +- .../leaks/probe/leakProbeChildSkipped.php | 16 ------ tests/phpunit/leaks/rules.php | 1 - 8 files changed, 9 insertions(+), 97 deletions(-) delete mode 100644 tests/phpunit/leaks/probe/leakProbeChildSkipped.php diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 3f780958f1ac2..e771fbf1edca2 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -26,7 +26,7 @@ Look for `PHPUnit Tests (full matrix)` in GitHub Actions and the PHPUnit checks 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 child process is snapshotted too, if the test has `@preserveGlobalState disabled` as core's do: only the state that outlives it (database, files, memcached, stale memcached options). It needs PHPUnit 9 or earlier: PHPUnit 10 removed test listeners. +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: diff --git a/tests/phpunit/leaks/bootstrap.php b/tests/phpunit/leaks/bootstrap.php index b8d224b8abe59..c55cbe282a537 100644 --- a/tests/phpunit/leaks/bootstrap.php +++ b/tests/phpunit/leaks/bootstrap.php @@ -42,8 +42,3 @@ require dirname( __DIR__ ) . '/includes/bootstrap.php'; require_once __DIR__ . '/class-wp-phpunit-leak-listener.php'; - -// A process-isolated test's child process loads this bootstrap but no listeners. -if ( isset( $GLOBALS['__PHPUNIT_BOOTSTRAP'] ) ) { - ( new WP_PHPUnit_Leak_Listener() )->watch_child(); -} diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 38d5a796de2f7..1cc5730fc11ca 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -43,7 +43,7 @@ '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 (isolated child)' => array( '/^db\|\w+links\|\d+$/' ), + '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$/' ), ); @@ -90,11 +90,6 @@ '/^stale\|memcached\|(?!1\|)\d+\|options\|leak_probe_cached_only$/', ); -// An isolated child's report holds only these, see OUTLIVES_PROCESS in the listener. -const CHILD_AREAS = '/^(db|schema|mc|file|stale\|memcached)\|/'; - -const CHILD_SUFFIX = ' (isolated child)'; - // 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)\|/', @@ -104,6 +99,8 @@ 'test Tests_Leak_Probe::test_leaks_constant' => '/^const\|(?!LEAK_PROBE_CONSTANT$)/', // 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$/', ); @@ -224,17 +221,6 @@ function snapshotted( $file, $class_name ) { } } -foreach ( $reported as $title => $keys ) { - // No str_ends_with() before PHP 8. - if ( substr( $title, -strlen( CHILD_SUFFIX ) ) !== CHILD_SUFFIX ) { - continue; - } - - foreach ( preg_grep( CHILD_AREAS, $keys, PREG_GREP_INVERT ) 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"; diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index ea6c80747040e..45b5d7384b11a 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -7,8 +7,6 @@ * test_end (after tearDown), class_end (after tearDownAfterClass). * A test_start right after its class's previous test_end holds no state and "reuse": true, * as nothing runs between them. - * In a process-isolated test's child process, test_start and test_end wrap the whole - * child, class hooks included, and snapshot only the areas that outlive it. * * Each snapshot is a flat map "area|key" => [hash, preview], appended as one JSON line * to WP_TESTS_LEAKS_OUT. diff.php compares snapshots. @@ -114,19 +112,9 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // 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, and the test name handed to an isolated child. + // The listener's own environment: its settings. private const ENV_PREFIX = 'WP_TESTS_LEAKS_'; - private const ENV_TEST = 'WP_TESTS_LEAKS_TEST'; - - // The child loads the test file after the bootstrap, where it plans. - private const ENV_FILE = 'WP_TESTS_LEAKS_FILE'; - - // Those an isolated child leaves its parent and later runs: not the in-process caches' stale|runtime and stale|local. - private const OUTLIVES_PROCESS = '/^(db|schema|mc|file|stale\|memcached)\|/'; - - private const CHILD_AREAS = array( 'db', 'schema', 'mc', 'file', 'stale' ); - private $out; private $scope; @@ -142,8 +130,6 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // Test file => plan, see plan(). private $plans = array(); - private $child = false; - // WP_TESTS_LEAKS_SCOPE=class: the state at the run start and at the running class start. private $installed = null; @@ -193,10 +179,6 @@ public function __construct( array $settings = array() ) { $this->rules_file = $this->absolute( $this->setting( 'RULES', $settings['rules'] ?? self::RULES ) ); $this->load_rules(); - // An isolated child inherits the environment, not the listener's arguments. - putenv( self::ENV_PREFIX . "SCOPE=$this->scope" ); - putenv( self::ENV_PREFIX . "RULES=$this->rules_file" ); - // 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 ); } @@ -425,30 +407,6 @@ private function kept( $key, array $patterns ) { return false; } - /** - * Snapshots this process-isolated child process, from now to its shutdown. - */ - public function watch_child() { - $id = getenv( self::ENV_TEST ); - $plan = array_intersect_key( $this->file_plan( (string) getenv( self::ENV_FILE ) ), array_flip( self::CHILD_AREAS ) ); - if ( self::SCOPE_CLASS === $this->scope || ! $plan ) { - return; - } - - $this->child = true; - - $this->write( 'test_start', $id, $plan ); - register_shutdown_function( - function () use ( $id, $plan ) { - global $wpdb; - - // A child that died mid-test left its transaction open: the snapshot's COMMIT would keep it. - $wpdb->query( 'ROLLBACK' ); - $this->write( 'test_end', $id, $plan ); - } - ); - } - public function track_temp_tables( $query ) { $this->sync_connection(); @@ -528,12 +486,7 @@ private function end_class( $class_name ) { } public function start_test( $test ) { - $name = $this->name( $test ); - - // An isolated child inherits the environment. - putenv( self::ENV_TEST . '=' . $name ); - putenv( self::ENV_FILE . '=' . ( new ReflectionClass( $test ) )->getFileName() ); - + $name = $this->name( $test ); $class = get_class( $test ); $reuse = $class === $this->ended; $this->ended = null; @@ -570,7 +523,6 @@ private function write( $point, $id, array $plan ) { private function line( $point, $id, array $state ) { return array( 'pid' => getmypid(), - 'child' => $this->child, 'point' => $point, 'id' => $id, 'state' => $state, @@ -652,9 +604,6 @@ private function state( array $plan ) { } $state = $this->filter( $state, $plan ); - if ( $this->child ) { - $state = array_intersect_key( $state, array_flip( preg_grep( self::OUTLIVES_PROCESS, array_keys( $state ) ) ) ); - } // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. $wpdb->query( 'COMMIT' ); diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 60cfcb035600d..e2a7c4aaac912 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -151,7 +151,7 @@ function class_starts( $file, $id ) { continue; } - if ( 'test' === $kind && empty( $snap['child'] ) ) { + if ( 'test' === $kind ) { $ended[ $snap['pid'] ] = $snap['state']; } @@ -160,8 +160,7 @@ function class_starts( $file, $id ) { continue; } - $where = empty( $snap['child'] ) ? '' : ' (isolated child)'; - $changes = report( "$kind {$snap['id']}$where leaves", compare( $open[ $slot ], $snap['state'] ) ) || $changes; + $changes = report( "$kind {$snap['id']} leaves", compare( $open[ $slot ], $snap['state'] ) ) || $changes; unset( $open[ $slot ] ); } diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index dab6ec9c57177..597952f3b6021 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -303,7 +303,7 @@ 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 too. + // Committed to a table no class cleanup resets, so the parent sees it. global $wpdb; $inserted = $wpdb->insert( $wpdb->links, diff --git a/tests/phpunit/leaks/probe/leakProbeChildSkipped.php b/tests/phpunit/leaks/probe/leakProbeChildSkipped.php deleted file mode 100644 index cbd4d0419d294..0000000000000 --- a/tests/phpunit/leaks/probe/leakProbeChildSkipped.php +++ /dev/null @@ -1,16 +0,0 @@ -assertTrue( true ); - } -} diff --git a/tests/phpunit/leaks/rules.php b/tests/phpunit/leaks/rules.php index 3972af3c11d7b..573f64a9eec50 100644 --- a/tests/phpunit/leaks/rules.php +++ b/tests/phpunit/leaks/rules.php @@ -57,7 +57,6 @@ 'why' => 'Leak probe: a file no pattern keeps is not snapshotted, see check-probes.php.', 'paths' => array( 'tests/phpunit/leaks/probe/leakProbeSkipped.php', - 'tests/phpunit/leaks/probe/leakProbeChildSkipped.php', ), 'areas' => array( '!*', From a2505846861510110ee138f8cbbf95f87308c679 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 11:28:54 +0100 Subject: [PATCH 14/18] Build/Test Tools: Tighten leak reuse checks Reset the reused test end at class end, so PHPUnit's --repeat does not reuse the previous pass's last test. Have check-probes.php catch a wrong reused start and a comparison that does not refuse the first class, and inline the plan helper the child removal left alone. --- tests/phpunit/README.md | 2 +- tests/phpunit/leaks/check-probes.php | 18 ++++++++++++++++-- .../leaks/class-wp-phpunit-leak-listener.php | 10 +++++----- tests/phpunit/leaks/diff.php | 10 +++++----- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index e771fbf1edca2..3453ada635369 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -43,7 +43,7 @@ To sweep the whole suite, use the `class` scope: it snapshots at class bounds on 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 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 class must run before it: `--filter` keeps file order, so use `--order-by=reverse` when the earlier class's file sorts after its: +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 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 class must run before it, else `diff.php` exits with 1: `--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 diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 1cc5730fc11ca..01137e106941e 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -95,8 +95,8 @@ '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 other constants. - 'test Tests_Leak_Probe::test_leaks_constant' => '/^const\|(?!LEAK_PROBE_CONSTANT$)/', + // 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$)/', // 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. @@ -113,6 +113,11 @@ // 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; + // Report header and changed key lines, see report() in diff.php. const HEADER = '/^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$/'; @@ -235,6 +240,15 @@ function snapshotted( $file, $class_name ) { $missed[] = SKIPPED_CLASS . ': snapshotted, but rules.php skips its file'; } +// The class scope writes no class_start. +if ( SCOPE_CLASS !== $setup['scope'] ) { + $file = escapeshellarg( $argv[1] ); + exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . " $file $file " . FIRST_CLASS . ' 2>&1', $refusal, $code ); + if ( DIFF_REFUSED !== $code || ! preg_grep( '/nothing ran before it/', $refusal ) ) { + $missed[] = FIRST_CLASS . ": comparison mode exited with $code, not refused as the first class"; + } +} + if ( $missed ) { fwrite( STDERR, "Missed or unexpected leaks:\n " . implode( "\n ", $missed ) . "\n" ); exit( 1 ); diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index 45b5d7384b11a..dd40df0e4f956 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -135,7 +135,7 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private $class_start = null; - // The class of the last test_end, until the next test starts. + // The class of the last test_end, until the next test starts or the class ends. private $ended = null; private $columns = array(); @@ -313,10 +313,7 @@ private function relative( $path ) { * all its keys, or its patterns, last first. Areas no pattern keeps are left out. */ private function plan( $class_name ) { - return $this->file_plan( class_exists( $class_name, false ) ? (string) ( new ReflectionClass( $class_name ) )->getFileName() : '' ); - } - - private function file_plan( $file ) { + $file = class_exists( $class_name, false ) ? (string) ( new ReflectionClass( $class_name ) )->getFileName() : ''; if ( isset( $this->plans[ $file ] ) ) { return $this->plans[ $file ]; } @@ -472,6 +469,9 @@ public function end_test_suite( $suite ) { } private function end_class( $class_name ) { + // PHPUnit's --repeat runs the class again. + $this->ended = null; + $plan = $this->plan( $class_name ); if ( ! $plan ) { return; diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index e2a7c4aaac912..3851808039a4c 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -131,7 +131,7 @@ function class_starts( $file, $id ) { $orphans = 0; $open = array(); $changes = false; -$ended = array(); +$ended = null; foreach ( $snaps as $snap ) { ++$count; if ( 'class_leaks' === $snap['point'] ) { @@ -140,11 +140,11 @@ function class_starts( $file, $id ) { } list( $kind, $edge ) = explode( '_', $snap['point'] ); - $slot = $snap['pid'] . '|' . $kind . '|' . $snap['id']; + $slot = $kind . '|' . $snap['id']; - // A reused start is the pid's last test_end; with none, its end is an orphan. + // 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[ $snap['pid'] ] ?? null ); + $state = empty( $snap['reuse'] ) ? $snap['state'] : $ended; if ( null !== $state ) { $open[ $slot ] = $state; } @@ -152,7 +152,7 @@ function class_starts( $file, $id ) { } if ( 'test' === $kind ) { - $ended[ $snap['pid'] ] = $snap['state']; + $ended = $snap['state']; } if ( ! isset( $open[ $slot ] ) ) { From 4d3cec75a21bad43faaa56ac789a174c7538d7d0 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 12:54:19 +0100 Subject: [PATCH 15/18] Build/Test Tools: Close leak harness test gaps Reuse a test end only until the class ends, the one guard the probe suite now pins. Warn on patterns that keep no key, and write no run_end when no snapshot kept one. Probe removed state, run noise and a cut run. Say "snapshotted class" where a skipped one cannot count. Drop the unused pid and a check that could not fail. --- tests/phpunit/README.md | 4 +- tests/phpunit/leaks/check-probes.php | 88 ++++++++++++++++--- .../leaks/class-wp-phpunit-leak-listener.php | 51 +++++++---- tests/phpunit/leaks/diff.php | 6 +- tests/phpunit/leaks/probe/leakProbe.php | 6 ++ 5 files changed, 124 insertions(+), 31 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index 3453ada635369..b20aa63760c4c 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -43,7 +43,7 @@ To sweep the whole suite, use the `class` scope: it snapshots at class bounds on 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 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 class must run before it, else `diff.php` exits with 1: `--filter` keeps file order, so use `--order-by=reverse` when the earlier class's file sorts after its: +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, else `diff.php` exits with 1: `--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 @@ -65,7 +65,7 @@ The leak configurations pass the listener its settings: `rules`, the rules file * `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. Takes shorthands: `all`, `persistent`, `database`, `caches`, `globals`, `statics`, `runtime`, `files`, e.g. `statics,globals` or `caches,!stale`. +* `WP_TESTS_LEAKS_AREAS`: comma-separated patterns replacing the scope's defaults in the rules file; its per-file rules still apply. The run lists on STDERR each pattern that kept no key, e.g. a typo. 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: diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 01137e106941e..0d51c48bc9408 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -34,6 +34,7 @@ '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$/' ), @@ -97,6 +98,8 @@ '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. @@ -105,11 +108,9 @@ 'test Tests_Leak_Probe::test_leaks_filtered_globals' => '/^global\|leak_probe_filtered_dropped$/', ); -// rules.php skips its file: no snapshot line names it, and no report blames its leak on another. +// rules.php skips its file: no snapshot line names it. const SKIPPED_CLASS = 'Tests_Leak_Probe_Skipped'; -const SKIPPED_LEAK = '/leak_probe_skipped/'; - // diff.php exits with 2 when it reports a leak, as every probe run must. const DIFF_LEAKS = 2; @@ -118,6 +119,13 @@ 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\)$/'; @@ -164,12 +172,56 @@ function snapshotted( $file, $class_name ) { 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 ); } -exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . ' ' . escapeshellarg( $argv[1] ), $output, $code ); +list( $code, $output ) = diff( array( $argv[1] ) ); if ( DIFF_LEAKS !== $code ) { fwrite( STDERR, "diff.php exited with $code, not " . DIFF_LEAKS . ".\n" ); exit( 1 ); @@ -230,10 +282,6 @@ function snapshotted( $file, $class_name ) { if ( false !== strpos( $title, SKIPPED_CLASS ) ) { $missed[] = "$title: reported, but rules.php skips its file"; } - - foreach ( preg_grep( SKIPPED_LEAK, $keys ) as $key ) { - $missed[] = "$title: unexpected $key"; - } } if ( snapshotted( $argv[1], SKIPPED_CLASS ) ) { @@ -242,13 +290,31 @@ function snapshotted( $file, $class_name ) { // The class scope writes no class_start. if ( SCOPE_CLASS !== $setup['scope'] ) { - $file = escapeshellarg( $argv[1] ); - exec( escapeshellarg( PHP_BINARY ) . ' ' . escapeshellarg( __DIR__ . '/diff.php' ) . " $file $file " . FIRST_CLASS . ' 2>&1', $refusal, $code ); - if ( DIFF_REFUSED !== $code || ! preg_grep( '/nothing ran before it/', $refusal ) ) { + 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 ); diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index dd40df0e4f956..d250228feb19c 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -135,8 +135,8 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private $class_start = null; - // The class of the last test_end, until the next test starts or the class ends. - private $ended = null; + // Whether the last snapshot was a test_end: the next test_start reuses it. + private $ended = false; private $columns = array(); @@ -153,9 +153,12 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // 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. + // Whether any snapshot kept a key: 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(); @@ -397,6 +400,7 @@ private function filter( array $state, array $plan ) { 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]; } } @@ -440,8 +444,6 @@ public function start_test_suite( $suite ) { return; } - $this->snapshotted = true; - if ( self::SCOPE_CLASS !== $this->scope ) { $this->write( 'class_start', $class_name, $plan ); return; @@ -459,18 +461,38 @@ public function end_test_suite( $suite ) { return; } + foreach ( $this->unmatched() as $glob ) { + fwrite( STDERR, "\"$glob\" kept no key: a typo, or nothing it names existed.\n" ); + } + // 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" ); + fwrite( STDERR, "No snapshot kept a key: nothing was snapshotted.\n" ); 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 ) { - // PHPUnit's --repeat runs the class again. - $this->ended = null; + // Class hooks run before the next test, this class's again with --repeat. + $this->ended = false; $plan = $this->plan( $class_name ); if ( ! $plan ) { @@ -487,11 +509,10 @@ private function end_class( $class_name ) { public function start_test( $test ) { $name = $this->name( $test ); - $class = get_class( $test ); - $reuse = $class === $this->ended; - $this->ended = null; + $reuse = $this->ended; + $this->ended = false; - $plan = $this->plan( $class ); + $plan = $this->plan( get_class( $test ) ); if ( self::SCOPE_CLASS === $this->scope || ! $plan ) { return; } @@ -508,7 +529,7 @@ 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 = get_class( $test ); + $this->ended = true; } } @@ -522,7 +543,6 @@ private function write( $point, $id, array $plan ) { private function line( $point, $id, array $state ) { return array( - 'pid' => getmypid(), 'point' => $point, 'id' => $id, 'state' => $state, @@ -603,7 +623,8 @@ private function state( array $plan ) { } } - $state = $this->filter( $state, $plan ); + $state = $this->filter( $state, $plan ); + $this->snapshotted = $this->snapshotted || $state; // Ends the snapshot's read view: its metadata locks would block e.g. a child's DDL. $wpdb->query( 'COMMIT' ); diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index 3851808039a4c..dc85c3e907785 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -8,7 +8,7 @@ * php diff.php alone.jsonl seq.jsonl ID State the class ID inherits: its class_start * in run A vs run B, minus run noise (timestamps, * env, install rows): keys both first class_starts, - * before any class ran, hold with different values. + * before any snapshotted class ran, hold with different values. * A key only one holds is its first class's rules. */ @@ -32,7 +32,7 @@ function load( $file ) { $line = fgets( $handle ); while ( false !== $line ) { $snap = json_decode( $line, true ); - if ( isset( $snap['pid'], $snap['point'], $snap['id'], $snap['state'] ) ) { + if ( isset( $snap['point'], $snap['id'], $snap['state'] ) ) { yield $snap; } else { ++$unreadable; @@ -106,7 +106,7 @@ function class_starts( $file, $id ) { // Its own start would be all noise: nothing to report. if ( $argv[3] === $first_id ) { - fwrite( STDERR, "{$argv[3]} is the first class in {$argv[2]}: nothing ran before it.\n" ); + fwrite( STDERR, "{$argv[3]} is the first class in {$argv[2]}: no snapshotted class ran before it.\n" ); exit( 1 ); } diff --git a/tests/phpunit/leaks/probe/leakProbe.php b/tests/phpunit/leaks/probe/leakProbe.php index 597952f3b6021..fc70ef66f4131 100644 --- a/tests/phpunit/leaks/probe/leakProbe.php +++ b/tests/phpunit/leaks/probe/leakProbe.php @@ -51,6 +51,7 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { $GLOBALS['leak_probe_big'] = range( 0, 2999 ); $GLOBALS['leak_probe_int'] = 1; + $GLOBALS['leak_probe_gone'] = 'original'; $GLOBALS['leak_probe_cb'] = function () { return 'original'; }; @@ -219,6 +220,11 @@ public function test_leaks_big_array_key() { $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 ); From c6622354076e1c22f6720cf10927b9c0981895bb Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 12:56:12 +0100 Subject: [PATCH 16/18] Build/Test Tools: Separate leak snapshot keys with / "|" means "or" in regexes and a pipe in shells, so patterns needed escaping and quoting. ":" and "::" already occur in cache keys and static property names. Only a key's first "/" is parsed, so one inside a key, e.g. a file path or a hook name, does not split it. --- tests/phpunit/README.md | 6 +- tests/phpunit/leaks/check-probes.php | 134 +++++++++--------- .../leaks/class-wp-phpunit-leak-listener.php | 101 ++++++------- tests/phpunit/leaks/diff.php | 2 +- tests/phpunit/leaks/rules.php | 48 +++---- 5 files changed, 146 insertions(+), 145 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index b20aa63760c4c..d182c0cfbe692 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -54,12 +54,12 @@ node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/di 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. 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' +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. +`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. +`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: diff --git a/tests/phpunit/leaks/check-probes.php b/tests/phpunit/leaks/check-probes.php index 0d51c48bc9408..34d7e0f870dfd 100644 --- a/tests/phpunit/leaks/check-probes.php +++ b/tests/phpunit/leaks/check-probes.php @@ -8,12 +8,12 @@ */ // Not site 1's. -const OTHER_SITE_ROW = '/^db\|\w+blogs\|(?!1$)\d+$/'; +const OTHER_SITE_ROW = '#^db/\w+blogs/(?!1$)\d+$#'; // Before PHP 8.1, a subclass has its own copy of an inherited method's static variables. -const PARENT_STATIC = '/^fstatic\|Leak_Probe_Counter::count\(\)\|\$calls$/'; +const PARENT_STATIC = '#^fstatic/Leak_Probe_Counter::count\(\)/\$calls$#'; -const CHILD_STATIC = '/^fstatic\|Leak_Probe_Counter_Child::count\(\)\|\$calls$/'; +const CHILD_STATIC = '#^fstatic/Leak_Probe_Counter_Child::count\(\)/\$calls$#'; const STATIC_TITLE = 'test Tests_Leak_Probe::test_leaks_function_static_var'; @@ -21,91 +21,91 @@ // Report title => 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$/' ), + '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$/' ), + '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$/', + '#^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$/', + '#^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$/', + '#^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$/', + '#^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)\|/', + '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$/', + '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$)/', + '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\|/', + '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)$/', + '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$/', + '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$/', + 'test Tests_Leak_Probe::test_leaks_filtered_globals' => '#^global/leak_probe_filtered_dropped$#', ); // rules.php skips its file: no snapshot line names it. @@ -122,14 +122,14 @@ 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 NOISE_KEY = 'global/leak_probe_noise'; -const INHERITED_KEY = 'global|leak_probe_inherited'; +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 HEADER = '#^== (.+) leaves(?:, unlike the install)? \(\d+ changed\)$#'; -const KEY_LINE = '/^ (\S.*)$/'; +const KEY_LINE = '#^ (\S.*)$#'; const SCOPE_CLASS = 'class'; @@ -307,7 +307,7 @@ function cut( $file ) { $cut = cut( $argv[1] ); list( $code, $incomplete ) = diff( array( $cut ) ); -if ( DIFF_INCOMPLETE !== $code || ! preg_grep( '/^Incomplete run/', $incomplete ) ) { +if ( DIFF_INCOMPLETE !== $code || ! preg_grep( '#^Incomplete run#', $incomplete ) ) { $missed[] = "run cut before run_end: diff.php exited with $code, not reported incomplete"; } diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index d250228feb19c..6fd30939c8a78 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -8,7 +8,7 @@ * A test_start right after its class's previous test_end holds no state and "reuse": true, * as nothing runs between them. * - * Each snapshot is a flat map "area|key" => [hash, preview], appended as one JSON line + * Each snapshot is a flat map "area/key" => [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 @@ -20,22 +20,22 @@ * 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] + * 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, + * 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 + * 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 { @@ -89,14 +89,14 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // 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|*' ), + '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. @@ -235,7 +235,7 @@ private function load_rules() { } } - // Entries to [negated, glob, whole area]: aliases expanded, a bare area name as "area|*". + // 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." ); @@ -250,10 +250,10 @@ private function patterns( $entries, $where ) { $negated = '!' === $entry[0]; $name = $negated ? substr( $entry, 1 ) : $entry; - $globs = self::ALIASES[ $name ] ?? array( str_contains( $name, '|' ) ? $name : "$name|*" ); + $globs = self::ALIASES[ $name ] ?? array( str_contains( $name, '/' ) ? $name : "$name/*" ); foreach ( $globs as $glob ) { - list( $area, $key ) = explode( '|', $glob, 2 ); + list( $area, $key ) = explode( '/', $glob, 2 ); if ( ! $this->areas_matching( $area ) ) { $this->fail( "$where: \"$entry\" matches no area: " . implode( ', ', $this->areas() ) . '.' ); } @@ -348,7 +348,7 @@ private function plan_for( array $patterns ) { foreach ( $this->areas() as $area ) { $last = array(); foreach ( array_reverse( $patterns ) as $pattern ) { - if ( ! fnmatch( strstr( $pattern[1], '|', true ), $area, FNM_NOESCAPE ) ) { + if ( ! fnmatch( strstr( $pattern[1], '/', true ), $area, FNM_NOESCAPE ) ) { continue; } @@ -387,7 +387,7 @@ private function union_plan() { private function filter( array $state, array $plan ) { $kept = array(); foreach ( $state as $key => $entry ) { - $area = $plan[ strstr( $key, '|', true ) ] ?? null; + $area = $plan[ strstr( $key, '/', true ) ] ?? null; if ( true === $area || ( $area && $this->kept( $key, $area ) ) ) { $kept[ $key ] = $entry; } @@ -672,9 +672,9 @@ private function db() { $this->check_query( $table ); $schema = preg_replace( self::AUTO_INCREMENT, '', $create ); - $state[ "schema|$table" ] = $this->text( $schema ); + $state[ "schema/$table" ] = $this->text( $schema ); if ( preg_match( self::AUTO_INCREMENT, $create, $m ) ) { - $state[ "autoinc|$table" ] = $this->text( $m[1] ); + $state[ "autoinc/$table" ] = $this->text( $m[1] ); } // Keyed by the schema, so a test's DDL refreshes them. @@ -714,18 +714,18 @@ private function db() { $this->check_query( $table ); foreach ( (array) $rows as $row ) { - $key = "db|$table|" . str_replace( "\x1f", ',', $row[0] ); + $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 ) ); + $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' ); + $state[ "temptable/$name" ] = $this->text( 'exists' ); } return $state; @@ -777,7 +777,7 @@ private function cache() { if ( isset( $wp_object_cache->m ) ) { foreach ( (array) $cache as $derived => $value ) { - $state[ "cache|$derived" ] = $this->entry( $value ); + $state[ "cache/$derived" ] = $this->entry( $value ); $state += $this->stale_derived( 'local', $derived, $value ); } @@ -788,7 +788,7 @@ private function cache() { foreach ( (array) $cache as $group => $entries ) { foreach ( (array) $entries as $id => $value ) { - $state[ "cache|$group|$id" ] = $this->entry( $value ); + $state[ "cache/$group/$id" ] = $this->entry( $value ); // Multisite prefixes non-global keys with ":". $blog = 1; @@ -858,7 +858,7 @@ private function memcached() { } foreach ( (array) $values as $key => $value ) { - $state[ "mc|$key" ] = $this->entry( $value ); + $state[ "mc/$key" ] = $this->entry( $value ); $state += $this->stale_derived( 'memcached', $key, $value ); } } @@ -884,7 +884,7 @@ private function stale_derived( $source, $derived, $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"; + $label = "stale/$source/$blog/$group/$key"; if ( 'options' === $group ) { $rows = $this->option_rows( $blog ); @@ -905,7 +905,7 @@ private function stale( $source, $blog, $group, $key, $value ) { 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 ); + $out[ "$label/$option" ] = $this->mismatch( $cached, $rows[ $option ] ?? null ); } } return $out; @@ -914,7 +914,7 @@ private function stale( $source, $blog, $group, $key, $value ) { 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 ] ); + $out[ "$label/$option" ] = $this->mismatch( '(cached as missing)', $rows[ $option ] ); } } return $out; @@ -1001,13 +1001,13 @@ private function globals() { 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 ); + $state[ "global/$name/$key" ] = $this->entry( $item ); } } continue; } - $state[ "global|$name" ] = $this->entry( $value ); + $state[ "global/$name" ] = $this->entry( $value ); } return $state; @@ -1038,7 +1038,7 @@ private function statics() { continue; } - $state[ "static|$class_name::\${$prop->getName()}" ] = $this->entry( $this->read( $prop ) ); + $state[ "static/$class_name::\${$prop->getName()}" ] = $this->entry( $this->read( $prop ) ); } } @@ -1077,7 +1077,7 @@ private function static_vars() { foreach ( $functions as $label => $ref ) { foreach ( $ref->getStaticVariables() as $var => $value ) { - $state[ "fstatic|$label|\$$var" ] = $this->entry( $value ); + $state[ "fstatic/$label/\$$var" ] = $this->entry( $value ); } } @@ -1088,7 +1088,7 @@ private function constants() { $state = array(); foreach ( get_defined_constants( true )['user'] ?? array() as $name => $value ) { - $state[ "const|$name" ] = $this->entry( $value ); + $state[ "const/$name" ] = $this->entry( $value ); } return $state; @@ -1099,12 +1099,12 @@ private function process() { $state = array(); foreach ( ini_get_all( null, false ) as $name => $value ) { - $state[ "ini|$name" ] = $this->text( (string) $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 ); + $state[ "env/$name" ] = $this->text( (string) $value ); } } @@ -1129,7 +1129,7 @@ private function process() { ); foreach ( $process as $what => $value ) { - $state[ "proc|$what" ] = $this->entry( $value ); + $state[ "proc/$what" ] = $this->entry( $value ); } return $state; @@ -1141,21 +1141,22 @@ private function files() { 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 ); + $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 ); + $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" ] ); + unset( $state[ 'file' . $own ] ); } return $state; diff --git a/tests/phpunit/leaks/diff.php b/tests/phpunit/leaks/diff.php index dc85c3e907785..17b89047ddba7 100644 --- a/tests/phpunit/leaks/diff.php +++ b/tests/phpunit/leaks/diff.php @@ -18,7 +18,7 @@ // A dropped cache entry is a miss, which reads the source again, and a stale one gone agrees with it: not a leak, // e.g. the test framework's flushes. -const CACHE_AREAS = '/^(cache|mc|stale)\|/'; +const CACHE_AREAS = '#^(cache|mc|stale)/#'; // Yields one snapshot at a time: a full run's file can exceed the memory limit. Returns the unreadable line count. function load( $file ) { diff --git a/tests/phpunit/leaks/rules.php b/tests/phpunit/leaks/rules.php index 573f64a9eec50..ca954613e9c11 100644 --- a/tests/phpunit/leaks/rules.php +++ b/tests/phpunit/leaks/rules.php @@ -2,7 +2,7 @@ /** * What WP_PHPUnit_Leak_Listener snapshots, see tests/phpunit/README.md. * - * Patterns are fnmatch() globs over snapshot keys, "area|key", without escapes. "!" negates. + * Patterns are fnmatch() globs over snapshot keys, "area/key", without escapes. "!" negates. * The last pattern matching a key decides. A bare area name means all its keys, e.g. "mc". * * 'areas' holds each scope's defaults; WP_TESTS_LEAKS_AREAS replaces them. A test file's @@ -12,22 +12,22 @@ return array( 'areas' => array( 'test' => array( - 'db|*', - 'dbcount|*', - 'autoinc|*', - 'schema|*', - 'temptable|*', - 'cache|*', - 'mc|*', - 'stale|*', - 'global|*', - 'static|*', - 'fstatic|*', - 'const|*', - 'ini|*', - 'env|*', - 'proc|*', - 'file|*', + '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 @@ -35,11 +35,11 @@ * connection can't see them. */ 'class' => array( - 'db|*', - 'schema|*', - 'mc|*', - 'file|*', - 'stale|*', + 'db/*', + 'schema/*', + 'mc/*', + 'file/*', + 'stale/*', ), ), 'files' => array( @@ -49,8 +49,8 @@ 'tests/phpunit/leaks/probe/leakProbe.php', ), 'areas' => array( - '!global|leak_probe_filtered_*', - 'global|leak_probe_filtered_kept', + '!global/leak_probe_filtered_*', + 'global/leak_probe_filtered_kept', ), ), array( From 888c2d91fab543fce9977077c1d6d67134182af0 Mon Sep 17 00:00:00 2001 From: Luca Tumedei Date: Wed, 25 Nov 2026 13:14:21 +0100 Subject: [PATCH 17/18] Build/Test Tools: End a leak run on its plans again e37929524b ended a run only when a snapshot kept a key: a clean run over stale or temporary tables read as incomplete, and the class scope's install snapshot ended a run no class was snapshotted in. End it when a class's plan kept an area, unless a pattern kept no key. Write keys with unescaped slashes, and say which checkout the README example needs. --- tests/phpunit/README.md | 4 ++-- .../leaks/class-wp-phpunit-leak-listener.php | 22 ++++++++++++------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index d182c0cfbe692..cc7971af72874 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -51,7 +51,7 @@ node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www 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 ``` -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. A sweep over the hook that should have filtered them names one class, instead of hundreds of global differences: +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' @@ -65,7 +65,7 @@ The leak configurations pass the listener its settings: `rules`, the rules file * `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. The run lists on STDERR each pattern that kept no key, e.g. a typo. Takes shorthands: `all`, `persistent`, `database`, `caches`, `globals`, `statics`, `runtime`, `files`, e.g. `statics,globals` or `caches,!stale`. +* `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: diff --git a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php index 6fd30939c8a78..70a2ff842cb90 100644 --- a/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php +++ b/tests/phpunit/leaks/class-wp-phpunit-leak-listener.php @@ -104,7 +104,7 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { private const SKIP_DIRS = array( 'data', 'build' ); - private const JSON_FLAGS = JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + 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+)/'; @@ -153,7 +153,7 @@ class WP_PHPUnit_Leak_Listener implements PHPUnit\Framework\TestListener { // Suites started and not ended: the run starts at the first and ends with it. private $open_suites = 0; - // Whether any snapshot kept a key: else diff.php would read the run as clean. + // 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(). @@ -444,6 +444,8 @@ public function start_test_suite( $suite ) { return; } + $this->snapshotted = true; + if ( self::SCOPE_CLASS !== $this->scope ) { $this->write( 'class_start', $class_name, $plan ); return; @@ -461,13 +463,18 @@ public function end_test_suite( $suite ) { return; } - foreach ( $this->unmatched() as $glob ) { + // 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" ); } - // With no run_end, diff.php reports the run as incomplete. - if ( ! $this->snapshotted ) { - fwrite( STDERR, "No snapshot kept a key: nothing was snapshotted.\n" ); + if ( $unmatched ) { return; } @@ -623,8 +630,7 @@ private function state( array $plan ) { } } - $state = $this->filter( $state, $plan ); - $this->snapshotted = $this->snapshotted || $state; + $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' ); From 7b47ede18497248a2c0f5cbbbb353975edd731cc Mon Sep 17 00:00:00 2001 From: andreivrabielucian-dev Date: Thu, 26 Nov 2026 08:32:29 +0200 Subject: [PATCH 18/18] Tests: Document leak comparison exit codes Describe the exit codes for differences, no differences, and missing or unusable class-start snapshots. Verified five comparison cases with PHP 8.1. Drafting and local verification were assisted by Codex. --- tests/phpunit/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/README.md b/tests/phpunit/README.md index cc7971af72874..c0ce694b9a93f 100644 --- a/tests/phpunit/README.md +++ b/tests/phpunit/README.md @@ -43,7 +43,7 @@ To sweep the whole suite, use the `class` scope: it snapshots at class bounds on 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, else `diff.php` exits with 1: `--filter` keeps file order, so use `--order-by=reverse` when the earlier class's file sorts after its: +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 @@ -51,6 +51,8 @@ node ./tools/local-env/scripts/docker.js run --rm -e WP_TESTS_LEAKS_OUT=/var/www 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: ```