From a491befb052b310d22746949bb4d7153b01887f9 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Thu, 23 Jul 2026 12:27:44 +0200 Subject: [PATCH 001/481] CSS API: Add CSS token processor foundations --- .../css-api/class-wp-css-builder.php | 261 + .../css-api/class-wp-css-token-processor.php | 1863 ++++++ src/wp-settings.php | 2 + .../phpunit/data/css-api/css-test-cases.json | 4988 +++++++++++++++++ tests/phpunit/tests/css-api/wpCssBuilder.php | 150 + .../tests/css-api/wpCssTokenProcessor.php | 2809 ++++++++++ 6 files changed, 10073 insertions(+) create mode 100644 src/wp-includes/css-api/class-wp-css-builder.php create mode 100644 src/wp-includes/css-api/class-wp-css-token-processor.php create mode 100644 tests/phpunit/data/css-api/css-test-cases.json create mode 100644 tests/phpunit/tests/css-api/wpCssBuilder.php create mode 100644 tests/phpunit/tests/css-api/wpCssTokenProcessor.php diff --git a/src/wp-includes/css-api/class-wp-css-builder.php b/src/wp-includes/css-api/class-wp-css-builder.php new file mode 100644 index 0000000000000..35250335da661 --- /dev/null +++ b/src/wp-includes/css-api/class-wp-css-builder.php @@ -0,0 +1,261 @@ += 0x80 ) { + $result .= $value[ $i ]; + continue; + } + + // ASCII letters and underscore: always valid in idents. + if ( + ( $byte >= 0x41 && $byte <= 0x5A ) || // A-Z + ( $byte >= 0x61 && $byte <= 0x7A ) || // a-z + 0x5F === $byte // _ + ) { + $result .= $value[ $i ]; + continue; + } + + // Hyphen: valid in idents, but check for hyphen-digit at start. + if ( 0x2D === $byte ) { + // Hyphen at position 0 followed by a digit at position 1: escape the digit. + if ( 0 === $i && $i + 1 < $length && ord( $value[ $i + 1 ] ) >= 0x30 && ord( $value[ $i + 1 ] ) <= 0x39 ) { + $result .= '-'; + ++$i; + $result .= sprintf( '\\%X ', ord( $value[ $i ] ) ); + continue; + } + $result .= '-'; + continue; + } + + // Digits: valid except at position 0. + if ( $byte >= 0x30 && $byte <= 0x39 ) { + if ( 0 === $i ) { + $result .= sprintf( '\\%X ', $byte ); + } else { + $result .= $value[ $i ]; + } + continue; + } + + // Everything else: hex-escape. + $result .= sprintf( '\\%X ', $byte ); + } + + return $result; + } + + /** + * Create a quoted CSS string from a plain PHP string value. + * + * Example: + * $value = 'CSS & a ""; + * + * CSS strings are quoted many characters that are problematic in HTML + * or may be complicated for rudimentary CSS or HTML processors to handle + * are encoded using Unicode escape sequences. + * + * @see https://www.w3.org/TR/css-syntax-3/#escaping + */ + public static function string( string $value ): string { + $value = wp_scrub_utf8( $value ); + $escaped = strtr( + $value, + array( + // Escape existing backslashes to prevent unintentional escapes in result. + '\\' => '\\5C ', + + // Pre-processing replaces NULLs and some newlines. Replace and escape as necessary. + "\0" => "\u{FFFD}", + + // Normalize and replace newlines. https://www.w3.org/TR/css-syntax-3/#input-preprocessing + "\r\n" => '\\A ', + "\r" => '\\A ', + "\f" => '\\A ', + + // Newlines must be escaped in CSS strings. + "\n" => '\\A ', + + // Arbitrary characters for Unicode escaping: + + // HTML syntax may be problematic. + '<' => '\\3C ', + '>' => '\\3E ', + '&' => '\\26 ', + + // CSS syntax may be problematic. + ',' => '\\2C ', + ';' => '\\3B ', + '{' => '\\7B ', + '}' => '\\7D ', + '"' => '\\22 ', + "'" => '\\27 ', + ) + ); + return "\"{$escaped}\""; + } + + public static function normalize_and_escape_css( string $css ): string { + $css = wp_scrub_utf8( $css ); + $processor = WP_CSS_Token_Processor::create( $css ); + if ( null === $processor ) { + return ''; + } + + $normalized_css = ''; + + while ( $processor->next_token() ) { + switch ( $processor->get_token_type() ) { + + // Basic punctuation: + case WP_CSS_Token_Processor::TOKEN_SEMICOLON: + $normalized_css .= ';'; + break; + case WP_CSS_Token_Processor::TOKEN_COMMA: + $normalized_css .= ','; + break; + case WP_CSS_Token_Processor::TOKEN_WHITESPACE: + $normalized_css .= ' '; + break; + case WP_CSS_Token_Processor::TOKEN_COLON: + $normalized_css .= ':'; + break; + + // Paired punctuation: + case WP_CSS_Token_Processor::TOKEN_LEFT_BRACE: + $normalized_css .= '{'; + break; + case WP_CSS_Token_Processor::TOKEN_RIGHT_BRACE: + $normalized_css .= '}'; + break; + case WP_CSS_Token_Processor::TOKEN_LEFT_PAREN: + $normalized_css .= '('; + break; + case WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN: + $normalized_css .= ')'; + break; + case WP_CSS_Token_Processor::TOKEN_LEFT_BRACKET: + $normalized_css .= '['; + break; + case WP_CSS_Token_Processor::TOKEN_RIGHT_BRACKET: + $normalized_css .= ']'; + break; + + // "@" + ident + case WP_CSS_Token_Processor::TOKEN_AT_KEYWORD: + $normalized_css .= '@' . self::ident( $processor->get_token_value() ); + break; + + // ident + "(" + case WP_CSS_Token_Processor::TOKEN_FUNCTION: + $normalized_css .= self::ident( $processor->get_token_value() ) . '('; + break; + + /* + * Hash tokens are not idents but their value can be escaped as such. + * + * ‖→ "#" →─┐ ┌──────────────────────────────┐ ┌─→‖ + * ├─→─┤ a-z A-Z 0-9 _ - or non-ASCII ├─→─┤ + * │ └──────────────────────────────┘ │ + * │ ┌──────────────────────────────┐ │ + * ├─→─┤ escape ├─→─┤ + * │ └──────────────────────────────┘ │ + * └──────────────────←───────────────────┘ + */ + case WP_CSS_Token_Processor::TOKEN_HASH: + $normalized_css .= '#' . self::ident( $processor->get_token_value() ); + break; + + case WP_CSS_Token_Processor::TOKEN_DIMENSION: + $normalized_css .= $processor->get_token_value() . $processor->get_token_unit(); + break; + + case WP_CSS_Token_Processor::TOKEN_PERCENTAGE: + $normalized_css .= "%{$processor->get_token_value()}"; + break; + + case WP_CSS_Token_Processor::TOKEN_NUMBER: + $normalized_css .= $processor->get_token_value(); + break; + + case WP_CSS_Token_Processor::TOKEN_DELIM: + $normalized_css .= $processor->get_token_value(); + break; + + case WP_CSS_Token_Processor::TOKEN_IDENT: + $normalized_css .= self::ident( $processor->get_token_value() ); + break; + + case WP_CSS_Token_Processor::TOKEN_STRING: + var_dump( $processor->get_token_value() ); + $normalized_css .= self::string( $processor->get_token_value() ); + break; + + // Keep or strip comments? + case WP_CSS_Token_Processor::TOKEN_COMMENT: + $normalized_css .= substr( $css, $processor->get_token_start(), $processor->get_token_length() ); + break; + + /** + * A is an open string that reaches a newline. + * + * @see https://www.w3.org/TR/css-syntax-3/#consume-string-token + * + * @see https://www.w3.org/TR/css-syntax-3/#preserved-tokens + * > Note: The tokens <}-token>s, <)-token>s, <]-token>, , and are always parse errors, but they are preserved in the token stream by this specification to allow other specs, such as Media Queries, to define more fine-grained error-handling than just dropping an entire declaration or block. + */ + case WP_CSS_Token_Processor::TOKEN_BAD_STRING: + $normalized_css .= substr( $css, $processor->get_token_start(), $processor->get_token_length() ) . "\n"; + break; + + case WP_CSS_Token_Processor::TOKEN_URL: + case WP_CSS_Token_Processor::TOKEN_BAD_URL: + case WP_CSS_Token_Processor::TOKEN_CDC: + case WP_CSS_Token_Processor::TOKEN_CDO: + default: + throw new Error( 'unhandled token type ' . $processor->get_token_type() . ' with value ' . var_export( $processor->get_token_value(), true ) ); + } + } + + return strtr( + $normalized_css, + array( + ' ' => '␠', + "\t" => "␉\t", + "\n" => "␊\n", + ) + ); + } +} diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php new file mode 100644 index 0000000000000..74c548dc1ec3a --- /dev/null +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -0,0 +1,1863 @@ + Replace any U+000D CARRIAGE RETURN (CR) code points, U+000C FORM FEED (FF) + * > code points, or pairs of U+000D CARRIAGE RETURN (CR) followed by U+000A LINE + * > FEED (LF) in input by a single U+000A LINE FEED (LF) code point. + * > Replace any U+0000 NULL or surrogate code points in input with U+FFFD REPLACEMENT + * > CHARACTER (�). + * + * This processor delays normalization as much as possible. That keeps the raw byte + * positions intact for accurate rewrites while still letting consumers ask for a + * normalized token when they need one. + * + * ### No EOF token + * + * The EOF token is a CSS parsing concept, not CSS tokenization concept. Therefore, + * this processor does not produce it. + * + * ### UTF-8 handling + * + * Only UTF-8 strings are supported. Invalid sequences are replaced with U+FFFD (�) + * using the maximal subpart approach described in + * https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf, section 3.9 Best Practices + * for Using U+FFFD. + * + * ## Usage + * + * Basic iteration: + * + * $css = 'width: 10px;'; + * $processor = WP_CSS_Token_Processor::create( $css ); + * while ( $processor->next_token() ) { + * echo $processor->get_normalized_token(); + * } + * // Outputs: + * // width: 10px; + * + * Rewriting a URL while keeping the rest of the stylesheet intact: + * + * $css = 'background: url(old.jpg) center / cover;'; + * $processor = WP_CSS_Token_Processor::create( $css ); + * while ( $processor->next_token() ) { + * if ( WP_CSS_Token_Processor::TOKEN_URL === $processor->get_token_type() ) { + * $processor->set_value( 'uploads/new.jpg' ); + * } + * } + * $result = $processor->get_updated_css(); + * // background: url(uploads/new.jpg) center / cover; + * + * Gathering diagnostics with byte offsets: + * + * $css = "color: red;\ncolor: re\nd;"; + * $processor = WP_CSS_Token_Processor::create( $css ); + * $bad_strings = array(); + * while ( $processor->next_token() ) { + * if ( WP_CSS_Token_Processor::TOKEN_BAD_STRING === $processor->get_token_type() ) { + * $bad_strings[] = array( + * 'start' => $processor->get_token_start(), + * 'length' => $processor->get_token_length(), + * 'value' => $processor->get_unnormalized_token(), + * ); + * } + * } + * + * @see https://www.w3.org/TR/css-syntax-3/#tokenization + */ +class WP_CSS_Token_Processor { + /** + * Token type constants matching the CSS Syntax Level 3 specification. + * + * @see https://www.w3.org/TR/css-syntax-3/#tokenization + */ + public const TOKEN_WHITESPACE = 'whitespace-token'; + public const TOKEN_COMMENT = 'comment'; + public const TOKEN_STRING = 'string-token'; + + /** + * BAD-STRING tokens occur when a string contains an unescaped newline. + * + * Valid strings: "hello", 'world', "line1\Aline2" (escaped newline) + * Invalid (produces bad-string): "hello + * world" (literal newline breaks the string) + * + * The processor stops at the newline and produces a bad-string token for error recovery. + * + * @see https://www.w3.org/TR/css-syntax-3/#typedef-bad-string-token + */ + public const TOKEN_BAD_STRING = 'bad-string-token'; + public const TOKEN_HASH = 'hash-token'; + public const HASH_TOKEN_ID = 'id'; + public const HASH_TOKEN_UNRESTRICTED = 'unrestricted'; + public const TOKEN_DELIM = 'delim-token'; + public const TOKEN_NUMBER = 'number-token'; + public const TOKEN_PERCENTAGE = 'percentage-token'; + public const TOKEN_DIMENSION = 'dimension-token'; + public const TOKEN_AT_KEYWORD = 'at-keyword-token'; + public const TOKEN_COLON = 'colon-token'; + public const TOKEN_SEMICOLON = 'semicolon-token'; + public const TOKEN_COMMA = 'comma-token'; + public const TOKEN_LEFT_PAREN = '(-token'; + public const TOKEN_RIGHT_PAREN = ')-token'; + public const TOKEN_LEFT_BRACKET = '[-token'; + public const TOKEN_RIGHT_BRACKET = ']-token'; + public const TOKEN_LEFT_BRACE = '{-token'; + public const TOKEN_RIGHT_BRACE = '}-token'; + public const TOKEN_FUNCTION = 'function-token'; + + /** + * URL tokens represent unquoted URLs in url() notation. + * + * For example, `url(image.jpg)` is a URL token. + * + * Quoted URLs like `url( "https://example.com" )` are handled as a function + * token, _not_ a URL token. + * + * Bad URL tokens are created when invalid characters are encountered in + * a URL token. + * + * @see https://www.w3.org/TR/css-syntax-3/#typedef-url-token + */ + public const TOKEN_URL = 'url-token'; + + /** + * BAD-URL tokens occur when a URL contains invalid characters. + * + * Invalid characters: quotes ("), apostrophes ('), parentheses (() + * Example invalid: url(image(.jpg) or url(image".jpg) + * + * When detected, the processor consumes everything up to ) or EOF. + * This prevents the bad URL from breaking subsequent tokens. + * + * @see https://www.w3.org/TR/css-syntax-3/#typedef-bad-url-token + */ + public const TOKEN_BAD_URL = 'bad-url-token'; + + /** + * Identifier tokens, such as `color`, `margin-top`, `red`, + * `inherit`, `--my-var`, `\x-escaped`, `über` (Unicode), etc. + * + * There are restrictions on the codepoints that start or are contained in + * an identifier, and identifiers may contain escape sequences. + * + * @see https://www.w3.org/TR/css-syntax-3/#typedef-ident-token + */ + public const TOKEN_IDENT = 'ident-token'; + + /** + * CDC (Comment Delimiter Close) token: --> + * + * Legacy token from when CSS was embedded in HTML + * + * Modern CSS no longer needs these, but they're preserved for compatibility. + * In stylesheets, they're typically treated like whitespace. + * + * @see https://www.w3.org/TR/css-syntax-3/#typedef-CDC-token + */ + public const TOKEN_CDC = 'CDC-token'; + + /** + * CDO (Comment Delimiter Open) token: ) + * + * Comment Delimiter Close - legacy HTML comment syntax in CSS. + * + * @see https://www.w3.org/TR/css-syntax-3/#CDC-token-diagram + */ + if ( + $this->at + 2 < $this->length && + '-' === $this->css[ $this->at + 1 ] && + '>' === $this->css[ $this->at + 2 ] + ) { + // Consume them and return a . + $this->at += 3; + $this->token_type = self::TOKEN_CDC; + $this->token_length = 3; + return true; + } + + // Otherwise, if the input stream starts with an ident sequence, + // reconsume the current input code point, consume an ident-like + // token, and return it. + if ( $this->check_if_3_code_points_start_an_ident_sequence( $this->at ) ) { + return $this->consume_ident_like(); + } + + // Otherwise, return a with its value set to the current input code point. + ++$this->at; + $this->token_type = self::TOKEN_DELIM; + $this->token_length = 1; + return true; + } + + /* + * U+003C LESS-THAN SIGN (<) + * If followed by !--, this is a CDO token (\n", + "tokens": [ + { + "type": "CDC-token", + "raw": "-->", + "startIndex": 0, + "endIndex": 3, + "normalized": "-->", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0001": { + "css": "foo\n", + "tokens": [ + { + "type": "ident-token", + "raw": "foo", + "startIndex": 0, + "endIndex": 3, + "normalized": "foo", + "value": "foo" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0002": { + "css": "--\n", + "tokens": [ + { + "type": "ident-token", + "raw": "--", + "startIndex": 0, + "endIndex": 2, + "normalized": "--", + "value": "--" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 2, + "endIndex": 3, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0003": { + "css": "--0\n", + "tokens": [ + { + "type": "ident-token", + "raw": "--0", + "startIndex": 0, + "endIndex": 3, + "normalized": "--0", + "value": "--0" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0004": { + "css": "-\\\n", + "tokens": [ + { + "type": "delim-token", + "raw": "-", + "startIndex": 0, + "endIndex": 1, + "normalized": "-", + "value": "-" + }, + { + "type": "delim-token", + "raw": "\\", + "startIndex": 1, + "endIndex": 2, + "normalized": "\\", + "value": "\\" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 2, + "endIndex": 3, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0005": { + "css": "-\\ \n", + "tokens": [ + { + "type": "ident-token", + "raw": "-\\ ", + "startIndex": 0, + "endIndex": 3, + "normalized": "- ", + "value": "- " + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0006": { + "css": "--💅\n", + "tokens": [ + { + "type": "ident-token", + "raw": "--💅", + "startIndex": 0, + "endIndex": 6, + "normalized": "--💅", + "value": "--💅" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 6, + "endIndex": 7, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0007": { + "css": "-§\n", + "tokens": [ + { + "type": "ident-token", + "raw": "-§", + "startIndex": 0, + "endIndex": 3, + "normalized": "-§", + "value": "-§" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0008": { + "css": "-×\n", + "tokens": [ + { + "type": "ident-token", + "raw": "-×", + "startIndex": 0, + "endIndex": 3, + "normalized": "-×", + "value": "-×" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 3, + "endIndex": 4, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident/0009": { + "css": "--a𐀀\n", + "tokens": [ + { + "type": "ident-token", + "raw": "--a𐀀", + "startIndex": 0, + "endIndex": 7, + "normalized": "--a𐀀", + "value": "--a𐀀" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 7, + "endIndex": 8, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0001": { + "css": "url(foo)\n", + "tokens": [ + { + "type": "url-token", + "raw": "url(foo)", + "startIndex": 0, + "endIndex": 8, + "normalized": "url(foo)", + "value": "foo" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 8, + "endIndex": 9, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0002": { + "css": "\\75 Rl(foo)\n", + "tokens": [ + { + "type": "url-token", + "raw": "\\75 Rl(foo)", + "startIndex": 0, + "endIndex": 11, + "normalized": "uRl(foo)", + "value": "foo" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 11, + "endIndex": 12, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0003": { + "css": "uR\\6c (foo)\n", + "tokens": [ + { + "type": "url-token", + "raw": "uR\\6c (foo)", + "startIndex": 0, + "endIndex": 11, + "normalized": "uRl(foo)", + "value": "foo" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 11, + "endIndex": 12, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0004": { + "css": "url('foo')\n", + "tokens": [ + { + "type": "function-token", + "raw": "url(", + "startIndex": 0, + "endIndex": 4, + "normalized": "url(", + "value": "url" + }, + { + "type": "string-token", + "raw": "'foo'", + "startIndex": 4, + "endIndex": 9, + "normalized": "'foo'", + "value": "foo" + }, + { + "type": ")-token", + "raw": ")", + "startIndex": 9, + "endIndex": 10, + "normalized": ")", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 10, + "endIndex": 11, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0005": { + "css": "url( 'foo')\n", + "tokens": [ + { + "type": "function-token", + "raw": "url(", + "startIndex": 0, + "endIndex": 4, + "normalized": "url(", + "value": "url" + }, + { + "type": "whitespace-token", + "raw": " ", + "startIndex": 4, + "endIndex": 5, + "normalized": " ", + "value": null + }, + { + "type": "string-token", + "raw": "'foo'", + "startIndex": 5, + "endIndex": 10, + "normalized": "'foo'", + "value": "foo" + }, + { + "type": ")-token", + "raw": ")", + "startIndex": 10, + "endIndex": 11, + "normalized": ")", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 11, + "endIndex": 12, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0006": { + "css": "url( 'foo')\n", + "tokens": [ + { + "type": "function-token", + "raw": "url(", + "startIndex": 0, + "endIndex": 4, + "normalized": "url(", + "value": "url" + }, + { + "type": "whitespace-token", + "raw": " ", + "startIndex": 4, + "endIndex": 6, + "normalized": " ", + "value": null + }, + { + "type": "string-token", + "raw": "'foo'", + "startIndex": 6, + "endIndex": 11, + "normalized": "'foo'", + "value": "foo" + }, + { + "type": ")-token", + "raw": ")", + "startIndex": 11, + "endIndex": 12, + "normalized": ")", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 12, + "endIndex": 13, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0007": { + "css": "url( 'foo')\n", + "tokens": [ + { + "type": "function-token", + "raw": "url(", + "startIndex": 0, + "endIndex": 4, + "normalized": "url(", + "value": "url" + }, + { + "type": "whitespace-token", + "raw": " ", + "startIndex": 4, + "endIndex": 7, + "normalized": " ", + "value": null + }, + { + "type": "string-token", + "raw": "'foo'", + "startIndex": 7, + "endIndex": 12, + "normalized": "'foo'", + "value": "foo" + }, + { + "type": ")-token", + "raw": ")", + "startIndex": 12, + "endIndex": 13, + "normalized": ")", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 13, + "endIndex": 14, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0008": { + "css": "not-url( 'foo')\n", + "tokens": [ + { + "type": "function-token", + "raw": "not-url(", + "startIndex": 0, + "endIndex": 8, + "normalized": "not-url(", + "value": "not-url" + }, + { + "type": "whitespace-token", + "raw": " ", + "startIndex": 8, + "endIndex": 11, + "normalized": " ", + "value": null + }, + { + "type": "string-token", + "raw": "'foo'", + "startIndex": 11, + "endIndex": 16, + "normalized": "'foo'", + "value": "foo" + }, + { + "type": ")-token", + "raw": ")", + "startIndex": 16, + "endIndex": 17, + "normalized": ")", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 17, + "endIndex": 18, + "normalized": "\n", + "value": null + } + ] + }, + "tests/ident-like/0009": { + "css": "url( foo)\n", + "tokens": [ + { + "type": "url-token", + "raw": "url( foo)", + "startIndex": 0, + "endIndex": 11, + "normalized": "url( foo)", + "value": "foo" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 11, + "endIndex": 12, + "normalized": "\n", + "value": null + } + ] + }, + "tests/left-curly-bracket/0001": { + "css": "{\n", + "tokens": [ + { + "type": "{-token", + "raw": "{", + "startIndex": 0, + "endIndex": 1, + "normalized": "{", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 1, + "endIndex": 2, + "normalized": "\n", + "value": null + } + ] + }, + "tests/left-parenthesis/0001": { + "css": "(\n", + "tokens": [ + { + "type": "(-token", + "raw": "(", + "startIndex": 0, + "endIndex": 1, + "normalized": "(", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 1, + "endIndex": 2, + "normalized": "\n", + "value": null + } + ] + }, + "tests/left-square-bracket/0001": { + "css": "[\n", + "tokens": [ + { + "type": "[-token", + "raw": "[", + "startIndex": 0, + "endIndex": 1, + "normalized": "[", + "value": null + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 1, + "endIndex": 2, + "normalized": "\n", + "value": null + } + ] + }, + "tests/less-than/0001": { + "css": "<\n", + "tokens": [ + { + "type": "delim-token", + "raw": "<", + "startIndex": 0, + "endIndex": 1, + "normalized": "<", + "value": "<" + }, + { + "type": "whitespace-token", + "raw": "\n", + "startIndex": 1, + "endIndex": 2, + "normalized": "\n", + "value": null + } + ] + }, + "tests/less-than/0002": { + "css": "', + WP_CSS_Token_Processor::TOKEN_BAD_STRING => "\"\n", + WP_CSS_Token_Processor::TOKEN_BAD_URL => 'url(()', + ); + + /** + * Closing token type of each token type that opens a block. + * + * @since 7.2.0 + * + * @var array + */ + private const BLOCK_CLOSERS = array( + WP_CSS_Token_Processor::TOKEN_FUNCTION => WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN, + WP_CSS_Token_Processor::TOKEN_LEFT_PAREN => WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN, + WP_CSS_Token_Processor::TOKEN_LEFT_BRACKET => WP_CSS_Token_Processor::TOKEN_RIGHT_BRACKET, + WP_CSS_Token_Processor::TOKEN_LEFT_BRACE => WP_CSS_Token_Processor::TOKEN_RIGHT_BRACE, + ); + + /** + * Serializes tokens as CSS text that reads as the same tokens. + * + * This follows CSS Syntax Level 3 §9 Serialization: + * + * > The only requirement for serialization is that it must "round-trip" with parsing, + * > that is, parsing the stylesheet must produce the same data structures as + * > parsing, serializing, and parsing again, + * > except for consecutive s, + * > which may be collapsed into a single token. + * + * Comment tokens are dropped. Each run of whitespace, including a run + * broken by comments, is written as one space; a run is never removed. + * + * Tokens are written from their decoded values. Identifiers, function + * names, at-keywords, hash names, dimension units, strings and url values + * are escaped again, so `\66 oo` becomes `foo` and `"a&b"` becomes `"a\26 b"`. + * + * > A containing U+005C REVERSE SOLIDUS (\) + * > must be serialized as U+005C REVERSE SOLIDUS + * > followed by a newline. + * > (The tokenizer only ever emits such a token followed by a + * > that starts with a newline.) + * + * > A with the "unrestricted" type flag may not need + * > as much escaping as the same token with the "id" type flag. + * + * A hash with the "id" flag is escaped as an identifier, so `#\31 a` stays + * `#\31 a`. A hash with the "unrestricted" flag may start with a digit or + * `-`, so `#1a` stays `#1a`. + * + * > The unit of a may need escaping + * > to disambiguate with scientific notation. + * + * A unit that starts with `e`, an optional `-`, and a digit has the `e` + * escaped, so the unit `e3` is written `1\65 3`, not `1e3`. + * + * > For any consecutive pair of tokens, + * > if the first token shows up in the row headings of the following table, + * > and the second token shows up in the column headings, + * > and there’s a ✗ in the cell denoted by the intersection of the chosen row and column, + * > the pair of tokens must be serialized with a comment between them. + * > + * > Single characters in the row and column headings represent a with that value, + * > except for "(", + * > which represents a (-token. + * + * ┌────────────┬───────┬──────────┬─────┬─────────┬───┬────────┬────────────┬───────────┬─────┬───┬───┬───┐ + * │ │ ident │ function │ url │ bad url │ - │ number │ percentage │ dimension │ CDC │ ( │ * │ % │ + * ├────────────┼───────┼──────────┼─────┼─────────┼───┼────────┼────────────┼───────────┼─────┼───┼───┼───┤ + * │ ident │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ + * │ at-keyword │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ + * │ hash │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ + * │ dimension │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ + * │ # │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ + * │ - │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ + * │ number │ ✗ │ ✗ │ ✗ │ ✗ │ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ ✗ │ + * │ @ │ ✗ │ ✗ │ ✗ │ ✗ │ ✗ │ │ │ │ ✗ │ │ │ │ + * │ . │ │ │ │ │ │ ✗ │ ✗ │ ✗ │ │ │ │ │ + * │ + │ │ │ │ │ │ ✗ │ ✗ │ ✗ │ │ │ │ │ + * │ / │ │ │ │ │ │ │ │ │ │ │ ✗ │ │ + * └────────────┴───────┴──────────┴─────┴─────────┴───┴────────┴────────────┴───────────┴─────┴───┴───┴───┘ + * + * Comments are not preserved, so an empty CSS comment is written between + * the tokens of a marked pair when no whitespace is between them. + * + * Bad-string and bad-url tokens have no value. A bad string is written as + * a quote followed by a newline, where the tokenizer ends one; a bad url is + * written as `url(()`. + * + * Strings and urls cut off by the end of the input are written closed. + * Blocks still open at the end are closed in reverse order, so `a(b[c` is + * written `a(b[c])`. + * + * Example: + * + * $processor = WP_CSS_Token_Processor::create( 'url( a&b ) calc(1px + 2px' ); + * $tokens = array(); + * while ( $processor->next_token() ) { + * $tokens[] = $processor->get_token(); + * } + * WP_CSS_Token_Serializer::serialize( $tokens ); // 'url(a\26 b) calc(1px + 2px)' + * + * @link https://www.w3.org/TR/css-syntax-3/#serialization + * + * @since 7.2.0 + * + * @param iterable $tokens Tokens read by WP_CSS_Token_Processor::get_token(). + * @return string CSS text. + */ + public static function serialize( iterable $tokens ): string { + $output = ''; + $closers = array(); + + // Pair key of the last token written, or the whitespace type after a space. + $last = null; + + foreach ( $tokens as $token ) { + $type = $token->get_type(); + + if ( WP_CSS_Token_Processor::TOKEN_COMMENT === $type ) { + continue; + } + + if ( WP_CSS_Token_Processor::TOKEN_WHITESPACE === $type ) { + if ( WP_CSS_Token_Processor::TOKEN_WHITESPACE !== $last ) { + $output .= ' '; + $last = WP_CSS_Token_Processor::TOKEN_WHITESPACE; + } + continue; + } + + $key = WP_CSS_Token_Processor::TOKEN_DELIM === $type ? $token->get_value() : $type; + if ( null !== $last && isset( self::MARKED_PAIRS[ $last ] ) && in_array( $key, self::MARKED_PAIRS[ $last ], true ) ) { + $output .= '/**/'; + } + $last = $key; + + $output .= self::serialize_token( $token ); + + if ( isset( self::BLOCK_CLOSERS[ $type ] ) ) { + $closers[] = self::BLOCK_CLOSERS[ $type ]; + } elseif ( end( $closers ) === $type ) { + array_pop( $closers ); + } + } + + while ( array() !== $closers ) { + $output .= self::FIXED_TEXT[ array_pop( $closers ) ]; + } + + return $output; + } + + /** + * Serializes one token other than whitespace or a comment. + * + * @since 7.2.0 + * + * @param WP_CSS_Token $token Token. + * @return string CSS text. + */ + private static function serialize_token( WP_CSS_Token $token ): string { + $value = $token->get_value(); + + switch ( $token->get_type() ) { + case WP_CSS_Token_Processor::TOKEN_IDENT: + return self::serialize_ident( $value ); + + case WP_CSS_Token_Processor::TOKEN_FUNCTION: + return self::serialize_ident( $value ) . '('; + + case WP_CSS_Token_Processor::TOKEN_AT_KEYWORD: + return '@' . self::serialize_ident( $value ); + + case WP_CSS_Token_Processor::TOKEN_HASH: + return WP_CSS_Token_Processor::HASH_TOKEN_ID === $token->get_flag() + ? '#' . self::serialize_ident( $value ) + : '#' . self::escape_name_code_points( $value ); + + case WP_CSS_Token_Processor::TOKEN_STRING: + return self::quote_string( $value ); + + case WP_CSS_Token_Processor::TOKEN_URL: + return 'url(' . self::serialize_url_value( $value ) . ')'; + + case WP_CSS_Token_Processor::TOKEN_NUMBER: + return $value; + + case WP_CSS_Token_Processor::TOKEN_PERCENTAGE: + return $value . '%'; + + case WP_CSS_Token_Processor::TOKEN_DIMENSION: + $unit = self::serialize_ident( $token->get_unit() ); + // A unit that starts with `e`, an optional `-`, and a digit would read as an exponent. + if ( 1 === preg_match( '/^[eE]-?[0-9]/', $unit ) ) { + $unit = sprintf( '\\%X ', ord( $unit[0] ) ) . substr( $unit, 1 ); + } + return $value . $unit; + + case WP_CSS_Token_Processor::TOKEN_DELIM: + return '\\' === $value ? "\\\n" : $value; + + default: + return self::FIXED_TEXT[ $token->get_type() ]; + } + } + /** * Serializes a plain PHP string as CSS identifier text. * @@ -118,40 +439,148 @@ public static function serialize_ident( string $value ): string { * @return string Serialized quoted CSS string text. */ public static function serialize_string( string $value ): string { + // Normalize newlines. https://www.w3.org/TR/css-syntax-3/#input-preprocessing + $value = strtr( + $value, + array( + "\r\n" => "\n", + "\r" => "\n", + "\f" => "\n", + ) + ); + + return self::quote_string( $value ); + } + + /** + * Creates a quoted CSS string from a decoded value without normalizing newlines. + * + * A CR or FF in a token value comes from an escape such as `\D `, so it is + * escaped, not written as a newline. + * + * @since 7.2.0 + * + * @param string $value Decoded string value to encode as a quoted CSS string. + * @return string Serialized quoted CSS string text. + */ + private static function quote_string( string $value ): string { $value = wp_scrub_utf8( $value ); $escaped = strtr( $value, array( // Escape existing backslashes to prevent unintentional escapes in result. - '\\' => '\\5C ', + '\\' => '\\5C ', - // Pre-processing replaces NULLs and some newlines. Replace and escape as necessary. - "\0" => "\u{FFFD}", - - // Normalize and replace newlines. https://www.w3.org/TR/css-syntax-3/#input-preprocessing - "\r\n" => '\\A ', - "\r" => '\\A ', - "\f" => '\\A ', + // Pre-processing replaces NULLs. Replace as necessary. + "\0" => "\u{FFFD}", // Newlines must be escaped in CSS strings. - "\n" => '\\A ', + "\n" => '\\A ', + "\r" => '\\D ', + "\f" => '\\C ', // Arbitrary characters for Unicode escaping: // HTML syntax may be problematic. - '<' => '\\3C ', - '>' => '\\3E ', - '&' => '\\26 ', + '<' => '\\3C ', + '>' => '\\3E ', + '&' => '\\26 ', // CSS syntax may be problematic. - ',' => '\\2C ', - ';' => '\\3B ', - '{' => '\\7B ', - '}' => '\\7D ', - '"' => '\\22 ', - "'" => '\\27 ', + ',' => '\\2C ', + ';' => '\\3B ', + '{' => '\\7B ', + '}' => '\\7D ', + '"' => '\\22 ', + "'" => '\\27 ', ) ); return "\"{$escaped}\""; } + + /** + * Escapes every code point that cannot appear in an identifier. + * + * Letters, digits, `-`, `_` and code points U+0080 and above are written + * as they are; every other code point is hex-escaped. Unlike + * serialize_ident(), a leading digit or `-` is not escaped, as the name of + * a hash token with the "unrestricted" flag requires. + * + * @since 7.2.0 + * + * @param string $value Decoded name. + * @return string Escaped name. + */ + private static function escape_name_code_points( string $value ): string { + $value = wp_scrub_utf8( $value ); + $result = ''; + $length = strlen( $value ); + + for ( $i = 0; $i < $length; $i++ ) { + $byte = ord( $value[ $i ] ); + + if ( 0x00 === $byte ) { + $result .= "\u{FFFD}"; + continue; + } + + if ( + $byte >= 0x80 || + ( $byte >= 0x30 && $byte <= 0x39 ) || // 0-9 + ( $byte >= 0x41 && $byte <= 0x5A ) || // A-Z + ( $byte >= 0x61 && $byte <= 0x7A ) || // a-z + 0x5F === $byte || // _ + 0x2D === $byte // - + ) { + $result .= $value[ $i ]; + continue; + } + + $result .= sprintf( '\\%X ', $byte ); + } + + return $result; + } + + /** + * Escapes the value of a url token. + * + * The code points an unquoted url cannot contain are hex-escaped: quotes, + * parentheses, `\`, whitespace and non-printable code points. So are the + * code points serialize_string() escapes for HTML and CSS: `< > & , ; { }`. + * + * @see https://www.w3.org/TR/css-syntax-3/#consume-url-token + * + * @since 7.2.0 + * + * @param string $value Decoded url value. + * @return string Escaped url value, without `url(` and `)`. + */ + private static function serialize_url_value( string $value ): string { + $value = wp_scrub_utf8( $value ); + $result = ''; + $length = strlen( $value ); + + for ( $i = 0; $i < $length; $i++ ) { + $byte = ord( $value[ $i ] ); + + if ( 0x00 === $byte ) { + $result .= "\u{FFFD}"; + continue; + } + + if ( + $byte <= 0x20 || + 0x7F === $byte || + false !== strpos( '"\'()\\<>&,;{}', $value[ $i ] ) + ) { + $result .= sprintf( '\\%X ', $byte ); + continue; + } + + $result .= $value[ $i ]; + } + + return $result; + } } diff --git a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php index 959d711df44af..016d4626a5a2a 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php +++ b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php @@ -177,4 +177,356 @@ public static function data_ident(): Generator { yield 'Semicolon' => array( 'a;b', 'a\\3B b' ); yield 'Backslash' => array( 'a\\b', 'a\\5C b' ); } + + /** + * Tests that serialize() writes an empty CSS comment between the tokens of a marked pair. + * + * @ticket 65738 + * @dataProvider data_marked_pairs + * + * @covers ::serialize + */ + public function test_marked_pair_is_separated_by_an_empty_comment( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + $this->assertSame( self::significant_tokens( $css ), self::significant_tokens( $expected ), 'The output must read as the same tokens.' ); + } + + /** + * Data provider for test_marked_pair_is_separated_by_an_empty_comment(). + * + * One case for each ✗ cell in the table in CSS Syntax Level 3 §9. + * + * @see https://www.w3.org/TR/css-syntax-3/#serialization + * + * @return Generator + */ + public static function data_marked_pairs(): Generator { + // Source text for the first token, keyed by its row heading. + $rows = array( + 'ident' => 'a', + 'at-keyword' => '@a', + 'hash' => '#a', + 'dimension' => '1px', + '#' => '#', + '-' => '-', + 'number' => '1', + '@' => '@', + '.' => '.', + '+' => '+', + '/' => '/', + ); + + // Source text and its serialization for the second token, keyed by its column heading. + $columns = array( + 'ident' => array( 'b', 'b' ), + 'function' => array( 'b()', 'b()' ), + 'url' => array( 'url(b)', 'url(b)' ), + 'bad url' => array( 'url(b c)', 'url(()' ), + '-' => array( '-', '-' ), + 'number' => array( '2', '2' ), + 'percentage' => array( '2%', '2%' ), + 'dimension' => array( '2px', '2px' ), + 'CDC' => array( '-->', '-->' ), + '(' => array( '()', '()' ), + '*' => array( '*', '*' ), + '%' => array( '%', '%' ), + ); + + $marked = array( + 'ident' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC', '(' ), + 'at-keyword' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC' ), + 'hash' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC' ), + 'dimension' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC' ), + '#' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC' ), + '-' => array( 'ident', 'function', 'url', 'bad url', '-', 'number', 'percentage', 'dimension', 'CDC' ), + 'number' => array( 'ident', 'function', 'url', 'bad url', 'number', 'percentage', 'dimension', 'CDC', '%' ), + '@' => array( 'ident', 'function', 'url', 'bad url', '-', 'CDC' ), + '.' => array( 'number', 'percentage', 'dimension' ), + '+' => array( 'number', 'percentage', 'dimension' ), + '/' => array( '*' ), + ); + + foreach ( $marked as $row => $row_columns ) { + foreach ( $row_columns as $column ) { + list( $column_css, $column_serialized ) = $columns[ $column ]; + yield "{$row} followed by {$column}" => array( + "{$rows[ $row ]}/**/{$column_css}", + "{$rows[ $row ]}/**/{$column_serialized}", + ); + } + } + } + + /** + * Tests that serialize() writes no comment between the tokens of an unmarked pair. + * + * @ticket 65738 + * @dataProvider data_unmarked_pairs + * + * @covers ::serialize + */ + public function test_unmarked_pair_is_not_separated( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + $this->assertSame( self::significant_tokens( $css ), self::significant_tokens( $expected ), 'The output must read as the same tokens.' ); + } + + /** + * Data provider for test_unmarked_pair_is_not_separated(). + * + * @return array[] + */ + public static function data_unmarked_pairs(): array { + return array( + 'ident followed by *' => array( 'a/**/*', 'a*' ), + 'ident followed by %' => array( 'a/**/%', 'a%' ), + 'ident followed by colon' => array( 'a/**/:', 'a:' ), + 'at-keyword followed by (' => array( '@a/**/()', '@a()' ), + 'hash followed by *' => array( '#a/**/*', '#a*' ), + 'dimension followed by %' => array( '1px/**/%', '1px%' ), + '# followed by %' => array( '#/**/%', '#%' ), + '- followed by *' => array( '-/**/*', '-*' ), + 'number followed by -' => array( '1/**/-', '1-' ), + 'number followed by (' => array( '1/**/()', '1()' ), + '@ followed by number' => array( '@/**/1', '@1' ), + '. followed by ident' => array( './**/a', '.a' ), + '+ followed by ident' => array( '+/**/a', '+a' ), + '/ followed by ident' => array( '//**/a', '/a' ), + 'string followed by ident' => array( '"a"/**/b', '"a"b' ), + 'url followed by ident' => array( 'url(a)/**/b', 'url(a)b' ), + 'function followed by ident' => array( 'a(/**/b)', 'a(b)' ), + ') followed by ident' => array( '(a)/**/b', '(a)b' ), + 'CDC followed by ident' => array( '-->/**/a', '-->a' ), + 'percentage followed by ident' => array( '1%/**/a', '1%a' ), + ); + } + + /** + * Tests that serialize() drops comments and writes each whitespace run as one space. + * + * @ticket 65738 + * @dataProvider data_whitespace_and_comments + * + * @covers ::serialize + */ + public function test_whitespace_and_comments( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + } + + /** + * Data provider for test_whitespace_and_comments(). + * + * @return array[] + */ + public static function data_whitespace_and_comments(): array { + return array( + 'empty input' => array( '', '' ), + 'one space' => array( 'a b', 'a b' ), + 'mixed whitespace run' => array( "a \t\r\n\f b", 'a b' ), + 'run broken by a comment' => array( 'a /* x */ b', 'a b' ), + 'whitespace then a comment' => array( 'a /**/b', 'a b' ), + 'a comment then whitespace' => array( 'a/**/ b', 'a b' ), + 'leading whitespace' => array( "\n a", ' a' ), + 'trailing whitespace' => array( "a \n", 'a ' ), + 'only whitespace' => array( "\t\n", ' ' ), + 'only a comment' => array( '/* x */', '' ), + 'comment in unmarked pair' => array( 'a/* x */,b', 'a,b' ), + 'unterminated comment' => array( 'a /* x', 'a ' ), + ); + } + + /** + * Tests how serialize() writes each token type. + * + * @ticket 65738 + * @dataProvider data_token_serialization + * + * @covers ::serialize + */ + public function test_token_serialization( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + $this->assertSame( self::significant_tokens( $css ), self::significant_tokens( $expected ), 'The output must read as the same tokens.' ); + } + + /** + * Data provider for test_token_serialization(). + * + * @return array[] + */ + public static function data_token_serialization(): array { + return array( + 'ident escapes decoded' => array( '\\66 oo', 'foo' ), + 'ident escapes added' => array( 'a\\:b', 'a\\3A b' ), + 'function' => array( '\\66 oo(1)', 'foo(1)' ), + 'at-keyword' => array( '@\\66 oo', '@foo' ), + 'hash id' => array( '#a\\:', '#a\\3A ' ), + 'hash id escaped digit' => array( '#\\31 a', '#\\31 a' ), + 'hash unrestricted' => array( '#1a', '#1a' ), + 'hash unrestricted escape' => array( '#1\\:', '#1\\3A ' ), + 'hash unrestricted hyphen' => array( '#-', '#-' ), + 'string' => array( "'a\"b'", '"a\\22 b"' ), + 'string ampersand' => array( '"a&b"', '"a\\26 b"' ), + 'string unterminated' => array( '"abc', '"abc"' ), + 'string escaped newline' => array( '"a\\A b"', '"a\\A b"' ), + 'string escaped carriage return' => array( '"a\\D b"', '"a\\D b"' ), + 'string escaped form feed' => array( '"a\\C b"', '"a\\C b"' ), + 'bad string' => array( "'a\nb", "\"\n b" ), + 'url' => array( 'url( a )', 'url(a)' ), + 'url empty' => array( 'url()', 'url()' ), + 'url escaped parenthesis' => array( 'url(a\\29 b)', 'url(a\\29 b)' ), + 'url escaped space' => array( 'url(a\\20 b)', 'url(a\\20 b)' ), + 'url escaped quote' => array( 'url(a\\"b)', 'url(a\\22 b)' ), + 'url escaped backslash' => array( 'url(a\\\\b)', 'url(a\\5C b)' ), + 'url escaped control' => array( 'url(a\\1 b)', 'url(a\\1 b)' ), + 'url escaped newline' => array( 'url(a\\A b)', 'url(a\\A b)' ), + 'url ampersand' => array( 'url(a&b)', 'url(a\\26 b)' ), + 'url NUL' => array( "url(a\x00b)", "url(a\u{FFFD}b)" ), + 'url unterminated' => array( 'url(a', 'url(a)' ), + 'url function with a string' => array( "url( 'a')", 'url( "a")' ), + 'bad url' => array( 'url(a b)', 'url(()' ), + 'number' => array( '+.5e-3', '+.5e-3' ), + 'percentage' => array( '-1.5%', '-1.5%' ), + 'dimension' => array( '1.5e3PX', '1.5e3PX' ), + 'dimension unit escape' => array( '1\\2D ', '1\\2D ' ), + 'dimension unit read as exponent' => array( '1\\65 3', '1\\65 3' ), + 'dimension unit read as signed exponent' => array( '1\\45 -3', '1\\45 -3' ), + 'dimension unit e' => array( '1e', '1e' ), + 'backslash delim keeps newline' => array( "a\\\nb", "a\\\n b" ), + 'delim' => array( '!', '!' ), + 'CDO and CDC' => array( '', '' ), + 'punctuation' => array( 'a:b;c,d', 'a:b;c,d' ), + ); + } + + /** + * Tests that serialize() closes blocks still open at the end, in reverse order. + * + * @ticket 65738 + * @dataProvider data_open_blocks + * + * @covers ::serialize + */ + public function test_open_blocks_are_closed( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + } + + /** + * Data provider for test_open_blocks_are_closed(). + * + * @return array[] + */ + public static function data_open_blocks(): array { + return array( + 'function' => array( 'calc(1px', 'calc(1px)' ), + 'nested blocks' => array( 'a(b[c{d', 'a(b[c{d}])' ), + 'closed block' => array( '(a)', '(a)' ), + 'mismatched closer' => array( '(]', '(])' ), + 'closer without a block' => array( ')', ')' ), + 'brace' => array( '{', '{}' ), + 'function with a string' => array( 'url("a"', 'url("a")' ), + 'inner block closed' => array( 'a((b)', 'a((b))' ), + ); + } + + /** + * Tests that the hash type flag is preserved. + * + * @ticket 65738 + * + * @covers ::serialize + */ + public function test_hash_flag_round_trips(): void { + foreach ( array( '#\\31 a', '#1a', '#a1', '#-1', '#--' ) as $css ) { + $tokens = self::tokenize( $css ); + $serialized = WP_CSS_Token_Serializer::serialize( $tokens ); + $reparsed = self::tokenize( $serialized ); + + $this->assertCount( 1, $reparsed, "{$css} must serialize as one token." ); + $this->assertSame( $tokens[0]->get_value(), $reparsed[0]->get_value(), "The value of {$css} changed." ); + $this->assertSame( $tokens[0]->get_flag(), $reparsed[0]->get_flag(), "The type flag of {$css} changed." ); + } + } + + /** + * Tests that serializing the corpus round-trips and is idempotent. + * + * The output must read as the input tokens, except that comments are dropped, + * whitespace runs are collapsed, and blocks still open are closed. + * + * @ticket 65738 + * @dataProvider data_corpus + * + * @covers ::serialize + */ + public function test_corpus_round_trips( string $css ): void { + $serialized = WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ); + + $expected = self::significant_tokens( $css ); + $actual = self::significant_tokens( $serialized ); + $closers = array_splice( $actual, count( $expected ) ); + + $this->assertSame( $expected, $actual, 'The output must read as the same tokens.' ); + foreach ( $closers as $closer ) { + $this->assertContains( + $closer[0], + array( WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN, WP_CSS_Token_Processor::TOKEN_RIGHT_BRACKET, WP_CSS_Token_Processor::TOKEN_RIGHT_BRACE ), + 'Only block closers may follow the input tokens.' + ); + } + $this->assertSame( $serialized, WP_CSS_Token_Serializer::serialize( self::tokenize( $serialized ) ), 'Serialization must be idempotent.' ); + } + + /** + * Data provider for test_corpus_round_trips(). + * + * @return array[] + */ + public static function data_corpus(): array { + $cases = json_decode( file_get_contents( DIR_TESTDATA . '/css-api/css-test-cases.json' ), true ); + return array_map( + static function ( array $test_case ): array { + return array( $test_case['css'] ); + }, + $cases + ); + } + + /** + * Tokenizes CSS. + * + * @param string $css CSS text. + * @return WP_CSS_Token[] Tokens. + */ + private static function tokenize( string $css ): array { + $processor = WP_CSS_Token_Processor::create( $css ); + $tokens = array(); + while ( $processor->next_token() ) { + $tokens[] = $processor->get_token(); + } + return $tokens; + } + + /** + * Tokenizes CSS for comparison: comments are dropped, and each run of + * whitespace and comments that includes whitespace is one whitespace token. + * + * @param string $css CSS text. + * @return array[] Type, flag, value and unit of each token. + */ + private static function significant_tokens( string $css ): array { + $tokens = array(); + foreach ( self::tokenize( $css ) as $token ) { + $type = $token->get_type(); + if ( WP_CSS_Token_Processor::TOKEN_COMMENT === $type ) { + continue; + } + if ( WP_CSS_Token_Processor::TOKEN_WHITESPACE === $type ) { + if ( array( $type ) !== end( $tokens ) ) { + $tokens[] = array( $type ); + } + continue; + } + $tokens[] = array( $type, $token->get_flag(), $token->get_value(), $token->get_unit() ); + } + return $tokens; + } } From 34588608d023eb82abf16dbc14b4aa69c6414b61 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Fri, 9 Oct 2026 20:34:10 +0400 Subject: [PATCH 016/481] Document why comment tokens are kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CSS Syntax 3 §9 allows a tokenizer to preserve comments when they have no effect on parsing. The processor emits them so callers can find comments by byte offset. --- .../css-api/class-wp-css-token-processor.php | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php index 87c8b022c74c9..1d9e2ad7b4246 100644 --- a/src/wp-includes/css-api/class-wp-css-token-processor.php +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -85,8 +85,21 @@ class WP_CSS_Token_Processor { * @see https://www.w3.org/TR/css-syntax-3/#tokenization */ public const TOKEN_WHITESPACE = 'whitespace-token'; - public const TOKEN_COMMENT = 'comment'; - public const TOKEN_STRING = 'string-token'; + + /** + * Comment tokens, such as `/* a *\/`. + * + * The specification's tokenizer produces no comment tokens. This processor + * does, so callers can find comments by their byte offsets. CSS Syntax + * Level 3 §9 allows this: + * + * > Implementations may preserve the contents of comments and their location in the token stream. + * > If they do, this preserved information must have no effect on the parsing step. + * + * @link https://www.w3.org/TR/css-syntax-3/#serialization + */ + public const TOKEN_COMMENT = 'comment'; + public const TOKEN_STRING = 'string-token'; /** * BAD-STRING tokens occur when a string contains an unescaped newline. From 47206d92f2f255db7a01c960e7f8e2a55ce2d973 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Fri, 9 Oct 2026 21:06:49 +0400 Subject: [PATCH 017/481] Escape CR and FF in strings instead of normalizing them serialize_string() replaced CR, CRLF and FF in its argument with LF, as if the argument were CSS source. Its output is escaped and never preprocessed, so the replacement changed the value: a string token written from "a\D b" read back with a newline. CR and FF are now written as \D and \C, so the string reads back as the same value; NULL still becomes U+FFFD. A caller that wants normalized line endings normalizes before calling. serialize() writes string tokens with serialize_string() again, and the private quote_string() is removed. --- .../css-api/class-wp-css-token-serializer.php | 32 +++----------- .../tests/css-api/wpCssTokenSerializer.php | 43 +++++-------------- 2 files changed, 16 insertions(+), 59 deletions(-) diff --git a/src/wp-includes/css-api/class-wp-css-token-serializer.php b/src/wp-includes/css-api/class-wp-css-token-serializer.php index ac4f4d23dc870..a49c7dac836c3 100644 --- a/src/wp-includes/css-api/class-wp-css-token-serializer.php +++ b/src/wp-includes/css-api/class-wp-css-token-serializer.php @@ -307,7 +307,7 @@ private static function serialize_token( WP_CSS_Token $token ): string { : '#' . self::escape_name_code_points( $value ); case WP_CSS_Token_Processor::TOKEN_STRING: - return self::quote_string( $value ); + return self::serialize_string( $value ); case WP_CSS_Token_Processor::TOKEN_URL: return 'url(' . self::serialize_url_value( $value ) . ')'; @@ -431,6 +431,9 @@ public static function serialize_ident( string $value ): string { * or may be complicated for rudimentary CSS or HTML processors to handle * are encoded using Unicode escape sequences. * + * The string reads back as the same value, except that NULL becomes U+FFFD. + * Line endings are not normalized: CR and FF are escaped as `\D ` and `\C `. + * * @see https://www.w3.org/TR/css-syntax-3/#escaping * * @since 7.2.0 @@ -439,31 +442,6 @@ public static function serialize_ident( string $value ): string { * @return string Serialized quoted CSS string text. */ public static function serialize_string( string $value ): string { - // Normalize newlines. https://www.w3.org/TR/css-syntax-3/#input-preprocessing - $value = strtr( - $value, - array( - "\r\n" => "\n", - "\r" => "\n", - "\f" => "\n", - ) - ); - - return self::quote_string( $value ); - } - - /** - * Creates a quoted CSS string from a decoded value without normalizing newlines. - * - * A CR or FF in a token value comes from an escape such as `\D `, so it is - * escaped, not written as a newline. - * - * @since 7.2.0 - * - * @param string $value Decoded string value to encode as a quoted CSS string. - * @return string Serialized quoted CSS string text. - */ - private static function quote_string( string $value ): string { $value = wp_scrub_utf8( $value ); $escaped = strtr( $value, @@ -471,7 +449,7 @@ private static function quote_string( string $value ): string { // Escape existing backslashes to prevent unintentional escapes in result. '\\' => '\\5C ', - // Pre-processing replaces NULLs. Replace as necessary. + // CSS cannot represent NULL; preprocessing replaces it with U+FFFD. "\0" => "\u{FFFD}", // Newlines must be escaped in CSS strings. diff --git a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php index 016d4626a5a2a..1bc1bd758cee0 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php +++ b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php @@ -16,27 +16,14 @@ class Tests_CssApi_WpCssTokenSerializer extends WP_UnitTestCase { public function test_string_escaping( string $input, string $expected ): void { $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize_string( $input ) ); - /** - * Ensure that a single, equivalent CSS string is produced. - * - * CSS pre-processing normalization is applied to the input to ensure - * a match can be found. - * - * @see https://www.w3.org/TR/css-syntax-3/#input-preprocessing + /* + * Ensure that a single CSS string with the same value is produced. + * CSS cannot represent NULL, which becomes U+FFFD. */ $processor = WP_CSS_Token_Processor::create( WP_CSS_Token_Serializer::serialize_string( $input ) ); $processor->next_token(); $this->assertSame( WP_CSS_Token_Processor::TOKEN_STRING, $processor->get_token_type() ); - $expected_decoded_value = strtr( - $input, - array( - "\r\n" => "\n", - "\r" => "\n", - "\f" => "\n", - "\0" => '�', - ) - ); - $this->assertSame( $expected_decoded_value, $processor->get_token_value() ); + $this->assertSame( str_replace( "\0", '�', $input ), $processor->get_token_value() ); $this->assertFalse( $processor->next_token() ); } @@ -64,11 +51,11 @@ public static function data_string_escaping(): array { // NULL byte → U+FFFD replacement character. 'null byte' => array( "a\0b", '"a�b"' ), - // Newline normalization — all variants become \A escape. + // Newlines are escaped as they are; CR and FF are not normalized to LF. 'LF' => array( "a\nb", '"a\A b"' ), - 'CR' => array( "a\rb", '"a\A b"' ), - 'CRLF as single escape' => array( "a\r\nb", '"a\A b"' ), - 'form feed' => array( "a\fb", '"a\A b"' ), + 'CR' => array( "a\rb", '"a\D b"' ), + 'CRLF' => array( "a\r\nb", '"a\D \A b"' ), + 'form feed' => array( "a\fb", '"a\C b"' ), // HTML-problematic characters. 'HTML characters < > &' => array( 'ac&d', '"a\3C b\3E c\26 d"' ), @@ -99,7 +86,7 @@ public function test_docblock_example(): void { */ public function test_mixed_newlines(): void { $input = "line1\nline2\rline3\r\nline4\fline5"; - $expected = '"line1\A line2\A line3\A line4\A line5"'; + $expected = '"line1\A line2\D line3\D \A line4\C line5"'; $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize_string( $input ) ); } @@ -126,16 +113,7 @@ public function test_ident( string $input, string $expected ): void { $this->assertTrue( $processor->next_token() ); $this->assertSame( WP_CSS_Token_Processor::TOKEN_IDENT, $processor->get_token_type() ); - $expected_decoded_value = strtr( - $input, - array( - "\r\n" => "\n", - "\r" => "\n", - "\f" => "\n", - "\0" => '�', - ) - ); - $this->assertSame( $expected_decoded_value, $processor->get_token_value() ); + $this->assertSame( str_replace( "\0", '�', $input ), $processor->get_token_value() ); $this->assertFalse( $processor->next_token() ); } @@ -167,6 +145,7 @@ public static function data_ident(): Generator { yield 'Multiple spaces within' => array( 'a b c', 'a\\20 b\\20 c' ); yield 'Tab within' => array( "has\ttab", 'has\\9 tab' ); yield 'Newline within' => array( "has\nnewline", 'has\\A newline' ); + yield 'Carriage return within' => array( "has\rreturn", 'has\\D return' ); yield 'NULL byte within' => array( "has\0null", 'has�null' ); yield 'DEL within' => array( "has\x7Fdelete", 'has\\7F delete' ); From 2626801d0766b35eeefd4332d1865b65c5f772e8 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Fri, 9 Oct 2026 21:07:32 +0400 Subject: [PATCH 018/481] Do not spell CDO or CDC from other tokens when serializing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CSS Syntax 3 §9 table compares token types in pairs. It misses two sequences that the tokenizer reads as a CDO or CDC token: `<`, `!` and a token that starts with `--` spell ``. So `` as `-->`. An empty comment is now written before the last token of each, so the output reads as the same tokens. --- .../css-api/class-wp-css-token-serializer.php | 33 ++++++++++++++--- .../tests/css-api/wpCssTokenSerializer.php | 37 +++++++++++++++++++ 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/src/wp-includes/css-api/class-wp-css-token-serializer.php b/src/wp-includes/css-api/class-wp-css-token-serializer.php index a49c7dac836c3..c4d4c780ba440 100644 --- a/src/wp-includes/css-api/class-wp-css-token-serializer.php +++ b/src/wp-includes/css-api/class-wp-css-token-serializer.php @@ -212,6 +212,12 @@ class WP_CSS_Token_Serializer { * Comments are not preserved, so an empty CSS comment is written between * the tokens of a marked pair when no whitespace is between them. * + * The table compares token types in pairs, so it misses two sequences that + * the tokenizer reads as a CDO or CDC token: `<`, `!` and a token that + * starts with `--`, which spell ``. An empty CSS comment is written before the last token + * of each. + * * Bad-string and bad-url tokens have no value. A bad string is written as * a quote followed by a newline, where the tokenizer ends one; a bad url is * written as `url(()`. @@ -243,6 +249,10 @@ public static function serialize( iterable $tokens ): string { // Pair key of the last token written, or the whitespace type after a space. $last = null; + // Text of the last two tokens written, or a space after whitespace. + $last_text = ''; + $before_last_text = ''; + foreach ( $tokens as $token ) { $type = $token->get_type(); @@ -252,19 +262,30 @@ public static function serialize( iterable $tokens ): string { if ( WP_CSS_Token_Processor::TOKEN_WHITESPACE === $type ) { if ( WP_CSS_Token_Processor::TOKEN_WHITESPACE !== $last ) { - $output .= ' '; - $last = WP_CSS_Token_Processor::TOKEN_WHITESPACE; + $output .= ' '; + $last = WP_CSS_Token_Processor::TOKEN_WHITESPACE; + $before_last_text = $last_text; + $last_text = ' '; } continue; } - $key = WP_CSS_Token_Processor::TOKEN_DELIM === $type ? $token->get_value() : $type; - if ( null !== $last && isset( self::MARKED_PAIRS[ $last ] ) && in_array( $key, self::MARKED_PAIRS[ $last ], true ) ) { + $key = WP_CSS_Token_Processor::TOKEN_DELIM === $type ? $token->get_value() : $type; + $text = self::serialize_token( $token ); + + if ( + ( null !== $last && isset( self::MARKED_PAIRS[ $last ] ) && in_array( $key, self::MARKED_PAIRS[ $last ], true ) ) || + // The table misses `<`, `!`, `--x`, which reads as ``. + ( '<' === $before_last_text && '!' === $last_text && 0 === strncmp( $text, '--', 2 ) ) || + ( '--' === $last_text && '>' === $text ) + ) { $output .= '/**/'; } - $last = $key; - $output .= self::serialize_token( $token ); + $output .= $text; + $last = $key; + $before_last_text = $last_text; + $last_text = $text; if ( isset( self::BLOCK_CLOSERS[ $type ] ) ) { $closers[] = self::BLOCK_CLOSERS[ $type ]; diff --git a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php index 1bc1bd758cee0..f4ce9281c9081 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php +++ b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php @@ -376,6 +376,43 @@ public static function data_token_serialization(): array { ); } + /** + * Tests that serialize() does not spell a CDO or CDC token from other tokens. + * + * The table in CSS Syntax Level 3 §9 compares token pairs by type. It does + * not cover `<`, `!` and a token that starts with `--`, which spell ``. + * + * @ticket 65738 + * @dataProvider data_cdo_and_cdc_sequences + * + * @covers ::serialize + */ + public function test_cdo_and_cdc_are_not_spelled( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + $this->assertSame( self::significant_tokens( $css ), self::significant_tokens( $expected ), 'The output must read as the same tokens.' ); + } + + /** + * Data provider for test_cdo_and_cdc_are_not_spelled(). + * + * @return array[] + */ + public static function data_cdo_and_cdc_sequences(): array { + return array( + '< ! ident' => array( ' array( ' array( ' array( '', '' ), + 'ident -- >' => array( '--/**/>', '--/**/>' ), + '< space ! ident' => array( '< !/**/--x', '< !--x' ), + '! ident without <' => array( 'a!/**/--x', 'a!--x' ), + '< ! ident without --' => array( '' => array( 'a--/**/>', 'a-->' ), + 'ident -- space >' => array( '-- >', '-- >' ), + ); + } + /** * Tests that serialize() closes blocks still open at the end, in reverse order. * From 08f3485b3bbae147b3894d57d074c6ee559e9423 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Fri, 9 Oct 2026 22:07:54 +0400 Subject: [PATCH 019/481] Make the token serializer internal A token list can hold tokens that have no valid CSS form, so the public way to write CSS will be at the declaration level, where the style attribute processor exposes only valid declarations. WP_CSS_Token_Serializer is marked @access private; its methods stay public so other core classes can call them. serialize_ident() and serialize_string() had no caller outside the serializer. They become escape_ident(), public for property names, and the private escape_string(); url values use the private escape_url(), which now returns the whole url token. CSSOM defines "serialize an identifier" and "serialize a string" with a different escape set, so the new names avoid suggesting those algorithms. The string escaping tests now run through serialize(). The class documentation states what the output guarantees: it parses to the same CSS as the tokens. It is not always valid CSS: bad-string and bad-url tokens are written as the same bad tokens. --- .../css-api/class-wp-css-token-serializer.php | 86 +++++++------- .../tests/css-api/wpCssTokenSerializer.php | 105 +++++++----------- 2 files changed, 84 insertions(+), 107 deletions(-) diff --git a/src/wp-includes/css-api/class-wp-css-token-serializer.php b/src/wp-includes/css-api/class-wp-css-token-serializer.php index c4d4c780ba440..2c451c42d75aa 100644 --- a/src/wp-includes/css-api/class-wp-css-token-serializer.php +++ b/src/wp-includes/css-api/class-wp-css-token-serializer.php @@ -8,16 +8,16 @@ */ /** - * Serializes CSS tokens and values as CSS text. + * Writes tokens read by WP_CSS_Token_Processor as CSS text. * - * serialize() writes tokens read by WP_CSS_Token_Processor. serialize_ident() - * and serialize_string() write a plain PHP string as an identifier or as a - * quoted string. + * This class is not a public API. Its methods are public so other core + * classes can call them. * - * Output is valid CSS that reads as the same tokens. Which characters are + * The output parses to the same CSS as the tokens. Which characters are * escaped may change. * * @since 7.2.0 + * @access private * * @see WP_CSS_Token_Processor */ @@ -147,7 +147,7 @@ class WP_CSS_Token_Serializer { ); /** - * Serializes tokens as CSS text that reads as the same tokens. + * Serializes tokens as CSS text that parses to the same CSS. * * This follows CSS Syntax Level 3 §9 Serialization: * @@ -220,7 +220,9 @@ class WP_CSS_Token_Serializer { * * Bad-string and bad-url tokens have no value. A bad string is written as * a quote followed by a newline, where the tokenizer ends one; a bad url is - * written as `url(()`. + * written as `url(()`. Both re-tokenize as the same bad token. If a later + * step replaces the newline after a bad string with a space, the quote + * starts a string that includes the text after it. * * Strings and urls cut off by the end of the input are written closed. * Blocks still open at the end are closed in reverse order, so `a(b[c` is @@ -314,24 +316,24 @@ private static function serialize_token( WP_CSS_Token $token ): string { switch ( $token->get_type() ) { case WP_CSS_Token_Processor::TOKEN_IDENT: - return self::serialize_ident( $value ); + return self::escape_ident( $value ); case WP_CSS_Token_Processor::TOKEN_FUNCTION: - return self::serialize_ident( $value ) . '('; + return self::escape_ident( $value ) . '('; case WP_CSS_Token_Processor::TOKEN_AT_KEYWORD: - return '@' . self::serialize_ident( $value ); + return '@' . self::escape_ident( $value ); case WP_CSS_Token_Processor::TOKEN_HASH: return WP_CSS_Token_Processor::HASH_TOKEN_ID === $token->get_flag() - ? '#' . self::serialize_ident( $value ) - : '#' . self::escape_name_code_points( $value ); + ? '#' . self::escape_ident( $value ) + : '#' . self::escape_name( $value ); case WP_CSS_Token_Processor::TOKEN_STRING: - return self::serialize_string( $value ); + return self::escape_string( $value ); case WP_CSS_Token_Processor::TOKEN_URL: - return 'url(' . self::serialize_url_value( $value ) . ')'; + return self::escape_url( $value ); case WP_CSS_Token_Processor::TOKEN_NUMBER: return $value; @@ -340,7 +342,7 @@ private static function serialize_token( WP_CSS_Token $token ): string { return $value . '%'; case WP_CSS_Token_Processor::TOKEN_DIMENSION: - $unit = self::serialize_ident( $token->get_unit() ); + $unit = self::escape_ident( $token->get_unit() ); // A unit that starts with `e`, an optional `-`, and a digit would read as an exponent. if ( 1 === preg_match( '/^[eE]-?[0-9]/', $unit ) ) { $unit = sprintf( '\\%X ', ord( $unit[0] ) ) . substr( $unit, 1 ); @@ -356,25 +358,24 @@ private static function serialize_token( WP_CSS_Token $token ): string { } /** - * Serializes a plain PHP string as CSS identifier text. + * Escapes a decoded value as identifier text. * - * Characters not valid in CSS identifiers are hex-escaped. This uses - * the same safety escaping as {@see WP_CSS_Token_Serializer::serialize_string()} for HTML - * and CSS-sensitive characters, plus escaping of whitespace and other - * characters not permitted in idents. + * Characters not valid in CSS identifiers are hex-escaped, as are the + * characters escape_string() escapes for HTML and CSS. * - * An empty string serializes to an empty string. Callers that require an - * ident token must reject an empty value. + * An empty value returns an empty string. Callers that require an ident + * token must reject an empty value. * * @see https://www.w3.org/TR/css-syntax-3/#escaping * @see https://www.w3.org/TR/css-syntax-3/#would-start-an-identifier * * @since 7.2.0 + * @access private * - * @param string $value Decoded string value to encode as a CSS identifier. - * @return string Serialized CSS identifier text. + * @param string $value Decoded value. + * @return string Identifier text. */ - public static function serialize_ident( string $value ): string { + public static function escape_ident( string $value ): string { $value = wp_scrub_utf8( $value ); $result = ''; $length = strlen( $value ); @@ -441,16 +442,11 @@ public static function serialize_ident( string $value ): string { } /** - * Creates a quoted CSS string from a plain PHP string value. + * Escapes a decoded value as a quoted string. * - * Example: - * $value = 'CSS & a ""; - * - * CSS strings are quoted, and many characters that are problematic in HTML - * or may be complicated for rudimentary CSS or HTML processors to handle - * are encoded using Unicode escape sequences. + * Many characters that are problematic in HTML or may be complicated for + * rudimentary CSS or HTML processors to handle are encoded using Unicode + * escape sequences. * * The string reads back as the same value, except that NULL becomes U+FFFD. * Line endings are not normalized: CR and FF are escaped as `\D ` and `\C `. @@ -459,10 +455,10 @@ public static function serialize_ident( string $value ): string { * * @since 7.2.0 * - * @param string $value Decoded string value to encode as a quoted CSS string. - * @return string Serialized quoted CSS string text. + * @param string $value Decoded value. + * @return string Quoted string text. */ - public static function serialize_string( string $value ): string { + private static function escape_string( string $value ): string { $value = wp_scrub_utf8( $value ); $escaped = strtr( $value, @@ -502,7 +498,7 @@ public static function serialize_string( string $value ): string { * * Letters, digits, `-`, `_` and code points U+0080 and above are written * as they are; every other code point is hex-escaped. Unlike - * serialize_ident(), a leading digit or `-` is not escaped, as the name of + * escape_ident(), a leading digit or `-` is not escaped, as the name of * a hash token with the "unrestricted" flag requires. * * @since 7.2.0 @@ -510,7 +506,7 @@ public static function serialize_string( string $value ): string { * @param string $value Decoded name. * @return string Escaped name. */ - private static function escape_name_code_points( string $value ): string { + private static function escape_name( string $value ): string { $value = wp_scrub_utf8( $value ); $result = ''; $length = strlen( $value ); @@ -542,20 +538,20 @@ private static function escape_name_code_points( string $value ): string { } /** - * Escapes the value of a url token. + * Escapes a decoded value as an unquoted url. * * The code points an unquoted url cannot contain are hex-escaped: quotes, * parentheses, `\`, whitespace and non-printable code points. So are the - * code points serialize_string() escapes for HTML and CSS: `< > & , ; { }`. + * code points escape_string() escapes for HTML and CSS: `< > & , ; { }`. * * @see https://www.w3.org/TR/css-syntax-3/#consume-url-token * * @since 7.2.0 * - * @param string $value Decoded url value. - * @return string Escaped url value, without `url(` and `)`. + * @param string $value Decoded value. + * @return string Url text, including `url(` and `)`. */ - private static function serialize_url_value( string $value ): string { + private static function escape_url( string $value ): string { $value = wp_scrub_utf8( $value ); $result = ''; $length = strlen( $value ); @@ -580,6 +576,6 @@ private static function serialize_url_value( string $value ): string { $result .= $value[ $i ]; } - return $result; + return "url({$result})"; } } diff --git a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php index f4ce9281c9081..084d339f407f3 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenSerializer.php +++ b/tests/phpunit/tests/css-api/wpCssTokenSerializer.php @@ -9,99 +9,84 @@ */ class Tests_CssApi_WpCssTokenSerializer extends WP_UnitTestCase { /** + * Tests that serialize() escapes a string token again from its decoded value. + * + * @ticket 65738 * @dataProvider data_string_escaping * - * @covers ::serialize_string + * @covers ::serialize */ - public function test_string_escaping( string $input, string $expected ): void { - $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize_string( $input ) ); - - /* - * Ensure that a single CSS string with the same value is produced. - * CSS cannot represent NULL, which becomes U+FFFD. - */ - $processor = WP_CSS_Token_Processor::create( WP_CSS_Token_Serializer::serialize_string( $input ) ); - $processor->next_token(); - $this->assertSame( WP_CSS_Token_Processor::TOKEN_STRING, $processor->get_token_type() ); - $this->assertSame( str_replace( "\0", '�', $input ), $processor->get_token_value() ); - $this->assertFalse( $processor->next_token() ); + public function test_string_escaping( string $css, string $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Serializer::serialize( self::tokenize( $css ) ) ); + $this->assertSame( self::significant_tokens( $css ), self::significant_tokens( $expected ), 'The output must read as the same tokens.' ); } /** - * Data provider for string escaping cases. + * Data provider for test_string_escaping(). * - * @return array + * @return array[] */ public static function data_string_escaping(): array { return array( // Passthrough — no escaping needed, only quoting. - 'empty string' => array( '', '""' ), - 'simple ASCII' => array( 'Arial', '"Arial"' ), - 'spaces preserved' => array( 'Exo 2', '"Exo 2"' ), - 'leading/trailing spaces' => array( ' Arial ', '" Arial "' ), - 'whitespace-only' => array( ' ', '" "' ), - 'numbers pass through' => array( '12345', '"12345"' ), - 'non-ASCII passthrough' => array( 'café', '"café"' ), + 'empty string' => array( "''", '""' ), + 'simple ASCII' => array( "'Arial'", '"Arial"' ), + 'spaces preserved' => array( "'Exo 2'", '"Exo 2"' ), + 'leading/trailing spaces' => array( "' Arial '", '" Arial "' ), + 'whitespace-only' => array( "' '", '" "' ), + 'numbers pass through' => array( "'12345'", '"12345"' ), + 'non-ASCII passthrough' => array( "'café'", '"café"' ), // Backslash escaping — must happen first to prevent double-escaping. - 'backslash' => array( 'Back\\Slash', '"Back\5C Slash"' ), - 'double backslash' => array( '\\\\', '"\5C \5C "' ), - 'backslash before quote' => array( "a\\'b", '"a\5C \27 b"' ), + 'backslash' => array( '"Back\\\\Slash"', '"Back\\5C Slash"' ), + 'double backslash' => array( '"\\\\\\\\"', '"\\5C \\5C "' ), + 'backslash before quote' => array( '"a\\\\\'b"', '"a\\5C \\27 b"' ), - // NULL byte → U+FFFD replacement character. - 'null byte' => array( "a\0b", '"a�b"' ), + // NULL → U+FFFD replacement character. + 'null byte' => array( "\"a\x00b\"", '"a�b"' ), + 'zero escape' => array( '"a\\0 b"', '"a�b"' ), - // Newlines are escaped as they are; CR and FF are not normalized to LF. - 'LF' => array( "a\nb", '"a\A b"' ), - 'CR' => array( "a\rb", '"a\D b"' ), - 'CRLF' => array( "a\r\nb", '"a\D \A b"' ), - 'form feed' => array( "a\fb", '"a\C b"' ), + // Escaped newlines keep their code points; CR and FF are not normalized to LF. + 'LF' => array( '"a\\A b"', '"a\\A b"' ), + 'CR' => array( '"a\\D b"', '"a\\D b"' ), + 'CRLF' => array( '"a\\D \\A b"', '"a\\D \\A b"' ), + 'form feed' => array( '"a\\C b"', '"a\\C b"' ), // HTML-problematic characters. - 'HTML characters < > &' => array( 'ac&d', '"a\3C b\3E c\26 d"' ), + 'HTML characters < > &' => array( '"ac&d"', '"a\\3C b\\3E c\\26 d"' ), // CSS-problematic characters. - 'CSS syntax , ; { }' => array( 'a,b;c{d}', '"a\2C b\3B c\7B d\7D "' ), - 'single quote' => array( "CSS's strings", '"CSS\27 s strings"' ), - 'double quote' => array( 'Say "Hi"', '"Say \22 Hi\22 "' ), + 'CSS syntax , ; { }' => array( '"a,b;c{d}"', '"a\\2C b\\3B c\\7B d\\7D "' ), + 'single quote' => array( '"CSS\'s strings"', '"CSS\\27 s strings"' ), + 'double quote' => array( '\'Say "Hi"\'', '"Say \\22 Hi\\22 "' ), ); } /** - * Tests the example from the class docblock. + * Tests the example in the serialize() docblock. * - * @covers ::serialize_string - */ - public function test_docblock_example(): void { - $value = 'CSS & a " + * * * Modern CSS no longer needs these, but they're preserved for compatibility. * In stylesheets, they're typically treated like whitespace. * - * @see https://www.w3.org/TR/css-syntax-3/#typedef-CDC-token + * @see WP_CSS_Token_Processor::TOKEN_CDO + * @link https://www.w3.org/TR/css-syntax-3/#typedef-cdc-token */ public const TOKEN_CDC = 'CDC-token'; /** - * CDO (Comment Delimiter Open) token: ) + * If followed by another hyphen and `>`, this is a CDC token (`-->`). * * Comment Delimiter Close - legacy HTML comment syntax in CSS. * - * @see https://www.w3.org/TR/css-syntax-3/#CDC-token-diagram + * @link https://www.w3.org/TR/css-syntax-3/#CDC-token-diagram */ if ( $this->at + 2 < $this->length && @@ -570,11 +617,11 @@ public function next_token(): bool { /* * U+003C LESS-THAN SIGN (<) - * If followed by !--, this is a CDO token (", "startIndex": 0, "endIndex": 3, - "normalized": "-->", "value": null }, { @@ -2751,7 +2471,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2764,7 +2483,6 @@ "raw": "foo", "startIndex": 0, "endIndex": 3, - "normalized": "foo", "value": "foo" }, { @@ -2772,7 +2490,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2785,7 +2502,6 @@ "raw": "--", "startIndex": 0, "endIndex": 2, - "normalized": "--", "value": "--" }, { @@ -2793,7 +2509,6 @@ "raw": "\n", "startIndex": 2, "endIndex": 3, - "normalized": "\n", "value": null } ] @@ -2806,7 +2521,6 @@ "raw": "--0", "startIndex": 0, "endIndex": 3, - "normalized": "--0", "value": "--0" }, { @@ -2814,7 +2528,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2827,7 +2540,6 @@ "raw": "-", "startIndex": 0, "endIndex": 1, - "normalized": "-", "value": "-" }, { @@ -2835,7 +2547,6 @@ "raw": "\\", "startIndex": 1, "endIndex": 2, - "normalized": "\\", "value": "\\" }, { @@ -2843,7 +2554,6 @@ "raw": "\n", "startIndex": 2, "endIndex": 3, - "normalized": "\n", "value": null } ] @@ -2856,7 +2566,6 @@ "raw": "-\\ ", "startIndex": 0, "endIndex": 3, - "normalized": "- ", "value": "- " }, { @@ -2864,7 +2573,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2877,7 +2585,6 @@ "raw": "--💅", "startIndex": 0, "endIndex": 6, - "normalized": "--💅", "value": "--💅" }, { @@ -2885,7 +2592,6 @@ "raw": "\n", "startIndex": 6, "endIndex": 7, - "normalized": "\n", "value": null } ] @@ -2898,7 +2604,6 @@ "raw": "-§", "startIndex": 0, "endIndex": 3, - "normalized": "-§", "value": "-§" }, { @@ -2906,7 +2611,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2919,7 +2623,6 @@ "raw": "-×", "startIndex": 0, "endIndex": 3, - "normalized": "-×", "value": "-×" }, { @@ -2927,7 +2630,6 @@ "raw": "\n", "startIndex": 3, "endIndex": 4, - "normalized": "\n", "value": null } ] @@ -2940,7 +2642,6 @@ "raw": "--a𐀀", "startIndex": 0, "endIndex": 7, - "normalized": "--a𐀀", "value": "--a𐀀" }, { @@ -2948,7 +2649,6 @@ "raw": "\n", "startIndex": 7, "endIndex": 8, - "normalized": "\n", "value": null } ] @@ -2961,7 +2661,6 @@ "raw": "url(foo)", "startIndex": 0, "endIndex": 8, - "normalized": "url(foo)", "value": "foo" }, { @@ -2969,7 +2668,6 @@ "raw": "\n", "startIndex": 8, "endIndex": 9, - "normalized": "\n", "value": null } ] @@ -2982,7 +2680,6 @@ "raw": "\\75 Rl(foo)", "startIndex": 0, "endIndex": 11, - "normalized": "uRl(foo)", "value": "foo" }, { @@ -2990,7 +2687,6 @@ "raw": "\n", "startIndex": 11, "endIndex": 12, - "normalized": "\n", "value": null } ] @@ -3003,7 +2699,6 @@ "raw": "uR\\6c (foo)", "startIndex": 0, "endIndex": 11, - "normalized": "uRl(foo)", "value": "foo" }, { @@ -3011,7 +2706,6 @@ "raw": "\n", "startIndex": 11, "endIndex": 12, - "normalized": "\n", "value": null } ] @@ -3024,7 +2718,6 @@ "raw": "url(", "startIndex": 0, "endIndex": 4, - "normalized": "url(", "value": "url" }, { @@ -3032,7 +2725,6 @@ "raw": "'foo'", "startIndex": 4, "endIndex": 9, - "normalized": "'foo'", "value": "foo" }, { @@ -3040,7 +2732,6 @@ "raw": ")", "startIndex": 9, "endIndex": 10, - "normalized": ")", "value": null }, { @@ -3048,7 +2739,6 @@ "raw": "\n", "startIndex": 10, "endIndex": 11, - "normalized": "\n", "value": null } ] @@ -3061,7 +2751,6 @@ "raw": "url(", "startIndex": 0, "endIndex": 4, - "normalized": "url(", "value": "url" }, { @@ -3069,7 +2758,6 @@ "raw": " ", "startIndex": 4, "endIndex": 5, - "normalized": " ", "value": null }, { @@ -3077,7 +2765,6 @@ "raw": "'foo'", "startIndex": 5, "endIndex": 10, - "normalized": "'foo'", "value": "foo" }, { @@ -3085,7 +2772,6 @@ "raw": ")", "startIndex": 10, "endIndex": 11, - "normalized": ")", "value": null }, { @@ -3093,7 +2779,6 @@ "raw": "\n", "startIndex": 11, "endIndex": 12, - "normalized": "\n", "value": null } ] @@ -3106,7 +2791,6 @@ "raw": "url(", "startIndex": 0, "endIndex": 4, - "normalized": "url(", "value": "url" }, { @@ -3114,7 +2798,6 @@ "raw": " ", "startIndex": 4, "endIndex": 6, - "normalized": " ", "value": null }, { @@ -3122,7 +2805,6 @@ "raw": "'foo'", "startIndex": 6, "endIndex": 11, - "normalized": "'foo'", "value": "foo" }, { @@ -3130,7 +2812,6 @@ "raw": ")", "startIndex": 11, "endIndex": 12, - "normalized": ")", "value": null }, { @@ -3138,7 +2819,6 @@ "raw": "\n", "startIndex": 12, "endIndex": 13, - "normalized": "\n", "value": null } ] @@ -3151,7 +2831,6 @@ "raw": "url(", "startIndex": 0, "endIndex": 4, - "normalized": "url(", "value": "url" }, { @@ -3159,7 +2838,6 @@ "raw": " ", "startIndex": 4, "endIndex": 7, - "normalized": " ", "value": null }, { @@ -3167,7 +2845,6 @@ "raw": "'foo'", "startIndex": 7, "endIndex": 12, - "normalized": "'foo'", "value": "foo" }, { @@ -3175,7 +2852,6 @@ "raw": ")", "startIndex": 12, "endIndex": 13, - "normalized": ")", "value": null }, { @@ -3183,7 +2859,6 @@ "raw": "\n", "startIndex": 13, "endIndex": 14, - "normalized": "\n", "value": null } ] @@ -3196,7 +2871,6 @@ "raw": "not-url(", "startIndex": 0, "endIndex": 8, - "normalized": "not-url(", "value": "not-url" }, { @@ -3204,7 +2878,6 @@ "raw": " ", "startIndex": 8, "endIndex": 11, - "normalized": " ", "value": null }, { @@ -3212,7 +2885,6 @@ "raw": "'foo'", "startIndex": 11, "endIndex": 16, - "normalized": "'foo'", "value": "foo" }, { @@ -3220,7 +2892,6 @@ "raw": ")", "startIndex": 16, "endIndex": 17, - "normalized": ")", "value": null }, { @@ -3228,7 +2899,6 @@ "raw": "\n", "startIndex": 17, "endIndex": 18, - "normalized": "\n", "value": null } ] @@ -3241,7 +2911,6 @@ "raw": "url( foo)", "startIndex": 0, "endIndex": 11, - "normalized": "url( foo)", "value": "foo" }, { @@ -3249,7 +2918,6 @@ "raw": "\n", "startIndex": 11, "endIndex": 12, - "normalized": "\n", "value": null } ] @@ -3262,7 +2930,6 @@ "raw": "{", "startIndex": 0, "endIndex": 1, - "normalized": "{", "value": null }, { @@ -3270,7 +2937,6 @@ "raw": "\n", "startIndex": 1, "endIndex": 2, - "normalized": "\n", "value": null } ] @@ -3283,7 +2949,6 @@ "raw": "(", "startIndex": 0, "endIndex": 1, - "normalized": "(", "value": null }, { @@ -3291,7 +2956,6 @@ "raw": "\n", "startIndex": 1, "endIndex": 2, - "normalized": "\n", "value": null } ] @@ -3304,7 +2968,6 @@ "raw": "[", "startIndex": 0, "endIndex": 1, - "normalized": "[", "value": null }, { @@ -3312,7 +2975,6 @@ "raw": "\n", "startIndex": 1, "endIndex": 2, - "normalized": "\n", "value": null } ] @@ -3325,7 +2987,6 @@ "raw": "<", "startIndex": 0, "endIndex": 1, - "normalized": "<", "value": "<" }, { @@ -3333,7 +2994,6 @@ "raw": "\n", "startIndex": 1, "endIndex": 2, - "normalized": "\n", "value": null } ] @@ -3346,7 +3006,6 @@ "raw": "B' ); + + $this->assertSame( + array( + array( + 'blockName' => 'core/group', + 'attrs' => array(), + 'innerBlocks' => array( + array( + 'blockName' => 'core/columns', + 'attrs' => array(), + 'innerBlocks' => array( + array( + 'blockName' => 'core/paragraph', + 'attrs' => array(), + 'innerBlocks' => array(), + 'innerHTML' => 'B', + 'innerContent' => array( 'B' ), + ), + ), + 'innerHTML' => '', + 'innerContent' => array( null ), + ), + ), + 'innerHTML' => '', + 'innerContent' => array( null ), + ), + ), + $blocks + ); + } } From 6d1a3e8c603ce4900a70abcae7d2973edabd022b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:22:10 +0000 Subject: [PATCH 058/481] Tests: Cover classic menu creation and deletion in the browser. Exercise menu creation, custom link insertion, theme location assignment, and deletion through the classic menu screen. Verify that the assigned menu appears in front-end navigation and that deletion removes the menu. Developed in: https://github.com/WordPress/wordpress-develop/pull/12669 Props csmcneill. See #54892, #52895. git-svn-id: https://develop.svn.wordpress.org/trunk@65063 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/specs/classic-menus.test.js | 125 ++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 tests/e2e/specs/classic-menus.test.js diff --git a/tests/e2e/specs/classic-menus.test.js b/tests/e2e/specs/classic-menus.test.js new file mode 100644 index 0000000000000..9fc301fbdabec --- /dev/null +++ b/tests/e2e/specs/classic-menus.test.js @@ -0,0 +1,125 @@ +/** + * WordPress dependencies + */ +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; + +/** + * The classic menus admin screen (nav-menus.php). Relies on Twenty + * Twenty-One being the active theme, which registers the "Primary menu" + * and "Secondary menu" locations. + */ +test.describe( 'Classic Menus', () => { + test.beforeEach( async ( { requestUtils } ) => { + await requestUtils.deleteAllMenus(); + } ); + + test( 'creates a menu, adds a custom link, and assigns it to a location', async ( { + admin, + page, + requestUtils, + } ) => { + await admin.visitAdminPage( '/nav-menus.php' ); + + // With no menus, the screen opens directly on the create form. + const menuNameField = page.getByRole( 'textbox', { + name: 'Menu Name', + } ); + await menuNameField.fill( 'E2E Menu' ); + await page + .getByRole( 'button', { name: 'Create Menu' } ) + .first() + .click(); + + // The screen reloads into the edit state for the new menu. + await expect( + page.getByRole( 'textbox', { name: 'Menu Name' } ) + ).toHaveValue( 'E2E Menu' ); + + // Add a custom link from the accordion. + await page.getByRole( 'button', { name: 'Custom Links' } ).click(); + await page + .getByRole( 'textbox', { name: 'URL' } ) + .fill( 'https://wordpress.org/' ); + await page + .getByRole( 'textbox', { name: 'Link Text' } ) + .fill( 'E2E Custom Link' ); + // Each accordion panel has its own submit; scope to Custom Links. + await page + .locator( '#customlinkdiv' ) + .getByRole( 'button', { name: 'Add to Menu' } ) + .click(); + + // The item lands in the menu structure. + await expect( + page + .locator( '#menu-to-edit' ) + .getByText( 'E2E Custom Link', { exact: true } ) + ).toBeVisible(); + + // Assign the menu to the theme's primary location and save. + await page.getByRole( 'checkbox', { name: 'Primary menu' } ).check(); + + // Activate via keyboard: the sticky footer bar can shift on focus + // and swallow the first pointer click at certain window heights. + // See https://core.trac.wordpress.org/ticket/65684. + await page.getByRole( 'button', { name: 'Save Menu' } ).first().focus(); + await page.keyboard.press( 'Enter' ); + + // The location assignment persists. + await expect + .poll( + async () => { + const menus = await requestUtils.rest( { + path: '/wp/v2/menus', + params: { context: 'edit' }, + } ); + return menus.find( ( menu ) => menu.name === 'E2E Menu' ) + ?.locations; + }, + { + message: + 'the menu should be assigned to the primary location', + } + ) + .toContain( 'primary' ); + + // The menu renders in the site navigation on the front end. + await page.goto( '/' ); + await expect( + page + .getByRole( 'navigation' ) + .getByRole( 'link', { name: 'E2E Custom Link' } ) + ).toBeVisible(); + } ); + + test( 'deletes a menu', async ( { admin, page, requestUtils } ) => { + await requestUtils.createClassicMenu( 'Doomed Menu' ); + + await admin.visitAdminPage( '/nav-menus.php' ); + + // Deleting asks for confirmation. + page.on( 'dialog', ( dialog ) => dialog.accept() ); + + // Activate via keyboard: the sticky footer bar can shift on focus + // and swallow the first pointer click at certain window heights. + // See https://core.trac.wordpress.org/ticket/65684. + await page.getByRole( 'link', { name: 'Delete Menu' } ).focus(); + await page.keyboard.press( 'Enter' ); + + // With the only menu gone, the screen returns to the create form. + await expect( + page.getByRole( 'textbox', { name: 'Menu Name' } ) + ).toHaveValue( '' ); + await expect + .poll( + async () => { + const menus = await requestUtils.rest( { + path: '/wp/v2/menus', + } ); + return menus.length; + }, + { message: 'no menus should remain' } + ) + .toBe( 0 ); + } ); +} ); From d1e68dd620f75c68099d103b775eca77dba9c09b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:31:01 +0000 Subject: [PATCH 059/481] Tests: Cover password-protected post form output. Test `get_the_password_form()` markup, filter arguments and returned output, incorrect-password feedback, and block-theme button markup. Developed in: https://github.com/WordPress/wordpress-develop/pull/14678 Props rejaulalomkhan, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65064 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/post/getThePasswordForm.php | 206 ++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 tests/phpunit/tests/post/getThePasswordForm.php diff --git a/tests/phpunit/tests/post/getThePasswordForm.php b/tests/phpunit/tests/post/getThePasswordForm.php new file mode 100644 index 0000000000000..7f0663a60ab27 --- /dev/null +++ b/tests/phpunit/tests/post/getThePasswordForm.php @@ -0,0 +1,206 @@ +post->create( array( 'post_password' => 'secret' ) ); + } + + public function set_up() { + parent::set_up(); + + $this->original_stylesheet = get_stylesheet(); + } + + public function tear_down() { + unset( $_SERVER['HTTP_REFERER'], $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ); + + if ( get_stylesheet() !== $this->original_stylesheet ) { + switch_theme( $this->original_stylesheet ); + } + + parent::tear_down(); + } + + /** + * Returns the expected form markup for the fixture post. + * + * Only the post ID is filled in; everything else is literal. + * + * @param string $form_class Extra form class. + * @param string $error_html Error markup after the redirect field. + * @param string $aria Extra password input attributes. + * @param string $button_open Markup before the submit button. + * @param string $button_class Submit button class attribute. + * @param string $button_close Markup after the submit button. + * @return string Expected form markup. + */ + private function expected_form( $form_class = '', $error_html = '', $aria = '', $button_open = '', $button_class = '', $button_close = '' ) { + $id = self::$post_id; + + return '
' + . '' + . $error_html + . "\n\t

This content is password-protected. To view it, please enter the password below.

" + . "\n\t" . '

' + . $button_open . '' . $button_close . "

\n\t"; + } + + /** + * Tests that the global post is used by default. + * + * @ticket 65819 + */ + public function test_uses_global_post_by_default() { + $GLOBALS['post'] = get_post( self::$post_id ); + + $this->assertSame( $this->expected_form(), get_the_password_form() ); + } + + /** + * Tests that the form has a random field ID and no redirect field without a post. + * + * @ticket 65819 + */ + public function test_form_without_post() { + $form = get_the_password_form(); + + $this->assertStringNotContainsString( 'redirect_to', $form, 'There should be no redirect field.' ); + + $processor = new WP_HTML_Tag_Processor( $form ); + $this->assertTrue( $processor->next_tag( 'LABEL' ), 'The label should exist.' ); + $field_id = $processor->get_attribute( 'for' ); + $this->assertMatchesRegularExpression( '/^pwbox-\d+$/', $field_id, 'The field ID should use a random number.' ); + $this->assertTrue( $processor->next_tag( 'INPUT' ), 'The password input should exist.' ); + $this->assertSame( $field_id, $processor->get_attribute( 'id' ), 'The label and the input should share the field ID.' ); + } + + /** + * Tests that no error is shown unless the referrer is the post and the password cookie is set. + * + * @ticket 65819 + * + * @dataProvider data_no_error_without_matching_referrer_and_cookie + * + * @param bool $same_referrer Whether the referrer is the post permalink. + * @param bool $cookie Whether the password cookie is set. + */ + public function test_no_error_without_matching_referrer_and_cookie( $same_referrer, $cookie ) { + $_SERVER['HTTP_REFERER'] = $same_referrer ? get_permalink( self::$post_id ) : 'http://' . WP_TESTS_DOMAIN . '/elsewhere/'; + + if ( $cookie ) { + $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] = 'hash'; + } + + $this->assertSame( $this->expected_form(), get_the_password_form( self::$post_id ) ); + } + + /** + * Data provider for test_no_error_without_matching_referrer_and_cookie(). + * + * @return array[] + */ + public static function data_no_error_without_matching_referrer_and_cookie() { + return array( + 'same referrer, no cookie' => array( true, false ), + 'other referrer, cookie' => array( false, true ), + ); + } + + /** + * Tests the arguments and return value of the 'the_password_form_incorrect_password' filter. + * + * @ticket 65819 + */ + public function test_incorrect_password_filter() { + $_SERVER['HTTP_REFERER'] = get_permalink( self::$post_id ); + $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] = 'hash'; + + $filter = new MockAction(); + add_filter( 'the_password_form_incorrect_password', array( $filter, 'filter' ), 10, 2 ); + add_filter( + 'the_password_form_incorrect_password', + static function ( $message ) { + return 'Try again. ' . $message; + }, + 20 + ); + + $form = get_the_password_form( self::$post_id ); + $args = $filter->get_args()[0]; + + $this->assertSame( 'Invalid password.', $args[0], 'The filter should receive the default message.' ); + $this->assertSame( self::$post_id, $args[1]->ID, 'The filter should receive the post.' ); + $this->assertStringContainsString( '

Try again. Invalid password.

', $form, 'The filtered message should be displayed.' ); + } + + /** + * Tests the arguments and return value of the 'the_password_form' filter. + * + * @ticket 65819 + */ + public function test_the_password_form_filter() { + $_SERVER['HTTP_REFERER'] = get_permalink( self::$post_id ); + $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] = 'hash'; + + $filter = new MockAction(); + add_filter( 'the_password_form', array( $filter, 'filter' ), 10, 3 ); + add_filter( + 'the_password_form', + static function ( $output ) { + return '
' . $output . '
'; + }, + 20 + ); + + $form = get_the_password_form( self::$post_id ); + $args = $filter->get_args()[0]; + + $expected = $this->expected_form( + ' password-form-error', + '', + ' aria-describedby="error-pwbox-' . self::$post_id . '"' + ); + + $this->assertSame( $expected, $args[0], 'The filter should receive the form markup.' ); + $this->assertSame( self::$post_id, $args[1]->ID, 'The filter should receive the post.' ); + $this->assertSame( 'Invalid password.', $args[2], 'The filter should receive the error message.' ); + $this->assertSame( '
' . $expected . '
', $form, 'The filtered form should be returned.' ); + } + + /** + * Tests the button markup in a block theme. + * + * @ticket 65819 + */ + public function test_block_theme_button() { + switch_theme( 'block-theme' ); + + $this->assertSame( + $this->expected_form( '', '', '', '', ' class="wp-block-button__link wp-element-button"', '' ), + get_the_password_form( self::$post_id ) + ); + } +} From b6f5add1fe5649df6e6fd726fd773bf8322b5067 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:32:45 +0000 Subject: [PATCH 060/481] Tests: Cover plugin activation behavior. Test `activate_plugin()` validation, active-plugin state, activation hooks, silent activation, unexpected output, and redirect handling. Cover network-wide and network-only activation on multisite. Developed in: https://github.com/WordPress/wordpress-develop/pull/14601 Props huzaifaalmesbah, mukesh27. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65065 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/includes/plugin/activatePlugin.php | 358 ++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/plugin/activatePlugin.php diff --git a/tests/phpunit/tests/admin/includes/plugin/activatePlugin.php b/tests/phpunit/tests/admin/includes/plugin/activatePlugin.php new file mode 100644 index 0000000000000..92070e31777f6 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/plugin/activatePlugin.php @@ -0,0 +1,358 @@ +slug = 'activation-test-plugin-' . wp_generate_password( 8, false ); + $this->old_networkwide = array_key_exists( 'networkwide', $_GET ) ? $_GET['networkwide'] : null; + $this->redirects = array(); + + add_filter( 'wp_redirect', array( $this, 'record_redirect' ) ); + } + + /** + * Removes the test plugin and restores global state. + */ + public function tear_down() { + global $wp_plugin_paths; + + $this->remove_plugin(); + wp_cache_delete( 'plugins', 'plugins' ); + + if ( is_array( $wp_plugin_paths ) ) { + unset( $wp_plugin_paths[ WP_PLUGIN_DIR . '/' . $this->get_file() ] ); + } + + if ( null !== $this->old_networkwide ) { + $_GET['networkwide'] = $this->old_networkwide; + } else { + unset( $_GET['networkwide'] ); + } + + parent::tear_down(); + } + + /** + * Tests that a plugin that is not installed is not activated. + * + * On multisite, is_network_only_plugin() reads the missing file before the plugin is validated. + * + * @ticket 65819 + * + * @group ms-excluded + */ + public function test_should_reject_plugin_that_is_not_installed() { + $result = activate_plugin( 'missing/missing.php' ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'plugin_not_found', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( array( 'zzz/zzz.php' ), get_option( 'active_plugins' ), 'The active plugins should not change.' ); + } + + /** + * Tests that a plugin whose requirements are not met is not activated. + * + * @ticket 65819 + */ + public function test_should_reject_plugin_with_unmet_requirements() { + $this->create_plugin( " * Requires PHP: 99.0\n" ); + + $result = activate_plugin( $this->get_file() ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'plugin_php_incompatible', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( array( 'zzz/zzz.php' ), get_option( 'active_plugins' ), 'The active plugins should not change.' ); + + if ( is_multisite() ) { + $this->assertSame( array(), get_site_option( 'active_sitewide_plugins' ), 'The active sitewide plugins should not change.' ); + } + } + + /** + * Tests that a plugin is activated, sorted into the active plugins, and the activation hooks fire. + * + * @ticket 65819 + */ + public function test_should_activate_plugin_and_fire_hooks() { + $this->create_plugin(); + + $actions = $this->watch_activation_hooks(); + + $this->assertNull( activate_plugin( $this->get_file() ), 'Nothing should be returned.' ); + $this->assertSame( array( $this->get_file(), 'zzz/zzz.php' ), get_option( 'active_plugins' ), 'The plugin should be added in order.' ); + $this->assertSame( + array( 'activate_plugin', "activate_{$this->get_file()}", 'activated_plugin' ), + $actions->get_hook_names(), + 'The activation hooks should fire in order.' + ); + $this->assertSame( + array( + array( $this->get_file(), false ), + array( false ), + array( $this->get_file(), false ), + ), + $actions->get_args(), + 'The activation hooks should receive the expected arguments.' + ); + } + + /** + * Tests that the plugin path is reduced to its basename. + * + * @ticket 65819 + */ + public function test_should_accept_full_path_with_whitespace() { + $this->create_plugin(); + + $this->assertNull( activate_plugin( ' ' . WP_PLUGIN_DIR . '/' . $this->get_file() . ' ' ), 'Nothing should be returned.' ); + $this->assertContains( $this->get_file(), get_option( 'active_plugins' ), 'The plugin should be active.' ); + } + + /** + * Tests that no hooks fire in silent mode. + * + * @ticket 65819 + */ + public function test_should_not_fire_hooks_in_silent_mode() { + $this->create_plugin(); + + $actions = $this->watch_activation_hooks(); + + $this->assertNull( activate_plugin( $this->get_file(), '', false, true ), 'Nothing should be returned.' ); + $this->assertContains( $this->get_file(), get_option( 'active_plugins' ), 'The plugin should be active.' ); + $this->assertSame( array(), $actions->get_events(), 'No activation hooks should fire.' ); + } + + /** + * Tests that an active plugin is not activated again. + * + * @ticket 65819 + */ + public function test_should_not_activate_active_plugin_again() { + $this->create_plugin(); + update_option( 'active_plugins', array( $this->get_file() ) ); + + $actions = $this->watch_activation_hooks(); + + $this->assertNull( activate_plugin( $this->get_file(), 'plugins.php' ), 'Nothing should be returned.' ); + $this->assertSame( array( $this->get_file() ), get_option( 'active_plugins' ), 'The active plugins should not change.' ); + $this->assertSame( array(), $actions->get_events(), 'No activation hooks should fire.' ); + $this->assertSame( array(), $this->redirects, 'No redirect should be sent.' ); + } + + /** + * Tests that output while loading the plugin is reported, after the plugin is activated. + * + * @ticket 65819 + */ + public function test_should_report_unexpected_output() { + $this->create_plugin( '', "echo 'Unexpected!';\n" ); + + $result = activate_plugin( $this->get_file() ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'unexpected_output', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( 'The plugin generated unexpected output.', $result->get_error_message(), 'The error message should match.' ); + $this->assertSame( 'Unexpected!', $result->get_error_data(), 'The output should be the error data.' ); + $this->assertContains( $this->get_file(), get_option( 'active_plugins' ), 'The plugin should still be activated.' ); + } + + /** + * Tests that a redirect to the error page is sent before the plugin is loaded. + * + * @ticket 65819 + */ + public function test_should_redirect_with_error_nonce() { + $this->create_plugin(); + + activate_plugin( $this->get_file(), 'plugins.php?error=true&plugin=' . $this->get_file() ); + + $this->assertSame( + array( "plugins.php?error=true&plugin={$this->slug}%2F{$this->slug}.php&_error_nonce=" . wp_create_nonce( 'plugin-activation-error_' . $this->get_file() ) ), + $this->redirects + ); + } + + /** + * Tests that a plugin is activated network-wide on multisite. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_activate_plugin_network_wide() { + $this->create_plugin(); + + $actions = $this->watch_activation_hooks(); + + $this->assertNull( activate_plugin( $this->get_file(), '', true ), 'Nothing should be returned.' ); + $this->assertSame( array( $this->get_file() ), array_keys( get_site_option( 'active_sitewide_plugins' ) ), 'The plugin should be network active.' ); + $this->assertSame( array( 'zzz/zzz.php' ), get_option( 'active_plugins' ), 'The site plugins should not change.' ); + $this->assertSame( 1, $_GET['networkwide'], 'The back-compat request value should be set.' ); + $this->assertSame( + array( 'activate_plugin', "activate_{$this->get_file()}", 'activated_plugin' ), + $actions->get_hook_names(), + 'The activation hooks should fire in order.' + ); + $this->assertSame( + array( + array( $this->get_file(), true ), + array( true ), + array( $this->get_file(), true ), + ), + $actions->get_args(), + 'The activation hooks should receive the expected arguments.' + ); + } + + /** + * Tests that a network-only plugin is always activated network-wide on multisite. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_activate_network_only_plugin_network_wide() { + $this->create_plugin( " * Network: true\n" ); + + $actions = $this->watch_activation_hooks(); + + $this->assertNull( activate_plugin( $this->get_file() ), 'Nothing should be returned.' ); + $this->assertArrayHasKey( $this->get_file(), get_site_option( 'active_sitewide_plugins' ), 'The plugin should be network active.' ); + $this->assertSame( array( 'zzz/zzz.php' ), get_option( 'active_plugins' ), 'The site plugins should not change.' ); + $this->assertSame( 1, $_GET['networkwide'], 'The back-compat request value should be set.' ); + $this->assertSame( + array( 'activate_plugin', "activate_{$this->get_file()}", 'activated_plugin' ), + $actions->get_hook_names(), + 'The activation hooks should fire in order.' + ); + $this->assertSame( + array( + array( $this->get_file(), true ), + array( true ), + array( $this->get_file(), true ), + ), + $actions->get_args(), + 'The activation hooks should receive the expected arguments.' + ); + } + + /** + * Tests that a network-active plugin is not activated again. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_not_activate_network_active_plugin_again() { + $this->create_plugin(); + update_site_option( 'active_sitewide_plugins', array( $this->get_file() => 1000 ) ); + + $this->assertNull( activate_plugin( $this->get_file(), '', true ), 'Nothing should be returned.' ); + $this->assertSame( array( $this->get_file() => 1000 ), get_site_option( 'active_sitewide_plugins' ), 'The activation time should not change.' ); + } + + /** + * Records redirect locations and stops the redirect. + * + * @param string $location The redirect location. + * @return false False, so that no header is sent. + */ + public function record_redirect( $location ) { + $this->redirects[] = $location; + + return false; + } + + /** + * Records the activation hooks using MockAction. + * + * @return MockAction The mock action recording hook calls. + */ + private function watch_activation_hooks() { + $mock = new MockAction(); + + foreach ( array( 'activate_plugin', "activate_{$this->get_file()}", 'activated_plugin' ) as $hook ) { + add_action( $hook, array( $mock, 'action' ), 10, 2 ); + } + + return $mock; + } + + /** + * Returns the plugin file of the test plugin. + * + * @return string The plugin file. + */ + private function get_file() { + return "{$this->slug}/{$this->slug}.php"; + } + + /** + * Creates the test plugin. + * + * @param string $headers Additional plugin headers. + * @param string $code Code after the headers. + */ + private function create_plugin( $headers = '', $code = '' ) { + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + + $this->remove_plugin(); + $this->assertTrue( mkdir( $dir ), 'The test plugin directory should be created.' ); + $this->assertNotFalse( + file_put_contents( "{$dir}/{$this->slug}.php", "slug; + + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } +} From 4a717359b40973b42c2d26be6b58faaf1e36e518 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:41:14 +0000 Subject: [PATCH 061/481] Code Modernization: Simplify block parser default length assignment. Use `??=` in `WP_Block_Parser::add_freeform()` to preserve the existing default-length behavior with a shorter assignment. Developed in: https://github.com/WordPress/wordpress-develop/pull/15149 Props shailu25, westonruter. See #65823. git-svn-id: https://develop.svn.wordpress.org/trunk@65066 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-block-parser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-block-parser.php b/src/wp-includes/class-wp-block-parser.php index 07ddf52fc54f8..5adc9d95e677b 100644 --- a/src/wp-includes/class-wp-block-parser.php +++ b/src/wp-includes/class-wp-block-parser.php @@ -319,7 +319,7 @@ public function freeform( $inner_html ) { * @param null|int $length How many bytes of document text to output. */ public function add_freeform( $length = null ) { - $length = $length ?? strlen( $this->document ) - $this->offset; + $length ??= strlen( $this->document ) - $this->offset; if ( 0 === $length ) { return; From a00dab92bd0cba3387b897b5d623b1334998e423 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:48:31 +0000 Subject: [PATCH 062/481] Tests: Make factory, abilities and link data providers static. Declare 44 existing data providers as `public static` for compatibility with newer PHPUnit versions. Preserve their datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15201, https://github.com/WordPress/wordpress-develop/pull/15202, https://github.com/WordPress/wordpress-develop/pull/15213 Props shailu25, devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65067 602fd350-edb4-49c9-b593-d223f7449a82 --- .../wpRegisterCoreContentAbility.php | 58 +++++++++---------- tests/phpunit/tests/includes/factory.php | 6 +- tests/phpunit/tests/includes/helpers.php | 6 +- .../phpunit/tests/includes/uploadSnapshot.php | 2 +- tests/phpunit/tests/link/editTermLink.php | 2 +- tests/phpunit/tests/link/getEditTermLink.php | 2 +- tests/phpunit/tests/link/getFeedLink.php | 4 +- tests/phpunit/tests/link/getPagenumLink.php | 4 +- .../tests/link/getThePostsNavigation.php | 2 +- tests/phpunit/tests/link/themeFile.php | 2 +- 10 files changed, 44 insertions(+), 44 deletions(-) diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php index 8e8772eb7776b..03dd69bb2b955 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php @@ -246,7 +246,7 @@ private function login_as( string $role ): void { * * @return array Role test cases. */ - public function data_roles_without_edit_access_to_other_users_posts(): array { + public static function data_roles_without_edit_access_to_other_users_posts(): array { return array( 'subscriber' => array( 'role' => 'subscriber', @@ -487,7 +487,7 @@ public function test_ids_combine_with_a_status_filter(): void { * * @return array}> Input test cases. */ - public function data_inputs_without_a_post_type(): array { + public static function data_inputs_without_a_post_type(): array { return array( 'missing where' => array( 'input' => array( 'fields' => array( 'id' ) ), @@ -519,7 +519,7 @@ public function data_inputs_without_a_post_type(): array { * * @return array Input test cases. */ - public function data_invalid_inputs(): array { + public static function data_invalid_inputs(): array { return array( 'no input' => array( 'input' => null, @@ -864,7 +864,7 @@ public function test_exposes_a_post_type_registered_by_another_plugin(): void { * * @return array Non-boolean `show_in_abilities` test cases. */ - public function data_show_in_abilities_values_other_than_true(): array { + public static function data_show_in_abilities_values_other_than_true(): array { return array( 'false' => array( 'value' => false, @@ -1144,7 +1144,7 @@ public function test_query_by_id_can_return_content_fields(): void { * * @return array}> The `where` values. */ - public function data_where_values_that_match_no_post(): array { + public static function data_where_values_that_match_no_post(): array { return array( 'missing ID' => array( 'where' => array( @@ -1237,7 +1237,7 @@ public function test_public_non_viewable_status_is_returned_only_with_edit_acces * * @return array}> Filter test cases. */ - public function data_filters_naming_a_post_in_a_viewable_custom_status(): array { + public static function data_filters_naming_a_post_in_a_viewable_custom_status(): array { return array( 'ids' => array( 'where' => array( @@ -1892,7 +1892,7 @@ public function test_ids_and_slugs_together_return_only_posts_in_both_lists(): v * * @return array}> Role test cases. */ - public function data_roles_with_and_without_access_to_others_drafts(): array { + public static function data_roles_with_and_without_access_to_others_drafts(): array { return array( 'subscriber' => array( 'role' => 'subscriber', @@ -1999,7 +1999,7 @@ public function test_unknown_requested_field_fails_schema_validation(): void { * * @return array Field path test cases. */ - public function data_sub_field_paths(): array { + public static function data_sub_field_paths(): array { return array( 'title.rendered' => array( 'field' => 'title.rendered', @@ -2063,7 +2063,7 @@ public function test_sub_field_path_returns_only_that_sub_field( string $field ) * * @return array}> Object field test cases. */ - public function data_object_fields(): array { + public static function data_object_fields(): array { return array( 'title' => array( 'field' => 'title', @@ -2484,7 +2484,7 @@ public function test_author_name_and_slug_are_returned_to_users_who_may_see_the_ * * @return array */ - public function data_author_visibility(): array { + public static function data_author_visibility(): array { return array( 'editor, pending post' => array( 'role' => 'editor', @@ -2918,7 +2918,7 @@ public function test_raw_field_requests_omit_raw_values_for_roles_without_edit_a * * @return array Status test cases. */ - public function data_statuses_that_require_edit_access(): array { + public static function data_statuses_that_require_edit_access(): array { return array( 'draft' => array( 'status' => 'draft', @@ -3309,7 +3309,7 @@ public function test_query_totals_may_include_rows_withheld_by_row_level_permiss * * @return array, total: int}> Role test cases. */ - public function data_default_statuses_with_ids_by_role(): array { + public static function data_default_statuses_with_ids_by_role(): array { return array( 'subscriber' => array( 'role' => 'subscriber', @@ -3474,7 +3474,7 @@ public function test_author_gets_their_own_draft_only_by_ids_or_slugs_without_a_ * * @return array Role test cases. */ - public function data_roles_with_edit_access_to_other_users_posts(): array { + public static function data_roles_with_edit_access_to_other_users_posts(): array { return array( 'administrator' => array( 'role' => 'administrator', @@ -4477,7 +4477,7 @@ public function test_rendered_fields_without_a_global_post_keep_an_earlier_the_p * * @return array Throwing post test cases. */ - public function data_posts_whose_the_post_callbacks_throw(): array { + public static function data_posts_whose_the_post_callbacks_throw(): array { return array( 'requested post' => array( 'throwing_post' => 'limited_role_content', @@ -4687,7 +4687,7 @@ public function test_query_out_of_range_page_is_rejected_rather_than_reported_as * * @return array The values to send. */ - public function data_whole_numbers_that_are_not_integers(): array { + public static function data_whole_numbers_that_are_not_integers(): array { return array( 'floats' => array( 2.0, 2.0, 99.0 ), 'decimal strings' => array( '2.0', '2.0', '99.0' ), @@ -4744,7 +4744,7 @@ public function test_query_honors_a_page_and_per_page_that_are_not_integers( $pa * * @return array The values to send for the post ID. */ - public function data_post_ids_that_are_not_integers(): array { + public static function data_post_ids_that_are_not_integers(): array { return array( 'float' => array( 'id' => (float) self::IMPORTED_POST_ID, @@ -4880,7 +4880,7 @@ public function test_query_empty_result_beyond_first_page_reports_zero_totals(): * * @return array Page size test cases. */ - public function data_page_sizes_set_by_a_query_filter(): array { + public static function data_page_sizes_set_by_a_query_filter(): array { return array( 'smaller page size' => array( 'posts_per_page' => 2, @@ -4993,7 +4993,7 @@ public function test_query_ids_return_every_requested_post_without_per_page(): v * * @return array Post meta priming test cases. */ - public function data_fields_that_prime_post_meta(): array { + public static function data_fields_that_prime_post_meta(): array { return array( 'content.rendered' => array( 'field' => 'content.rendered', @@ -5424,7 +5424,7 @@ private function replace_cached_post_date_columns( int $post_id, array $columns * * @return array */ - public function data_gmt_date_fields(): array { + public static function data_gmt_date_fields(): array { return array( 'date.gmt' => array( 'field' => 'date.gmt', @@ -5552,7 +5552,7 @@ public function test_gmt_date_is_null_when_no_usable_date_exists( string $field, * * @return array */ - public function data_date_fields(): array { + public static function data_date_fields(): array { return array( 'date.site' => array( 'field' => 'date.site', @@ -5620,7 +5620,7 @@ public function test_malformed_date_is_null( string $field, string $column ): vo * * @return array The `where.author` values. */ - public function data_author_filters_without_an_id_or_a_slug(): array { + public static function data_author_filters_without_an_id_or_a_slug(): array { return array( 'string' => array( 'author' => 'author-slug', @@ -5698,7 +5698,7 @@ public function test_execute_callback_rejects_an_author_filter_without_an_id_or_ * * @return array The `where.author.id` values. */ - public function data_author_ids_that_are_not_positive_integers(): array { + public static function data_author_ids_that_are_not_positive_integers(): array { return array( 'zero' => array( 'id' => 0, @@ -5762,7 +5762,7 @@ public function test_execute_callback_rejects_an_author_id_that_is_not_a_positiv * * @return array The type names, as `settype()` takes them. */ - public function data_author_id_whole_number_types(): array { + public static function data_author_id_whole_number_types(): array { return array( 'string of digits' => array( 'type' => 'string', @@ -5823,7 +5823,7 @@ public function test_execute_callback_accepts_an_author_id_given_as_a_whole_numb * * @return array, param: string}> The filters and parameters. */ - public function data_author_filters_with_several_problems(): array { + public static function data_author_filters_with_several_problems(): array { return array( 'unknown property next to a bad id' => array( 'author' => array( @@ -5896,7 +5896,7 @@ public function test_execute_callback_reports_the_first_problem_of_an_author_fil * * @return array The `where.author.slug` values. */ - public function data_author_slugs_that_are_not_non_empty_strings(): array { + public static function data_author_slugs_that_are_not_non_empty_strings(): array { return array( 'integer' => array( 'slug' => 5, @@ -6111,7 +6111,7 @@ public function test_execute_callback_rejects_non_integer_parent_filter(): void * * @return array The `where.ids` values. */ - public function data_ids_with_no_valid_ids(): array { + public static function data_ids_with_no_valid_ids(): array { return array( 'zero' => array( 'ids' => array( 0 ), @@ -6232,7 +6232,7 @@ public function test_execute_callback_drops_an_invalid_id_next_to_a_valid_one(): * * @return array The `where.slugs` values. */ - public function data_slugs_with_no_slug_left(): array { + public static function data_slugs_with_no_slug_left(): array { return array( 'empty slug' => array( 'slugs' => array( '' ), @@ -6287,7 +6287,7 @@ public function test_execute_callback_rejects_slugs_with_no_slug_left( $slugs ): * * @return array}> The `where` filters. */ - public function data_where_filters_with_statuses_that_cannot_be_queried(): array { + public static function data_where_filters_with_statuses_that_cannot_be_queried(): array { return array( 'empty status list' => array( 'where' => array( @@ -6490,7 +6490,7 @@ public function test_ids_and_slugs_accept_comma_separated_strings_and_single_val * * @return array The values to send. */ - public function data_values_that_are_not_objects(): array { + public static function data_values_that_are_not_objects(): array { return array( 'query string' => array( 'value' => 'id=5&page=2', diff --git a/tests/phpunit/tests/includes/factory.php b/tests/phpunit/tests/includes/factory.php index e39f97c6bcdb8..9d8396ad94f24 100644 --- a/tests/phpunit/tests/includes/factory.php +++ b/tests/phpunit/tests/includes/factory.php @@ -96,7 +96,7 @@ public function test_create_should_throw_an_exception_when_a_non_positive_id_is_ * * @return array */ - public function data_non_positive_object_ids() { + public static function data_non_positive_object_ids() { return array( 'zero' => array( 0 ), 'a negative ID' => array( -1 ), @@ -327,7 +327,7 @@ static function ( int $created_id ) { * * @return array */ - public function data_term_taxonomy_sources(): array { + public static function data_term_taxonomy_sources(): array { return array( 'factory taxonomy, in the args' => array( 'post_tag', false ), 'another taxonomy, in the args' => array( 'category', false ), @@ -471,7 +471,7 @@ public function test_create_and_get_should_throw_an_exception_when_a_legacy_fact * * @return array */ - public function data_legacy_retrieval_failures(): array { + public static function data_legacy_retrieval_failures(): array { return array( 'null' => array( null, 'Unable to retrieve the object with ID 5. Args: []' ), 'false' => array( false, 'Unable to retrieve the object with ID 5. Args: []' ), diff --git a/tests/phpunit/tests/includes/helpers.php b/tests/phpunit/tests/includes/helpers.php index 5b9b83f463f94..1160f3b901310 100644 --- a/tests/phpunit/tests/includes/helpers.php +++ b/tests/phpunit/tests/includes/helpers.php @@ -7,7 +7,7 @@ class Tests_TestHelpers extends WP_UnitTestCase { /** * @ticket 30522 */ - public function data_assertSameSets() { + public static function data_assertSameSets() { return array( array( array( 1, 2, 3 ), // Test expected. @@ -68,7 +68,7 @@ public function test_assertSameSets( $expected, $actual, $exception ) { /** * @ticket 30522 */ - public function data_assertSameSetsWithIndex() { + public static function data_assertSameSetsWithIndex() { return array( array( array( 1, 2, 3 ), // Test expected. @@ -316,7 +316,7 @@ public function test_die_process_input( $input, $expected ) { $this->assertSameSets( $expected['args'], array_intersect_key( $args, $expected['args'] ) ); } - public function data_die_process_input() { + public static function data_die_process_input() { return array( array( array( diff --git a/tests/phpunit/tests/includes/uploadSnapshot.php b/tests/phpunit/tests/includes/uploadSnapshot.php index 142bf80fbdf8e..f86ac782f651a 100644 --- a/tests/phpunit/tests/includes/uploadSnapshot.php +++ b/tests/phpunit/tests/includes/uploadSnapshot.php @@ -29,7 +29,7 @@ public function test_scan_user_uploads_preserves_initial_snapshot( $initial_file /** * @return array[] */ - public function data_initial_uploads() { + public static function data_initial_uploads() { return array( 'empty uploads' => array( array() ), 'existing upload' => array( array( 'existing.jpg' ) ), diff --git a/tests/phpunit/tests/link/editTermLink.php b/tests/phpunit/tests/link/editTermLink.php index 49bdab12b8689..f1fa9d13e7777 100644 --- a/tests/phpunit/tests/link/editTermLink.php +++ b/tests/phpunit/tests/link/editTermLink.php @@ -122,7 +122,7 @@ function ( $location, $term ) { * * @return array */ - public function data_edit_term_link() { + public static function data_edit_term_link() { return array( 'category passing term_id' => array( 'taxonomy' => 'category', diff --git a/tests/phpunit/tests/link/getEditTermLink.php b/tests/phpunit/tests/link/getEditTermLink.php index 451e63e0446a8..f083df8c3e4dd 100644 --- a/tests/phpunit/tests/link/getEditTermLink.php +++ b/tests/phpunit/tests/link/getEditTermLink.php @@ -213,7 +213,7 @@ function ( $location, $term ) { * * @return array */ - public function data_get_edit_term_link() { + public static function data_get_edit_term_link() { return array( 'category passing term_id' => array( 'taxonomy' => 'category', diff --git a/tests/phpunit/tests/link/getFeedLink.php b/tests/phpunit/tests/link/getFeedLink.php index 41d6d922d2dba..63ddccfbbfb45 100644 --- a/tests/phpunit/tests/link/getFeedLink.php +++ b/tests/phpunit/tests/link/getFeedLink.php @@ -19,7 +19,7 @@ public function tests_plain_permastruct( $expected, $type ) { $this->assertSame( home_url( $expected ), get_feed_link( $type ) ); } - public function data_plain_permastruct() { + public static function data_plain_permastruct() { return array( array( '?feed=rss2', '' ), array( '?feed=atom', 'atom' ), @@ -55,7 +55,7 @@ public function tests_pretty_permastruct_with_prefix( $expected, $type ) { $this->assertSame( home_url( $expected ), get_feed_link( $type ) ); } - public function data_pretty_permastruct() { + public static function data_pretty_permastruct() { return array( array( '/feed/', '' ), array( '/feed/atom/', 'atom' ), diff --git a/tests/phpunit/tests/link/getPagenumLink.php b/tests/phpunit/tests/link/getPagenumLink.php index 9c81cc84548cf..68d068034a763 100644 --- a/tests/phpunit/tests/link/getPagenumLink.php +++ b/tests/phpunit/tests/link/getPagenumLink.php @@ -89,7 +89,7 @@ public function test_get_pagenum_link_should_not_add_trailing_slash( $permalink_ * * @return array[] */ - public function data_get_pagenum_link_plain_permalinks() { + public static function data_get_pagenum_link_plain_permalinks() { return array( 'page 1 and plain permalinks' => array( 'permalink_structure' => '', @@ -144,7 +144,7 @@ public function test_get_pagenum_link_should_add_trailing_slash( $permalink_stru * * @return array[] */ - public function data_get_pagenum_link() { + public static function data_get_pagenum_link() { return array( 'page 1 and index.php' => array( 'permalink_structure' => '/index.php/%year%/%monthnum%/%day%/%postname%', diff --git a/tests/phpunit/tests/link/getThePostsNavigation.php b/tests/phpunit/tests/link/getThePostsNavigation.php index d7d3846b9a1fd..0cb39b07453ee 100644 --- a/tests/phpunit/tests/link/getThePostsNavigation.php +++ b/tests/phpunit/tests/link/getThePostsNavigation.php @@ -76,7 +76,7 @@ public function test_get_the_posts_navigation( $per_page, $paged_num, $older, $n * * @return array[] */ - public function data_get_the_posts_navigation() { + public static function data_get_the_posts_navigation() { return array( 'older posts' => array( 'post_per_page' => 1, diff --git a/tests/phpunit/tests/link/themeFile.php b/tests/phpunit/tests/link/themeFile.php index 2a16671453262..ee57ca6394c40 100644 --- a/tests/phpunit/tests/link/themeFile.php +++ b/tests/phpunit/tests/link/themeFile.php @@ -167,7 +167,7 @@ public function test_theme_file_uri_returns_valid_uri( $file, $expected_theme, $ $this->assertSame( sanitize_url( $parent_uri ), $parent_uri ); } - public function data_theme_files() { + public static function data_theme_files() { $parent = 'theme-file-parent'; $child = 'theme-file-child'; From ae93f311cb9080b1d5beb485677e4dbdadadd2f3 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:51:34 +0000 Subject: [PATCH 063/481] Tests: Make request, sitemap and KSES data providers static. Declare nine existing data providers as `public static` for compatibility with newer PHPUnit versions. Preserve their datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15214, https://github.com/WordPress/wordpress-develop/pull/15215, https://github.com/WordPress/wordpress-develop/pull/15216 Props devmuhib, shailu25, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65068 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/kses/wpFilterGlobalStylesPost.php | 2 +- tests/phpunit/tests/kses/wpKsesHair.php | 4 ++-- tests/phpunit/tests/sitemaps/wpSitemapsPosts.php | 2 +- tests/phpunit/tests/sitemaps/wpSitemapsTaxonomies.php | 2 +- tests/phpunit/tests/wp/handle404.php | 2 +- tests/phpunit/tests/wp/handleRandom.php | 6 +++--- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/phpunit/tests/kses/wpFilterGlobalStylesPost.php b/tests/phpunit/tests/kses/wpFilterGlobalStylesPost.php index a6f6f895ff980..aa219e2145fed 100644 --- a/tests/phpunit/tests/kses/wpFilterGlobalStylesPost.php +++ b/tests/phpunit/tests/kses/wpFilterGlobalStylesPost.php @@ -46,7 +46,7 @@ public function test_should_not_remove_safe_global_style_rules( $rule ) { * * @return array */ - public function data_should_not_remove_safe_global_style_rules() { + public static function data_should_not_remove_safe_global_style_rules() { $result = array(); foreach ( WP_Theme_JSON::VALID_TOP_LEVEL_KEYS as $safe_rule ) { $result[ $safe_rule ] = array( $safe_rule ); diff --git a/tests/phpunit/tests/kses/wpKsesHair.php b/tests/phpunit/tests/kses/wpKsesHair.php index 0ef834880cd5c..d60225e06a2b1 100644 --- a/tests/phpunit/tests/kses/wpKsesHair.php +++ b/tests/phpunit/tests/kses/wpKsesHair.php @@ -38,7 +38,7 @@ public function test_attribute_parsing( string $input, array $expected ) { * * @return Generator */ - public function data_attribute_parsing() { + public static function data_attribute_parsing() { yield 'empty attributes' => array( '', array(), @@ -966,7 +966,7 @@ public function test_protocol_filtering( string $input, array $expected ) { * * @return Generator */ - public function data_protocol_filtering() { + public static function data_protocol_filtering() { yield 'href allowed protocol http' => array( 'href="http://example.com"', array( diff --git a/tests/phpunit/tests/sitemaps/wpSitemapsPosts.php b/tests/phpunit/tests/sitemaps/wpSitemapsPosts.php index a7b7a4d71e183..414373645dde6 100644 --- a/tests/phpunit/tests/sitemaps/wpSitemapsPosts.php +++ b/tests/phpunit/tests/sitemaps/wpSitemapsPosts.php @@ -685,7 +685,7 @@ static function () { * * @return array */ - public function data_sitemap_does_not_404_for_valid_sitemap_subtypes(): array { + public static function data_sitemap_does_not_404_for_valid_sitemap_subtypes(): array { return array( 'post' => array( 'post' ), 'valid cpt' => array( 'valid_cpt' ), diff --git a/tests/phpunit/tests/sitemaps/wpSitemapsTaxonomies.php b/tests/phpunit/tests/sitemaps/wpSitemapsTaxonomies.php index c7864721d8b8a..855ee016ea695 100644 --- a/tests/phpunit/tests/sitemaps/wpSitemapsTaxonomies.php +++ b/tests/phpunit/tests/sitemaps/wpSitemapsTaxonomies.php @@ -323,7 +323,7 @@ static function () { * * @return array */ - public function data_sitemap_does_not_404_for_valid_sitemap_subtypes(): array { + public static function data_sitemap_does_not_404_for_valid_sitemap_subtypes(): array { return array( 'category' => array( 'category' ), 'valid custom taxonomy' => array( 'valid_custom_taxonomy' ), diff --git a/tests/phpunit/tests/wp/handle404.php b/tests/phpunit/tests/wp/handle404.php index e43af4da01d04..63843dced400e 100644 --- a/tests/phpunit/tests/wp/handle404.php +++ b/tests/phpunit/tests/wp/handle404.php @@ -46,7 +46,7 @@ public function test_sitemap_requests_should_not_be_404ed_by_an_empty_main_query * * @return array */ - public function data_sitemap_requests(): array { + public static function data_sitemap_requests(): array { return array( 'index' => array( '/?sitemap=index' ), 'posts provider' => array( '/?sitemap=posts&sitemap-subtype=post' ), diff --git a/tests/phpunit/tests/wp/handleRandom.php b/tests/phpunit/tests/wp/handleRandom.php index 0e669fd36b186..8fe206cb6b15e 100644 --- a/tests/phpunit/tests/wp/handleRandom.php +++ b/tests/phpunit/tests/wp/handleRandom.php @@ -89,7 +89,7 @@ public function test_requests_without_the_random_query_var_are_not_handled( arra * * @return array }> */ - public function data_requests_without_the_random_query_var(): array { + public static function data_requests_without_the_random_query_var(): array { return array( 'no query vars' => array( array() ), 'other query vars' => array( array( 'post_type' => 'post' ) ), @@ -164,7 +164,7 @@ public function test_main_query_runs_unchanged_for_requests_that_are_not_random_ * * @return array, 1: non-falsy-string }> */ - public function data_requests_that_are_not_random_content_requests(): array { + public static function data_requests_that_are_not_random_content_requests(): array { return array( 'post request' => array( array( 'random' => '' ), 'POST' ), 'non-randomable without posts' => array( @@ -207,7 +207,7 @@ static function () use ( $permalink ): string { * * @return array */ - public function data_permalinks_that_cannot_be_redirected_to(): array { + public static function data_permalinks_that_cannot_be_redirected_to(): array { return array( 'empty permalink' => array( '' ), 'off-site permalink' => array( 'https://elsewhere.example/post/' ), From 075aca25d59d07038dbb755359124e1382ba6557 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:54:58 +0000 Subject: [PATCH 064/481] Tests: Make privacy, plural-form and updater data providers static. Declare five existing data providers as `public static` for compatibility with newer PHPUnit versions. Preserve their datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15217, https://github.com/WordPress/wordpress-develop/pull/15229, https://github.com/WordPress/wordpress-develop/pull/15230 Props devmuhib, shailu25, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65069 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/admin/wpAutomaticUpdater.php | 2 +- tests/phpunit/tests/pomo/pluralForms.php | 2 +- .../privacy/wpPrivacyProcessPersonalDataExportPage.php | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/phpunit/tests/admin/wpAutomaticUpdater.php b/tests/phpunit/tests/admin/wpAutomaticUpdater.php index eb7d982f2a0f6..96beca77dff75 100644 --- a/tests/phpunit/tests/admin/wpAutomaticUpdater.php +++ b/tests/phpunit/tests/admin/wpAutomaticUpdater.php @@ -874,7 +874,7 @@ static function () use ( $scrape_result, $upgrading ) { * expected_message: string|null, * }> */ - public function data_has_fatal_error_should_record_fatal_error_details(): array { + public static function data_has_fatal_error_should_record_fatal_error_details(): array { return array( 'fatal error with a stack trace' => array( 'scrape_result' => array( diff --git a/tests/phpunit/tests/pomo/pluralForms.php b/tests/phpunit/tests/pomo/pluralForms.php index aace128123e2a..a5cb29fa2911f 100644 --- a/tests/phpunit/tests/pomo/pluralForms.php +++ b/tests/phpunit/tests/pomo/pluralForms.php @@ -176,7 +176,7 @@ public function test_exceptions( $expression, $expected_message, $call_get ) { } } - public function data_exceptions() { + public static function data_exceptions() { return array( array( 'n # 2', // Invalid expression to parse. diff --git a/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php b/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php index fb610a3d2cfd5..d49fa1d51aca2 100644 --- a/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php +++ b/tests/phpunit/tests/privacy/wpPrivacyProcessPersonalDataExportPage.php @@ -295,7 +295,7 @@ public function test_wp_privacy_process_personal_data_export_page( $expected_res * } * } */ - public function data_wp_privacy_process_personal_data_export_page() { + public static function data_wp_privacy_process_personal_data_export_page() { return array( // Response is not an array. array( @@ -340,7 +340,7 @@ public function data_wp_privacy_process_personal_data_export_page() { * } * } */ - public function data_send_as_email_options() { + public static function data_send_as_email_options() { return array( array( true, @@ -634,7 +634,7 @@ public function test_request_status_transitions_correctly( $expected_status, $re * } * } */ - public function data_export_page_status_transitions() { + public static function data_export_page_status_transitions() { return array( // Mark the request as completed for the last exporter on the last page, with email. array( From 2957830b409d6ebf9d02f10a0d576a1a69b81714 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 17:58:36 +0000 Subject: [PATCH 065/481] Tests: Make block and HTML-tree data providers static. Declare nine existing data providers in the block-binding, HTML-tree comparison and block-template tests as `public static`. Preserve their datasets and assertions for compatibility with newer PHPUnit versions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15231, https://github.com/WordPress/wordpress-develop/pull/15232, https://github.com/WordPress/wordpress-develop/pull/15233 Props devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65070 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/block-bindings/render.php | 6 +++--- tests/phpunit/tests/block-template.php | 6 +++--- tests/phpunit/tests/build-visual-html-tree.php | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/phpunit/tests/block-bindings/render.php b/tests/phpunit/tests/block-bindings/render.php index 32886a838c705..1055affb66dcd 100644 --- a/tests/phpunit/tests/block-bindings/render.php +++ b/tests/phpunit/tests/block-bindings/render.php @@ -78,7 +78,7 @@ public static function wpTearDownAfterClass() { unregister_block_type( 'test/block' ); } - public function data_update_block_with_value_from_source() { + public static function data_update_block_with_value_from_source() { return array( 'paragraph block' => array( 'content', @@ -180,7 +180,7 @@ public function test_update_block_with_value_from_source( $bound_attribute, $blo ); } - public function data_different_get_value_callbacks() { + public static function data_different_get_value_callbacks() { return array( 'pass arguments to source' => array( function ( $source_args, $block_instance, $attribute_name ) { @@ -533,7 +533,7 @@ public function test_filter_block_bindings_source_value() { * * @return array[] */ - public function data_rich_text_binding_preserves_nested_inner_blocks() { + public static function data_rich_text_binding_preserves_nested_inner_blocks() { $child_list = self::build_list_block( array( self::build_list_item_block( 'Nested child' ), diff --git a/tests/phpunit/tests/block-template.php b/tests/phpunit/tests/block-template.php index 85a09b7039ebc..a70f60f86cc89 100644 --- a/tests/phpunit/tests/block-template.php +++ b/tests/phpunit/tests/block-template.php @@ -382,7 +382,7 @@ public function test_get_the_block_template_html_does_not_add_skip_link_when_act * * @return array> */ - public function data_provider_skip_link_actions(): array { + public static function data_provider_skip_link_actions(): array { return array( 'the_block_template_skip_link' => array( 'action' => 'wp_footer', @@ -428,7 +428,7 @@ public function test_get_block_theme_folders( $theme, $expected ) { * * @return array[] */ - public function data_get_block_theme_folders() { + public static function data_get_block_theme_folders() { return array( 'block-theme' => array( 'block-theme', @@ -596,7 +596,7 @@ static function () use ( $theme_dir ) { * * @return array */ - public function data_get_block_templates_files_slugs() { + public static function data_get_block_templates_files_slugs() { return array( 'template parts in a theme whose directory name does not end with parts' => array( 'theme_directory' => 'default', diff --git a/tests/phpunit/tests/build-visual-html-tree.php b/tests/phpunit/tests/build-visual-html-tree.php index 528d95a61e256..d537fce5b658f 100644 --- a/tests/phpunit/tests/build-visual-html-tree.php +++ b/tests/phpunit/tests/build-visual-html-tree.php @@ -8,7 +8,7 @@ * @group testsuite */ class Tests_Build_Equivalent_HTML_Semantic_Tree extends WP_UnitTestCase { - public function data_build_equivalent_html_semantic_tree() { + public static function data_build_equivalent_html_semantic_tree() { $block_markup = <<<'HTML'
@@ -100,7 +100,7 @@ public function test_build_equivalent_html_semantic_tree( $markup, $expected ) { $this->assertSame( $expected, $actual ); } - public function data_build_equivalent_html_semantic_tree_with_equivalent_html() { + public static function data_build_equivalent_html_semantic_tree_with_equivalent_html() { return array( 'Different attribute order' => array( 'The WordPress logo', @@ -151,7 +151,7 @@ public function test_build_equivalent_html_semantic_tree_with_equivalent_html( $ $this->assertSame( $tree_expected, $tree_actual ); } - public function data_build_equivalent_html_semantic_tree_with_non_equivalent_html() { + public static function data_build_equivalent_html_semantic_tree_with_non_equivalent_html() { return array( 'Different attributes' => array( 'The WordPress logo', From 1622a69cc14210d6b0d1d79264e2417690994986 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 18:05:28 +0000 Subject: [PATCH 066/481] Tests: Make database charset data providers static. Declare seven existing data providers as `public static`. Make the read-only table definitions static and update property access and assertion calls, preserving datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15234 Props devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65071 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/db/charset.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/phpunit/tests/db/charset.php b/tests/phpunit/tests/db/charset.php index e7f3feda07309..f57119d103ccf 100644 --- a/tests/phpunit/tests/db/charset.php +++ b/tests/phpunit/tests/db/charset.php @@ -69,7 +69,7 @@ public static function set_up_before_class() { /** * @ticket 21212 */ - public function data_strip_invalid_text() { + public static function data_strip_invalid_text() { $fields = array( 'latin1' => array( // latin1. latin1 never changes. @@ -449,8 +449,8 @@ public function data_strip_invalid_text() { $big5 = mb_convert_encoding( $utf8, 'BIG-5', 'UTF-8' ); $conv_utf8 = mb_convert_encoding( $big5, 'UTF-8', 'BIG-5' ); // Make sure PHP's multibyte conversions are working correctly. - $this->assertNotSame( $utf8, $big5 ); - $this->assertSame( $utf8, $conv_utf8 ); + self::assertNotSame( $utf8, $big5 ); + self::assertSame( $utf8, $conv_utf8 ); $fields['big5'] = array( 'charset' => 'big5', @@ -560,7 +560,7 @@ public function test_process_fields_failure() { /** * @ticket 21212 */ - public function data_process_field_charsets() { + public static function data_process_field_charsets() { if ( $GLOBALS['wpdb']->charset ) { $charset = $GLOBALS['wpdb']->charset; } else { @@ -699,7 +699,7 @@ public function test_strip_invalid_text_for_column() { * * @var array */ - protected $table_and_column_defs = array( + protected static $table_and_column_defs = array( array( 'definition' => '( a INT, b FLOAT )', 'table_expected' => false, @@ -769,11 +769,11 @@ public function test_strip_invalid_text_for_column() { /** * @ticket 21212 */ - public function data_get_table_charset() { + public static function data_get_table_charset() { $table_name = 'test_get_table_charset'; $vars = array(); - foreach ( $this->table_and_column_defs as $i => $value ) { + foreach ( self::$table_and_column_defs as $i => $value ) { $this_table_name = $table_name . '_' . $i; $drop = "DROP TABLE IF EXISTS $this_table_name"; $create = "CREATE TABLE $this_table_name {$value['definition']}"; @@ -805,11 +805,11 @@ public function test_get_table_charset( $drop, $create, $table, $expected_charse /** * @ticket 21212 */ - public function data_get_column_charset() { + public static function data_get_column_charset() { $table_name = 'test_get_column_charset'; $vars = array(); - foreach ( $this->table_and_column_defs as $i => $value ) { + foreach ( self::$table_and_column_defs as $i => $value ) { $this_table_name = $table_name . '_' . $i; $drop = "DROP TABLE IF EXISTS $this_table_name"; $create = "CREATE TABLE $this_table_name {$value['definition']}"; @@ -896,7 +896,7 @@ public function test_get_column_charset_is_mysql_undefined( $drop, $create, $tab /** * @ticket 21212 */ - public function data_strip_invalid_text_from_query() { + public static function data_strip_invalid_text_from_query() { $table_name = 'strip_invalid_text_from_query_table'; $data = array( 'utf8 + binary' => array( @@ -947,7 +947,7 @@ public function test_strip_invalid_text_from_query( $create, $query, $expected, /** * @ticket 32104 */ - public function data_dont_strip_text_from_schema_queries() { + public static function data_dont_strip_text_from_schema_queries() { // An obviously invalid and fake table name. $table_name = "\xff\xff\xff\xff"; @@ -997,7 +997,7 @@ public function test_invalid_characters_in_query() { /** * @ticket 21212 */ - public function data_table_collation_check() { + public static function data_table_collation_check() { $table_name = 'table_collation_check'; $data = array( 'utf8_bin' => array( From 8af9d90441d8efce463218e83eebbf582085b71a Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 30 Oct 2026 18:10:18 +0000 Subject: [PATCH 067/481] Abilities API: Encode empty object results as JSON objects. The run endpoint prepared only associative array results for JSON clients, so an empty array returned for an object output schema, such as the `core/settings-get` result when no setting matches, was encoded as `[]` and failed output validation in JSON clients. Prepare every result, including root results, lists, object and `JsonSerializable` results, so empty objects are encoded as `{}` while arrays stay arrays. Register the run endpoint with the `data_processing` route option set to `false`, so the `_fields` and `_embed` parameters and response links leave the result unchanged and it follows the ability's output schema whether it is an object, an array, or a scalar value. The REST API client fixture lists the disabled processing for the run endpoint. Follow-up to [64311], [64592], [64689]. Props jorgefilipecosta, gziolo. See #66267. git-svn-id: https://develop.svn.wordpress.org/trunk@65072 602fd350-edb4-49c9-b593-d223f7449a82 --- ...ss-wp-rest-abilities-v1-run-controller.php | 21 +- .../wpRestAbilitiesSettingsController.php | 23 +- .../wpRestAbilitiesV1RunController.php | 251 +++++++++++++++++- 3 files changed, 273 insertions(+), 22 deletions(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php index ac3f8eb5c630d..f92eafe3f6828 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php @@ -65,6 +65,13 @@ public function register_routes(): void { 'callback' => array( $this, 'execute_ability' ), 'permission_callback' => array( $this, 'check_ability_permissions' ), 'args' => $this->get_run_args(), + + /* + * Serve the ability result as returned, so it follows the ability's output + * schema whether it is an object, an array, or a scalar value: `_fields`, + * `_embed` and response links leave it unchanged. + */ + 'data_processing' => false, ), 'schema' => array( $this, 'get_run_schema' ), ) @@ -96,18 +103,10 @@ public function execute_ability( $request ) { } /* - * Preserve empty objects in nested properties when encoding an associative - * result as JSON. Preparation can convert empty PHP arrays to stdClass. - * - * The REST server's `_fields` and `_embed` processing expects arrays at the - * response root and for numeric collection items. Converting those values - * to objects would cause type errors, so skip root empty arrays and numeric - * collections until that processing supports objects. An empty object result - * therefore still encodes as [], and a list containing one encodes as [[]]. + * Preserve empty objects when encoding the result as JSON. Preparation can + * convert empty PHP arrays to stdClass, also within object results. */ - if ( is_array( $result ) && ! wp_is_numeric_array( $result ) ) { - $result = wp_prepare_json_value_for_client( $result, $ability->get_output_schema() ); - } + $result = wp_prepare_json_value_for_client( $result, $ability->get_output_schema() ); return rest_ensure_response( $result ); } diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php index 278041158ef90..311672a5238db 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php @@ -15,7 +15,7 @@ class Tests_REST_API_WpRestAbilitiesSettingsController extends WP_UnitTestCase { /** * The REST server instance for the current test. * - * @var WP_REST_Server + * @var Spy_REST_Server */ protected $server; @@ -108,7 +108,7 @@ public function set_up(): void { parent::set_up(); global $wp_rest_server; - $wp_rest_server = new WP_REST_Server(); + $wp_rest_server = new Spy_REST_Server(); $this->server = $wp_rest_server; do_action( 'rest_api_init' ); @@ -196,6 +196,25 @@ public function test_fields_filter_from_query_string_limits_settings(): void { $this->assertEqualSets( array( 'title', 'posts_per_page' ), array_keys( $data ), 'Only the settings from the comma-separated list should be returned.' ); } + /** + * An empty result is served as a JSON object, which the output schema requires. + * + * @ticket 66267 + */ + public function test_no_matching_setting_is_encoded_as_an_empty_object(): void { + $_GET = array( + 'input' => array( + 'group' => 'reading', + 'fields' => 'title', + ), + ); + + $this->server->serve_request( self::RUN_ROUTE ); + + $this->assertSame( 200, $this->server->status, 'Filters that match no setting should be accepted.' ); + $this->assertSame( '{}', $this->server->sent_body, 'The empty result should be served as an empty object.' ); + } + /** * @ticket 64605 */ diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php index 8d0d0c5079ce8..3f89d742b9da2 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php @@ -443,6 +443,118 @@ private function register_test_abilities(): void { ) ); + // Ability that returns an object result with an empty object property. + $this->register_test_ability( + 'test/nested-empty-object-in-object-output', + array( + 'label' => 'Nested Empty Object In Object Output', + 'description' => 'Returns an object result with an empty object property.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'object', + 'properties' => array( + 'settings' => array( 'type' => 'object' ), + ), + ), + 'execute_callback' => static function () { + return (object) array( 'settings' => array() ); + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + + // Ability that returns a JsonSerializable result with an empty object property. + $this->register_test_ability( + 'test/nested-empty-object-in-json-serializable-output', + array( + 'label' => 'Nested Empty Object In JsonSerializable Output', + 'description' => 'Returns a JsonSerializable result with an empty object property.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'object', + 'properties' => array( + 'settings' => array( 'type' => 'object' ), + ), + ), + 'execute_callback' => static function () { + return new class() implements JsonSerializable { + public function jsonSerialize(): array { + return array( 'settings' => array() ); + } + }; + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + + // Ability that returns an empty list. + $this->register_test_ability( + 'test/empty-list-output', + array( + 'label' => 'Empty List Output', + 'description' => 'Returns an empty list.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'object' ), + ), + 'execute_callback' => static function () { + return array(); + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + + // Ability that returns a list of strings. + $this->register_test_ability( + 'test/string-list-output', + array( + 'label' => 'String List Output', + 'description' => 'Returns a list of strings.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'execute_callback' => static function () { + return array( 'a', 'b' ); + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + + // Ability that returns a string. + $this->register_test_ability( + 'test/string-output', + array( + 'label' => 'String Output', + 'description' => 'Returns a string.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'string', + ), + 'execute_callback' => static function () { + return 'value'; + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + // Read-only ability for query params testing. $this->register_test_ability( 'test/query-params', @@ -637,15 +749,19 @@ public function test_output_validation(): void { */ public static function data_output_is_prepared_for_json_clients(): array { return array( - 'root empty object stays unchanged' => array( 'test/empty-object-output', '[]' ), - 'nested empty object' => array( 'test/nested-empty-object-output', '{"settings":{}}' ), - 'numeric collection stays unchanged' => array( 'test/empty-object-list-output', '[[]]' ), + 'root empty object' => array( 'test/empty-object-output', '{}' ), + 'nested empty object' => array( 'test/nested-empty-object-output', '{"settings":{}}' ), + 'numeric collection' => array( 'test/empty-object-list-output', '[{}]' ), + 'object result' => array( 'test/nested-empty-object-in-object-output', '{"settings":{}}' ), + 'JsonSerializable result' => array( 'test/nested-empty-object-in-json-serializable-output', '{"settings":{}}' ), + 'root empty list' => array( 'test/empty-list-output', '[]' ), + 'list of strings' => array( 'test/string-list-output', '["a","b"]' ), + 'string' => array( 'test/string-output', '"value"' ), ); } /** - * Tests that ability results are prepared for JSON clients without breaking - * the global `_fields` and `_embed` parameters. + * Tests that ability results are prepared for JSON clients. * * @ticket 66267 * @dataProvider data_output_is_prepared_for_json_clients @@ -657,15 +773,132 @@ public function test_output_is_prepared_for_json_clients( string $ability_name, $request = new WP_REST_Request( 'POST', "/wp-abilities/v1/abilities/{$ability_name}/run" ); $response = $this->server->dispatch( $request ); - $this->assertSame( 200, $response->get_status() ); - $this->assertSame( $expected, wp_json_encode( $response->get_data() ) ); + $this->assertSame( 200, $response->get_status(), 'The ability should run successfully.' ); + $this->assertSame( $expected, wp_json_encode( $response->get_data() ), 'The result should be encoded as expected.' ); + } + + /** + * Tests that the global `_fields` and `_embed` parameters and response links leave + * ability results unchanged. + * + * @ticket 66267 + */ + public function test_global_parameters_and_response_links_leave_output_unchanged(): void { + $request = new WP_REST_Request( 'POST', '/wp-abilities/v1/abilities/test/nested-empty-object-output/run' ); + + // The result has no `other` field, so filtering would leave none of the result. + $request->set_query_params( + array( + '_fields' => 'other', + '_embed' => '1', + ) + ); - $request->set_param( '_fields', 'settings' ); + add_filter( + 'rest_post_dispatch', + static function ( $response ) { + $response->add_link( 'alternate', rest_url( '/wp-abilities/v1/abilities' ), array( 'embeddable' => true ) ); + return $response; + } + ); + + $response = $this->server->dispatch( $request ); + + $this->assertSame( 200, $response->get_status(), 'The ability should run successfully.' ); add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 ); $response = apply_filters( 'rest_post_dispatch', $response, $this->server, $request ); + $data = $this->server->response_to_data( $response, rest_parse_embed_param( $request['_embed'] ) ); + + $this->assertSame( '{"settings":{}}', wp_json_encode( $data ), 'The result should be left unchanged.' ); + } + + /** + * Tests that the global `_embed` parameter leaves the `_links` returned by an ability + * unchanged, without requesting the linked resources. + * + * @ticket 66267 + */ + public function test_links_in_the_result_are_not_embedded(): void { + $result = array( + 'id' => 1, + '_links' => array( + 'author' => array( + array( + 'href' => rest_url( '/wp-abilities/v1/abilities' ), + 'embeddable' => true, + ), + ), + ), + ); + $this->register_test_ability( + 'test/links-output', + array( + 'label' => 'Links Output', + 'description' => 'Returns an object with its own embeddable link.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'object', + ), + 'execute_callback' => static function () use ( $result ) { + return $result; + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'show_in_rest' => true, + ), + ) + ); + + $request = new WP_REST_Request( 'POST', '/wp-abilities/v1/abilities/test/links-output/run' ); + $request->set_query_params( array( '_embed' => '1' ) ); + + $response = $this->server->dispatch( $request ); + + $this->assertSame( 200, $response->get_status(), 'The ability should run successfully.' ); + + $dispatch = new MockAction(); + add_filter( 'rest_pre_dispatch', array( $dispatch, 'filter' ) ); + $data = $this->server->response_to_data( $response, rest_parse_embed_param( $request['_embed'] ) ); + + $this->assertSame( $result, $data, 'The links returned by the ability should be left unchanged.' ); + $this->assertSame( 0, $dispatch->get_call_count(), 'No linked resource should be requested.' ); + } + + /** + * Tests that preloading a read-only ability run keeps the result prepared for + * JSON clients, also with the global `_fields` and `_embed` parameters. + * + * @ticket 66267 + */ + public function test_preloaded_output_is_prepared_for_json_clients(): void { + $this->register_test_ability( + 'test/readonly-output', + array( + 'label' => 'Read-only Output', + 'description' => 'Returns an empty object from a read-only ability.', + 'category' => 'general', + 'output_schema' => array( + 'type' => 'object', + ), + 'execute_callback' => static function () { + return array(); + }, + 'permission_callback' => '__return_true', + 'meta' => array( + 'annotations' => array( + 'readonly' => true, + ), + 'show_in_rest' => true, + ), + ) + ); + + $path = '/wp-abilities/v1/abilities/test/readonly-output/run?_fields=other&_embed=1'; + $preload = rest_preload_api_request( array(), $path ); - $this->assertSame( $expected, wp_json_encode( $this->server->response_to_data( $response, true ) ) ); + $this->assertArrayHasKey( $path, $preload, 'The ability run should be preloaded.' ); + $this->assertSame( '{}', wp_json_encode( $preload[ $path ]['body'] ), 'The preloaded result should be encoded as an empty object.' ); } /** From 81dcbe6299d608d6203baa2d1546018d8ffc5aa1 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 18:10:20 +0000 Subject: [PATCH 068/481] Tests: Make user data providers and capability helpers static. Declare twelve existing user-test data providers as `public static`. Convert their capability-map helpers and update helper calls without changing datasets or assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15235 Props devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65073 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/user/capabilities.php | 54 +++++++++---------- tests/phpunit/tests/user/mapMetaCap.php | 2 +- .../tests/user/newUserEmailAdminNotice.php | 2 +- tests/phpunit/tests/user/queryCache.php | 2 +- tests/phpunit/tests/user/wpListUsers.php | 4 +- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/phpunit/tests/user/capabilities.php b/tests/phpunit/tests/user/capabilities.php index cc5f9356fc76b..b41d7c2aaaeb6 100644 --- a/tests/phpunit/tests/user/capabilities.php +++ b/tests/phpunit/tests/user/capabilities.php @@ -102,7 +102,7 @@ public function meta_filter( $meta_value, $meta_key, $meta_type ) { return $meta_value; } - private function _getSingleSitePrimitiveCaps() { + private static function _getSingleSitePrimitiveCaps() { return array( 'unfiltered_html' => array( 'administrator', 'editor' ), @@ -184,7 +184,7 @@ private function _getSingleSitePrimitiveCaps() { ); } - private function _getMultiSitePrimitiveCaps() { + private static function _getMultiSitePrimitiveCaps() { return array( 'unfiltered_html' => array(), @@ -267,7 +267,7 @@ private function _getMultiSitePrimitiveCaps() { ); } - private function _getSingleSiteMetaCaps() { + private static function _getSingleSiteMetaCaps() { return array( 'create_sites' => array(), 'delete_sites' => array(), @@ -307,7 +307,7 @@ private function _getSingleSiteMetaCaps() { ); } - private function _getMultiSiteMetaCaps() { + private static function _getMultiSiteMetaCaps() { return array( 'create_sites' => array(), 'delete_sites' => array(), @@ -347,9 +347,9 @@ private function _getMultiSiteMetaCaps() { ); } - public function dataAllCapsAndRoles() { + public static function dataAllCapsAndRoles() { $data = array(); - $caps = $this->getAllCapsAndRoles(); + $caps = self::getAllCapsAndRoles(); foreach ( self::$users as $role => $null ) { foreach ( $caps as $cap => $roles ) { @@ -372,7 +372,7 @@ public function dataAllCapsAndRoles() { * @type string $role The role to test for. * } */ - public function data_single_site_roles_to_check() { + public static function data_single_site_roles_to_check() { return array( array( 'anonymous' ), array( 'administrator' ), @@ -383,23 +383,23 @@ public function data_single_site_roles_to_check() { ); } - protected function getAllCapsAndRoles() { - return $this->getPrimitiveCapsAndRoles() + $this->getMetaCapsAndRoles(); + protected static function getAllCapsAndRoles() { + return self::getPrimitiveCapsAndRoles() + self::getMetaCapsAndRoles(); } - protected function getPrimitiveCapsAndRoles() { + protected static function getPrimitiveCapsAndRoles() { if ( is_multisite() ) { - return $this->_getMultiSitePrimitiveCaps(); + return self::_getMultiSitePrimitiveCaps(); } else { - return $this->_getSingleSitePrimitiveCaps(); + return self::_getSingleSitePrimitiveCaps(); } } - protected function getMetaCapsAndRoles() { + protected static function getMetaCapsAndRoles() { if ( is_multisite() ) { - return $this->_getMultiSiteMetaCaps(); + return self::_getMultiSiteMetaCaps(); } else { - return $this->_getSingleSiteMetaCaps(); + return self::_getSingleSiteMetaCaps(); } } @@ -407,14 +407,14 @@ protected function getMetaCapsAndRoles() { * Test the tests. */ public function test_single_and_multisite_cap_tests_match() { - $single_primitive = array_keys( $this->_getSingleSitePrimitiveCaps() ); - $multi_primitive = array_keys( $this->_getMultiSitePrimitiveCaps() ); + $single_primitive = array_keys( self::_getSingleSitePrimitiveCaps() ); + $multi_primitive = array_keys( self::_getMultiSitePrimitiveCaps() ); sort( $single_primitive ); sort( $multi_primitive ); $this->assertSame( $single_primitive, $multi_primitive ); - $single_meta = array_keys( $this->_getSingleSiteMetaCaps() ); - $multi_meta = array_keys( $this->_getMultiSiteMetaCaps() ); + $single_meta = array_keys( self::_getSingleSiteMetaCaps() ); + $multi_meta = array_keys( self::_getMultiSiteMetaCaps() ); sort( $single_meta ); sort( $multi_meta ); $this->assertSame( $single_meta, $multi_meta ); @@ -424,7 +424,7 @@ public function test_single_and_multisite_cap_tests_match() { * Test the tests. */ public function test_all_caps_of_users_are_being_tested() { - $caps = $this->getPrimitiveCapsAndRoles(); + $caps = self::getPrimitiveCapsAndRoles(); // `manage_links` is a special case. $this->assertSame( '0', get_option( 'link_manager_enabled' ) ); @@ -814,9 +814,9 @@ public function test_user_can_edit_comment_on_others_post( $role, $can_edit_othe $this->assertSame( $can_edit_others_post, $user_can_edit ); } - public function data_user_with_role_can_edit_own_post() { + public static function data_user_with_role_can_edit_own_post() { $data = array(); - $caps = $this->getPrimitiveCapsAndRoles(); + $caps = self::getPrimitiveCapsAndRoles(); foreach ( self::$users as $role => $null ) { $data[] = array( @@ -828,9 +828,9 @@ public function data_user_with_role_can_edit_own_post() { return $data; } - public function data_user_with_role_can_edit_others_posts() { + public static function data_user_with_role_can_edit_others_posts() { $data = array(); - $caps = $this->getPrimitiveCapsAndRoles(); + $caps = self::getPrimitiveCapsAndRoles(); foreach ( self::$users as $role => $null ) { $data[] = array( @@ -1361,7 +1361,7 @@ public function test_authorless_post( $status ) { $this->assertSame( 'publish' === $status, $contributor->has_cap( 'read_post', $post ) ); } - public function data_authorless_post() { + public static function data_authorless_post() { return array( array( 'draft' ), array( 'private' ), array( 'publish' ) ); } @@ -1566,7 +1566,7 @@ public function test_taxonomy_caps_map_correctly_to_their_meta_cap( $taxonomy ) } } - public function dataTaxonomies() { + public static function dataTaxonomies() { return array( array( 'post_tag', @@ -2436,7 +2436,7 @@ public function test_block_caps( $role, $cap, $use_post, $expected ) { } } - public function data_block_caps() { + public static function data_block_caps() { $post_caps = array( 'edit_block', 'read_block', diff --git a/tests/phpunit/tests/user/mapMetaCap.php b/tests/phpunit/tests/user/mapMetaCap.php index 7bf46174a859b..b969a5d8f4f58 100644 --- a/tests/phpunit/tests/user/mapMetaCap.php +++ b/tests/phpunit/tests/user/mapMetaCap.php @@ -414,7 +414,7 @@ public function test_meta_caps_throw_doing_it_wrong_without_required_argument_pr * @type string $cap The meta capability requiring an argument. * } */ - public function data_meta_caps_throw_doing_it_wrong_without_required_argument_provided() { + public static function data_meta_caps_throw_doing_it_wrong_without_required_argument_provided() { return array( array( 'delete_post' ), array( 'delete_page' ), diff --git a/tests/phpunit/tests/user/newUserEmailAdminNotice.php b/tests/phpunit/tests/user/newUserEmailAdminNotice.php index 3699929c5c85d..6c358493579e4 100644 --- a/tests/phpunit/tests/user/newUserEmailAdminNotice.php +++ b/tests/phpunit/tests/user/newUserEmailAdminNotice.php @@ -165,7 +165,7 @@ public function test_should_not_be_hooked_to_multisite_admin_notice_actions( $ho * * @return array[] */ - public function data_multisite_admin_notice_actions() { + public static function data_multisite_admin_notice_actions() { return array( 'user_admin_notices' => array( 'user_admin_notices' ), 'network_admin_notices' => array( 'network_admin_notices' ), diff --git a/tests/phpunit/tests/user/queryCache.php b/tests/phpunit/tests/user/queryCache.php index b70b940feb367..49fe342102b05 100644 --- a/tests/phpunit/tests/user/queryCache.php +++ b/tests/phpunit/tests/user/queryCache.php @@ -186,7 +186,7 @@ public function test_query_cache( array $args ) { * * @return array */ - public function data_query_cache() { + public static function data_query_cache() { $data = array( 'id' => array( 'args' => array( 'fields' => array( 'id' ) ), diff --git a/tests/phpunit/tests/user/wpListUsers.php b/tests/phpunit/tests/user/wpListUsers.php index 56bcdb5485792..f4d9bfae70949 100644 --- a/tests/phpunit/tests/user/wpListUsers.php +++ b/tests/phpunit/tests/user/wpListUsers.php @@ -97,7 +97,7 @@ public function test_should_create_a_user_list( $args, $expected ) { * * @return array */ - public function data_should_create_a_user_list() { + public static function data_should_create_a_user_list() { return array( 'defaults when no args are supplied' => array( 'args' => '', @@ -189,7 +189,7 @@ public function test_should_not_create_a_user_list( $args ) { * * @return array */ - public function data_should_not_create_a_user_list() { + public static function data_should_not_create_a_user_list() { return array( 'an empty user query result' => array( 'args' => array( From 25e1477600be4c9b85eed9028664765862abf3f7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 18:15:53 +0000 Subject: [PATCH 069/481] Tests: Make image data providers and editor discovery static. Declare fourteen existing image-test data providers as `public static`. Make the editor-discovery helper static and update helper calls, preserving datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15236 Props devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65074 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/image/editor.php | 4 +-- tests/phpunit/tests/image/editorGd.php | 4 +-- tests/phpunit/tests/image/functions.php | 34 ++++++++++++------------- tests/phpunit/tests/image/size.php | 2 +- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/tests/phpunit/tests/image/editor.php b/tests/phpunit/tests/image/editor.php index 92e6f390a0021..90a04a7f7f988 100644 --- a/tests/phpunit/tests/image/editor.php +++ b/tests/phpunit/tests/image/editor.php @@ -304,7 +304,7 @@ public function test_wp_get_webp_info( $file, $expected ) { /** * Data provider for test_wp_get_webp_info(). */ - public function data_wp_get_webp_info() { + public static function data_wp_get_webp_info() { return array( // Standard JPEG. array( @@ -381,7 +381,7 @@ public function test_wp_get_avif_info( $file, $expected ) { /** * Data provider for test_wp_get_avif_info(). */ - public function data_wp_get_avif_info() { + public static function data_wp_get_avif_info() { return array( // Standard JPEG. array( diff --git a/tests/phpunit/tests/image/editorGd.php b/tests/phpunit/tests/image/editorGd.php index a563d7c3358a1..e1763a7d5dd3e 100644 --- a/tests/phpunit/tests/image/editorGd.php +++ b/tests/phpunit/tests/image/editorGd.php @@ -445,7 +445,7 @@ public function test_crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h ); } - public function data_crop() { + public static function data_crop() { return array( 'src height and width must be greater than 0' => array( 'src_x' => 0, @@ -497,7 +497,7 @@ public function test_crop_invalid_dimensions( $src_x, $src_y, $src_w, $src_h, $d $this->assertSame( 'image_crop_error', $actual->get_error_code() ); } - public function data_crop_invalid_dimensions() { + public static function data_crop_invalid_dimensions() { return array( 'src height must be greater than 0' => array( 'src_x' => 0, diff --git a/tests/phpunit/tests/image/functions.php b/tests/phpunit/tests/image/functions.php index 10fd74cadd81e..647c96d6e761f 100644 --- a/tests/phpunit/tests/image/functions.php +++ b/tests/phpunit/tests/image/functions.php @@ -35,7 +35,7 @@ public function set_up() { * * @return string[] Available image editor classes; empty array when none are available. */ - private function get_image_editor_engine_classes() { + private static function get_image_editor_engine_classes() { $classes = array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' ); foreach ( $classes as $key => $class ) { @@ -53,8 +53,8 @@ private function get_image_editor_engine_classes() { * * @return array */ - public function data_image_editor_engine_classes() { - return $this->text_array_to_dataprovider( $this->get_image_editor_engine_classes() ); + public static function data_image_editor_engine_classes() { + return self::text_array_to_dataprovider( self::get_image_editor_engine_classes() ); } /** @@ -95,7 +95,7 @@ public function test_file_is_valid_image_positive( $file ) { * * @return array */ - public function data_file_is_valid_image_positive() { + public static function data_file_is_valid_image_positive() { // These are all image files recognized by PHP. $files = array( 'test-image-cmyk.jpg', @@ -120,7 +120,7 @@ public function data_file_is_valid_image_positive() { 'avif-transparent.avif', ); - return $this->text_array_to_dataprovider( $files ); + return self::text_array_to_dataprovider( $files ); } /** @@ -143,7 +143,7 @@ public function test_file_is_valid_image_negative( $file ) { * * @return array */ - public function data_file_is_valid_image_negative() { + public static function data_file_is_valid_image_negative() { // These are actually image files but aren't recognized or usable by PHP. $files = array( 'test-image.pct', @@ -151,7 +151,7 @@ public function data_file_is_valid_image_negative() { 'test-image.sgi', ); - return $this->text_array_to_dataprovider( $files ); + return self::text_array_to_dataprovider( $files ); } /** @@ -173,7 +173,7 @@ public function test_file_is_displayable_image_positive( $file ) { * * @return array */ - public function data_file_is_displayable_image_positive() { + public static function data_file_is_displayable_image_positive() { // These are all usable in typical web browsers. $files = array( 'test-image.gif', @@ -204,7 +204,7 @@ public function data_file_is_displayable_image_positive() { $files[] = 'avif-transparent.avif'; } - return $this->text_array_to_dataprovider( $files ); + return self::text_array_to_dataprovider( $files ); } /** @@ -226,7 +226,7 @@ public function test_file_is_displayable_image_negative( $file ) { * * @return array */ - public function data_file_is_displayable_image_negative() { + public static function data_file_is_displayable_image_negative() { // These are image files but aren't suitable for web pages because of compatibility or size issues. $files = array( // 'test-image-cmyk.jpg', Allowed in r9727. @@ -243,7 +243,7 @@ public function data_file_is_displayable_image_negative() { 'test-image.heic', ); - return $this->text_array_to_dataprovider( $files ); + return self::text_array_to_dataprovider( $files ); } /** @@ -317,8 +317,8 @@ public function test_wp_save_image_file( $class_name, $mime_type ) { * * @return array */ - public function data_wp_save_image_file() { - $classes = $this->get_image_editor_engine_classes(); + public static function data_wp_save_image_file() { + $classes = self::get_image_editor_engine_classes(); // Mime types. $mime_types = array( @@ -438,7 +438,7 @@ public function test_wp_image_editor_should_respect_image_edit_thumbnails_separa * * @return array[] */ - public function data_wp_image_editor_should_respect_image_edit_thumbnails_separately_filters() { + public static function data_wp_image_editor_should_respect_image_edit_thumbnails_separately_filters() { return array( 'true' => array( 'callback' => '__return_true', @@ -571,8 +571,8 @@ public function test_inferred_mime_types_when_saving_an_image( $class_name, $ext * * @return array */ - public function data_inferred_mime_types_when_saving_an_image() { - $classes = $this->get_image_editor_engine_classes(); + public static function data_inferred_mime_types_when_saving_an_image() { + $classes = self::get_image_editor_engine_classes(); // Mime types. $mime_types = array( @@ -1099,7 +1099,7 @@ public function test_wp_exif_frac2dec( $fraction, $expect ) { * * @return array */ - public function data_wp_exif_frac2dec() { + public static function data_wp_exif_frac2dec() { return array( 'invalid input: null' => array( 'fraction' => null, diff --git a/tests/phpunit/tests/image/size.php b/tests/phpunit/tests/image/size.php index eaa83b08f1f47..fb137b392c021 100644 --- a/tests/phpunit/tests/image/size.php +++ b/tests/phpunit/tests/image/size.php @@ -256,7 +256,7 @@ public function test_constrain_size_for_editor_invalid_size( $size ) { * * @return array[] */ - public function data_constrain_size_for_editor_invalid_size() { + public static function data_constrain_size_for_editor_invalid_size() { return array( 'null' => array( null ), 'false' => array( false ), From 9865c4acd55c79a27c7c4976f10cf4d32d0935dc Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 30 Oct 2026 18:16:36 +0000 Subject: [PATCH 070/481] Docs: Document hooks that may pass a null post object. Several hooks document their post parameter as `WP_Post` even though `get_post()` can return null before the hook fires, so callbacks that type-hint `WP_Post` fatal with a `TypeError`. This was reported for the Image Placeholders plugin, where a plugin filtered `post_thumbnail_id` to an ID with no post, leading `wp_get_attachment_image()` to pass a null `$attachment` to `wp_get_attachment_image_attributes`. The same applies to `post_password_required` and `the_password_form` when no post is found, and to `media_view_settings` and `media_view_strings` whenever `wp_enqueue_media()` is not called for a specific post. Core and bundled theme callbacks of these hooks are updated to match. Developed in https://github.com/WordPress/wordpress-develop/pull/15257. See #65860. git-svn-id: https://develop.svn.wordpress.org/trunk@65075 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-content/themes/twentyseventeen/functions.php | 2 +- src/wp-content/themes/twentysixteen/functions.php | 2 +- .../twentytwentyone/inc/template-functions.php | 7 ++++--- .../abilities/class-wp-abilities-content.php | 4 ++-- src/wp-includes/media.php | 10 +++++----- src/wp-includes/post-template.php | 12 ++++++------ .../endpoints/class-wp-rest-posts-controller.php | 4 ++-- 7 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/wp-content/themes/twentyseventeen/functions.php b/src/wp-content/themes/twentyseventeen/functions.php index e693c0fe16f8e..356ab022a05eb 100644 --- a/src/wp-content/themes/twentyseventeen/functions.php +++ b/src/wp-content/themes/twentyseventeen/functions.php @@ -609,7 +609,7 @@ function twentyseventeen_header_image_tag( $html, $header, $attr ) { * * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. * See wp_get_attachment_image(). - * @param WP_Post $attachment Image attachment post. + * @param WP_Post|null $attachment Image attachment post, or null if no post is found. * @param string|int[] $size Requested image size. Can be any registered image size name, or * an array of width and height values in pixels (in that order). * @return string[] The filtered attributes for the image markup. diff --git a/src/wp-content/themes/twentysixteen/functions.php b/src/wp-content/themes/twentysixteen/functions.php index 72bfab48f0d21..f6939eaa227f4 100644 --- a/src/wp-content/themes/twentysixteen/functions.php +++ b/src/wp-content/themes/twentysixteen/functions.php @@ -593,7 +593,7 @@ function twentysixteen_content_image_sizes_attr( $sizes, $size ) { * * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. * See wp_get_attachment_image(). - * @param WP_Post $attachment Image attachment post. + * @param WP_Post|null $attachment Image attachment post, or null if no post is found. * @param string|int[] $size Requested image size. Can be any registered image size name, or * an array of width and height values in pixels (in that order). * @return string[] The filtered attributes for the image markup. diff --git a/src/wp-content/themes/twentytwentyone/inc/template-functions.php b/src/wp-content/themes/twentytwentyone/inc/template-functions.php index f141b99a8cf8f..b7cbb1c6b12c2 100644 --- a/src/wp-content/themes/twentytwentyone/inc/template-functions.php +++ b/src/wp-content/themes/twentytwentyone/inc/template-functions.php @@ -424,8 +424,9 @@ function twenty_twenty_one_print_first_instance_of_block( $block_name, $content * @since Twenty Twenty-One 1.4 Corrected parameter name for `$output`, * added the `$post` parameter. * - * @param string $output The password form HTML output. - * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. + * @param string $output The password form HTML output. + * @param int|WP_Post|null $post Optional. Post ID or WP_Post object, or null if no post is found. + * Default is global $post. * @return string HTML content for password form for password protected post. */ function twenty_twenty_one_password_form( $output, $post = 0 ) { @@ -446,7 +447,7 @@ function twenty_twenty_one_password_form( $output, $post = 0 ) { * * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. * See wp_get_attachment_image(). - * @param WP_Post $attachment Image attachment post. + * @param WP_Post|null $attachment Image attachment post, or null if no post is found. * @param string|int[] $size Requested image size. Can be any registered image size name, or * an array of width and height values in pixels (in that order). * @return string[] The filtered attributes for the image markup. diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php index 6be7e065e0988..17e1a81ac30df 100644 --- a/src/wp-includes/abilities/class-wp-abilities-content.php +++ b/src/wp-includes/abilities/class-wp-abilities-content.php @@ -1549,8 +1549,8 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit * * @since 7.2.0 * - * @param mixed $required Whether the post currently requires a password. - * @param mixed $post The post being checked; a WP_Post when invoked by the core filter. + * @param bool $required Whether the post currently requires a password. + * @param WP_Post|null $post The post being checked, or null if no post is found. * @return bool Whether the post still requires a password. */ private function allow_password_content( $required, $post ): bool { diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 54638b4ed7c74..4cd69ade6cbb7 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -1275,7 +1275,7 @@ function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = f * * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name. * See wp_get_attachment_image(). - * @param WP_Post $attachment Image attachment post. + * @param WP_Post|null $attachment Image attachment post, or null if no post is found. * @param string|int[] $size Requested image size. Can be any registered image size name, or * an array of width and height values in pixels (in that order). */ @@ -5281,8 +5281,8 @@ function wp_enqueue_media( $args = array() ) { * * @since 3.5.0 * - * @param array $settings List of media view settings. - * @param WP_Post $post Post object. + * @param array $settings List of media view settings. + * @param WP_Post|null $post Post object, or null if the media modal is not for a specific post. */ $settings = apply_filters( 'media_view_settings', $settings, $post ); @@ -5291,8 +5291,8 @@ function wp_enqueue_media( $args = array() ) { * * @since 3.5.0 * - * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript. - * @param WP_Post $post Post object. + * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript. + * @param WP_Post|null $post Post object, or null if the media modal is not for a specific post. */ $strings = apply_filters( 'media_view_strings', $strings, $post ); diff --git a/src/wp-includes/post-template.php b/src/wp-includes/post-template.php index 8a571495e96ca..0c2e25112f9a4 100644 --- a/src/wp-includes/post-template.php +++ b/src/wp-includes/post-template.php @@ -914,9 +914,9 @@ function post_password_required( $post = null ) { * * @since 4.7.0 * - * @param bool $required Whether the user needs to supply a password. True if password has not been - * provided or is incorrect, false if password has been supplied or is not required. - * @param WP_Post $post Post object. + * @param bool $required Whether the user needs to supply a password. True if password has not been + * provided or is incorrect, false if password has been supplied or is not required. + * @param WP_Post|null $post Post object, or null if no post is found. */ return apply_filters( 'post_password_required', $required, $post ); } @@ -1862,9 +1862,9 @@ function get_the_password_form( $post = 0 ) { * @since 5.8.0 Added the `$post` parameter. * @since 6.8.0 Added the `$invalid_password` parameter. * - * @param string $output The password form HTML output. - * @param WP_Post $post Post object. - * @param string $invalid_password The invalid password message. + * @param string $output The password form HTML output. + * @param WP_Post|null $post Post object, or null if no post is found. + * @param string $invalid_password The invalid password message. */ return apply_filters( 'the_password_form', $output, $post, $invalid_password ); } diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php index 0a747714504ec..0c24925ff9245 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php @@ -181,8 +181,8 @@ public function get_items_permissions_check( $request ) { * * @since 5.7.1 * - * @param bool $required Whether the post requires a password check. - * @param WP_Post $post The post been password checked. + * @param bool $required Whether the post requires a password check. + * @param WP_Post|null $post The post being password checked, or null if no post is found. * @return bool Result of password check taking into account REST API considerations. */ public function check_password_required( $required, $post ) { From eb9d2336c4b9079168bc52760e72b21e619da009 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 18:28:35 +0000 Subject: [PATCH 071/481] Tests: Cover login URL generation and filtering. Test the default `wp_login_url()` result, redirect and reauthentication parameters separately and together, and the arguments and return value of the `login_url` filter. Developed in: https://github.com/WordPress/wordpress-develop/pull/15225 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65076 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/general/wpLoginUrl.php | 96 ++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 tests/phpunit/tests/general/wpLoginUrl.php diff --git a/tests/phpunit/tests/general/wpLoginUrl.php b/tests/phpunit/tests/general/wpLoginUrl.php new file mode 100644 index 0000000000000..952d8496f0118 --- /dev/null +++ b/tests/phpunit/tests/general/wpLoginUrl.php @@ -0,0 +1,96 @@ +assertSame( site_url( 'wp-login.php', 'login' ), wp_login_url() ); + } + + /** + * Tests that wp_login_url() appends the redirect_to parameter when a redirect is provided. + * + * @ticket 65819 + */ + public function test_wp_login_url_with_redirect() { + $redirect = home_url( '/custom-dashboard/' ); + $login_url = wp_login_url( $redirect ); + + $query = array(); + wp_parse_str( wp_parse_url( $login_url, PHP_URL_QUERY ), $query ); + + $this->assertSame( $redirect, $query['redirect_to'] ); + $this->assertArrayNotHasKey( 'reauth', $query ); + } + + /** + * Tests that wp_login_url() appends reauth=1 when $force_reauth is true. + * + * @ticket 65819 + */ + public function test_wp_login_url_with_force_reauth() { + $login_url = wp_login_url( '', true ); + + $query = array(); + wp_parse_str( wp_parse_url( $login_url, PHP_URL_QUERY ), $query ); + + $this->assertSame( '1', $query['reauth'] ); + $this->assertArrayNotHasKey( 'redirect_to', $query ); + } + + /** + * Tests that wp_login_url() appends both redirect_to and reauth when both parameters are set. + * + * @ticket 65819 + */ + public function test_wp_login_url_with_redirect_and_force_reauth() { + $redirect = home_url( '/profile/' ); + $login_url = wp_login_url( $redirect, true ); + + $query = array(); + wp_parse_str( wp_parse_url( $login_url, PHP_URL_QUERY ), $query ); + + $this->assertSame( $redirect, $query['redirect_to'] ); + $this->assertSame( '1', $query['reauth'] ); + } + + /** + * Tests that the 'login_url' filter receives the expected arguments and modifies the URL. + * + * @ticket 65819 + */ + public function test_login_url_filter() { + $filter = new MockAction(); + add_filter( 'login_url', array( $filter, 'filter' ), 10, 3 ); + + $redirect = home_url( '/landing/' ); + $url = wp_login_url( $redirect, true ); + + $this->assertSame( 1, $filter->get_call_count() ); + + $filter_args = $filter->get_args(); + $this->assertSame( $url, $filter_args[0][0] ); + $this->assertSame( $redirect, $filter_args[0][1] ); + $this->assertTrue( $filter_args[0][2] ); + + $custom_login_callback = static function ( $login_url, $redirect, $force_reauth ) { + return 'https://sso.example.com/login'; + }; + + add_filter( 'login_url', $custom_login_callback, 10, 3 ); + $this->assertSame( 'https://sso.example.com/login', wp_login_url() ); + remove_filter( 'login_url', $custom_login_callback, 10 ); + } +} From 18efcdac54e1b601bbe74055cf434f499c175c53 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 18:57:50 +0000 Subject: [PATCH 072/481] Tests: Use keyboard activation for the menu location checkbox. Focus the primary menu location checkbox and activate it with Space to avoid a click being lost when focus scrolls the menu screen. Assert the checked state before saving, retaining the saved-location and front-end navigation checks. Follow-up to [65063]. The underlying pointer-interaction issue remains tracked in #65684. Developed in: https://github.com/WordPress/wordpress-develop/pull/15261 Props westonruter. See #54892, #65684. git-svn-id: https://develop.svn.wordpress.org/trunk@65077 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/specs/classic-menus.test.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/e2e/specs/classic-menus.test.js b/tests/e2e/specs/classic-menus.test.js index 9fc301fbdabec..072eb7ed48a4c 100644 --- a/tests/e2e/specs/classic-menus.test.js +++ b/tests/e2e/specs/classic-menus.test.js @@ -57,7 +57,13 @@ test.describe( 'Classic Menus', () => { ).toBeVisible(); // Assign the menu to the theme's primary location and save. - await page.getByRole( 'checkbox', { name: 'Primary menu' } ).check(); + const primaryMenu = page.getByRole( 'checkbox', { + name: 'Primary menu', + } ); + // Use the keyboard to avoid the focus-induced scroll described in #65684. + await primaryMenu.focus(); + await page.keyboard.press( 'Space' ); + await expect( primaryMenu ).toBeChecked(); // Activate via keyboard: the sticky footer bar can shift on focus // and swallow the first pointer click at certain window heights. From b41584351a6518d9d4e1c86f79f055ab07806e4f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 30 Oct 2026 19:31:03 +0000 Subject: [PATCH 073/481] Build/Test Tools: Update PHPStan to 2.3.4. This also brings in the 2.3.3 release, which replaces the regular expression parser used to infer the shapes of `preg_match()` and `preg_match_all()` matches, along with a number of type resolution and robustness fixes. The 2.3.4 release follows with fixes to unions involving constant scalars. Developed in https://github.com/WordPress/wordpress-develop/pull/15137. Follow-up to r64757. Props westonruter, lancewillett, mukesh27. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65078 602fd350-edb4-49c9-b593-d223f7449a82 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 4f6c9de976d94..1586264a73f78 100644 --- a/composer.json +++ b/composer.json @@ -52,7 +52,7 @@ "squizlabs/php_codesniffer": "3.13.5", "wp-coding-standards/wpcs": "~3.4.1", "phpcompatibility/phpcompatibility-wp": "~2.1.3", - "phpstan/phpstan": "2.3.2", + "phpstan/phpstan": "2.3.4", "phpstan/phpstan-phpunit": "2.1.1", "yoast/phpunit-polyfills": "^1.1.0" }, From ee329435c8d9087d1ff53b6fbaf7f647af954671 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 19:39:27 +0000 Subject: [PATCH 074/481] Tests: Document intentional object value comparisons. Explain why the Abilities API coercion error and plugin update transient assertions retain `assertEquals()` to compare objects by value rather than identity. Developed in: https://github.com/WordPress/wordpress-develop/pull/15209 Props shailu25. See #64895. git-svn-id: https://develop.svn.wordpress.org/trunk@65079 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/abilities-api/wpAbility.php | 1 + .../phpunit/tests/admin/includes/plugin/wpCleanPluginsCache.php | 2 ++ 2 files changed, 3 insertions(+) diff --git a/tests/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index b8249037061df..8fdb67e29cd7f 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2494,6 +2494,7 @@ public function test_input_coercion_errors( array $schema, $input, string $path $this->assertWPError( $error ); $this->assertSame( 'ability_invalid_input', $error->get_error_code() ); $this->assertStringContainsString( $path . ' has duplicate items.', $error->get_error_message() ); + // Keep assertEquals() because the objects are intentionally compared by value. $this->assertEquals( $error, $ability->execute( $input ), 'Execution should propagate the coercion error.' ); } diff --git a/tests/phpunit/tests/admin/includes/plugin/wpCleanPluginsCache.php b/tests/phpunit/tests/admin/includes/plugin/wpCleanPluginsCache.php index f21d98f67161a..464de4d2e03c5 100644 --- a/tests/phpunit/tests/admin/includes/plugin/wpCleanPluginsCache.php +++ b/tests/phpunit/tests/admin/includes/plugin/wpCleanPluginsCache.php @@ -62,6 +62,7 @@ public function test_clears_plugins_cache_and_update_transient_by_default() { wp_cache_get( 'plugins', 'plugins' ), 'Plugins cache should be primed before the call.' ); + // Keep assertEquals() because the objects are intentionally compared by value. $this->assertEquals( $this->update_plugins_data, get_site_transient( 'update_plugins' ), @@ -90,6 +91,7 @@ public function test_keeps_update_transient_when_clear_update_cache_is_false() { wp_cache_get( 'plugins', 'plugins' ), 'Plugins object cache should still be cleared.' ); + // Keep assertEquals() because the objects are intentionally compared by value. $this->assertEquals( $this->update_plugins_data, get_site_transient( 'update_plugins' ), From f74408361d964a32f4519adf305ff37bdad372ff Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 19:41:18 +0000 Subject: [PATCH 075/481] Tests: Cover media dimension expansion. Verify that `wp_expand_dimensions()` expands example dimensions to fit maximum bounds while preserving aspect ratio. Cover matching, landscape, portrait, square, and numeric-string inputs with explicit expected dimensions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15246 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65080 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/media/wpExpandDimensions.php | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 tests/phpunit/tests/media/wpExpandDimensions.php diff --git a/tests/phpunit/tests/media/wpExpandDimensions.php b/tests/phpunit/tests/media/wpExpandDimensions.php new file mode 100644 index 0000000000000..6e60663941132 --- /dev/null +++ b/tests/phpunit/tests/media/wpExpandDimensions.php @@ -0,0 +1,46 @@ +assertSame( + $expected, + wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) + ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_expand_dimensions() { + return array( + 'matching 4:3 ratio fills the box' => array( 4, 3, 1024, 768, array( 1024, 768 ) ), + 'landscape 16:9 limited by width' => array( 16, 9, 1024, 768, array( 1024, 576 ) ), + 'portrait 9:16 limited by height' => array( 9, 16, 1024, 768, array( 432, 768 ) ), + 'square limited by shorter max side' => array( 1, 1, 800, 600, array( 600, 600 ) ), + 'numeric strings are cast to integers' => array( '16', '9', '1024', '768', array( 1024, 576 ) ), + ); + } +} From 8bc75eb805c79bb80bf040abb245e4e842afd54d Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 19:48:14 +0000 Subject: [PATCH 076/481] Tests: Cover media metadata keys and supported formats. Verify the display, edit, and JavaScript field sets returned by `wp_get_attachment_id3_keys()`, including filter arguments and returned values. Cover the default audio and video extension lists and their filters. Developed in: https://github.com/WordPress/wordpress-develop/pull/15249, https://github.com/WordPress/wordpress-develop/pull/15251 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65081 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/media/wpGetAttachmentId3Keys.php | 120 ++++++++++++++++++ .../tests/media/wpGetAudioVideoExtensions.php | 65 ++++++++++ 2 files changed, 185 insertions(+) create mode 100644 tests/phpunit/tests/media/wpGetAttachmentId3Keys.php create mode 100644 tests/phpunit/tests/media/wpGetAudioVideoExtensions.php diff --git a/tests/phpunit/tests/media/wpGetAttachmentId3Keys.php b/tests/phpunit/tests/media/wpGetAttachmentId3Keys.php new file mode 100644 index 0000000000000..3d3a3bfc4d393 --- /dev/null +++ b/tests/phpunit/tests/media/wpGetAttachmentId3Keys.php @@ -0,0 +1,120 @@ +attachment->create_and_get(); + } + + /** + * @ticket 65819 + */ + public function test_returns_display_keys_by_default() { + $fields = wp_get_attachment_id3_keys( self::$attachment ); + + $this->assertSame( + array( + 'artist', + 'album', + 'genre', + 'year', + 'length_formatted', + ), + array_keys( $fields ) + ); + $this->assertSame( 'Artist', $fields['artist'] ); + $this->assertSame( 'Album', $fields['album'] ); + $this->assertSame( 'Genre', $fields['genre'] ); + $this->assertSame( 'Year', $fields['year'] ); + $this->assertSame( 'Length', $fields['length_formatted'] ); + } + + /** + * @ticket 65819 + */ + public function test_returns_base_keys_for_edit_context() { + $fields = wp_get_attachment_id3_keys( self::$attachment, 'edit' ); + + $this->assertSame( + array( + 'artist', + 'album', + ), + array_keys( $fields ) + ); + $this->assertSame( 'Artist', $fields['artist'] ); + $this->assertSame( 'Album', $fields['album'] ); + } + + /** + * @ticket 65819 + */ + public function test_returns_js_context_keys() { + $fields = wp_get_attachment_id3_keys( self::$attachment, 'js' ); + + $this->assertSame( + array( + 'artist', + 'album', + 'bitrate', + 'bitrate_mode', + ), + array_keys( $fields ) + ); + $this->assertSame( 'Bitrate', $fields['bitrate'] ); + $this->assertSame( 'Bitrate Mode', $fields['bitrate_mode'] ); + } + + /** + * @ticket 65819 + */ + public function test_filter_can_modify_keys() { + add_filter( + 'wp_get_attachment_id3_keys', + static function ( $fields ) { + $fields['custom'] = 'Custom'; + return $fields; + } + ); + + $fields = wp_get_attachment_id3_keys( self::$attachment, 'edit' ); + + $this->assertArrayHasKey( 'custom', $fields ); + $this->assertSame( 'Custom', $fields['custom'] ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_attachment_and_context() { + $received_args = array(); + + add_filter( + 'wp_get_attachment_id3_keys', + static function ( $fields, $attachment, $context ) use ( &$received_args ) { + $received_args = array( $attachment, $context ); + return $fields; + }, + 10, + 3 + ); + + wp_get_attachment_id3_keys( self::$attachment, 'js' ); + + $this->assertSame( array( self::$attachment, 'js' ), $received_args ); + } +} diff --git a/tests/phpunit/tests/media/wpGetAudioVideoExtensions.php b/tests/phpunit/tests/media/wpGetAudioVideoExtensions.php new file mode 100644 index 0000000000000..ec3fe8d1e615d --- /dev/null +++ b/tests/phpunit/tests/media/wpGetAudioVideoExtensions.php @@ -0,0 +1,65 @@ +assertSame( + array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ), + wp_get_audio_extensions() + ); + } + + /** + * @ticket 65819 + * + * @covers ::wp_get_audio_extensions + */ + public function test_filter_can_modify_audio_extensions() { + add_filter( + 'wp_audio_extensions', + static function () { + return array( 'mp3', 'aac' ); + } + ); + + $this->assertSame( array( 'mp3', 'aac' ), wp_get_audio_extensions() ); + } + + /** + * @ticket 65819 + * + * @covers ::wp_get_video_extensions + */ + public function test_returns_default_video_extensions() { + $this->assertSame( + array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ), + wp_get_video_extensions() + ); + } + + /** + * @ticket 65819 + * + * @covers ::wp_get_video_extensions + */ + public function test_filter_can_modify_video_extensions() { + add_filter( + 'wp_video_extensions', + static function () { + return array( 'mp4', 'mkv' ); + } + ); + + $this->assertSame( array( 'mp4', 'mkv' ), wp_get_video_extensions() ); + } +} From f17a0cfb819bf101ee88fa8fc4c9855f5c750a52 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:00:19 +0000 Subject: [PATCH 077/481] Tests: Cover user-name escaping in admin output. Verify that account-menu titles, user-list rows, and network user-list columns escape display names and logins containing HTML. Check checkbox labels and visible escaped text. Developed in: https://github.com/WordPress/wordpress-develop/pull/15208 Props ravipatel. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65082 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/admin/wpMsUsersListTable.php | 37 +++++++++++++++++++ .../phpunit/tests/admin/wpUsersListTable.php | 21 +++++++++++ tests/phpunit/tests/adminbar.php | 27 ++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 tests/phpunit/tests/admin/wpMsUsersListTable.php diff --git a/tests/phpunit/tests/admin/wpMsUsersListTable.php b/tests/phpunit/tests/admin/wpMsUsersListTable.php new file mode 100644 index 0000000000000..d32b5d46833c8 --- /dev/null +++ b/tests/phpunit/tests/admin/wpMsUsersListTable.php @@ -0,0 +1,37 @@ +user->create( array( 'role' => 'administrator' ) ); + grant_super_admin( $super_admin_id ); + wp_set_current_user( $super_admin_id ); + + $table = _get_list_table( 'WP_MS_Users_List_Table', array( 'screen' => 'users-network' ) ); + + $user = get_userdata( self::factory()->user->create() ); + $user->user_login = ''; + + foreach ( array( 'column_username', 'column_cb' ) as $column ) { + $output = get_echo( array( $table, $column ), array( $user ) ); + + $this->assertStringNotContainsString( 'assertStringContainsString( '<svg onload=alert(1)>', $output, "The escaped login should be shown in {$column}()." ); + } + } +} diff --git a/tests/phpunit/tests/admin/wpUsersListTable.php b/tests/phpunit/tests/admin/wpUsersListTable.php index 17438d074c3b4..b1ebab4ca6b14 100644 --- a/tests/phpunit/tests/admin/wpUsersListTable.php +++ b/tests/phpunit/tests/admin/wpUsersListTable.php @@ -30,4 +30,25 @@ public function test_get_views_should_return_views_by_default() { $this->assertSame( $expected, $this->table->get_views() ); } + + /** + * The user login is escaped in the username column and the checkbox label. + * + * @ticket 65819 + * + * @covers WP_Users_List_Table::single_row + */ + public function test_single_row_escapes_user_login() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $user = get_userdata( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + $user->user_login = ''; + + $row = $this->table->single_row( $user ); + + $this->assertStringNotContainsString( 'assertMatchesRegularExpression( '#(]+>)?<svg onload=alert\(1\)>#', $row, 'The escaped login should be shown in the username column.' ); + $this->assertStringContainsString( 'Select <svg onload=alert(1)>', $row, 'The escaped login should be in the checkbox label.' ); + } } diff --git a/tests/phpunit/tests/adminbar.php b/tests/phpunit/tests/adminbar.php index 5cdd37cfdf6e3..0183c38e58e04 100644 --- a/tests/phpunit/tests/adminbar.php +++ b/tests/phpunit/tests/adminbar.php @@ -963,6 +963,33 @@ public function test_my_account_falls_back_to_user_login_when_display_name_is_em $this->assertStringContainsString( "Hey — boo?', wptexturize( 'Hey -- boo?' ) ); } - public function test_disable() { + /** + * Tests texturization is disabled inside certain HTML elements. + */ + public function test_disable(): void { $this->assertSame( '
---&
', wptexturize( '
---&
' ) ); $this->assertSame( '
--&
', wptexturize( '
--&
' ) ); @@ -35,25 +41,31 @@ public function test_disable() { } /** + * Tests bracketed quote conversion. + * * @ticket 1418 */ - public function test_bracketed_quotes_1418() { + public function test_bracketed_quotes_1418(): void { $this->assertSame( '(“test”)', wptexturize( '("test")' ) ); $this->assertSame( '(‘test’)', wptexturize( "('test')" ) ); $this->assertSame( '(’twas)', wptexturize( "('twas)" ) ); } /** + * Tests bracketed quote conversion with a specific example. + * * @ticket 3810 */ - public function test_bracketed_quotes_3810() { + public function test_bracketed_quotes_3810(): void { $this->assertSame( 'A dog (“Hubertus”) was sent out.', wptexturize( 'A dog ("Hubertus") was sent out.' ) ); } /** + * Tests basic quote conversion (apostrophes, single quotes, double quotes). + * * @ticket 4539 */ - public function test_basic_quotes() { + public function test_basic_quotes(): void { $this->assertSame( 'test’s', wptexturize( 'test\'s' ) ); $this->assertSame( '‘quoted’', wptexturize( '\'quoted\'' ) ); @@ -73,10 +85,12 @@ public function test_basic_quotes() { } /** + * Tests full sentences with unmatched single quotes. + * * @ticket 4539 * @ticket 15241 */ - public function test_full_sentences_with_unmatched_single_quotes() { + public function test_full_sentences_with_unmatched_single_quotes(): void { $this->assertSame( 'That means every moment you’re working on something without it being in the public it’s actually dying.', wptexturize( "That means every moment you're working on something without it being in the public it's actually dying." ) @@ -84,9 +98,11 @@ public function test_full_sentences_with_unmatched_single_quotes() { } /** + * Tests quote conversion with various surrounding contexts. + * * @ticket 4539 */ - public function test_quotes() { + public function test_quotes(): void { $this->assertSame( '“Quoted String”', wptexturize( '"Quoted String"' ) ); // $this->assertSame( 'Here is “a test with a link”', wptexturize( 'Here is "a test with a link"' ) ); // $this->assertSame( 'Here is “a test with a link and a period”.', wptexturize( 'Here is "a test with a link and a period".' ) ); @@ -103,9 +119,11 @@ public function test_quotes() { } /** + * Tests quotes before an "s" (possessives and contractions). + * * @ticket 4539 */ - public function test_quotes_before_s() { + public function test_quotes_before_s(): void { $this->assertSame( 'test’s', wptexturize( "test's" ) ); $this->assertSame( '‘test’s', wptexturize( "'test's" ) ); $this->assertSame( '‘test’s’', wptexturize( "'test's'" ) ); @@ -114,9 +132,11 @@ public function test_quotes_before_s() { } /** + * Tests quotes before numbers (year abbreviations, etc.). + * * @ticket 4539 */ - public function test_quotes_before_numbers() { + public function test_quotes_before_numbers(): void { $this->assertSame( 'Class of ’99', wptexturize( "Class of '99" ) ); $this->assertSame( 'Class of ’99’s', wptexturize( "Class of '99's" ) ); $this->assertSame( '‘Class of ’99’', wptexturize( "'Class of '99'" ) ); @@ -143,25 +163,36 @@ public function test_quotes_before_numbers() { $this->assertSame( '}”Class of ’99″{', wptexturize( "}\"Class of '99\"{" ) ); } - public function test_quotes_after_numbers() { + /** + * Tests quotes after numbers. + */ + public function test_quotes_after_numbers(): void { $this->assertSame( 'Class of ’99', wptexturize( "Class of '99" ) ); } /** + * Tests quotes next to HTML tags. + * * @ticket 4539 * @ticket 15241 */ - public function test_other_html() { + public function test_other_html(): void { $this->assertSame( '‘', wptexturize( "'" ) ); // $this->assertSame( '‘Quoted Text’,', wptexturize( "'Quoted Text'," ) ); // $this->assertSame( '“Quoted Text”,', wptexturize( '"Quoted Text",' ) ); } - public function test_x() { + /** + * Tests multiplication sign (x between digits) conversion. + */ + public function test_x(): void { $this->assertSame( '14×24', wptexturize( '14x24' ) ); } - public function test_minutes_seconds() { + /** + * Tests prime (minutes/feet) and double-prime (seconds/inches) conversion. + */ + public function test_minutes_seconds(): void { $this->assertSame( '9′', wptexturize( '9\'' ) ); $this->assertSame( '9″', wptexturize( '9"' ) ); @@ -173,9 +204,11 @@ public function test_minutes_seconds() { } /** + * Tests quotes around numbers. + * * @ticket 8775 */ - public function test_wptexturize_quotes_around_numbers() { + public function test_wptexturize_quotes_around_numbers(): void { $this->assertSame( '“12345”', wptexturize( '"12345"' ) ); $this->assertSame( '‘12345’', wptexturize( '\'12345\'' ) ); $this->assertSame( '“a 9′ plus a ‘9’, maybe a 9′ ‘9’”', wptexturize( '"a 9\' plus a \'9\', maybe a 9\' \'9\'"' ) ); @@ -183,34 +216,42 @@ public function test_wptexturize_quotes_around_numbers() { } /** + * Tests HTML comments are not texturized. + * * @ticket 8912 */ - public function test_wptexturize_html_comments() { + public function test_wptexturize_html_comments(): void { $this->assertSame( '', wptexturize( '' ) ); $this->assertSame( '', wptexturize( '' ) ); $this->assertSame( '
  • Hello.
', wptexturize( '
  • Hello.
' ) ); } /** + * Tests quote cuddling with HTML entities. + * * @ticket 4539 * @ticket 15241 */ - public function test_entity_quote_cuddling() { + public function test_entity_quote_cuddling(): void { $this->assertSame( ' “Testing”', wptexturize( ' "Testing"' ) ); // $this->assertSame( '&“Testing”', wptexturize( '&"Testing"' ) ); } /** + * Tests apostrophes before primes in version numbers. + * * @ticket 22823 */ - public function test_apostrophes_before_primes() { + public function test_apostrophes_before_primes(): void { $this->assertSame( 'WordPress 3.5’s release date', wptexturize( "WordPress 3.5's release date" ) ); } /** + * Tests spaces around hyphens and dashes. + * * @ticket 23185 */ - public function test_spaces_around_hyphens() { + public function test_spaces_around_hyphens(): void { $nbsp = "\xC2\xA0"; $this->assertSame( ' – ', wptexturize( ' - ' ) ); @@ -231,9 +272,11 @@ public function test_spaces_around_hyphens() { } /** + * Tests hyphens and dashes at the start or end of strings. + * * @ticket 31030 */ - public function test_hyphens_at_start_and_end() { + public function test_hyphens_at_start_and_end(): void { $this->assertSame( '– ', wptexturize( '- ' ) ); $this->assertSame( '– –', wptexturize( '- -' ) ); $this->assertSame( ' –', wptexturize( ' -' ) ); @@ -250,7 +293,7 @@ public function test_hyphens_at_start_and_end() { * * @ticket 22692 */ - public function test_spaces_around_quotes_never() { + public function test_spaces_around_quotes_never(): void { $nbsp = "\xC2\xA0"; $problem_input = "$nbsp\"A"; @@ -267,11 +310,16 @@ public function test_spaces_around_quotes_never() { * @ticket 22692 * @dataProvider data_spaces_around_quotes */ - public function test_spaces_around_quotes( $input, $output ) { + public function test_spaces_around_quotes( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_spaces_around_quotes() { + /** + * Data provider for {@see self::test_spaces_around_quotes()}. + * + * @return list + */ + public static function data_spaces_around_quotes(): array { $nbsp = "\xC2\xA0"; $pi = "\xCE\xA0"; @@ -323,11 +371,16 @@ public static function data_spaces_around_quotes() { * @ticket 22692 * @dataProvider data_apos_before_digits */ - public function test_apos_before_digits( $input, $output ) { + public function test_apos_before_digits( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_apos_before_digits() { + /** + * Data provider for {@see self::test_apos_before_digits()}. + * + * @return list + */ + public static function data_apos_before_digits(): array { return array( array( "word '99 word", @@ -364,11 +417,16 @@ public static function data_apos_before_digits() { * @ticket 22692 * @dataProvider data_opening_single_quote */ - public function test_opening_single_quote( $input, $output ) { + public function test_opening_single_quote( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_opening_single_quote() { + /** + * Data provider for {@see self::test_opening_single_quote()}. + * + * @return list + */ + public static function data_opening_single_quote(): array { return array( array( "word 'word word", @@ -493,11 +551,16 @@ public static function data_opening_single_quote() { * @ticket 22692 * @dataProvider data_double_prime */ - public function test_double_prime( $input, $output ) { + public function test_double_prime( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_double_prime() { + /** + * Data provider for {@see self::test_double_prime()}. + * + * @return list + */ + public static function data_double_prime(): array { return array( array( 'word 99" word', @@ -526,11 +589,16 @@ public static function data_double_prime() { * @ticket 22692 * @dataProvider data_single_prime */ - public function test_single_prime( $input, $output ) { + public function test_single_prime( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_single_prime() { + /** + * Data provider for {@see self::test_single_prime()}. + * + * @return list + */ + public static function data_single_prime(): array { return array( array( "word 99' word", @@ -559,11 +627,16 @@ public static function data_single_prime() { * @ticket 22692 * @dataProvider data_contractions */ - public function test_contractions( $input, $output ) { + public function test_contractions( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_contractions() { + /** + * Data provider for {@see self::test_contractions()}. + * + * @return list + */ + public static function data_contractions(): array { return array( array( "word word's word", @@ -600,11 +673,16 @@ public static function data_contractions() { * @ticket 22692 * @dataProvider data_opening_quote */ - public function test_opening_quote( $input, $output ) { + public function test_opening_quote( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_opening_quote() { + /** + * Data provider for {@see self::test_opening_quote()}. + * + * @return list + */ + public static function data_opening_quote(): array { return array( array( 'word "word word', @@ -677,11 +755,16 @@ public static function data_opening_quote() { * @ticket 22692 * @dataProvider data_closing_quote */ - public function test_closing_quote( $input, $output ) { + public function test_closing_quote( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_closing_quote() { + /** + * Data provider for {@see self::test_closing_quote()}. + * + * @return list + */ + public static function data_closing_quote(): array { return array( array( 'word word" word', @@ -766,11 +849,16 @@ public static function data_closing_quote() { * @ticket 22692 * @dataProvider data_closing_single_quote */ - public function test_closing_single_quote( $input, $output ) { + public function test_closing_single_quote( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_closing_single_quote() { + /** + * Data provider for {@see self::test_closing_single_quote()}. + * + * @return list + */ + public static function data_closing_single_quote(): array { return array( array( "word word' word", @@ -856,11 +944,16 @@ public static function data_closing_single_quote() { * @ticket 30445 * @dataProvider data_multiplication */ - public function test_multiplication( $input, $output ) { + public function test_multiplication( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_multiplication() { + /** + * Data provider for {@see self::test_multiplication()}. + * + * @return list + */ + public static function data_multiplication(): array { return array( array( '9x9', @@ -906,11 +999,16 @@ public static function data_multiplication() { * @ticket 22692 * @dataProvider data_ampersand */ - public function test_ampersand( $input, $output ) { + public function test_ampersand( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_ampersand() { + /** + * Data provider for {@see self::test_ampersand()}. + * + * @return list + */ + public static function data_ampersand(): array { return array( array( 'word & word', @@ -971,11 +1069,16 @@ public static function data_ampersand() { * @ticket 22692 * @dataProvider data_cockney */ - public function test_cockney( $input, $output ) { + public function test_cockney( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_cockney() { + /** + * Data provider for {@see self::test_cockney()}. + * + * @return list + */ + public static function data_cockney(): array { return array( array( "word 'tain't word", @@ -1032,11 +1135,16 @@ public static function data_cockney() { * @ticket 22692 * @dataProvider data_smart_dashes */ - public function test_smart_dashes( $input, $output ) { + public function test_smart_dashes( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_smart_dashes() { + /** + * Data provider for {@see self::test_smart_dashes()}. + * + * @return list + */ + public static function data_smart_dashes(): array { return array( array( 'word --- word', @@ -1085,11 +1193,16 @@ public static function data_smart_dashes() { * @ticket 22692 * @dataProvider data_misc_static_replacements */ - public function test_misc_static_replacements( $input, $output ) { + public function test_misc_static_replacements( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_misc_static_replacements() { + /** + * Data provider for {@see self::test_misc_static_replacements()}. + * + * @return list + */ + public static function data_misc_static_replacements(): array { return array( array( 'word ... word', @@ -1140,11 +1253,16 @@ public static function data_misc_static_replacements() { * @ticket 8775 * @dataProvider data_quoted_numbers */ - public function test_quoted_numbers( $input, $output ) { + public function test_quoted_numbers( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_quoted_numbers() { + /** + * Data provider for {@see self::test_quoted_numbers()}. + * + * @return list + */ + public static function data_quoted_numbers(): array { return array( array( 'word "42.00" word', @@ -1191,11 +1309,16 @@ public static function data_quoted_numbers() { * @ticket 20342 * @dataProvider data_quotes_and_dashes */ - public function test_quotes_and_dashes( $input, $output ) { + public function test_quotes_and_dashes( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_quotes_and_dashes() { + /** + * Data provider for {@see self::test_quotes_and_dashes()}. + * + * @return list + */ + public static function data_quotes_and_dashes(): array { return array( array( 'word---"quote"', @@ -1254,11 +1377,16 @@ public static function data_quotes_and_dashes() { * @ticket 12690 * @dataProvider data_tag_avoidance */ - public function test_tag_avoidance( $input, $output ) { + public function test_tag_avoidance( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_tag_avoidance() { + /** + * Data provider for {@see self::test_tag_avoidance()}. + * + * @return list + */ + public static function data_tag_avoidance(): array { return array( array( '[ ... ]', @@ -1477,11 +1605,16 @@ public static function data_tag_avoidance() { * @ticket 26850 * @dataProvider data_year_abbr */ - public function test_year_abbr( $input, $output ) { + public function test_year_abbr( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_year_abbr() { + /** + * Data provider for {@see self::test_year_abbr()}. + * + * @return list + */ + public static function data_year_abbr(): array { return array( array( "word '99 word", @@ -1566,7 +1699,7 @@ public static function data_year_abbr() { * @ticket 27426 * @dataProvider data_translate */ - public function test_translate( $input, $output ) { + public function test_translate( string $input, string $output ): void { add_filter( 'gettext_with_context', array( $this, 'filter_translate' ), 10, 4 ); $result = wptexturize( $input, true ); @@ -1606,7 +1739,12 @@ public function filter_translate( $translations, $text, $context, $domain ) { } } - public static function data_translate() { + /** + * Data provider for {@see self::test_translate()}. + * + * @return list + */ + public static function data_translate(): array { return array( array( "word '99 word", @@ -1793,11 +1931,16 @@ public static function data_translate() { * @ticket 28483 * @dataProvider data_element_stack */ - public function test_element_stack( $input, $output ) { + public function test_element_stack( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_element_stack() { + /** + * Data provider for {@see self::test_element_stack()}. + * + * @return list + */ + public static function data_element_stack(): array { return array( array( 'hello---', @@ -1844,13 +1987,12 @@ public static function data_element_stack() { * @ticket 29557 * @dataProvider data_unregistered_shortcodes */ - public function test_unregistered_shortcodes( $input, $output ) { + public function test_unregistered_shortcodes( string $input, string $output ): void { add_filter( 'no_texturize_shortcodes', array( $this, 'filter_shortcodes' ), 10, 1 ); - $output = $this->assertSame( $output, wptexturize( $input ) ); + $this->assertSame( $output, wptexturize( $input ) ); remove_filter( 'no_texturize_shortcodes', array( $this, 'filter_shortcodes' ) ); - return $output; } public function filter_shortcodes( $disabled ) { @@ -1858,7 +2000,12 @@ public function filter_shortcodes( $disabled ) { return $disabled; } - public static function data_unregistered_shortcodes() { + /** + * Data provider for {@see self::test_unregistered_shortcodes()}. + * + * @return list + */ + public static function data_unregistered_shortcodes(): array { return array( array( '[a]a--b[audio]---[/audio]a--b[/a]', @@ -1929,11 +2076,16 @@ public static function data_unregistered_shortcodes() { * @ticket 29256 * @dataProvider data_primes_vs_quotes */ - public function test_primes_vs_quotes( $input, $output ) { + public function test_primes_vs_quotes( string $input, string $output ): void { $this->assertSame( $output, wptexturize( $input ) ); } - public static function data_primes_vs_quotes() { + /** + * Data provider for {@see self::test_primes_vs_quotes()}. + * + * @return list + */ + public static function data_primes_vs_quotes(): array { return array( array( "George's porch is 99' long.", @@ -1991,7 +2143,7 @@ public static function data_primes_vs_quotes() { * @ticket 29256 * @dataProvider data_primes_quotes_translation */ - public function test_primes_quotes_translation( $input, $output ) { + public function test_primes_quotes_translation( string $input, string $output ): void { add_filter( 'gettext_with_context', array( $this, 'filter_translate2' ), 10, 4 ); $result = wptexturize( $input, true ); @@ -2029,7 +2181,12 @@ public function filter_translate2( $translations, $text, $context, $domain ) { } } - public static function data_primes_quotes_translation() { + /** + * Data provider for {@see self::test_primes_quotes_translation()}. + * + * @return list + */ + public static function data_primes_quotes_translation(): array { return array( array( "George's porch is 99' long.", @@ -2086,8 +2243,9 @@ public static function data_primes_quotes_translation() { * * @covers ::_get_wptexturize_split_regex * @covers ::_get_wptexturize_shortcode_regex + * @covers ::get_html_split_regex */ - public function test_pcre_performance( $input ) { + public function test_pcre_performance( string $input ): void { global $shortcode_tags; // With shortcodes disabled. @@ -2099,7 +2257,7 @@ public function test_pcre_performance( $input ) { $shortcode_regex = _get_wptexturize_shortcode_regex( array_keys( $shortcode_tags ) ); $regex = _get_wptexturize_split_regex( $shortcode_regex ); $result = benchmark_pcre_backtracking( $regex, $input, 'split' ); - return $this->assertLessThan( 200, $result ); + $this->assertLessThan( 200, $result ); } /** @@ -2107,11 +2265,16 @@ public function test_pcre_performance( $input ) { * * @ticket 35864 */ - public function test_trailing_less_than() { + public function test_trailing_less_than(): void { $this->assertSame( 'F–oo<', wptexturize( 'F--oo<', true ) ); } - public static function data_whole_posts() { + /** + * Data provider for {@see self::test_pcre_performance()}. + * + * @return array + */ + public static function data_whole_posts(): array { require_once DIR_TESTDATA . '/formatting/whole-posts.php'; return data_whole_posts(); } From 5abc04732ffecc6d9cdaa3a405669d2612b2bba2 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:23:41 +0000 Subject: [PATCH 082/481] Tests: Cover filtering the path passed to `wp_delete_file()`. Verify that an empty filtered path prevents deletion and that a replacement path is deleted while the original file remains. Extend the existing basic deletion tests with both filter outcomes. Developed in: https://github.com/WordPress/wordpress-develop/pull/14890 Props bluefairydevelopment, pbearne. Fixes #59788. git-svn-id: https://develop.svn.wordpress.org/trunk@65087 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/functions/wpDeleteFile.php | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/phpunit/tests/functions/wpDeleteFile.php b/tests/phpunit/tests/functions/wpDeleteFile.php index 33de72a9ed1d4..6cbc596855b75 100644 --- a/tests/phpunit/tests/functions/wpDeleteFile.php +++ b/tests/phpunit/tests/functions/wpDeleteFile.php @@ -35,4 +35,39 @@ public function test_wp_delete_file_with_file_that_does_not_exist() { $this->assertFileDoesNotExist( $file, "$file already existed as a file before testing." ); $this->assertFalse( wp_delete_file( $file ), 'Attempting to delete a non-existent file should return false.' ); } + + /** + * @ticket 59788 + */ + public function test_wp_delete_file_does_not_delete_when_filter_returns_empty() { + $file = wp_tempnam( 'a_file_that_exists.txt' ); + + add_filter( 'wp_delete_file', '__return_empty_string' ); + + $this->assertFalse( wp_delete_file( $file ), 'wp_delete_file() should return false when the filter returns an empty path.' ); + $this->assertFileExists( $file, 'The file should not be deleted when the filter returns an empty path.' ); + + unlink( $file ); + } + + /** + * @ticket 59788 + */ + public function test_wp_delete_file_deletes_the_filtered_path() { + $file = wp_tempnam( 'a_file_that_exists.txt' ); + $filtered = wp_tempnam( 'a_filtered_file.txt' ); + + add_filter( + 'wp_delete_file', + static function () use ( $filtered ) { + return $filtered; + } + ); + + $this->assertTrue( wp_delete_file( $file ), 'wp_delete_file() should return true when the filtered path is deleted.' ); + $this->assertFileDoesNotExist( $filtered, 'The filtered path should be deleted.' ); + $this->assertFileExists( $file, 'The original path should not be deleted when the filter changes it.' ); + + unlink( $file ); + } } From 29e4849bf8e8d9b7acd30517f9f9b22290b4d3e5 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:24:59 +0000 Subject: [PATCH 083/481] Tests: Delete real files in filesystem deletion tests. Use the stored fixture path without appending its key. Assert that the visible and hidden files exist before deletion, so the tests exercise `WP_Filesystem_Direct::delete()` on real files instead of passing for nonexistent paths. Developed in: https://github.com/WordPress/wordpress-develop/pull/14902 Props benitoalba. See #57774. git-svn-id: https://develop.svn.wordpress.org/trunk@65088 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/filesystem/wpFilesystemDirect/delete.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/filesystem/wpFilesystemDirect/delete.php b/tests/phpunit/tests/filesystem/wpFilesystemDirect/delete.php index c65e1475ac19f..60fb392bffd86 100644 --- a/tests/phpunit/tests/filesystem/wpFilesystemDirect/delete.php +++ b/tests/phpunit/tests/filesystem/wpFilesystemDirect/delete.php @@ -72,8 +72,9 @@ public function test_should_delete_a_directory_with_contents() { * @param string $file The key for the file in `self::$file_structure`. */ public function test_should_delete_a_file( $file ) { - $file = self::$file_structure[ $file ]['path'] . $file; + $file = self::$file_structure[ $file ]['path']; + $this->assertFileExists( $file, 'The file did not exist before deletion.' ); $this->assertTrue( self::$filesystem->delete( $file ), 'File deletion failed.' ); $this->assertFileDoesNotExist( $file, 'The file was not deleted.' ); } From 92eb256c75426d3c97619c4d4e21e8c32d1f692f Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:32:46 +0000 Subject: [PATCH 084/481] Tests: Cover attachment field inheritance when editing images. Verify that edited attachments inherit omitted title, caption, description, and alt text from the original. Cover absent alt metadata and requests that override selected fields while inheriting the others. Developed in: https://github.com/WordPress/wordpress-develop/pull/14893 Props irozum. See #50675. git-svn-id: https://develop.svn.wordpress.org/trunk@65089 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/rest-attachments-controller.php | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/tests/phpunit/tests/rest-api/rest-attachments-controller.php b/tests/phpunit/tests/rest-api/rest-attachments-controller.php index 953713638fea4..2a4cd1feaef79 100644 --- a/tests/phpunit/tests/rest-api/rest-attachments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-attachments-controller.php @@ -3751,6 +3751,124 @@ public function test_edit_image_updates_attachment_fields() { $this->assertSame( 'Test Alt Text', get_post_meta( $new_attachment_id, '_wp_attachment_image_alt', true ), 'Alt text of the updated attachment is not identical.' ); } + /** + * Tests that an edited image inherits the title, caption, description and alt text of the original attachment. + * + * @ticket 50675 + * @requires function imagejpeg + */ + public function test_edit_image_copies_fields_from_original_attachment() { + $attachment = $this->create_attachment_with_original_fields(); + + $new_attachment_id = $this->crop_attachment_via_edit_endpoint( $attachment ); + $new_attachment = get_post( $new_attachment_id ); + + $this->assertNotSame( $attachment, $new_attachment_id, 'A new attachment should have been created.' ); + $this->assertSame( 'Original Title', $new_attachment->post_title, 'Title was not copied from the original attachment.' ); + $this->assertSame( 'Original Caption', $new_attachment->post_excerpt, 'Caption was not copied from the original attachment.' ); + $this->assertSame( 'Original Description', $new_attachment->post_content, 'Description was not copied from the original attachment.' ); + $this->assertSame( 'Original Alt Text', get_post_meta( $new_attachment_id, '_wp_attachment_image_alt', true ), 'Alt text was not copied from the original attachment.' ); + } + + /** + * Tests that no alt text meta is created for an edited image when the original attachment has none. + * + * @ticket 50675 + * @requires function imagejpeg + */ + public function test_edit_image_does_not_copy_empty_alt_text_from_original_attachment() { + $attachment = $this->create_attachment_with_original_fields( false ); + + $new_attachment_id = $this->crop_attachment_via_edit_endpoint( $attachment ); + + $this->assertFalse( metadata_exists( 'post', $new_attachment_id, '_wp_attachment_image_alt' ), 'Alt text meta should not exist when the original has none.' ); + } + + /** + * Tests that fields passed in the request take precedence over the original attachment, while omitted fields are still inherited. + * + * @ticket 50675 + * @requires function imagejpeg + */ + public function test_edit_image_request_fields_override_original_attachment_fields() { + $attachment = $this->create_attachment_with_original_fields(); + + $new_attachment_id = $this->crop_attachment_via_edit_endpoint( + $attachment, + array( + 'title' => 'New Title', + 'alt_text' => 'New Alt Text', + ) + ); + $new_attachment = get_post( $new_attachment_id ); + + $this->assertSame( 'New Title', $new_attachment->post_title, 'Title from the request was not used.' ); + $this->assertSame( 'New Alt Text', get_post_meta( $new_attachment_id, '_wp_attachment_image_alt', true ), 'Alt text from the request was not used.' ); + $this->assertSame( 'Original Caption', $new_attachment->post_excerpt, 'Omitted caption was not copied from the original attachment.' ); + $this->assertSame( 'Original Description', $new_attachment->post_content, 'Omitted description was not copied from the original attachment.' ); + } + + /** + * Creates an uploaded image attachment with distinctive title, caption, description and, optionally, alt text. + * + * @param bool $with_alt_text Whether to set alt text on the attachment. + * @return int Attachment ID. + */ + private function create_attachment_with_original_fields( $with_alt_text = true ) { + wp_set_current_user( self::$superadmin_id ); + $attachment = self::factory()->attachment->create_upload_object( self::$test_file ); + + wp_update_post( + array( + 'ID' => $attachment, + 'post_title' => 'Original Title', + 'post_excerpt' => 'Original Caption', + 'post_content' => 'Original Description', + ) + ); + + if ( $with_alt_text ) { + update_post_meta( $attachment, '_wp_attachment_image_alt', 'Original Alt Text' ); + } + + return $attachment; + } + + /** + * Crops an attachment through the edit endpoint and returns the ID of the newly created attachment. + * + * @param int $attachment Attachment ID to edit. + * @param array $extra_params Additional request parameters. + * @return int New attachment ID. + */ + private function crop_attachment_via_edit_endpoint( $attachment, array $extra_params = array() ) { + $request = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" ); + $request->set_body_params( + array_merge( + array( + 'src' => wp_get_attachment_image_url( $attachment, 'full' ), + 'modifiers' => array( + array( + 'type' => 'crop', + 'args' => array( + 'left' => 10, + 'top' => 10, + 'width' => 80, + 'height' => 80, + ), + ), + ), + ), + $extra_params + ) + ); + $response = rest_do_request( $request ); + + $this->assertSame( 201, $response->get_status() ); + + return $response->get_data()['id']; + } + /** * Tests that the image is flipped correctly vertically and horizontally. * From fc4beffbd8e7aa11fa2133ad8261c4d19b14dc14 Mon Sep 17 00:00:00 2001 From: Dennis Snell Date: Fri, 30 Oct 2026 20:37:08 +0000 Subject: [PATCH 085/481] Blocks: Fix duplicated content when implicitly closing a final open block When a fix was recently applied to the block parser for implicitly closing open blocks that remain open at the end of a document, a mistake was made when collecting HTML spans preceding the still-open blocks. This led to duplicated content in documents missing expected closing delimiters. This patch adjusts the implict closing algorithm to properly detect those HTML spans. Developed in: https://github.com/WordPress/wordpress-develop/pull/15197 Discussed in: https://core.trac.wordpress.org/ticket/66138 Follow-up to r64996. Props chihsuan, dmsnell. See #66138. git-svn-id: https://develop.svn.wordpress.org/trunk@65090 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-block-parser.php | 53 ++++++++----- tests/phpunit/tests/blocks/wpBlockParser.php | 82 ++++++++++++++++++++ 2 files changed, 116 insertions(+), 19 deletions(-) diff --git a/src/wp-includes/class-wp-block-parser.php b/src/wp-includes/class-wp-block-parser.php index 5adc9d95e677b..06342fc5acb64 100644 --- a/src/wp-includes/class-wp-block-parser.php +++ b/src/wp-includes/class-wp-block-parser.php @@ -395,40 +395,55 @@ public function add_block_from_stack( $end_offset = null ) { * @since 7.2.0 */ public function implicitly_close_and_add_all_open_blocks(): void { - $implicitly_closed = null; - $last_freeform = null; - + $last_closed_block = null; + $last_opener_at = strlen( $this->document ); + $last_leading_html = null; + + /** + * There is a stack of open blocks, starting with a top-level block, + * and where each successive item in the stack is a child of that block. + * There are also spans of HTML content between the block delimiters. + * + * As the stack is collapsed, any HTML segments within that block must + * be collected into it, before closing and appending to its parent’s + * inner blocks array. + */ while ( null !== ( $stack_top = array_pop( $this->stack ) ) ) { - if ( isset( $last_freeform ) ) { - $html = substr( $this->document, $stack_top->prev_offset, $last_freeform[1] - $stack_top->prev_offset ); - } else { - $html = substr( $this->document, $stack_top->prev_offset ); - } + /* + * Since there is no open inner block on the top-most block on the stack, + * the first iteration’s remaining HTML span will be from the last `prev_offset` + * until the end of the document. For each containing parent, it will run from + * the `prev_offset` until the opening of the block that was just closed. + */ + $html_length = $last_opener_at - $stack_top->prev_offset; + if ( 0 !== $html_length ) { + $html = substr( $this->document, $stack_top->prev_offset, $html_length ); - if ( '' !== $html ) { $stack_top->block->innerHTML .= $html; $stack_top->block->innerContent[] = $html; } - // Trap potential leading freeform content for the final output. - $last_freeform = array( $stack_top->leading_html_start ?? 0, $stack_top->token_start ); - - if ( isset( $implicitly_closed ) ) { + if ( isset( $last_closed_block ) ) { $stack_top->block->innerContent[] = null; - $stack_top->block->innerBlocks[] = (array) $implicitly_closed; + $stack_top->block->innerBlocks[] = (array) $last_closed_block; } - $implicitly_closed = $stack_top->block; + $last_closed_block = $stack_top->block; + $last_opener_at = $stack_top->token_start; + $last_leading_html = $stack_top->leading_html_start; } - if ( isset( $last_freeform ) && $last_freeform[1] > $last_freeform[0] ) { - $html = substr( $this->document, $last_freeform[0], $last_freeform[1] - $last_freeform[0] ); + // Collect any HTML preceding the outermost open block. + if ( isset( $last_leading_html ) && $last_opener_at > $last_leading_html ) { + $html = substr( $this->document, $last_leading_html, $last_opener_at - $last_leading_html ); $this->output[] = (array) $this->freeform( $html ); } - if ( isset( $implicitly_closed ) ) { - $this->output[] = (array) $implicitly_closed; + if ( isset( $last_closed_block ) ) { + $this->output[] = (array) $last_closed_block; } + + $this->offset = strlen( $this->document ); } } diff --git a/tests/phpunit/tests/blocks/wpBlockParser.php b/tests/phpunit/tests/blocks/wpBlockParser.php index 16963876f0008..e9cc62bcf5d62 100644 --- a/tests/phpunit/tests/blocks/wpBlockParser.php +++ b/tests/phpunit/tests/blocks/wpBlockParser.php @@ -42,6 +42,88 @@ public function test_parses_basic_empty_block() { ); } + /** + * Ensures that implicitly closing a final open block does not repeat content parsed before it. + * + * @ticket 66138 + * + * @dataProvider data_documents_with_implicit_closings + * + * @param string[] $tokens List of block and HTML tokens comprising a document, where the first + * is a partial document ending in open blocks, while the rest are the + * explicit closers corresponding to those open blocks. + */ + public function test_implicitly_closed_blocks_is_equivalent_to_explicitly_closed( $tokens ) { + $parser = new WP_Block_Parser(); + $full_document = $parser->parse( implode( '', $tokens ) ); + $document = array_shift( $tokens ); + + foreach ( $tokens as $token ) { + $document .= $token; + + $this->assertSame( + $full_document, + $parser->parse( $document ), + 'Should have implicitly closed open blocks as if the closers had been there.' + ); + } + } + + /** + * Data provider. + * + * @return array> + */ + public static function data_documents_with_implicit_closings() { + return array( + 'After a closed block' => array( + array( + 'A', + '', + ), + ), + 'After leading HTML and a closed block' => array( + array( + 'HiA', + '', + ), + ), + 'After a closed block and HTML' => array( + array( + 'ABye', + '', + ), + ), + 'Deeply-nested open blocks' => array( + array( + '01234', + '', + '', + '', + '', + ), + ), + 'After a closed void block' => array( + array( + 'A', + '', + ), + ), + 'With the wrong closer' => array( + array( + 'A', + '', + ), + ), + 'With an invalid closer' => array( + array( + 'A', + '', + ), + ), + ); + } + /** * @dataProvider data_parsing_test_filenames * @ticket 45109 From f567b527a587efb72eb4bf00175d0a67262af6be Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:38:48 +0000 Subject: [PATCH 086/481] Tests: Cover application password creation emails. Cover notification delivery, placeholder replacement, filtering, and invalid inputs in `wp_application_password_created_notification()`. Protect the admin-email placeholder fix. Developed in: https://github.com/WordPress/wordpress-develop/pull/14721 Props ravipatel. See #63927. git-svn-id: https://develop.svn.wordpress.org/trunk@65091 602fd350-edb4-49c9-b593-d223f7449a82 --- ...ApplicationPasswordCreatedNotification.php | 187 ++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php diff --git a/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php b/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php new file mode 100644 index 0000000000000..387e192f038cf --- /dev/null +++ b/tests/phpunit/tests/functions/wpApplicationPasswordCreatedNotification.php @@ -0,0 +1,187 @@ +user->create_and_get( + array( + 'user_email' => 'app-password-user@example.org', + 'display_name' => 'App Password User', + ) + ); + } + + public function set_up() { + parent::set_up(); + reset_phpmailer_instance(); + } + + public function tear_down() { + reset_phpmailer_instance(); + parent::tear_down(); + } + + /** + * @ticket 63927 + */ + public function test_sends_email_when_application_password_is_created() { + $created = WP_Application_Passwords::create_new_application_password( self::$user->ID, array( 'name' => 'My App' ) ); + + $this->assertNotWPError( $created, 'The application password should be created.' ); + + $mailer = tests_retrieve_phpmailer_instance(); + $this->assertCount( 1, $mailer->mock_sent, 'Exactly one email should be sent.' ); + $this->assertSame( self::$user->user_email, $mailer->get_recipient( 'to' )->address ); + } + + /** + * @ticket 63927 + */ + public function test_email_replaces_all_placeholders() { + update_option( 'blogname', 'Test Blog' ); + update_option( 'admin_email', 'site-admin@example.org' ); + // Changing the admin email sends its own notification. + reset_phpmailer_instance(); + + wp_application_password_created_notification( self::$user->ID, array( 'name' => 'My App' ) ); + + $mailer = tests_retrieve_phpmailer_instance(); + $sent = $mailer->get_sent(); + + $this->assertSame( '[Test Blog] Application Password Created', $sent->subject ); + $this->assertStringNotContainsString( '###', $sent->body, 'All placeholders should be replaced.' ); + $this->assertStringContainsString( 'Hi App Password User,', $sent->body ); + $this->assertStringContainsString( 'Application password name: My App', $sent->body ); + $this->assertStringContainsString( 'site-admin@example.org', $sent->body ); + $this->assertStringContainsString( 'This email has been sent to app-password-user@example.org', $sent->body ); + $this->assertStringContainsString( 'All at Test Blog', $sent->body ); + $this->assertStringContainsString( home_url(), $sent->body ); + } + + /** + * @ticket 63927 + */ + public function test_does_not_send_email_when_disabled_by_filter() { + add_filter( 'wp_send_application_password_created_email', '__return_false' ); + + wp_application_password_created_notification( self::$user->ID, array( 'name' => 'My App' ) ); + + $this->assertEmpty( tests_retrieve_phpmailer_instance()->mock_sent ); + } + + /** + * @ticket 63927 + */ + public function test_send_filter_receives_user_and_application_password() { + $filter = new MockAction(); + add_filter( 'wp_send_application_password_created_email', array( $filter, 'filter' ), 10, 3 ); + + $new_item = array( 'name' => 'My App' ); + wp_application_password_created_notification( self::$user->ID, $new_item ); + + $args = $filter->get_args(); + $this->assertCount( 1, $args, 'The filter should run once.' ); + $this->assertTrue( $args[0][0], 'The email should be sent by default.' ); + $this->assertSame( self::$user->ID, $args[0][1]->ID ); + $this->assertSame( $new_item, $args[0][2] ); + } + + /** + * @ticket 63927 + */ + public function test_email_can_be_changed_by_filter() { + add_filter( + 'wp_application_password_created_email', + static function ( $email ) { + $email['to'] = 'someone-else@example.org'; + $email['subject'] = 'Custom subject for %s'; + $email['message'] = 'Custom message for ###APPLICATION_PASSWORD_NAME###'; + return $email; + } + ); + update_option( 'blogname', 'Test Blog' ); + + wp_application_password_created_notification( self::$user->ID, array( 'name' => 'My App' ) ); + + $mailer = tests_retrieve_phpmailer_instance(); + $sent = $mailer->get_sent(); + + $this->assertSame( 'someone-else@example.org', $mailer->get_recipient( 'to' )->address ); + $this->assertSame( 'Custom subject for Test Blog', $sent->subject ); + $this->assertStringContainsString( 'Custom message for My App', $sent->body, 'Placeholders in a filtered message should still be replaced.' ); + } + + /** + * @ticket 63927 + * @dataProvider data_does_not_send_email_for_invalid_input + * + * @param callable $get_args Returns the user ID and application password details to pass. + */ + public function test_does_not_send_email_for_invalid_input( $get_args ) { + list( $user_id, $new_item ) = $get_args( self::$user->ID ); + + wp_application_password_created_notification( $user_id, $new_item ); + + $this->assertEmpty( tests_retrieve_phpmailer_instance()->mock_sent ); + } + + /** + * Data provider for test_does_not_send_email_for_invalid_input(). + * + * @return array + */ + public static function data_does_not_send_email_for_invalid_input() { + return array( + 'user does not exist' => array( + static function () { + return array( PHP_INT_MAX, array( 'name' => 'My App' ) ); + }, + ), + 'application password unnamed' => array( + static function ( $user_id ) { + return array( $user_id, array( 'name' => '' ) ); + }, + ), + 'name missing' => array( + static function ( $user_id ) { + return array( $user_id, array() ); + }, + ), + ); + } + + /** + * @ticket 63927 + */ + public function test_does_not_send_email_when_user_email_is_invalid() { + global $wpdb; + + $user_id = self::factory()->user->create(); + $wpdb->update( $wpdb->users, array( 'user_email' => 'not-an-email' ), array( 'ID' => $user_id ) ); + clean_user_cache( $user_id ); + + wp_application_password_created_notification( $user_id, array( 'name' => 'My App' ) ); + + $this->assertEmpty( tests_retrieve_phpmailer_instance()->mock_sent ); + } +} From 87ff67721bc3ddd71f2e5afd9a9aa2a22ec82407 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:42:07 +0000 Subject: [PATCH 087/481] Tests: Cover password reset URL formatting in emails. Verify that `retrieve_password()` and `wp_new_user_notification()` include password reset links without surrounding angle brackets. Developed in: https://github.com/WordPress/wordpress-develop/pull/14078 Props irozum, huzaifaalmesbah. See #65819, #44589. git-svn-id: https://develop.svn.wordpress.org/trunk@65092 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/user.php | 36 +++++++++++++++++++ tests/phpunit/tests/user/retrievePassword.php | 36 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/tests/phpunit/tests/user.php b/tests/phpunit/tests/user.php index ce4d3972df643..c87e852012f1f 100644 --- a/tests/phpunit/tests/user.php +++ b/tests/phpunit/tests/user.php @@ -2012,6 +2012,42 @@ static function ( $email ) use ( &$user_email_locale ) { $this->assertSame( 'es_ES', $user_email_locale, 'User email was not sent in the expected locale' ); } + /** + * The reset link in the new user notification email should not be wrapped + * in angle brackets, as that caused some email clients to include the + * closing bracket as part of the URL and break the link. + * + * @ticket 44589 + */ + public function test_wp_new_user_notification_does_not_wrap_reset_link_in_angle_brackets() { + $message = ''; + + add_filter( + 'wp_new_user_notification_email', + static function ( $email ) use ( &$message ) { + $message = $email['message']; + return $email; + } + ); + + wp_new_user_notification( self::$contrib_id, null, 'user' ); + + $this->assertNotEmpty( $message, 'The notification email message should not be empty.' ); + + $reset_link_line = ''; + + foreach ( explode( "\r\n", $message ) as $line ) { + if ( str_contains( $line, 'wp-login.php' ) ) { + $reset_link_line = $line; + break; + } + } + + $this->assertNotEmpty( $reset_link_line, 'The reset password link should be present in the email message.' ); + $this->assertFalse( str_starts_with( $reset_link_line, '<' ), 'The reset password link should not start with an angle bracket.' ); + $this->assertFalse( str_ends_with( $reset_link_line, '>' ), 'The reset password link should not end with an angle bracket.' ); + } + /** * Callback that returns 0.0. * diff --git a/tests/phpunit/tests/user/retrievePassword.php b/tests/phpunit/tests/user/retrievePassword.php index da72bed8b70de..7f51019c447ba 100644 --- a/tests/phpunit/tests/user/retrievePassword.php +++ b/tests/phpunit/tests/user/retrievePassword.php @@ -106,4 +106,40 @@ public function test_retrieve_password_does_not_throw_fatal_error_with_array_par $error_codes = $error->get_error_codes(); $this->assertContains( 'empty_username', $error_codes, 'The "empty_username" error code should be present.' ); } + + /** + * The password reset link in the notification email should not be wrapped + * in angle brackets, as that caused some email clients to include the + * closing bracket as part of the URL and break the link. + * + * @ticket 44589 + */ + public function test_retrieve_password_email_does_not_wrap_reset_link_in_angle_brackets() { + $message = ''; + + add_filter( + 'retrieve_password_notification_email', + static function ( $defaults ) use ( &$message ) { + $message = $defaults['message']; + return $defaults; + } + ); + + retrieve_password( $this->user->user_login ); + + $this->assertNotEmpty( $message, 'The notification email message should not be empty.' ); + + $reset_link_line = ''; + + foreach ( explode( "\r\n", $message ) as $line ) { + if ( str_contains( $line, 'wp-login.php' ) ) { + $reset_link_line = $line; + break; + } + } + + $this->assertNotEmpty( $reset_link_line, 'The reset password link should be present in the email message.' ); + $this->assertFalse( str_starts_with( $reset_link_line, '<' ), 'The reset password link should not start with an angle bracket.' ); + $this->assertFalse( str_ends_with( $reset_link_line, '>' ), 'The reset password link should not end with an angle bracket.' ); + } } From f4e580167ec8d1fc423a30fa467e9662a537b80b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:42:53 +0000 Subject: [PATCH 088/481] Tests: Cover directory copy skip lists. Verify that `copy_dir()` skips exact file and directory matches while preserving other content. Protect the strict comparison that distinguishes `0019` from the skip-list entry `19`. Developed in: https://github.com/WordPress/wordpress-develop/pull/14107 Props irozum, huzaifaalmesbah. See #65819, #46581. git-svn-id: https://develop.svn.wordpress.org/trunk@65093 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/filesystem/copyDir.php | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/phpunit/tests/filesystem/copyDir.php b/tests/phpunit/tests/filesystem/copyDir.php index ff80273c8afb2..7577242446277 100644 --- a/tests/phpunit/tests/filesystem/copyDir.php +++ b/tests/phpunit/tests/filesystem/copyDir.php @@ -80,4 +80,61 @@ public function test_should_create_destination_it_if_does_not_exist() { $this->assertDirectoryExists( $to . 'subfolder1/', 'The destination subfolder was not created.' ); $this->assertFileExists( $to . 'subfolder1/file2.txt', 'The destination subfolder file was not created.' ); } + + /** + * Tests that files and directories named in the skip list are not copied. + * + * @ticket 46581 + */ + public function test_should_skip_files_and_directories_in_the_skip_list() { + global $wp_filesystem; + + $from = self::$test_dir . 'folder1/'; + $to = self::$test_dir . 'folder2/'; + + $wp_filesystem->mkdir( $from ); + $wp_filesystem->touch( $from . 'keep-me.txt' ); + $wp_filesystem->touch( $from . 'skip-me.txt' ); + $wp_filesystem->mkdir( $from . 'keep-folder' ); + $wp_filesystem->touch( $from . 'keep-folder/file.txt' ); + $wp_filesystem->mkdir( $from . 'skip-folder' ); + $wp_filesystem->touch( $from . 'skip-folder/file.txt' ); + + $this->assertTrue( copy_dir( $from, $to, array( 'skip-me.txt', 'skip-folder' ) ), 'copy_dir() failed.' ); + + $this->assertFileExists( $to . 'keep-me.txt', 'The non-skip-listed file was not copied.' ); + $this->assertDirectoryExists( $to . 'keep-folder', 'The non-skip-listed directory was not copied.' ); + $this->assertFileExists( $to . 'keep-folder/file.txt', 'The contents of the non-skip-listed directory were not copied.' ); + + $this->assertFileDoesNotExist( $to . 'skip-me.txt', 'The skip-listed file was copied.' ); + $this->assertDirectoryDoesNotExist( $to . 'skip-folder', 'The skip-listed directory was copied.' ); + } + + /** + * Tests that a numeric-looking directory name is not skipped just because + * it's loosely equal to an unrelated `$skip_list` entry. + * + * `in_array( $filename, $skip_list )` without strict type checking compares + * two numeric strings numerically, so a directory named `0019` would be + * considered equal to a `$skip_list` entry of `19` even though the two + * strings are different paths. `copy_dir()` must use a strict comparison + * so only an exact match is skipped. + * + * @ticket 46581 + */ + public function test_should_not_skip_directory_loosely_equal_to_a_skip_list_entry() { + global $wp_filesystem; + + $from = self::$test_dir . 'folder1/'; + $to = self::$test_dir . 'folder2/'; + + $wp_filesystem->mkdir( $from ); + $wp_filesystem->mkdir( $from . '0019' ); + $wp_filesystem->touch( $from . '0019/file.txt' ); + + $this->assertTrue( copy_dir( $from, $to, array( '19' ) ), 'copy_dir() failed.' ); + + $this->assertDirectoryExists( $to . '0019', 'The directory was incorrectly skipped due to a loose comparison with an unrelated skip list entry.' ); + $this->assertFileExists( $to . '0019/file.txt', 'The contents of the incorrectly skipped directory were not copied.' ); + } } From 194910300a54e984911fbcbbcc3bf200d3aef3ab Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:47:29 +0000 Subject: [PATCH 089/481] Tests: Cover HTML class sanitization. Cover character stripping, fallback sanitization, and the filter contract in `sanitize_html_class()`. Verify that the filter changes the returned value. Developed in: https://github.com/WordPress/wordpress-develop/pull/15147 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65094 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/formatting/sanitizeHtmlClass.php | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 tests/phpunit/tests/formatting/sanitizeHtmlClass.php diff --git a/tests/phpunit/tests/formatting/sanitizeHtmlClass.php b/tests/phpunit/tests/formatting/sanitizeHtmlClass.php new file mode 100644 index 0000000000000..14e495bf09092 --- /dev/null +++ b/tests/phpunit/tests/formatting/sanitizeHtmlClass.php @@ -0,0 +1,101 @@ +assertSame( $expected, sanitize_html_class( $classname, $fallback ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_sanitize_html_class() { + return array( + 'empty string' => array( + '', + '', + ), + 'already valid class unchanged' => array( + 'foo-bar_123', + 'foo-bar_123', + ), + 'preserves mixed case' => array( + 'FooBar', + 'FooBar', + ), + 'strips spaces' => array( + 'foo bar', + 'foobar', + ), + 'strips punctuation' => array( + 'foo.bar!baz', + 'foobarbaz', + ), + 'strips percent-encoded sequences' => array( + 'foo%20bar%2Fbaz', + 'foobarbaz', + ), + 'strips incomplete percent encoding' => array( + 'foo%2', + 'foo2', + ), + 'strips high-bit characters' => array( + "caf\xC3\xA9-latte", + 'caf-latte', + ), + 'empty classname uses fallback' => array( + '', + 'fallback-class', + 'fallback-class', + ), + 'fully stripped classname uses fallback' => array( + '%20!!!', + 'ok-fallback', + 'ok-fallback', + ), + 'fallback is also sanitized' => array( + '', + 'okfallback', + 'ok fallback!', + ), + ); + } + + /** + * @ticket 65819 + */ + public function test_sanitize_html_class_filter_receives_original_args() { + $filter = new MockAction(); + add_filter( 'sanitize_html_class', array( $filter, 'filter_append' ), 10, 3 ); + + $result = sanitize_html_class( 'foo bar', 'fallback' ); + + $this->assertSame( 'foobar_append', $result, 'Unexpected sanitized class.' ); + $this->assertSame( 1, $filter->get_call_count(), 'The filter was not applied once.' ); + $this->assertSame( + array( 'foobar', 'foo bar', 'fallback' ), + $filter->get_args()[0], + 'The filter did not receive the sanitized class, original classname, and fallback.' + ); + } +} From f5554b86016070b05d3ad71648c099837ba996b7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:48:57 +0000 Subject: [PATCH 090/481] Tests: Cover site information formatting in RSS feeds. Verify that `get_bloginfo_rss()` strips tags and converts ampersands before filtering. Check the filtered return value and the requested site information field. Developed in: https://github.com/WordPress/wordpress-develop/pull/15160 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65095 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/feed/getBloginfoRss.php | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tests/phpunit/tests/feed/getBloginfoRss.php diff --git a/tests/phpunit/tests/feed/getBloginfoRss.php b/tests/phpunit/tests/feed/getBloginfoRss.php new file mode 100644 index 0000000000000..6956d706df4e1 --- /dev/null +++ b/tests/phpunit/tests/feed/getBloginfoRss.php @@ -0,0 +1,45 @@ +World & Co'; + } + ); + + $this->assertSame( 'Hello World & Co', get_bloginfo_rss( 'name' ) ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_converted_value_and_show() { + $filter = new MockAction(); + add_filter( 'get_bloginfo_rss', array( $filter, 'filter_append' ), 10, 2 ); + + add_filter( + 'pre_option_blogdescription', + static function () { + return 'Feed Description & Co'; + } + ); + + $result = get_bloginfo_rss( 'description' ); + + $this->assertSame( 'Feed Description & Co_append', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'Feed Description & Co', 'description' ), $filter->get_args()[0] ); + } +} From 951fa98b0ba9a0b7ccc92d67cc58335b4c5d9899 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 20:52:31 +0000 Subject: [PATCH 091/481] Tests: Cover bookmark field retrieval and contexts. Cover invalid bookmarks, unknown fields, context forwarding, and attribute escaping in `get_bookmark_field()`. Use literal expected output to keep assertions independent of the implementation. Developed in: https://github.com/WordPress/wordpress-develop/pull/15161 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65096 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/bookmark/getBookmarkField.php | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 tests/phpunit/tests/bookmark/getBookmarkField.php diff --git a/tests/phpunit/tests/bookmark/getBookmarkField.php b/tests/phpunit/tests/bookmark/getBookmarkField.php new file mode 100644 index 0000000000000..65e400eb85e44 --- /dev/null +++ b/tests/phpunit/tests/bookmark/getBookmarkField.php @@ -0,0 +1,106 @@ +bookmark->create( + array( + 'link_name' => 'Example Link', + 'link_url' => 'https://example.com/', + 'link_description' => 'An example bookmark', + 'link_rel' => 'nofollow', + ) + ); + } + + /** + * Delete shared fixtures. + */ + public static function wpTearDownAfterClass() { + wp_delete_link( self::$bookmark_id ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_for_invalid_bookmark() { + $this->assertSame( '', get_bookmark_field( 'link_name', 0 ) ); + $this->assertSame( '', get_bookmark_field( 'link_name', PHP_INT_MAX ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_for_unknown_field() { + $this->assertSame( '', get_bookmark_field( 'not_a_real_field', self::$bookmark_id ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_sanitized_bookmark_field() { + $this->assertSame( 'Example Link', get_bookmark_field( 'link_name', self::$bookmark_id ) ); + } + + /** + * @ticket 65819 + */ + public function test_forwards_context_to_sanitize_bookmark_field() { + add_filter( + 'link_name', + static function ( $value ) { + return $value . '|link_name'; + } + ); + add_filter( + 'edit_link_name', + static function ( $value ) { + return $value . '|edit_link_name'; + } + ); + + $this->assertSame( 'Example Link', get_bookmark_field( 'link_name', self::$bookmark_id, 'raw' ) ); + $this->assertSame( 'Example Link|link_name', get_bookmark_field( 'link_name', self::$bookmark_id, 'display' ) ); + $this->assertSame( 'Example Link|link_name', get_bookmark_field( 'link_name', self::$bookmark_id, 'attribute' ) ); + $this->assertSame( 'Example Link|edit_link_name', get_bookmark_field( 'link_name', self::$bookmark_id, 'edit' ) ); + } + + /** + * @ticket 65819 + */ + public function test_attribute_context_escapes_markup_in_link_name() { + $bookmark = get_bookmark( self::$bookmark_id ); + $original_name = $bookmark->link_name; + + $bookmark->link_name = 'Bold Name & Co'; + wp_cache_set( self::$bookmark_id, $bookmark, 'bookmark' ); + + remove_all_filters( 'link_name' ); + + $this->assertSame( + 'Bold <b>Name</b> & Co', + get_bookmark_field( 'link_name', self::$bookmark_id, 'attribute' ) + ); + + $bookmark->link_name = $original_name; + wp_cache_set( self::$bookmark_id, $bookmark, 'bookmark' ); + } +} From 4f0b127e70dfcc7ae4e03cb33d8cfcbd235434dd Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:29:04 +0000 Subject: [PATCH 092/481] Tests: Cover HTML comment preservation when balancing tags. Extend the existing `balanceTags()` tests with ordinary and spaced comment openers. Verify that balancing surrounding markup preserves both comment forms. Developed in: https://github.com/WordPress/wordpress-develop/pull/15141 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65097 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/formatting/balanceTags.php | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/phpunit/tests/formatting/balanceTags.php b/tests/phpunit/tests/formatting/balanceTags.php index 72d14373e4e01..7cc79b3571a2b 100644 --- a/tests/phpunit/tests/formatting/balanceTags.php +++ b/tests/phpunit/tests/formatting/balanceTags.php @@ -449,4 +449,36 @@ public static function data_custom_elements() { public function test_custom_elements( $source, $expected ) { $this->assertSame( $expected, balanceTags( $source, true ) ); } + + /** + * Comment fixtures that force_balance_tags() should preserve while still balancing tags. + * + * @ticket 65819 + * + * @dataProvider data_preserves_html_comments + * + * @param string $input Input markup. + * @param string $expected Expected balanced markup. + */ + public function test_preserves_html_comments( $input, $expected ) { + $this->assertSame( $expected, balanceTags( $input, true ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_preserves_html_comments() { + return array( + 'preserves html comments' => array( + '

Hi', + '

Hi

', + ), + 'preserves spaced comment opener' => array( + '< !-- comment -->

Hi', + '< !-- comment -->

Hi

', + ), + ); + } } From 71183dbe4de6ed8307775e782897ee52af95b464 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:32:39 +0000 Subject: [PATCH 093/481] Tests: Cover post MIME type retrieval. Verify that `get_post_mime_type()` returns the stored attachment MIME type and returns `false` for a nonexistent post. Reuse existing `get_post()` coverage for input resolution. Developed in: https://github.com/WordPress/wordpress-develop/pull/15145 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65098 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getPostMimeType.php | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 tests/phpunit/tests/post/getPostMimeType.php diff --git a/tests/phpunit/tests/post/getPostMimeType.php b/tests/phpunit/tests/post/getPostMimeType.php new file mode 100644 index 0000000000000..0a938c7d13872 --- /dev/null +++ b/tests/phpunit/tests/post/getPostMimeType.php @@ -0,0 +1,31 @@ +assertFalse( get_post_mime_type( PHP_INT_MAX ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_stored_mime_type_for_attachment() { + $attachment_id = self::factory()->attachment->create_object( + array( + 'post_mime_type' => 'image/jpeg', + 'post_type' => 'attachment', + ) + ); + + $this->assertSame( 'image/jpeg', get_post_mime_type( $attachment_id ) ); + } +} From 048cc4b405f08c01f5aeb3d4fbf1e01f908cd542 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:33:31 +0000 Subject: [PATCH 094/481] Tests: Cover default comment status options and filtering. Cover closed default options and distinct comment and ping defaults for a supported custom post type. Verify that the `get_default_comment_status` filter receives its arguments and changes the returned value. Developed in: https://github.com/WordPress/wordpress-develop/pull/15151 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65099 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/comment/getDefaultCommentStatus.php | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 tests/phpunit/tests/comment/getDefaultCommentStatus.php diff --git a/tests/phpunit/tests/comment/getDefaultCommentStatus.php b/tests/phpunit/tests/comment/getDefaultCommentStatus.php new file mode 100644 index 0000000000000..e825f80405aba --- /dev/null +++ b/tests/phpunit/tests/comment/getDefaultCommentStatus.php @@ -0,0 +1,64 @@ +assertSame( 'closed', get_default_comment_status( 'post' ) ); + $this->assertSame( 'closed', get_default_comment_status() ); + } + + /** + * @ticket 65819 + */ + public function test_posts_use_closed_default_ping_status_option() { + update_option( 'default_ping_status', 'closed' ); + + $this->assertSame( 'closed', get_default_comment_status( 'post', 'pingback' ) ); + } + + /** + * @ticket 65819 + */ + public function test_supported_custom_post_type_uses_opposed_comment_and_ping_options() { + register_post_type( + 'with_comments_cpt', + array( + 'public' => true, + 'supports' => array( 'comments', 'trackbacks' ), + ) + ); + + update_option( 'default_comment_status', 'open' ); + update_option( 'default_ping_status', 'closed' ); + + $this->assertSame( 'open', get_default_comment_status( 'with_comments_cpt' ) ); + $this->assertSame( 'closed', get_default_comment_status( 'with_comments_cpt', 'trackback' ) ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_status_post_type_and_comment_type() { + $filter = new MockAction(); + add_filter( 'get_default_comment_status', array( $filter, 'filter_append' ), 10, 3 ); + + update_option( 'default_comment_status', 'open' ); + + $result = get_default_comment_status( 'post', 'comment' ); + + $this->assertSame( 'open_append', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'open', 'post', 'comment' ), $filter->get_args()[0] ); + } +} From 437928a42312a64d1aa726f255081ea8b4474469 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:43:13 +0000 Subject: [PATCH 095/481] Tests: Cover string IDs in REST search results. Verify that the search endpoint schema accepts integer and string IDs. Check that post-format searches preserve string slugs rather than coercing them to integers. Developed in: https://github.com/WordPress/wordpress-develop/pull/14049 Props irozum, huzaifaalmesbah. See #65819, #51131. git-svn-id: https://develop.svn.wordpress.org/trunk@65100 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/rest-search-controller.php | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/phpunit/tests/rest-api/rest-search-controller.php b/tests/phpunit/tests/rest-api/rest-search-controller.php index c996e49147a0f..eeff234dc08ed 100644 --- a/tests/phpunit/tests/rest-api/rest-search-controller.php +++ b/tests/phpunit/tests/rest-api/rest-search-controller.php @@ -567,6 +567,21 @@ public function test_get_item_schema() { $this->assertArrayHasKey( 'subtype', $properties ); } + /** + * The id property's schema should accept both integer and string ids, + * as search handlers are not required to use integer ids. + * + * @ticket 51131 + */ + public function test_get_item_schema_id_accepts_integer_and_string() { + $request = new WP_REST_Request( 'OPTIONS', '/wp/v2/search' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['schema']['properties']; + + $this->assertSame( array( 'integer', 'string' ), $properties['id']['type'] ); + } + /** * Tests that non-public post types are not allowed. * @@ -872,6 +887,30 @@ public function test_get_items_search_type_post_format() { ); } + /** + * Post format search results should return the format slug as a string id, not an integer. + * + * @ticket 51131 + */ + public function test_get_items_search_type_post_format_returns_string_ids() { + $response = $this->do_request_with_params( + array( + 'per_page' => 100, + 'type' => 'post-format', + ) + ); + + $this->assertSame( 200, $response->get_status() ); + + $ids = wp_list_pluck( $response->get_data(), 'id' ); + + $this->assertContains( 'aside', $ids ); + + foreach ( $ids as $id ) { + $this->assertIsString( $id ); + } + } + /** * Search through all that matches a 'Aside' search. * From 280925806c3915d2194c56662338880e8f97fe11 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:44:08 +0000 Subject: [PATCH 096/481] Tests: Cover filter suppression in post queries. Verify that `get_posts()` suppresses `posts_where` filters by default and honors an explicit `suppress_filters` value of `false`. Developed in: https://github.com/WordPress/wordpress-develop/pull/14015 Props irozum, huzaifaalmesbah. See #65819, #7326. git-svn-id: https://develop.svn.wordpress.org/trunk@65101 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getPosts.php | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/phpunit/tests/post/getPosts.php b/tests/phpunit/tests/post/getPosts.php index 927e874f2f612..953e3ec3f5733 100644 --- a/tests/phpunit/tests/post/getPosts.php +++ b/tests/phpunit/tests/post/getPosts.php @@ -5,6 +5,8 @@ * @group query */ class Tests_Post_GetPosts extends WP_UnitTestCase { + private $posts_where_filter_fired = false; + public function test_offset_should_be_null_by_default() { $p1 = self::factory()->post->create( array( @@ -215,4 +217,35 @@ public function test_should_return_parent_ids_keyed_by_post_id_when_cached(): vo $this->assertSame( $expected, get_posts( $args ), 'The uncached call is not of the expected form.' ); $this->assertSame( $expected, get_posts( $args ), 'The cached call is not of the expected form.' ); } + + /** + * @ticket 7326 + */ + public function test_should_suppress_posts_where_filter_by_default() { + self::factory()->post->create(); + + add_filter( 'posts_where', array( $this, 'filter_posts_where_set_flag' ) ); + get_posts(); + remove_filter( 'posts_where', array( $this, 'filter_posts_where_set_flag' ) ); + + $this->assertFalse( $this->posts_where_filter_fired ); + } + + /** + * @ticket 7326 + */ + public function test_suppress_filters_false_should_apply_posts_where_filter() { + self::factory()->post->create(); + + add_filter( 'posts_where', array( $this, 'filter_posts_where_set_flag' ) ); + get_posts( array( 'suppress_filters' => false ) ); + remove_filter( 'posts_where', array( $this, 'filter_posts_where_set_flag' ) ); + + $this->assertTrue( $this->posts_where_filter_fired ); + } + + public function filter_posts_where_set_flag( $where ) { + $this->posts_where_filter_fired = true; + return $where; + } } From 9fa2e3f1d8ac40ecf1ae478ee2d806e3eaf694ac Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 21:45:07 +0000 Subject: [PATCH 097/481] Docs: Correct the canonical test helper return type. Document the return type of `WP_Canonical_UnitTestCase::get_canonical()` as `string` instead of a variable name. Developed in: https://github.com/WordPress/wordpress-develop/pull/14271 Props soean. See #65860. git-svn-id: https://develop.svn.wordpress.org/trunk@65102 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/includes/testcase-canonical.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/includes/testcase-canonical.php b/tests/phpunit/includes/testcase-canonical.php index 01d87c2f6d042..e99e14b619fe7 100644 --- a/tests/phpunit/includes/testcase-canonical.php +++ b/tests/phpunit/includes/testcase-canonical.php @@ -347,8 +347,8 @@ public function assertCanonical( $test_url, $expected, $ticket = 0, $expected_do * * @param string $test_url Should be relative to the site "front", ie /category/uncategorized/ * as opposed to http://example.com/category/uncategorized/ - * @return $can_url Returns the original $test_url if no canonical can be generated, otherwise returns - * the fully-qualified URL as generated by redirect_canonical(). + * @return string Returns the original $test_url if no canonical can be generated, otherwise returns + * the fully-qualified URL as generated by redirect_canonical(). */ public function get_canonical( $test_url ) { if ( isset( $_SERVER['HTTP_HOST'] ) ) { From 7375f7b76eb599de60409bacc049bbf6c3741e93 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 22:00:32 +0000 Subject: [PATCH 098/481] Tests: Cover Site Health zero-count messages. Verify the plugin and theme checks report the intended messages when there are no active plugins or installed themes. Developed in: https://github.com/WordPress/wordpress-develop/pull/13960 Props irozum, huzaifaalmesbah. See #65819, #56134. git-svn-id: https://develop.svn.wordpress.org/trunk@65103 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/admin/wpSiteHealth.php | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 2ad2052369ba1..e325c917b50ff 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -707,4 +707,39 @@ public function test_get_test_opcode_cache_result_by_environment() { $this->assertStringContainsString( __( 'Enabling this cache can significantly improve the performance of your site.' ), $result['description'] ); } } + + /** + * @ticket 56134 + * + * @covers ::get_test_plugin_version + */ + public function test_get_test_plugin_version_with_no_active_plugins() { + update_option( 'active_plugins', array() ); + + $result = $this->instance->get_test_plugin_version(); + + $this->assertStringContainsString( 'Your site does not have any active plugins.', $result['description'] ); + } + + /** + * @ticket 56134 + * + * @covers ::get_test_theme_version + */ + public function test_get_test_theme_version_with_no_installed_themes() { + $orig_theme_directories = $GLOBALS['wp_theme_directories']; + + $GLOBALS['wp_theme_directories'] = array(); + wp_clean_themes_cache(); + unset( $GLOBALS['wp_themes'] ); + + $result = $this->instance->get_test_theme_version(); + + $GLOBALS['wp_theme_directories'] = $orig_theme_directories; + wp_clean_themes_cache(); + unset( $GLOBALS['wp_themes'] ); + + $this->assertSame( 'good', $result['status'] ); + $this->assertStringContainsString( 'Your site does not have any installed themes.', $result['description'] ); + } } From 6c3ee0f50e68c7c4210237197ed5f04871a103fe Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 22:01:46 +0000 Subject: [PATCH 099/481] Tests: Cover block template changes after cache population. Verify `WP_Theme::get_post_templates()` includes newly created custom block templates and excludes deleted templates after its file-based cache has been populated. Developed in: https://github.com/WordPress/wordpress-develop/pull/14051 Props irozum, huzaifaalmesbah. See #65819, #57886. git-svn-id: https://develop.svn.wordpress.org/trunk@65104 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/theme/wpThemeGetPostTemplates.php | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/tests/phpunit/tests/theme/wpThemeGetPostTemplates.php b/tests/phpunit/tests/theme/wpThemeGetPostTemplates.php index 9a4775124cdbf..69efe0c1f81b1 100644 --- a/tests/phpunit/tests/theme/wpThemeGetPostTemplates.php +++ b/tests/phpunit/tests/theme/wpThemeGetPostTemplates.php @@ -117,4 +117,81 @@ public function test_get_post_templates_uses_get_file_data() { // Verify the `extra_theme_headers` filter is called. $this->assertGreaterThan( 0, $filter->get_call_count(), 'The `extra_theme_headers` filter should be called at least once.' ); } + + /** + * @ticket 57886 + */ + public function test_get_post_templates_includes_block_template_added_after_cache_is_populated() { + $theme = $this->switch_to_block_theme(); + + // First call caches the file-based post templates and merges in the block templates that exist at this point. + $theme->get_post_templates(); + + $this->create_custom_block_template( $theme, 'late-added-custom-template' ); + + $post_templates = $theme->get_post_templates(); + + // The cached file-based templates must not have locked in the set of block templates from the first call. + $this->assertArrayHasKey( 'late-added-custom-template', $post_templates['post'], 'A block template created after the cache was populated should still be returned.' ); + } + + /** + * @ticket 57886 + */ + public function test_get_post_templates_does_not_include_block_template_removed_after_cache_is_populated() { + $theme = $this->switch_to_block_theme(); + $custom_template = $this->create_custom_block_template( $theme, 'removed-custom-template' ); + + // First call caches the file-based post templates and merges in the block template created above. + $post_templates = $theme->get_post_templates(); + $this->assertArrayHasKey( 'removed-custom-template', $post_templates['post'], 'The block template should be present before it is deleted.' ); + + wp_delete_post( $custom_template->ID, true ); + + $post_templates = $theme->get_post_templates(); + + // The cached file-based templates must not have locked in the now-deleted block template. + $this->assertArrayNotHasKey( 'removed-custom-template', $post_templates['post'], 'A block template deleted after the cache was populated should no longer be returned.' ); + } + + /** + * Switches to the "block-theme" test theme and runs the setup hooks it relies on + * to gain `current_theme_supports( 'block-templates' )` support. + * + * @return WP_Theme + */ + private function switch_to_block_theme() { + $theme = wp_get_theme( 'block-theme' ); + $this->assertNotEmpty( $theme ); + + switch_theme( $theme['Template'], $theme['Stylesheet'] ); + do_action( 'setup_theme' ); + do_action( 'after_setup_theme' ); + + return $theme; + } + + /** + * Creates a `wp_template` post assigned to the given theme, the same way a user-customized + * block template is stored. + * + * @param WP_Theme $theme Theme the template belongs to. + * @param string $slug Template slug. + * @return WP_Post + */ + private function create_custom_block_template( $theme, $slug ) { + $custom_template = self::factory()->post->create_and_get( + array( + 'post_type' => 'wp_template', + 'post_name' => $slug, + 'post_title' => $slug, + 'tax_input' => array( + 'wp_theme' => array( $theme->get_stylesheet() ), + ), + ) + ); + wp_set_post_terms( $custom_template->ID, $theme->get_stylesheet(), 'wp_theme' ); + + return $custom_template; + } } From 3b38db62192f995bc08393b358f7ed63508cd954 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 22:03:11 +0000 Subject: [PATCH 100/481] Tests: Cover admin bar shortlink output. Verify `wp_admin_bar_shortlink_menu()` omits the node for an empty shortlink, renders the expected link and input, and escapes attribute values. Developed in: https://github.com/WordPress/wordpress-develop/pull/13883 Props r1k0, mukesh27, pbearne, anntrauf. See #66223. git-svn-id: https://develop.svn.wordpress.org/trunk@65105 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/adminbar.php | 82 ++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/phpunit/tests/adminbar.php b/tests/phpunit/tests/adminbar.php index 0183c38e58e04..ecdbf0e4174a7 100644 --- a/tests/phpunit/tests/adminbar.php +++ b/tests/phpunit/tests/adminbar.php @@ -1019,6 +1019,88 @@ public function test_menu_property_is_defined() { $this->assertSame( array(), $admin_bar->menu, 'WP_Admin_Bar::$menu should be equal to an empty array.' ); } + /** + * Tests that the Shortlink node is not added when shortlink is empty. + * + * @ticket 66223 + * + * @covers ::wp_admin_bar_shortlink_menu + */ + public function test_wp_admin_bar_shortlink_menu_does_not_add_node_when_shortlink_is_empty() { + $this->go_to( home_url( '/' ) ); + $this->assertFalse( is_singular(), 'Precondition: the query should not be singular.' ); + + $admin_bar = new WP_Admin_Bar(); + + wp_admin_bar_shortlink_menu( $admin_bar ); + + $node = $admin_bar->get_node( 'get-shortlink' ); + + $this->assertNull( $node, 'The Shortlink node should not be added when shortlink is empty.' ); + } + + /** + * Tests that the Shortlink node is added when a shortlink exists. + * + * @ticket 66223 + * + * @covers ::wp_admin_bar_shortlink_menu + */ + public function test_wp_admin_bar_shortlink_menu_adds_node_when_shortlink_exists() { + $post_id = self::factory()->post->create(); + $expected = home_url( '?p=' . $post_id ); + + $this->go_to( get_permalink( $post_id ) ); + + $admin_bar = new WP_Admin_Bar(); + wp_admin_bar_shortlink_menu( $admin_bar ); + $node = $admin_bar->get_node( 'get-shortlink' ); + + $this->assertNotNull( $node, 'The Shortlink node should be added when shortlink exists.' ); + $this->assertSame( $expected, $node->href, 'The node href should be the post shortlink.' ); + $this->assertSame( 'Shortlink', $node->title, 'The node title should be "Shortlink".' ); + $this->assertStringContainsString( + 'value="' . esc_attr( $expected ) . '"', + $node->meta['html'], + 'The node HTML should contain the shortlink as the input value.' + ); + $this->assertStringContainsString( + 'aria-label="Shortlink"', + $node->meta['html'], + 'The node HTML should contain "Shortlink" as the aria label.' + ); + } + + /** + * Tests that the Shortlink node escapes the shortlink value in the HTML input value. + * + * @ticket 66223 + * + * @covers ::wp_admin_bar_shortlink_menu + */ + public function test_wp_admin_bar_shortlink_menu_escapes_shortlink_in_input_value() { + $expected = home_url( '?test="first"&coverage="second"' ); + + add_filter( + 'pre_get_shortlink', + static function () { + return home_url( '?test="first"&coverage="second"' ); + } + ); + + $admin_bar = new WP_Admin_Bar(); + wp_admin_bar_shortlink_menu( $admin_bar ); + + $node = $admin_bar->get_node( 'get-shortlink' ); + + $this->assertNotNull( $node, 'The Shortlink node should be added when a shortlink exists.' ); + $this->assertStringContainsString( + 'value="' . $expected . '"', + $node->meta['html'], + 'The node HTML should contain the properly escaped shortlink in the input value.' + ); + } + /** * Returns a pattern that matches a rendered item made of an SVG icon element followed by the given HTML. * From 900283f441d9c64bb14cc7762503c7662942b0f8 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 22:12:24 +0000 Subject: [PATCH 101/481] Tests: Cover empty objects in REST media responses. Verify empty `media_details.sizes` and missing attachment metadata are returned as objects that encode to `{}`, preserving the REST response schema. Developed in: https://github.com/WordPress/wordpress-develop/pull/13685 Props therssoftware, huzaifaalmesbah. See #65251. git-svn-id: https://develop.svn.wordpress.org/trunk@65106 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/rest-attachments-controller.php | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/phpunit/tests/rest-api/rest-attachments-controller.php b/tests/phpunit/tests/rest-api/rest-attachments-controller.php index 2a4cd1feaef79..2b79e679b6afb 100644 --- a/tests/phpunit/tests/rest-api/rest-attachments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-attachments-controller.php @@ -1194,6 +1194,63 @@ public function test_get_item_sizes_with_no_url() { $this->assertArrayNotHasKey( 'source_url', $data['media_details']['sizes']['rest-api-test'] ); } + /** + * @ticket 65251 + */ + public function test_get_item_sizes_empty_sizes_is_object() { + $attachment_id = self::factory()->attachment->create_object( + self::$test_file, + 0, + array( + 'post_mime_type' => 'image/jpeg', + 'post_excerpt' => 'A sample caption', + ), + self::$test_file + ); + + wp_update_attachment_metadata( + $attachment_id, + array( + 'width' => 50, + 'height' => 50, + 'file' => 'canola.jpg', + 'sizes' => array(), + 'image_meta' => array(), + ) + ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/media/' . $attachment_id ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertInstanceOf( 'stdClass', $data['media_details']['sizes'], 'Sizes should be an empty object (stdClass) when empty.' ); + $this->assertSame( '{}', wp_json_encode( $data['media_details']['sizes'] ), 'Sizes must JSON-encode as an empty object.' ); + } + + /** + * @ticket 65251 + */ + public function test_get_item_empty_media_details_is_object() { + $attachment_id = self::factory()->attachment->create_object( + self::$test_file, + 0, + array( + 'post_mime_type' => 'image/jpeg', + 'post_excerpt' => 'A sample caption', + ), + self::$test_file + ); + + delete_post_meta( $attachment_id, '_wp_attachment_metadata' ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/media/' . $attachment_id ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertInstanceOf( 'stdClass', $data['media_details'], 'media_details should be an empty object (stdClass) when metadata is missing.' ); + $this->assertSame( '{}', wp_json_encode( $data['media_details'] ), 'media_details must JSON-encode as an empty object.' ); + } + public function test_get_item_private_post_not_authenticated() { wp_set_current_user( 0 ); $draft_post = self::factory()->post->create( array( 'post_status' => 'draft' ) ); From d1bd61ecf2f1b9ab4d0d57ca7dc38e9f46b2bbeb Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 23:46:03 +0000 Subject: [PATCH 102/481] Tests: Cover font collection response preparation. Verify collection data, REST links, and requested-field filtering in `WP_REST_Font_Collections_Controller::prepare_item_for_response()`. Use a nonempty font-family fixture to detect missing response content. Developed in: https://github.com/WordPress/wordpress-develop/pull/14697 Props devmuhib, shailu25, huzaifaalmesbah. See #40538. git-svn-id: https://develop.svn.wordpress.org/trunk@65107 602fd350-edb4-49c9-b593-d223f7449a82 --- .../wpRestFontCollectionsController.php | 94 ++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/fonts/font-library/wpRestFontCollectionsController.php b/tests/phpunit/tests/fonts/font-library/wpRestFontCollectionsController.php index 254958137f8f0..50c3e5d30bd93 100644 --- a/tests/phpunit/tests/fonts/font-library/wpRestFontCollectionsController.php +++ b/tests/phpunit/tests/fonts/font-library/wpRestFontCollectionsController.php @@ -322,10 +322,100 @@ public function test_delete_item() { } /** - * @doesNotPerformAssertions + * @ticket 40538 + * + * @covers WP_REST_Font_Collections_Controller::prepare_item_for_response */ public function test_prepare_item() { - // Controller does not use test_prepare_item(). + $font_families = array( + array( + 'font_family_settings' => array( + 'name' => 'Open Sans', + 'slug' => 'open-sans', + 'fontFamily' => '"Open Sans", sans-serif', + 'preview' => 'https://example.com/open-sans.png', + 'fontFace' => array( + array( + 'fontFamily' => 'Open Sans', + 'fontStyle' => 'normal', + 'fontWeight' => '400', + 'src' => 'https://example.com/open-sans.woff2', + ), + ), + ), + 'categories' => array( 'sans-serif' ), + ), + ); + + wp_register_font_collection( + 'test-prepare-item', + array( + 'name' => 'Test Collection', + 'description' => 'Test description', + 'font_families' => $font_families, + 'categories' => array( + array( + 'name' => 'Sans Serif', + 'slug' => 'sans-serif', + ), + ), + ) + ); + + try { + $collection = WP_Font_Library::get_instance()->get_font_collection( 'test-prepare-item' ); + $controller = new WP_REST_Font_Collections_Controller(); + $request = new WP_REST_Request( 'GET', '/wp/v2/font-collections/test-prepare-item' ); + $response = $controller->prepare_item_for_response( $collection, $request ); + } finally { + wp_unregister_font_collection( 'test-prepare-item' ); + } + + $this->assertInstanceOf( WP_REST_Response::class, $response ); + $this->assertSame( 200, $response->get_status() ); + + $data = $response->get_data(); + $this->assertSame( 'test-prepare-item', $data['slug'] ); + $this->assertSame( 'Test Collection', $data['name'] ); + $this->assertSame( 'Test description', $data['description'] ); + $this->assertSame( $font_families, $data['font_families'] ); + $this->assertSame( + array( + array( + 'name' => 'Sans Serif', + 'slug' => 'sans-serif', + ), + ), + $data['categories'] + ); + + $links = $response->get_links(); + $this->assertArrayHasKey( 'self', $links ); + $this->assertSame( rest_url( 'wp/v2/font-collections/test-prepare-item' ), $links['self'][0]['href'] ); + $this->assertArrayHasKey( 'collection', $links ); + $this->assertSame( rest_url( 'wp/v2/font-collections' ), $links['collection'][0]['href'] ); + } + + /** + * @ticket 40538 + * + * @covers WP_REST_Font_Collections_Controller::prepare_item_for_response + */ + public function test_prepare_item_limit_fields() { + $collection = WP_Font_Library::get_instance()->get_font_collection( 'mock-col-slug' ); + $controller = new WP_REST_Font_Collections_Controller(); + $request = new WP_REST_Request( 'GET', '/wp/v2/font-collections/mock-col-slug' ); + $request->set_param( '_fields', 'slug,name' ); + + $response = $controller->prepare_item_for_response( $collection, $request ); + $this->assertSame( + array( + 'slug' => 'mock-col-slug', + 'name' => 'My collection', + ), + $response->get_data() + ); + $this->assertEmpty( $response->get_links() ); } public function test_get_item_schema() { From d4efa6d7cbb6ac3cf3d93ba71b633b0b4b2a1ffe Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 30 Oct 2026 23:47:11 +0000 Subject: [PATCH 103/481] Tests: Cover home query flags during REST requests. Verify `WP_Query::parse_query()` suppresses `is_home` for the main query during REST requests while allowing secondary queries to retain it. Isolate the tests in separate processes to define `REST_REQUEST`. Developed in: https://github.com/WordPress/wordpress-develop/pull/14797 Props irozum. See #65819, #50213. git-svn-id: https://develop.svn.wordpress.org/trunk@65108 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/query/parseQuery.php | 45 ++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/phpunit/tests/query/parseQuery.php b/tests/phpunit/tests/query/parseQuery.php index ccb0ae57809bd..5fb7a0e7dce0a 100644 --- a/tests/phpunit/tests/query/parseQuery.php +++ b/tests/phpunit/tests/query/parseQuery.php @@ -242,4 +242,49 @@ public function test_parse_query_hierarchical_taxonomy_query_var_array() { $this->assertIsArray( $q->posts ); } + + /** + * Tests that a secondary query can be `is_home` while serving a REST request. + * + * Runs in a separate process because constants cannot be redefined. + * + * @ticket 50213 + * + * @covers WP_Query::parse_query + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_secondary_query_during_rest_request_can_be_home() { + define( 'REST_REQUEST', true ); + + $query = new WP_Query(); + $query->parse_query( array() ); + + $this->assertFalse( $query->is_main_query(), 'Precondition: the query must not be the main query.' ); + $this->assertTrue( $query->is_home ); + } + + /** + * Tests that the main query is not `is_home` while serving a REST request. + * + * Runs in a separate process because constants cannot be redefined. + * + * @ticket 50213 + * + * @covers WP_Query::parse_query + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_main_query_during_rest_request_is_not_home() { + define( 'REST_REQUEST', true ); + + $query = new WP_Query(); + $GLOBALS['wp_the_query'] = $query; + $query->parse_query( array() ); + + $this->assertTrue( $query->is_main_query(), 'Precondition: the query must be the main query.' ); + $this->assertFalse( $query->is_home ); + } } From ec285af8d99509efaebef7ed76c1a773b35533b5 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Fri, 30 Oct 2026 23:54:34 +0000 Subject: [PATCH 104/481] Tests: Correct test class name for `wp_register_ability()` tests. Follow-up to r61032. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65110 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/abilities-api/wpRegisterAbility.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/phpunit/tests/abilities-api/wpRegisterAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterAbility.php index ca7420a193c85..4c54eeeb2163f 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterAbility.php @@ -20,7 +20,7 @@ protected function do_execute( $input = null ) { * * @group abilities-api */ -class Test_Abilities_API_WpRegisterAbility extends WP_UnitTestCase { +class Tests_Abilities_API_WpRegisterAbility extends WP_UnitTestCase { public static $test_ability_name = 'test/add-numbers'; public static $test_ability_args = array(); From aca248cd9d2747102e1705f14b7e8cb474df7920 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 00:00:24 +0000 Subject: [PATCH 105/481] Tests: Cover plugin validation and list-table row metadata. Cover invalid active-plugin options, silent deactivation, and network-plugin permissions in `validate_active_plugins()`. Consolidate the existing validation coverage in the dedicated test file. Cover version, author, details and site links in `WP_Plugins_List_Table::single_row()`, including capability-dependent links and the `plugin_row_meta` filter. Scope temporary plugin cleanup to each test's own directory. Developed in: https://github.com/WordPress/wordpress-develop/pull/14608, https://github.com/WordPress/wordpress-develop/pull/14603 Props huzaifaalmesbah, mukesh27. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65111 602fd350-edb4-49c9-b593-d223f7449a82 --- .../includes/plugin/validateActivePlugins.php | 227 +++++++++++ tests/phpunit/tests/admin/includesPlugin.php | 19 - .../tests/admin/wpPluginsListTableRowMeta.php | 369 ++++++++++++++++++ 3 files changed, 596 insertions(+), 19 deletions(-) create mode 100644 tests/phpunit/tests/admin/includes/plugin/validateActivePlugins.php create mode 100644 tests/phpunit/tests/admin/wpPluginsListTableRowMeta.php diff --git a/tests/phpunit/tests/admin/includes/plugin/validateActivePlugins.php b/tests/phpunit/tests/admin/includes/plugin/validateActivePlugins.php new file mode 100644 index 0000000000000..e49dfef026ff8 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/plugin/validateActivePlugins.php @@ -0,0 +1,227 @@ +user->create( array( 'role' => 'administrator' ) ); + + if ( is_multisite() ) { + grant_super_admin( self::$super_admin_id ); + } + } + + /** + * Revokes the super admin grant before the fixture users are deleted. + */ + public static function wpTearDownAfterClass() { + if ( is_multisite() ) { + revoke_super_admin( self::$super_admin_id ); + } + } + + /** + * Removes stale plugin files and resets the active plugins. + */ + public function set_up() { + parent::set_up(); + + $this->no_header_dir = 'validate-test-no-header-' . wp_generate_password( 6, false ); + $this->remove_plugin(); + + wp_clean_plugins_cache( false ); + update_site_option( 'active_sitewide_plugins', array() ); + } + + /** + * Removes the plugin file without a header. + */ + public function tear_down() { + $this->remove_plugin(); + + wp_clean_plugins_cache( false ); + + parent::tear_down(); + } + + /** + * Tests that an active plugins option that is not an array is reset. + * + * @ticket 65819 + * + * @dataProvider data_invalid_options + * + * @param mixed $value The option value. + */ + public function test_should_reset_option_that_is_not_an_array( $value ) { + update_option( 'active_plugins', $value ); + + $this->assertSame( array(), validate_active_plugins(), 'No invalid plugins should be returned.' ); + $this->assertSame( array(), get_option( 'active_plugins' ), 'The option should be reset.' ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_invalid_options() { + return array( + 'string' => array( 'hello.php' ), + 'integer' => array( 1 ), + 'boolean' => array( false ), + 'null' => array( null ), + 'object' => array( new stdClass() ), + ); + } + + /** + * Tests that an empty array is returned when no plugins are active. + * + * @ticket 65819 + */ + public function test_should_return_empty_array_when_no_active_plugins() { + update_option( 'active_plugins', array() ); + + $this->assertSame( array(), validate_active_plugins() ); + } + + /** + * Tests that valid active plugins are kept. + * + * @ticket 65819 + */ + public function test_should_keep_valid_plugins() { + update_option( 'active_plugins', array( 'hello.php', 'internationalized-plugin.php' ) ); + + $this->assertSame( array(), validate_active_plugins(), 'No invalid plugins should be returned.' ); + $this->assertSame( array( 'hello.php', 'internationalized-plugin.php' ), get_option( 'active_plugins' ), 'The plugins should stay active.' ); + } + + /** + * Tests that invalid active plugins are reported and deactivated silently. + * + * @ticket 65819 + */ + public function test_should_report_and_deactivate_invalid_plugins() { + if ( ! is_writable( WP_PLUGIN_DIR ) ) { + $this->markTestSkipped( 'WP_PLUGIN_DIR is not writable.' ); + } + + $dir = WP_PLUGIN_DIR . '/' . $this->no_header_dir; + $this->assertTrue( mkdir( $dir ), 'The test directory should be created.' ); + $this->assertNotFalse( file_put_contents( $dir . '/functions.php', "no_header_dir . '/functions.php'; + update_option( 'active_plugins', array( 'hello.php', '../outside.php', 'missing/missing.php', $no_header ) ); + + $deactivate = new MockAction(); + add_action( 'deactivate_plugin', array( $deactivate, 'action' ) ); + add_action( 'deactivated_plugin', array( $deactivate, 'action' ) ); + add_action( "deactivate_{$no_header}", array( $deactivate, 'action' ) ); + + $invalid = validate_active_plugins(); + + $this->assertSame( array( '../outside.php', 'missing/missing.php', $no_header ), array_keys( $invalid ), 'Each invalid plugin should be reported.' ); + $this->assertSame( + array( + '../outside.php' => 'plugin_invalid', + 'missing/missing.php' => 'plugin_not_found', + $no_header => 'no_plugin_header', + ), + array_map( + static function ( $error ) { + return $error->get_error_code(); + }, + $invalid + ), + 'Each invalid plugin should have its expected error code.' + ); + $this->assertSame( array( 'hello.php' ), array_values( get_option( 'active_plugins' ) ), 'Only the valid plugin should stay active.' ); + $this->assertSame( 0, $deactivate->get_call_count(), 'Invalid plugins should be deactivated silently.' ); + } + + /** + * Tests that network-active plugins are validated for a user who can manage network plugins, + * and that a missing plugin present in both active_plugins and active_sitewide_plugins is removed from both. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_validate_network_plugins_for_network_admin() { + wp_set_current_user( self::$super_admin_id ); + + update_option( 'active_plugins', array( 'missing/missing.php' ) ); + update_site_option( + 'active_sitewide_plugins', + array( + 'hello.php' => 1000, + 'missing/missing.php' => 1000, + ) + ); + + $this->assertSame( array( 'missing/missing.php' ), array_keys( validate_active_plugins() ), 'The invalid network plugin should be reported.' ); + $this->assertSame( array( 'hello.php' => 1000 ), get_site_option( 'active_sitewide_plugins' ), 'The invalid network plugin should be deactivated from network.' ); + $this->assertNotContains( 'missing/missing.php', get_option( 'active_plugins' ), 'The invalid plugin should also be deactivated from site active plugins.' ); + } + + /** + * Tests that network-active plugins are not validated for other users. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_not_validate_network_plugins_for_other_users() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + update_option( 'active_plugins', array() ); + update_site_option( 'active_sitewide_plugins', array( 'missing/missing.php' => 1000 ) ); + + $this->assertSame( array(), validate_active_plugins(), 'No plugins should be validated.' ); + $this->assertSame( array( 'missing/missing.php' => 1000 ), get_site_option( 'active_sitewide_plugins' ), 'The network plugins should not change.' ); + } + + /** + * Removes the plugin file without a header. + */ + private function remove_plugin() { + if ( $this->no_header_dir ) { + $dir = WP_PLUGIN_DIR . '/' . $this->no_header_dir; + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } + } +} diff --git a/tests/phpunit/tests/admin/includesPlugin.php b/tests/phpunit/tests/admin/includesPlugin.php index c471d3b493076..1d5997e15a068 100644 --- a/tests/phpunit/tests/admin/includesPlugin.php +++ b/tests/phpunit/tests/admin/includesPlugin.php @@ -738,25 +738,6 @@ public function test_activate_plugins_single_array() { deactivate_plugins( $name ); } - /** - * @covers ::validate_active_plugins - */ - public function test_validate_active_plugins_remove_invalid() { - $plugin = $this->_create_plugin(); - - activate_plugin( $plugin[0] ); - unlink( $plugin[1] ); - - $result = validate_active_plugins(); - $this->assertArrayHasKey( $plugin[0], $result ); - } - - /** - * @covers ::validate_active_plugins - */ - public function test_validate_active_plugins_empty() { - $this->assertSame( array(), validate_active_plugins() ); - } /** * @covers ::is_uninstallable_plugin diff --git a/tests/phpunit/tests/admin/wpPluginsListTableRowMeta.php b/tests/phpunit/tests/admin/wpPluginsListTableRowMeta.php new file mode 100644 index 0000000000000..8ad060e649454 --- /dev/null +++ b/tests/phpunit/tests/admin/wpPluginsListTableRowMeta.php @@ -0,0 +1,369 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$activator_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + get_userdata( self::$activator_id )->add_cap( 'activate_plugins' ); + + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + } + + /** + * Revokes the super admin grant before the fixture users are deleted. + */ + public static function wpTearDownAfterClass() { + if ( is_multisite() ) { + revoke_super_admin( self::$admin_id ); + } + } + + /** + * Sets up the Plugins screen and the list table globals. + */ + public function set_up() { + parent::set_up(); + + foreach ( array( 'status', 's', 'totals' ) as $name ) { + if ( array_key_exists( $name, $GLOBALS ) ) { + $this->original_globals[ $name ] = $GLOBALS[ $name ]; + } + } + + set_current_screen( 'plugins' ); + + $GLOBALS['status'] = 'all'; + $GLOBALS['page'] = 1; + $GLOBALS['s'] = ''; + $GLOBALS['totals'] = array(); + + $this->filter_args = null; + $this->slug = 'row-meta-plugin-' . ++self::$counter . '-' . wp_generate_password( 6, false ); + + add_filter( 'plugin_row_meta', array( $this, 'capture_meta' ), PHP_INT_MAX, 4 ); + + wp_set_current_user( self::$admin_id ); + } + + /** + * Restores the globals and removes the test plugin. + */ + public function tear_down() { + foreach ( array( 'status', 's', 'totals' ) as $name ) { + if ( array_key_exists( $name, $this->original_globals ) ) { + $GLOBALS[ $name ] = $this->original_globals[ $name ]; + } else { + unset( $GLOBALS[ $name ] ); + } + } + + $this->remove_plugin(); + + parent::tear_down(); + } + + /** + * Tests the version, linked author and View details link of a plugin from the directory. + * + * @ticket 65819 + */ + public function test_should_list_version_author_and_details_link() { + $expected_details_url = esc_url( + network_admin_url( + 'plugin-install.php?tab=plugin-information&plugin=' . $this->slug . + '&TB_iframe=true&width=600&height=550' + ) + ); + + $this->assertSame( + array( + 'Version 1.2.3', + 'By Jane', + 'View details', + ), + $this->get_meta( + array( + 'Name' => 'My "Plugin"', + 'Version' => '1.2.3', + 'Author' => 'Jane', + 'AuthorURI' => 'https://example.org/jane/', + 'PluginURI' => 'https://example.org/plugin/', + 'slug' => $this->slug, + ) + ) + ); + } + + /** + * Tests the author without a link and the plugin site link of a plugin that is not from the directory. + * + * @ticket 65819 + */ + public function test_should_link_plugin_site_without_directory_slug() { + $this->assertSame( + array( + 'Version 1.2.3', + 'By Jane', + 'Visit plugin site', + ), + $this->get_meta( + array( + 'Version' => '1.2.3', + 'Author' => 'Jane', + 'PluginURI' => 'https://example.org/plugin/?a=1&b=2', + ) + ) + ); + } + + /** + * Tests that a user who cannot install plugins gets the plugin site link instead of View details. + * + * @ticket 65819 + */ + public function test_should_link_plugin_site_for_user_without_install_capability() { + wp_set_current_user( self::$activator_id ); + + $this->assertSame( + array( 'Visit plugin site' ), + $this->get_meta( + array( + 'slug' => $this->slug, + 'PluginURI' => 'https://example.org/plugin/', + ) + ) + ); + } + + /** + * Tests that empty fields are left out. + * + * @ticket 65819 + * + * @dataProvider data_empty_values + * + * @param mixed $value The empty value of the version, author, author URI and plugin URI. + */ + public function test_should_leave_out_empty_fields( $value ) { + $this->assertSame( + array(), + $this->get_meta( + array( + 'Version' => $value, + 'Author' => $value, + 'AuthorURI' => 'https://example.org/jane/', + 'PluginURI' => $value, + ) + ) + ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_empty_values() { + return array( + 'empty string' => array( '' ), + 'zero string' => array( '0' ), + ); + } + + /** + * Tests that an empty or '0' author URI does not link the author. + * + * @ticket 65819 + * + * @dataProvider data_empty_values + * + * @param string $empty_uri Empty or '0' author URI. + */ + public function test_should_not_link_author_when_author_uri_is_empty( $empty_uri ) { + $this->assertSame( + array( 'By Jane' ), + $this->get_meta( + array( + 'Author' => 'Jane', + 'AuthorURI' => $empty_uri, + ) + ) + ); + } + + /** + * Tests that the filter receives the plugin file, data and status, and its links are joined. + * + * @ticket 65819 + */ + public function test_should_filter_and_join_meta() { + add_filter( + 'plugin_row_meta', + static function ( $meta ) { + $meta[] = 'Docs'; + + return $meta; + } + ); + + $output = $this->render( array( 'Version' => '1.2.3' ) ); + + $this->assertIsArray( $this->filter_args, 'The plugin_row_meta filter should run.' ); + $this->assertSame( $this->get_file(), $this->filter_args[1], 'The filter should receive the plugin file.' ); + $this->assertSame( 'My Plugin', $this->filter_args[2]['Name'], 'The filter should receive the plugin data.' ); + $this->assertSame( 'all', $this->filter_args[3], 'The filter should receive the status.' ); + $this->assertStringContainsString( 'plugin-version-author-uri\'>Version 1.2.3 | Docs', $output, 'The links should be joined.' ); + } + + /** + * Captures the arguments of the plugin_row_meta filter. + * + * @param string[] $meta The row meta. + * @param string $plugin_file The plugin file. + * @param array $plugin_data The plugin data. + * @param string $status The plugin status. + * @return string[] The unchanged row meta. + */ + public function capture_meta( $meta, $plugin_file, $plugin_data, $status ) { + $this->filter_args = array( $meta, $plugin_file, $plugin_data, $status ); + + return $meta; + } + + /** + * Renders the row of the test plugin and returns its row meta. + * + * @param array $plugin_data The plugin data to add. + * @return string[] The row meta, before the plugin_row_meta filter. + */ + private function get_meta( $plugin_data ) { + $this->render( $plugin_data ); + + $this->assertIsArray( $this->filter_args, 'The plugin_row_meta filter should run.' ); + + return $this->filter_args[0]; + } + + /** + * Renders the row of the test plugin. + * + * @param array $plugin_data The plugin data to add. + * @return string The row markup. + */ + private function render( $plugin_data ) { + // is_network_only_plugin() reads the plugin headers only on multisite. + if ( is_multisite() ) { + if ( ! is_writable( WP_PLUGIN_DIR ) ) { + $this->markTestSkipped( 'WP_PLUGIN_DIR is not writable.' ); + } + + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + $this->remove_plugin(); + $this->assertTrue( mkdir( $dir ), 'The test plugin directory should be created.' ); + $this->assertNotFalse( file_put_contents( $dir . '/' . $this->slug . '.php', " 'plugins' ) ); + + return get_echo( + array( $table, 'single_row' ), + array( + array( + $this->get_file(), + array_merge( + array( + 'Name' => 'My Plugin', + 'Description' => '', + 'Version' => '', + 'Author' => '', + 'AuthorURI' => '', + 'PluginURI' => '', + ), + $plugin_data + ), + ), + ) + ); + } + + /** + * Returns the plugin file of the test plugin. + * + * @return string The plugin file. + */ + private function get_file() { + return "{$this->slug}/{$this->slug}.php"; + } + + /** + * Removes the test plugin. + */ + private function remove_plugin() { + if ( is_multisite() && $this->slug ) { + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } + } +} From bcf08b1cbf76e74b50bb716794713ca6536c7448 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 00:05:14 +0000 Subject: [PATCH 106/481] Tests: Expand coverage for `wp_list_filter()`. Cover lists of arrays, mixed arrays and objects, null-value matching, and case-insensitive operators. Verify the default `AND` operator, key preservation, and empty and invalid inputs. Developed in: https://github.com/WordPress/wordpress-develop/pull/13718 Props mindctrl, huzaifaalmesbah. See #53987. git-svn-id: https://develop.svn.wordpress.org/trunk@65112 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/functions/wpListFilter.php | 288 +++++++++++++++++- 1 file changed, 279 insertions(+), 9 deletions(-) diff --git a/tests/phpunit/tests/functions/wpListFilter.php b/tests/phpunit/tests/functions/wpListFilter.php index 1039b70f3ec20..2c9a8a7d6b134 100644 --- a/tests/phpunit/tests/functions/wpListFilter.php +++ b/tests/phpunit/tests/functions/wpListFilter.php @@ -10,6 +10,8 @@ class Tests_Functions_wpListFilter extends WP_UnitTestCase { /** + * @ticket 53987 + * * @dataProvider data_wp_list_filter * * @param array $input_list An array of objects to filter. @@ -22,6 +24,32 @@ public function test_wp_list_filter( $input_list, $args, $operator, $expected ) $this->assertEqualSetsWithIndex( $expected, wp_list_filter( $input_list, $args, $operator ) ); } + /** + * Tests that the 'AND' operator is used when no operator is passed. + * + * @ticket 53987 + */ + public function test_wp_list_filter_should_default_to_and_operator() { + $input_list = array( + (object) array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + (object) array( 'foo' => 'bar' ), + ); + + $this->assertEqualSetsWithIndex( + array( 0 => $input_list[0] ), + wp_list_filter( + $input_list, + array( + 'foo' => 'bar', + 'bar' => 'baz', + ) + ) + ); + } + /** * Data provider. * @@ -29,25 +57,25 @@ public function test_wp_list_filter( $input_list, $args, $operator, $expected ) */ public static function data_wp_list_filter() { return array( - 'string instead of array' => array( + 'string instead of array' => array( 'foo', array(), 'AND', array(), ), - 'object instead of array' => array( + 'object instead of array' => array( (object) array( 'foo' ), array(), 'AND', array(), ), - 'empty args' => array( + 'empty args' => array( array( 'foo', 'bar' ), array(), 'AND', array( 'foo', 'bar' ), ), - 'invalid operator' => array( + 'invalid operator' => array( array( (object) array( 'foo' => 'bar' ), (object) array( 'foo' => 'baz' ), @@ -56,7 +84,7 @@ public static function data_wp_list_filter() { 'XOR', array(), ), - 'single argument to match' => array( + 'single argument to match' => array( array( (object) array( 'foo' => 'bar', @@ -94,7 +122,7 @@ public static function data_wp_list_filter() { ), ), ), - 'all must match' => array( + 'all must match' => array( array( (object) array( 'foo' => 'bar', @@ -132,7 +160,7 @@ public static function data_wp_list_filter() { ), ), ), - 'any must match' => array( + 'any must match' => array( array( (object) array( 'foo' => 'bar', @@ -179,7 +207,7 @@ public static function data_wp_list_filter() { ), ), ), - 'none must match' => array( + 'none must match' => array( array( (object) array( 'foo' => 'bar', @@ -216,7 +244,7 @@ public static function data_wp_list_filter() { ), ), ), - 'string to int comparison' => array( + 'string to int comparison' => array( array( (object) array( 'foo' => '1', @@ -230,6 +258,248 @@ public static function data_wp_list_filter() { ), ), ), + 'bool to string comparison' => array( + array( + (object) array( + 'foo' => true, + ), + ), + array( 'foo' => 'yes' ), + 'AND', + array( + 0 => (object) array( + 'foo' => true, + ), + ), + ), + 'null instead of array' => array( + null, + array( 'foo' => 'bar' ), + 'AND', + array(), + ), + 'empty list' => array( + array(), + array( 'foo' => 'bar' ), + 'AND', + array(), + ), + + /* + * Empty arguments are checked before the operator is validated, + * so the original list is returned even for an invalid operator. + */ + 'empty args, invalid operator' => array( + array( 'foo', 'bar' ), + array(), + 'XOR', + array( 'foo', 'bar' ), + ), + + // The operator is uppercased before it is validated. + 'lowercase AND operator' => array( + array( + (object) array( 'foo' => 'bar' ), + (object) array( 'foo' => 'baz' ), + ), + array( 'foo' => 'bar' ), + 'and', + array( + 0 => (object) array( 'foo' => 'bar' ), + ), + ), + 'mixed case OR operator' => array( + array( + (object) array( 'foo' => 'bar' ), + (object) array( 'foo' => 'baz' ), + ), + array( 'foo' => 'bar' ), + 'oR', + array( + 0 => (object) array( 'foo' => 'bar' ), + ), + ), + 'lowercase NOT operator' => array( + array( + (object) array( 'foo' => 'bar' ), + (object) array( 'foo' => 'baz' ), + ), + array( 'foo' => 'bar' ), + 'not', + array( + 1 => (object) array( 'foo' => 'baz' ), + ), + ), + + // Lists of arrays are supported alongside lists of objects. + 'arrays: single argument to match' => array( + array( + array( + 'foo' => 'bar', + 'key' => 'foo', + ), + array( + 'foo' => 'baz', + 'key' => 'value', + ), + array( + 'foo' => 'bar', + 'key' => 'value', + ), + ), + array( 'foo' => 'bar' ), + 'AND', + array( + 0 => array( + 'foo' => 'bar', + 'key' => 'foo', + ), + 2 => array( + 'foo' => 'bar', + 'key' => 'value', + ), + ), + ), + 'arrays: all must match' => array( + array( + array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + array( 'foo' => 'bar' ), + ), + array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + 'AND', + array( + 0 => array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + ), + ), + 'arrays: any must match' => array( + array( + array( 'foo' => 'bar' ), + array( 'bar' => 'baz' ), + array( 'foo' => 'baz' ), + ), + array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + 'OR', + array( + 0 => array( 'foo' => 'bar' ), + 1 => array( 'bar' => 'baz' ), + ), + ), + 'arrays: none must match' => array( + array( + array( 'foo' => 'bar' ), + array( 'bar' => 'baz' ), + array( 'foo' => 'baz' ), + ), + array( + 'foo' => 'bar', + 'bar' => 'baz', + ), + 'NOT', + array( + 2 => array( 'foo' => 'baz' ), + ), + ), + 'mixed arrays and objects' => array( + array( + array( 'foo' => 'bar' ), + (object) array( 'foo' => 'bar' ), + array( 'foo' => 'baz' ), + (object) array( 'foo' => 'baz' ), + ), + array( 'foo' => 'bar' ), + 'AND', + array( + 0 => array( 'foo' => 'bar' ), + 1 => (object) array( 'foo' => 'bar' ), + ), + ), + + /* + * Values that are neither arrays nor objects can never match, + * so they are only returned by the 'NOT' operator. + */ + 'scalar values with AND' => array( + array( 'a string', 42, null, array( 'foo' => 'bar' ) ), + array( 'foo' => 'bar' ), + 'AND', + array( + 3 => array( 'foo' => 'bar' ), + ), + ), + 'scalar values with NOT' => array( + array( 'a string', 42, null, array( 'foo' => 'bar' ) ), + array( 'foo' => 'bar' ), + 'NOT', + array( + 0 => 'a string', + 1 => 42, + 2 => null, + ), + ), + + /* + * Array values are checked with array_key_exists(), so a null value + * matches, while object properties are checked with isset(), + * so a null property does not. + */ + 'array with a null value matching null' => array( + array( array( 'foo' => null ) ), + array( 'foo' => null ), + 'AND', + array( + 0 => array( 'foo' => null ), + ), + ), + 'object with a null property matching null' => array( + array( (object) array( 'foo' => null ) ), + array( 'foo' => null ), + 'AND', + array(), + ), + + 'string keys are preserved' => array( + array( + 'first' => (object) array( 'foo' => 'bar' ), + 'second' => (object) array( 'foo' => 'baz' ), + 'third' => (object) array( 'foo' => 'bar' ), + ), + array( 'foo' => 'bar' ), + 'AND', + array( + 'first' => (object) array( 'foo' => 'bar' ), + 'third' => (object) array( 'foo' => 'bar' ), + ), + ), + 'no matches with OR' => array( + array( + (object) array( 'foo' => 'baz' ), + (object) array( 'foo' => 'qux' ), + ), + array( 'foo' => 'bar' ), + 'OR', + array(), + ), + 'all matches with NOT' => array( + array( + (object) array( 'foo' => 'bar' ), + (object) array( 'foo' => 'bar' ), + ), + array( 'foo' => 'bar' ), + 'NOT', + array(), + ), ); } } From 76875722c7eef7d75f064f59757f244b4b11f7b7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 00:06:49 +0000 Subject: [PATCH 107/481] Tests: Cover plugin file editing and loopback rollback. Cover request validation, permissions, file boundaries, and saving plugin files through `wp_edit_theme_plugin_file()`. Verify loopback requests for active PHP files, authenticated requests, restored content on failure, and scrape-key cleanup. Remove temporary plugin fixtures and run the parent teardown before checking for unconsumed mock responses. Developed in: https://github.com/WordPress/wordpress-develop/pull/14600 Props huzaifaalmesbah, mukesh27. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65113 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/wpEditThemePluginFilePlugin.php | 662 ++++++++++++++++++ 1 file changed, 662 insertions(+) create mode 100644 tests/phpunit/tests/admin/wpEditThemePluginFilePlugin.php diff --git a/tests/phpunit/tests/admin/wpEditThemePluginFilePlugin.php b/tests/phpunit/tests/admin/wpEditThemePluginFilePlugin.php new file mode 100644 index 0000000000000..a97fa7e37a851 --- /dev/null +++ b/tests/phpunit/tests/admin/wpEditThemePluginFilePlugin.php @@ -0,0 +1,662 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + } + + /** + * Revokes the super admin grant before the fixture users are deleted. + */ + public static function wpTearDownAfterClass() { + if ( is_multisite() ) { + revoke_super_admin( self::$admin_id ); + } + } + + /** + * Creates the test plugin and records loopback requests. + */ + public function set_up() { + parent::set_up(); + + if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) { + $this->markTestSkipped( 'File editing is disabled via DISALLOW_FILE_EDIT.' ); + } + + if ( ! is_writable( WP_PLUGIN_DIR ) ) { + $this->markTestSkipped( 'WP_PLUGIN_DIR is not writable.' ); + } + + $this->remove_plugin(); + + $dir = WP_PLUGIN_DIR . '/' . self::SLUG; + $this->assertTrue( mkdir( $dir ), 'The test plugin directory should be created.' ); + + $files = array( + self::SLUG . '.php' => " "Original readme.\n", + 'logo.png' => 'Not really an image.', + ); + foreach ( $files as $name => $contents ) { + $this->assertNotFalse( file_put_contents( $dir . '/' . $name, $contents ), "{$name} should be written." ); + } + + $other_dir = WP_PLUGIN_DIR . '/' . self::OTHER_SLUG; + $this->assertTrue( mkdir( $other_dir ), 'The second test plugin directory should be created.' ); + $this->assertNotFalse( + file_put_contents( + $other_dir . '/' . self::OTHER_SLUG . '.php', + "loopback_requests = array(); + $this->scrape_results = array(); + add_filter( 'pre_http_request', array( $this, 'record_loopback' ), 10, 3 ); + + wp_set_current_user( self::$admin_id ); + } + + /** + * Removes the test plugin. + */ + public function tear_down() { + unset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ); + + if ( is_multisite() ) { + update_site_option( 'active_sitewide_plugins', array() ); + } + + $this->remove_plugin(); + + parent::tear_down(); + + $this->assertEmpty( $this->scrape_results, 'All queued scrape results should be consumed.' ); + } + + /** + * Tests the errors for incomplete requests. + * + * @ticket 65819 + * + * @dataProvider data_incomplete_requests + * + * @param array $args The arguments, merged over a valid request. + * @param string $code The expected error code. + */ + public function test_should_reject_incomplete_request( $args, $code ) { + $request = array_merge( $this->get_request( 'readme.txt' ), $args ); + $request = array_filter( + $request, + static function ( $value ) { + return null !== $value; + } + ); + + $result = wp_edit_theme_plugin_file( $request ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( $code, $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( "Original readme.\n", $this->get_contents( 'readme.txt' ), 'The file should not change.' ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_incomplete_requests() { + return array( + 'no file' => array( array( 'file' => null ), 'missing_file' ), + 'empty file' => array( array( 'file' => '' ), 'missing_file' ), + 'file outside the plugins' => array( array( 'file' => '../wp-config.php' ), 'bad_file' ), + 'no content' => array( array( 'newcontent' => null ), 'missing_content' ), + 'no nonce' => array( array( 'nonce' => null ), 'missing_nonce' ), + 'no plugin or theme' => array( array( 'plugin' => null ), 'missing_theme_or_plugin' ), + 'empty plugin' => array( array( 'plugin' => '' ), 'missing_theme_or_plugin' ), + ); + } + + /** + * Tests that a user who cannot edit plugins is rejected. + * + * @ticket 65819 + */ + public function test_should_reject_user_without_capability() { + wp_set_current_user( self::$subscriber_id ); + + $result = wp_edit_theme_plugin_file( $this->get_request( 'readme.txt' ) ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'unauthorized', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( 'Sorry, you are not allowed to edit plugins for this site.', $result->get_error_message(), 'The error message should match.' ); + } + + /** + * Tests that a request with a nonce for another file is rejected. + * + * @ticket 65819 + */ + public function test_should_reject_nonce_for_another_file() { + $request = $this->get_request( 'readme.txt' ); + $request['nonce'] = wp_create_nonce( 'edit-plugin_' . $this->get_plugin() ); + + $result = wp_edit_theme_plugin_file( $request ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'nonce_failure', $result->get_error_code(), 'The error code should match.' ); + } + + /** + * Tests that editing an uninstalled plugin is rejected. + * + * @ticket 65819 + */ + public function test_should_reject_uninstalled_plugin() { + $result = wp_edit_theme_plugin_file( + array_merge( + $this->get_request( 'readme.txt' ), + array( 'plugin' => 'missing/missing.php' ) + ) + ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'invalid_plugin', $result->get_error_code(), 'The error code should match.' ); + } + + /** + * Tests that a file of another plugin is rejected with a valid nonce for it. + * + * @ticket 65819 + */ + public function test_should_reject_file_of_another_plugin() { + $other_file = self::OTHER_SLUG . '/' . self::OTHER_SLUG . '.php'; + $other_filepath = WP_PLUGIN_DIR . '/' . $other_file; + $original_content = file_get_contents( $other_filepath ); + + $result = wp_edit_theme_plugin_file( + array( + 'plugin' => $this->get_plugin(), + 'file' => $other_file, + 'newcontent' => 'New content.', + 'nonce' => wp_create_nonce( 'edit-plugin_' . $other_file ), + ) + ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'bad_plugin_file_path', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( 'Sorry, that file cannot be edited.', $result->get_error_message(), 'The error message should match.' ); + $this->assertSame( $original_content, file_get_contents( $other_filepath ), 'The other plugin file should be unchanged.' ); + } + + /** + * Tests that a plugin file that is missing on disk is rejected. + * + * @ticket 65819 + */ + public function test_should_reject_missing_file() { + wp_cache_set( 'plugins', array( '' => array( 'ghost/ghost.php' => array( 'Name' => 'Ghost' ) ) ), 'plugins' ); + + $result = wp_edit_theme_plugin_file( + array( + 'plugin' => 'ghost/ghost.php', + 'file' => 'ghost/ghost.php', + 'newcontent' => 'New content.', + 'nonce' => wp_create_nonce( 'edit-plugin_ghost/ghost.php' ), + ) + ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'file_does_not_exist', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( 'File does not exist! Please double check the name and try again.', $result->get_error_message(), 'The error message should match.' ); + } + + /** + * Tests that a file type that is not editable is rejected. + * + * @ticket 65819 + */ + public function test_should_reject_file_type_that_is_not_editable() { + $result = wp_edit_theme_plugin_file( $this->get_request( 'logo.png' ) ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'illegal_file_type', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( 'Files of this type are not editable.', $result->get_error_message(), 'The error message should match.' ); + $this->assertSame( 'Not really an image.', $this->get_contents( 'logo.png' ), 'The file should not change.' ); + } + + /** + * Tests that the editable file types can be filtered per plugin. + * + * @ticket 65819 + */ + public function test_should_apply_editable_extensions_filter() { + $filter = new MockAction(); + add_filter( 'editable_extensions', array( $filter, 'filter' ), 10, 2 ); + add_filter( + 'editable_extensions', + static function ( $types ) { + return array_diff( $types, array( 'txt' ) ); + }, + 11 + ); + + $result = wp_edit_theme_plugin_file( $this->get_request( 'readme.txt' ) ); + $args = $filter->get_args(); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'illegal_file_type', $result->get_error_code(), 'Text files should no longer be editable.' ); + $this->assertSame( $this->get_plugin(), $args[0][1], 'The filter should receive the plugin.' ); + } + + /** + * Tests that a file of an inactive plugin is saved without a loopback check. + * + * @ticket 65819 + * + * @dataProvider data_files + * + * @param string $file The file, relative to the plugin directory. + */ + public function test_should_save_file_of_inactive_plugin( $file ) { + $this->assertTrue( wp_edit_theme_plugin_file( $this->get_request( $file, "New content.\n" ) ), 'The file should be saved.' ); + $this->assertSame( "New content.\n", $this->get_contents( $file ), 'The new content should be written.' ); + $this->assertSame( array(), $this->loopback_requests, 'No loopback request should be made.' ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_files() { + return array( + 'text file' => array( 'readme.txt' ), + 'main plugin file' => array( self::SLUG . '.php' ), + ); + } + + /** + * Tests that a non-PHP file of an active plugin is saved without a loopback check. + * + * @ticket 65819 + */ + public function test_should_save_non_php_file_of_active_plugin_without_loopback() { + update_option( 'active_plugins', array( $this->get_plugin() ) ); + + $this->assertTrue( wp_edit_theme_plugin_file( $this->get_request( 'readme.txt', "New content.\n" ) ), 'The file should be saved.' ); + $this->assertSame( "New content.\n", $this->get_contents( 'readme.txt' ), 'The new content should be written.' ); + $this->assertSame( array(), $this->loopback_requests, 'No loopback request should be made.' ); + } + + /** + * Tests that a PHP file of an active plugin is saved when both loopback checks pass. + * + * @ticket 65819 + */ + public function test_should_save_php_file_of_active_plugin_when_loopback_passes() { + update_option( 'active_plugins', array( $this->get_plugin() ) ); + $this->scrape_results = array( 'true', 'true' ); + + $this->assertTrue( wp_edit_theme_plugin_file( $this->get_request( self::SLUG . '.php', self::EDITED_PHP ) ), 'The file should be saved.' ); + $this->assertSame( self::EDITED_PHP, $this->get_contents( self::SLUG . '.php' ), 'The new content should be written.' ); + $this->assertSame( + array( + wp_parse_url( admin_url( 'plugin-editor.php' ), PHP_URL_PATH ), + wp_parse_url( home_url( '/' ), PHP_URL_PATH ), + ), + $this->get_loopback_paths(), + 'The editor and the home page should be checked.' + ); + $this->assert_scrape_key_deleted(); + } + + /** + * Tests that a Basic Authorization header is included in loopback requests when PHP_AUTH credentials exist. + * + * @ticket 65819 + */ + public function test_should_include_basic_auth_in_loopback_requests() { + $_SERVER['PHP_AUTH_USER'] = 'testuser'; + $_SERVER['PHP_AUTH_PW'] = 'testpass'; + + update_option( 'active_plugins', array( $this->get_plugin() ) ); + $this->scrape_results = array( 'true', 'true' ); + + $captured_headers = array(); + add_filter( + 'pre_http_request', + function ( $response, $args, $url ) use ( &$captured_headers ) { + if ( str_contains( $url, 'wp_scrape_key' ) ) { + $captured_headers[] = $args['headers']; + } + return $response; + }, + 5, + 3 + ); + + $result = wp_edit_theme_plugin_file( $this->get_request( self::SLUG . '.php', self::EDITED_PHP ) ); + + $this->assertTrue( $result, 'The file should be saved.' ); + $this->assertNotEmpty( $captured_headers, 'Loopback requests should be made.' ); + $expected_auth = 'Basic ' . base64_encode( 'testuser:testpass' ); + foreach ( $captured_headers as $headers ) { + $this->assertArrayHasKey( 'Authorization', $headers, 'Basic Auth header should be included.' ); + $this->assertSame( $expected_auth, $headers['Authorization'], 'Basic Auth header should match.' ); + } + } + + /** + * Tests that a PHP file of a network-active plugin triggers loopback checks on multisite. + * + * @ticket 65819 + * @group ms-required + */ + public function test_should_trigger_loopback_for_network_active_plugin() { + update_site_option( 'active_sitewide_plugins', array( $this->get_plugin() => time() ) ); + $this->scrape_results = array( 'true', 'true' ); + + $this->assertTrue( wp_edit_theme_plugin_file( $this->get_request( self::SLUG . '.php', self::EDITED_PHP ) ), 'The file should be saved.' ); + $this->assertSame( self::EDITED_PHP, $this->get_contents( self::SLUG . '.php' ), 'The new content should be written.' ); + $this->assertSame( + array( + wp_parse_url( admin_url( 'plugin-editor.php' ), PHP_URL_PATH ), + wp_parse_url( home_url( '/' ), PHP_URL_PATH ), + ), + $this->get_loopback_paths(), + 'The editor and the home page should be checked.' + ); + $this->assert_scrape_key_deleted(); + } + + /** + * Tests that a PHP file edit of an active plugin is reverted when a loopback check fails. + * + * @ticket 65819 + * + * @dataProvider data_failed_loopbacks + * + * @param array $scrape_results The scrape results of the loopback requests. + * @param string $message The expected error message. + * @param array $data The expected error data. + * @param string[] $paths The expected paths of the loopback requests. + */ + public function test_should_revert_php_file_of_active_plugin_when_loopback_fails( $scrape_results, $message, $data, $paths ) { + update_option( 'active_plugins', array( $this->get_plugin() ) ); + $original = $this->get_contents( self::SLUG . '.php' ); + $this->scrape_results = $scrape_results; + + $result = wp_edit_theme_plugin_file( $this->get_request( self::SLUG . '.php', self::EDITED_PHP ) ); + + $this->assertWPError( $result, 'An error should be returned.' ); + $this->assertSame( 'php_error', $result->get_error_code(), 'The error code should match.' ); + $this->assertSame( $message, $result->get_error_message(), 'The error message should match.' ); + $this->assertSame( $data, $result->get_error_data(), 'The error data should match.' ); + $this->assertSame( $original, $this->get_contents( self::SLUG . '.php' ), 'The previous content should be restored.' ); + $this->assertSame( $paths, $this->get_loopback_paths(), 'The loopback requests should match.' ); + $this->assert_scrape_key_deleted(); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_failed_loopbacks() { + $loopback_failed = 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.'; + $editor_path = wp_parse_url( admin_url( 'plugin-editor.php' ), PHP_URL_PATH ); + $home_path = wp_parse_url( home_url( '/' ), PHP_URL_PATH ); + + return array( + 'editor request fails' => array( + array( null ), + $loopback_failed, + array( 'code' => 'loopback_request_failed' ), + array( $editor_path ), + ), + 'editor reports an error' => array( + array( '{"code":"E_ERROR","message":"Fatal error.","line":5}' ), + 'Fatal error.', + array( + 'code' => 'E_ERROR', + 'line' => 5, + ), + array( $editor_path ), + ), + 'editor returns no JSON' => array( + array( 'not JSON' ), + 'An error occurred. Please try again later.', + array( 'code' => 'json_parse_error' ), + array( $editor_path ), + ), + 'home page returns no JSON' => array( + array( 'true', 'not JSON' ), + 'An error occurred. Please try again later.', + array( 'code' => 'json_parse_error' ), + array( $editor_path, $home_path ), + ), + 'home page request fails' => array( + array( 'true', null ), + $loopback_failed, + array( 'code' => 'loopback_request_failed' ), + array( $editor_path, $home_path ), + ), + 'home page reports an error' => array( + array( 'true', '{"code":"E_PARSE","message":"Parse error."}' ), + 'Parse error.', + array( 'code' => 'E_PARSE' ), + array( $editor_path, $home_path ), + ), + ); + } + + /** + * Records loopback requests and answers them with the next scrape result. + * + * @param false|array $response A preemptive response. + * @param array $args The request arguments. + * @param string $url The request URL. + * @return false|array The response. + */ + public function record_loopback( $response, $args, $url ) { + if ( ! str_contains( $url, 'wp_scrape_key' ) ) { + return $response; + } + + $this->loopback_requests[] = $url; + + wp_parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query ); + $this->assertArrayHasKey( 'wp_scrape_key', $query, 'The loopback should include the scrape key.' ); + $this->assertArrayHasKey( 'wp_scrape_nonce', $query, 'The loopback should include the scrape nonce.' ); + + $editor_path = wp_parse_url( admin_url( 'plugin-editor.php' ), PHP_URL_PATH ); + if ( wp_parse_url( $url, PHP_URL_PATH ) === $editor_path ) { + $this->assertArrayHasKey( 'plugin', $query, 'The editor loopback should include the plugin query arg.' ); + $this->assertSame( $this->get_plugin(), $query['plugin'], 'The editor loopback should specify the edited plugin.' ); + $this->assertArrayHasKey( 'file', $query, 'The editor loopback should include the file query arg.' ); + $this->assertSame( self::SLUG . '/' . self::SLUG . '.php', $query['file'], 'The editor loopback should specify the edited file.' ); + } + + $key = $query['wp_scrape_key']; + $this->assertSame( $query['wp_scrape_nonce'], get_transient( 'scrape_key_' . $key ), 'The scrape nonce should match its live transient.' ); + + $scrape_result = array_shift( $this->scrape_results ); + if ( null === $scrape_result ) { + return new WP_Error( 'loopback_blocked', 'Loopback requests are not made in tests.' ); + } + + return array( + 'headers' => array(), + 'body' => "\n###### wp_scraping_result_start:{$key} ######\n{$scrape_result}\n###### wp_scraping_result_end:{$key} ######\n", + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'cookies' => array(), + 'filename' => null, + ); + } + + /** + * Returns the scrape key of a loopback request. + * + * @param string $url The request URL. + * @return string The scrape key. + */ + private function get_scrape_key( $url ) { + wp_parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query ); + + return $query['wp_scrape_key'] ?? ''; + } + + /** + * Returns the paths of the loopback requests. + * + * @return string[] The paths. + */ + private function get_loopback_paths() { + return array_map( + static function ( $url ) { + return wp_parse_url( $url, PHP_URL_PATH ); + }, + $this->loopback_requests + ); + } + + /** + * Asserts that the scrape key transient of the loopback requests was deleted. + */ + private function assert_scrape_key_deleted() { + $this->assertNotEmpty( $this->loopback_requests, 'A loopback request should be made.' ); + $this->assertFalse( get_transient( 'scrape_key_' . $this->get_scrape_key( $this->loopback_requests[0] ) ), 'The scrape key should be deleted.' ); + } + + /** + * Returns a valid request to edit a file of the test plugin. + * + * @param string $file The file, relative to the plugin directory. + * @param string $content The new content. + * @return array The request. + */ + private function get_request( $file, $content = 'New content.' ) { + $path = self::SLUG . '/' . $file; + + return array( + 'plugin' => $this->get_plugin(), + 'file' => $path, + 'newcontent' => $content, + 'nonce' => wp_create_nonce( 'edit-plugin_' . $path ), + ); + } + + /** + * Returns the plugin file of the test plugin. + * + * @return string The plugin file. + */ + private function get_plugin() { + return self::SLUG . '/' . self::SLUG . '.php'; + } + + /** + * Returns the contents of a file of the test plugin. + * + * @param string $file The file, relative to the plugin directory. + * @return string The contents. + */ + private function get_contents( $file ) { + return file_get_contents( WP_PLUGIN_DIR . '/' . self::SLUG . '/' . $file ); + } + + /** + * Removes the test plugin and clears the plugins cache. + */ + private function remove_plugin() { + foreach ( array( self::SLUG, self::OTHER_SLUG ) as $slug ) { + $dir = WP_PLUGIN_DIR . '/' . $slug; + + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } + + wp_cache_delete( 'plugins', 'plugins' ); + } +} From 3ed60aa67e0c7920c4e50642dfa4ab82c5fd7d4c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 00:07:49 +0000 Subject: [PATCH 108/481] Tests: Guard query freshness during metadata insertion. Verify that post and comment metadata observers see newly added metadata, and that comment queries remain fresh after insertion. Preserve an intentionally removed comment-cache invalidation callback. Developed in: https://github.com/WordPress/wordpress-develop/pull/14553 Props shanerounce, huzaifaalmesbah. See #65485. git-svn-id: https://develop.svn.wordpress.org/trunk@65114 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/comment.php | 95 +++++++++++++++++++++++ tests/phpunit/tests/post/wpInsertPost.php | 45 +++++++++++ 2 files changed, 140 insertions(+) diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index 51c1d5180d7fc..c5c40b9b34da6 100644 --- a/tests/phpunit/tests/comment.php +++ b/tests/phpunit/tests/comment.php @@ -2559,4 +2559,99 @@ public function test_get_comment_should_only_treat_numeric_values_as_comment_ids $this->assertNull( get_comment( $comment_id . 'abc' ), 'Expected a malformed numeric string not to be cast to a comment ID.' ); $this->assertNull( get_comment( true ), 'Expected true not to be cast to comment ID 1.' ); // @phpstan-ignore argument.type (Intentionally passing an invalid value.) } + + /** + * Queries made by metadata observers must see the newly added metadata. + * + * @ticket 65485 + * @group cache + * @covers ::wp_insert_comment + */ + public function test_meta_query_is_fresh_inside_added_comment_meta_action() { + $result = $this->insert_comment_with_query_observer(); + + $this->assertSame( array(), $result['before'] ); + $this->assertSameSets( array( $result['id'] ), $result['during'] ); + } + + /** + * A query primed partway through insertion must be fresh after insertion. + * + * @ticket 65485 + * @group cache + * @covers ::wp_insert_comment + */ + public function test_meta_query_is_fresh_after_comment_insertion() { + $result = $this->insert_comment_with_query_observer(); + + $this->assertSame( array(), $result['before'] ); + $this->assertSameSets( array( $result['id'] ), $result['after'] ); + } + + /** + * Inserts a comment while observing a query affected by its second meta key. + * + * @return array Recorded query results and the inserted comment ID. + */ + private function insert_comment_with_query_observer() { + $post_id = self::factory()->post->create(); + $args = array( + 'post_id' => $post_id, + 'fields' => 'ids', + 'meta_key' => 'target_meta_key', + 'meta_value' => 'present', + ); + $result = array(); + + // Prime a query before its matching metadata is added, then repeat it afterwards. + $observer = static function ( $meta_id, $comment_id, $meta_key ) use ( $args, &$result ) { + if ( 'first_meta_key' === $meta_key ) { + $result['before'] = get_comments( $args ); + } + if ( 'target_meta_key' === $meta_key ) { + $result['during'] = get_comments( $args ); + } + }; + + add_action( 'added_comment_meta', $observer, 20, 3 ); + try { + $result['id'] = wp_insert_comment( + array( + 'comment_post_ID' => $post_id, + 'comment_content' => 'Cache observer fixture', + 'comment_meta' => array( + 'first_meta_key' => 'present', + 'target_meta_key' => 'present', + ), + ) + ); + $result['after'] = get_comments( $args ); + } finally { + remove_action( 'added_comment_meta', $observer, 20 ); + } + + return $result; + } + + /** + * An intentionally absent invalidation callback must remain absent. + * + * @ticket 65485 + * @group cache + * @covers ::wp_insert_comment + */ + public function test_meta_query_invalidation_preserves_absent_callback() { + remove_action( 'added_comment_meta', 'wp_cache_set_comments_last_changed' ); + try { + wp_insert_comment( + array( + 'comment_content' => 'Callback preservation fixture', + 'comment_meta' => array( 'target_meta_key' => 'present' ), + ) + ); + $this->assertFalse( has_action( 'added_comment_meta', 'wp_cache_set_comments_last_changed' ) ); + } finally { + add_action( 'added_comment_meta', 'wp_cache_set_comments_last_changed' ); + } + } } diff --git a/tests/phpunit/tests/post/wpInsertPost.php b/tests/phpunit/tests/post/wpInsertPost.php index 76213efad3213..389ec6b8aae21 100644 --- a/tests/phpunit/tests/post/wpInsertPost.php +++ b/tests/phpunit/tests/post/wpInsertPost.php @@ -1548,4 +1548,49 @@ public function test_scheduled_post_with_a_past_date_should_be_published() { $this->assertSame( 'future', get_post_status( $post_id ) ); } + + /** + * Post metadata observers must see the newly added metadata. + * + * @ticket 65485 + * @group cache + * @covers ::wp_insert_post + */ + public function test_meta_query_is_fresh_inside_added_post_meta_action() { + $args = array( + 'fields' => 'ids', + 'posts_per_page' => -1, + 'meta_key' => 'target_meta_key', + 'meta_value' => 'present', + ); + $results = array(); + + // Prime a query before its matching metadata is added, then repeat it afterwards. + $observer = static function ( $meta_id, $post_id, $meta_key ) use ( $args, &$results ) { + if ( 'first_meta_key' === $meta_key ) { + $results['before'] = get_posts( $args ); + } + if ( 'target_meta_key' === $meta_key ) { + $results['during'] = get_posts( $args ); + } + }; + + add_action( 'added_post_meta', $observer, 20, 3 ); + try { + $post_id = wp_insert_post( + array( + 'post_title' => 'Cache observer fixture', + 'post_status' => 'publish', + 'meta_input' => array( + 'first_meta_key' => 'present', + 'target_meta_key' => 'present', + ), + ) + ); + $this->assertSame( array(), $results['before'] ); + $this->assertSameSets( array( $post_id ), $results['during'] ); + } finally { + remove_action( 'added_post_meta', $observer, 20 ); + } + } } From 518fcad26afd87e5422ddda0d95b6af15bea8057 Mon Sep 17 00:00:00 2001 From: John James Jacoby Date: Sat, 31 Oct 2026 03:38:40 +0000 Subject: [PATCH 109/481] Security: Harden the random aspect of the hash used for network admin email changes. Replace `mt_rand()` with `wp_rand()` when generating the network admin email confirmation hash, matching the site admin and user profile email change hashes. Developed in: https://github.com/WordPress/wordpress-develop/pull/15267 Props extremsx. Fixes #66426. git-svn-id: https://develop.svn.wordpress.org/trunk@65115 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/ms-functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/ms-functions.php b/src/wp-includes/ms-functions.php index b5097bca8ae0d..17e7041b883cf 100644 --- a/src/wp-includes/ms-functions.php +++ b/src/wp-includes/ms-functions.php @@ -2806,7 +2806,7 @@ function update_network_option_new_admin_email( $old_value, $value ) { return; } - $hash = md5( $value . time() . mt_rand() ); + $hash = md5( $value . time() . wp_rand() ); $new_admin_email = array( 'hash' => $hash, 'newemail' => $value, From cd46a70b2e41b016f40c1270c3d8f5999470e81c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:31:22 +0000 Subject: [PATCH 110/481] Tests: Use an unsupported image format for upload failures. Use a TGA fixture so the unsupported-format assertions remain meaningful when AVIF support is available. Developed in: https://github.com/WordPress/wordpress-develop/pull/10057 Props jigneshnakrani. See #64225, #63167. git-svn-id: https://develop.svn.wordpress.org/trunk@65116 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/rest-attachments-controller.php | 76 ++++++++++++++----- 1 file changed, 55 insertions(+), 21 deletions(-) diff --git a/tests/phpunit/tests/rest-api/rest-attachments-controller.php b/tests/phpunit/tests/rest-api/rest-attachments-controller.php index 2b79e679b6afb..a8499a34ed274 100644 --- a/tests/phpunit/tests/rest-api/rest-attachments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-attachments-controller.php @@ -32,6 +32,11 @@ class WP_Test_REST_Attachments_Controller extends WP_Test_REST_Post_Type_Control */ private static string $test_avif_file; + /** + * @var string The path to the TGA test image. + */ + private static string $test_tga_file; + /** * @var string The path to the SVG test image. */ @@ -101,6 +106,9 @@ public static function wpTearDownAfterClass() { if ( file_exists( self::$test_avif_file ) ) { unlink( self::$test_avif_file ); } + if ( file_exists( self::$test_tga_file ) ) { + unlink( self::$test_tga_file ); + } if ( file_exists( self::$test_video_file ) ) { unlink( self::$test_video_file ); } @@ -153,6 +161,12 @@ static function () { copy( $orig_avif_file, self::$test_avif_file ); } + $orig_tga_file = DIR_TESTDATA . '/images/test-image.tga'; + self::$test_tga_file = get_temp_dir() . 'test-image.tga'; + if ( ! file_exists( self::$test_tga_file ) ) { + copy( $orig_tga_file, self::$test_tga_file ); + } + $test_svg_file = DIR_TESTDATA . '/uploads/video-play.svg'; self::$test_svg_file = get_temp_dir() . 'video-play.svg'; if ( ! file_exists( self::$test_svg_file ) ) { @@ -3502,46 +3516,66 @@ static function () { /** * Test that uploading unsupported image types throws a `rest_upload_image_type_not_supported` error. * + * Uses TGA because it is reliably unsupported by the image editors, unlike AVIF which + * is commonly supported in CI. File params are required because the permission check + * reads `get_file_params()`. + * * @ticket 61167 + * @ticket 64225 */ public function test_upload_unsupported_image_type() { - - // Only run this test when the editor doesn't support AVIF. - if ( wp_image_editor_supports( array( 'AVIF' ) ) ) { - $this->markTestSkipped( 'The image editor suppports AVIF.' ); + // Only run this test when the editor doesn't support TGA. + if ( wp_image_editor_supports( array( 'mime_type' => 'image/tga' ) ) ) { + $this->markTestSkipped( 'The image editor supports TGA.' ); } - $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); - wp_set_current_user( self::$author_id ); - $request->set_header( 'Content-Type', 'image/avif' ); - $request->set_header( 'Content-Disposition', 'attachment; filename=avif-lossy.avif' ); - $request->set_body( file_get_contents( self::$test_avif_file ) ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_file_params( + array( + 'file' => array( + 'name' => 'test-image.tga', + 'type' => 'image/tga', + 'tmp_name' => self::$test_tga_file, + 'error' => 0, + 'size' => filesize( self::$test_tga_file ), + ), + ) + ); $response = rest_get_server()->dispatch( $request ); $this->assertErrorResponse( 'rest_upload_image_type_not_supported', $response, 400 ); } /** - * Test that the `wp_prevent_unsupported_image_uploads` filter enables uploading of unsupported image types. + * Test that the `wp_prevent_unsupported_mime_type_uploads` filter enables uploading of unsupported image types. + * + * Forces the image editors list empty so the format is treated as unsupported regardless + * of host capabilities, then uses an allowed upload mime (AVIF) so the request can still + * complete with a successful 201 once the filter bypasses the editor-support check. * * @ticket 61167 + * @ticket 64225 */ public function test_upload_unsupported_image_type_with_filter() { + add_filter( 'wp_image_editors', '__return_empty_array' ); + add_filter( 'wp_prevent_unsupported_mime_type_uploads', '__return_false' ); - // Only run this test when the editor doesn't support AVIF. - if ( wp_image_editor_supports( array( 'AVIF' ) ) ) { - $this->markTestSkipped( 'The image editor suppports AVIF.' ); - } - - add_filter( 'wp_prevent_unsupported_image_uploads', '__return_false' ); + wp_set_current_user( self::$author_id ); $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); - - wp_set_current_user( self::$author_id ); - $request->set_header( 'Content-Type', 'image/avif' ); - $request->set_header( 'Content-Disposition', 'attachment; filename=avif-lossy.avif' ); - $request->set_body( file_get_contents( self::$test_avif_file ) ); + $request->set_file_params( + array( + 'file' => array( + 'name' => 'avif-lossy.avif', + 'type' => 'image/avif', + 'tmp_name' => self::$test_avif_file, + 'error' => 0, + 'size' => filesize( self::$test_avif_file ), + ), + ) + ); $response = rest_get_server()->dispatch( $request ); $this->assertSame( 201, $response->get_status() ); From 3e1acb201154f1f457ca66e60bf8d46a363d5086 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:32:47 +0000 Subject: [PATCH 111/481] Tests: Cover term slugs with duplicate names. Verify slug generation for terms with duplicate names in different parent hierarchies. Developed in: https://github.com/WordPress/wordpress-develop/pull/12544 Props sainathpoojary. See #31270. git-svn-id: https://develop.svn.wordpress.org/trunk@65117 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/term/wpInsertTerm.php | 71 +++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/tests/phpunit/tests/term/wpInsertTerm.php b/tests/phpunit/tests/term/wpInsertTerm.php index a1f301f6986fb..475619703a4f6 100644 --- a/tests/phpunit/tests/term/wpInsertTerm.php +++ b/tests/phpunit/tests/term/wpInsertTerm.php @@ -917,6 +917,77 @@ public function test_wp_insert_term_with_empty_name_after_db_sanitization() { $this->assertSame( 'invalid_term_name', $term->get_error_code() ); } + /** + * @ticket 31270 + */ + public function test_wp_insert_term_root_level_term_with_same_name_as_child_should_get_clean_slug() { + register_taxonomy( 'wptests_tax', 'post', array( 'hierarchical' => true ) ); + + $t1 = self::factory()->term->create( + array( + 'name' => 'Foo', + 'taxonomy' => 'wptests_tax', + ) + ); + + self::factory()->term->create( + array( + 'name' => 'Bar', + 'slug' => 'foo-bar', + 'parent' => $t1, + 'taxonomy' => 'wptests_tax', + ) + ); + + $t3 = wp_insert_term( 'Bar', 'wptests_tax' ); + + $this->assertNotWPError( $t3 ); + $t3_term = get_term( $t3['term_id'], 'wptests_tax' ); + $this->assertSame( 'bar', $t3_term->slug ); + } + + /** + * @ticket 31270 + */ + public function test_wp_insert_term_child_term_with_same_name_as_another_child_under_different_parent_should_get_clean_slug() { + register_taxonomy( 'wptests_tax', 'post', array( 'hierarchical' => true ) ); + + $t1 = self::factory()->term->create( + array( + 'name' => 'Parent One', + 'taxonomy' => 'wptests_tax', + ) + ); + + $t2 = self::factory()->term->create( + array( + 'name' => 'Parent Two', + 'taxonomy' => 'wptests_tax', + ) + ); + + self::factory()->term->create( + array( + 'name' => 'Child', + 'slug' => 'parent-one-child', + 'parent' => $t1, + 'taxonomy' => 'wptests_tax', + ) + ); + + $t4 = wp_insert_term( + 'Child', + 'wptests_tax', + array( + 'parent' => $t2, + ) + ); + + $this->assertNotWPError( $t4 ); + $t4_term = get_term( $t4['term_id'], 'wptests_tax' ); + $this->assertSame( 'child', $t4_term->slug ); + } + /** * Non-ASCII slugs are stored percent-encoded, so a short term name can still * overflow the 200 character `slug` column once a parent slug is appended. From 78f43b1c0480b44cb131c76927764f903c0269e9 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:34:13 +0000 Subject: [PATCH 112/481] Tests: Cover plugin list-table action links. Verify the site and network plugin action links and their filters in `WP_Plugins_List_Table::single_row()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/14598, https://github.com/WordPress/wordpress-develop/pull/14602 Props huzaifaalmesbah, mukesh27. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65118 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/wpPluginsListTableActionLinks.php | 551 ++++++++++++++++++ .../wpPluginsListTableNetworkActionLinks.php | 512 ++++++++++++++++ 2 files changed, 1063 insertions(+) create mode 100644 tests/phpunit/tests/admin/wpPluginsListTableActionLinks.php create mode 100644 tests/phpunit/tests/admin/wpPluginsListTableNetworkActionLinks.php diff --git a/tests/phpunit/tests/admin/wpPluginsListTableActionLinks.php b/tests/phpunit/tests/admin/wpPluginsListTableActionLinks.php new file mode 100644 index 0000000000000..644c321388cae --- /dev/null +++ b/tests/phpunit/tests/admin/wpPluginsListTableActionLinks.php @@ -0,0 +1,551 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + + if ( is_multisite() ) { + grant_super_admin( self::$admin_id ); + } + } + + /** + * Revokes the super admin grant before the fixture users are deleted. + */ + public static function wpTearDownAfterClass() { + if ( is_multisite() ) { + revoke_super_admin( self::$admin_id ); + } + } + + /** + * Sets up the Plugins screen, the list table globals and the dependency state. + */ + public function set_up() { + parent::set_up(); + + $this->original_globals = array(); + foreach ( array( 's', 'totals', '_paused_plugins' ) as $name ) { + if ( array_key_exists( $name, $GLOBALS ) ) { + $this->original_globals[ $name ] = $GLOBALS[ $name ]; + } + } + + $this->original_request = array( + 'plugin_status' => $_REQUEST['plugin_status'] ?? null, + 'paged' => $_REQUEST['paged'] ?? null, + ); + + set_current_screen( 'plugins' ); + + $_REQUEST['plugin_status'] = 'all'; + $_REQUEST['paged'] = 1; + + $GLOBALS['s'] = ''; + $GLOBALS['totals'] = array(); + $GLOBALS['_paused_plugins'] = array(); + + $this->set_property_value( 'plugins', array() ); + $this->set_property_value( 'dependencies', array() ); + $this->set_property_value( 'dependency_slugs', array() ); + $this->set_property_value( 'dependency_filepaths', array() ); + $this->set_property_value( 'circular_dependencies_slugs', array() ); + $this->set_property_value( 'circular_dependencies_pairs', array() ); + $this->set_property_value( 'initialized', true ); + + update_option( 'active_plugins', array() ); + update_site_option( 'active_sitewide_plugins', array() ); + + $this->actions = null; + $this->row_output = ''; + $this->slug = 'action-links-plugin-' . wp_generate_password( 8, false ); + + add_filter( 'plugin_action_links', array( $this, 'capture_actions' ), PHP_INT_MAX ); + + wp_set_current_user( self::$admin_id ); + } + + /** + * Restores the globals and removes the test plugin. + */ + public function tear_down() { + foreach ( $this->original_globals as $name => $value ) { + $GLOBALS[ $name ] = $value; + } + + foreach ( array( 's', 'totals', '_paused_plugins' ) as $name ) { + if ( ! array_key_exists( $name, $this->original_globals ) ) { + unset( $GLOBALS[ $name ] ); + } + } + + foreach ( $this->original_request as $key => $value ) { + if ( null !== $value ) { + $_REQUEST[ $key ] = $value; + } else { + unset( $_REQUEST[ $key ] ); + } + } + + $this->remove_plugin(); + + parent::tear_down(); + } + + /** + * Tests the Deactivate link of an active plugin. + * + * @ticket 65819 + */ + public function test_should_link_deactivate_for_active_plugin() { + $this->activate(); + + $this->assertSame( + array( + 'deactivate' => 'Deactivate', + ), + $this->get_actions() + ); + } + + /** + * Tests that an active plugin that other active plugins require cannot be deactivated. + * + * @ticket 65819 + */ + public function test_should_not_link_deactivate_for_plugin_with_active_dependents() { + $this->set_dependent( true ); + $this->activate(); + + $this->assertSame( + array( + 'deactivate' => 'DeactivateYou cannot deactivate this plugin as other plugins depend on it.', + ), + $this->get_actions() + ); + } + + /** + * Tests the Resume link of an active plugin that was paused. + * + * @ticket 65819 + */ + public function test_should_link_resume_for_paused_plugin() { + $this->activate(); + $this->pause(); + + $this->assertSame( + array( + 'deactivate' => 'Deactivate', + 'resume' => 'Resume', + ), + $this->get_actions() + ); + } + + /** + * Tests the Activate and Delete links of an inactive plugin. + * + * @ticket 65819 + */ + public function test_should_link_activate_and_delete_for_inactive_plugin() { + $expected_actions = array( + 'activate' => 'Activate', + ); + + if ( ! is_multisite() ) { + $expected_actions['delete'] = $this->get_delete_link(); + } + + $this->assertSame( $expected_actions, $this->get_actions() ); + } + + /** + * Tests that a plugin whose requirements are not met cannot be activated. + * + * @ticket 65819 + * + * @dataProvider data_unmet_requirements + * + * @param array $plugin_data The plugin's requirement headers. + */ + public function test_should_not_activate_plugin_with_unmet_requirements( $plugin_data ) { + $this->assertSame( 'Cannot Activate', $this->get_actions( $plugin_data )['activate'] ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_unmet_requirements() { + return array( + 'PHP version' => array( array( 'RequiresPHP' => '99.0' ) ), + 'WordPress version' => array( array( 'RequiresWP' => '99.0' ) ), + ); + } + + /** + * Tests that a plugin with unmet dependencies cannot be activated. + * + * @ticket 65819 + */ + public function test_should_not_activate_plugin_with_unmet_dependencies() { + $this->set_property_value( 'dependencies', array( $this->get_file() => array( 'missing' ) ) ); + $this->set_property_value( 'dependency_filepaths', array( 'missing' => false ) ); + + $this->assertSame( + 'ActivateYou cannot activate this plugin as it has unmet requirements.', + $this->get_actions()['activate'] + ); + } + + /** + * Tests that a plugin that other plugins require cannot be deleted, unless the dependency is circular. + * + * @ticket 65819 + * + * @group ms-excluded + * + * @dataProvider data_circular_dependencies + * + * @param bool $circular Whether the dependency is circular. + */ + public function test_delete_link_for_plugin_with_dependents( $circular ) { + $this->set_dependent( false ); + + if ( $circular ) { + $this->set_property_value( 'circular_dependencies_slugs', array( $this->slug ) ); + } + + $this->assertSame( + $circular + ? $this->get_delete_link() + : 'DeleteYou cannot delete this plugin as other plugins require it.', + $this->get_actions()['delete'] + ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_circular_dependencies() { + return array( + 'regular dependency' => array( false ), + 'circular dependency' => array( true ), + ); + } + + /** + * Tests that a user who cannot manage plugins gets no action links. + * + * @ticket 65819 + * + * @dataProvider data_active_states + * + * @param bool $active Whether the plugin is active. + */ + public function test_should_not_add_links_for_user_without_capabilities( $active ) { + wp_set_current_user( self::$subscriber_id ); + + if ( $active ) { + $this->activate(); + $this->pause(); + } + + $this->assertSame( array(), $this->get_actions() ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_active_states() { + return array( + 'active plugin' => array( true ), + 'inactive plugin' => array( false ), + ); + } + + /** + * Tests that a network-active plugin only shows that it is network active on a site. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_only_show_network_active_on_site_screen() { + update_site_option( 'active_sitewide_plugins', array( $this->get_file() => time() ) ); + + $this->assertSame( array( 'network_active' => 'Network Active' ), $this->get_actions() ); + } + + /** + * Tests that an inactive network-only plugin shows "Network Only" on a site's Plugins screen. + * + * @ticket 65819 + * + * @group ms-required + */ + public function test_should_show_network_only_for_inactive_network_only_plugin() { + $this->assertSame( + array( 'network_only' => 'Network Only' ), + $this->get_actions( array(), " * Network: true\n" ) + ); + } + + /** + * Tests that the filter receives the plugin file, data and context. + * + * @ticket 65819 + */ + public function test_should_pass_plugin_and_context_to_filter() { + $filter = new MockAction(); + add_filter( 'plugin_action_links', array( $filter, 'filter' ), 10, 4 ); + + $distinctive_link = 'Distinctive Site Link'; + add_filter( + 'plugin_action_links', + static function ( $actions ) use ( $distinctive_link ) { + $actions['distinctive'] = $distinctive_link; + return $actions; + }, + 20 + ); + + $this->get_actions(); + + $args = $filter->get_args(); + + $this->assertSame( $this->get_file(), $args[0][1], 'The filter should receive the plugin file.' ); + $this->assertSame( 'My Plugin', $args[0][2]['Name'], 'The filter should receive the plugin data.' ); + $this->assertSame( 'all', $args[0][3], 'The filter should receive the context.' ); + + $this->assertStringContainsString( + $distinctive_link, + $this->row_output, + 'The rendered row should contain action links added by filters.' + ); + } + + /** + * Captures the actions passed to the plugin_action_links filter. + * + * @param array $actions The action links. + * @return array The unchanged action links. + */ + public function capture_actions( $actions ) { + $this->actions = $actions; + + return $actions; + } + + /** + * Renders the row of the test plugin and returns its action links. + * + * @param array $plugin_data The plugin data to add. + * @param string $headers Additional plugin headers for the file on multisite. + * @return array The action links. + */ + private function get_actions( $plugin_data = array(), $headers = '' ) { + // is_network_only_plugin() reads the plugin headers on multisite. + if ( is_multisite() ) { + if ( ! is_writable( WP_PLUGIN_DIR ) ) { + $this->markTestSkipped( 'WP_PLUGIN_DIR is not writable.' ); + } + + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + $this->remove_plugin(); + $this->assertTrue( mkdir( $dir ), 'The test plugin directory should be created.' ); + $this->assertNotFalse( + file_put_contents( + $dir . '/' . $this->slug . '.php', + " 'plugins' ) ); + + $this->row_output = get_echo( + array( $table, 'single_row' ), + array( + array( + $this->get_file(), + array_merge( + array( + 'Name' => 'My Plugin', + 'slug' => $this->slug, + 'Description' => '', + 'Version' => '1.0', + 'Author' => '', + 'AuthorURI' => '', + 'PluginURI' => '', + ), + $plugin_data + ), + ), + ) + ); + + return $this->actions; + } + + /** + * Returns the plugin file of the test plugin. + * + * @return string The plugin file. + */ + private function get_file() { + return "{$this->slug}/{$this->slug}.php"; + } + + /** + * Returns the expected URL of an action. + * + * @param string $action The action. + * @param string $nonce The nonce action. + * @return string The escaped URL. + */ + private function get_url( $action, $nonce ) { + return "plugins.php?action={$action}&plugin={$this->slug}%2F{$this->slug}.php&plugin_status=all&paged=1&s&_wpnonce=" . wp_create_nonce( $nonce ); + } + + /** + * Returns the expected Delete URL. + * + * @return string The escaped URL. + */ + private function get_delete_url() { + return "plugins.php?action=delete-selected&checked%5B0%5D={$this->slug}%2F{$this->slug}.php&plugin_status=all&paged=1&s&_wpnonce=" . wp_create_nonce( 'bulk-plugins' ); + } + + /** + * Returns the expected Delete link markup. + * + * @return string The Delete link markup. + */ + private function get_delete_link() { + return 'Delete'; + } + + /** + * Activates the test plugin. + */ + private function activate() { + update_option( 'active_plugins', array_merge( get_option( 'active_plugins' ), array( $this->get_file() ) ) ); + } + + /** + * Pauses the test plugin. + */ + private function pause() { + $GLOBALS['_paused_plugins'] = array( + $this->slug => array( + 'type' => E_ERROR, + 'line' => 1, + 'file' => WP_PLUGIN_DIR . '/' . $this->get_file(), + 'message' => 'Error.', + ), + ); + } + + /** + * Makes another plugin require the test plugin. + * + * @param bool $active Whether the other plugin is active. + */ + private function set_dependent( $active ) { + $this->set_property_value( 'plugins', array( 'dependent/dependent.php' => array( 'Name' => 'Dependent' ) ) ); + $this->set_property_value( 'dependencies', array( 'dependent/dependent.php' => array( $this->slug ) ) ); + $this->set_property_value( 'dependency_slugs', array( $this->slug ) ); + + if ( $active ) { + update_option( 'active_plugins', array_merge( (array) get_option( 'active_plugins', array() ), array( 'dependent/dependent.php' ) ) ); + } + } + + /** + * Removes the test plugin, including one left over by an interrupted run. + */ + private function remove_plugin() { + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } +} diff --git a/tests/phpunit/tests/admin/wpPluginsListTableNetworkActionLinks.php b/tests/phpunit/tests/admin/wpPluginsListTableNetworkActionLinks.php new file mode 100644 index 0000000000000..fa1f1bc62907a --- /dev/null +++ b/tests/phpunit/tests/admin/wpPluginsListTableNetworkActionLinks.php @@ -0,0 +1,512 @@ +user->create(); + self::$admin_id = $factory->user->create( array( 'role' => 'administrator' ) ); + + grant_super_admin( self::$super_admin_id ); + } + + /** + * Revokes the super admin grant before the fixture users are deleted. + */ + public static function wpTearDownAfterClass() { + revoke_super_admin( self::$super_admin_id ); + } + + /** + * Sets up the network admin Plugins screen, the list table globals and the dependency state. + */ + public function set_up() { + parent::set_up(); + + $this->original_globals = array(); + foreach ( array( 'status', 'page', 's', 'totals' ) as $name ) { + if ( array_key_exists( $name, $GLOBALS ) ) { + $this->original_globals[ $name ] = $GLOBALS[ $name ]; + } + } + + set_current_screen( 'plugins-network' ); + + $GLOBALS['status'] = 'all'; + $GLOBALS['page'] = 1; + $GLOBALS['s'] = ''; + $GLOBALS['totals'] = array(); + + $this->set_property_value( 'plugins', array() ); + $this->set_property_value( 'dependencies', array() ); + $this->set_property_value( 'dependency_slugs', array() ); + $this->set_property_value( 'dependency_filepaths', array() ); + $this->set_property_value( 'circular_dependencies_slugs', array() ); + $this->set_property_value( 'circular_dependencies_pairs', array() ); + $this->set_property_value( 'initialized', true ); + + update_option( 'active_plugins', array() ); + update_site_option( 'active_sitewide_plugins', array() ); + + $this->actions = null; + $this->row_output = ''; + $this->slug = 'network-action-links-plugin-' . wp_generate_password( 8, false ); + + add_filter( 'network_admin_plugin_action_links', array( $this, 'capture_actions' ), PHP_INT_MAX ); + + wp_set_current_user( self::$super_admin_id ); + } + + /** + * Restores the globals and removes the test plugin. + */ + public function tear_down() { + foreach ( $this->original_globals as $name => $value ) { + $GLOBALS[ $name ] = $value; + } + + foreach ( array( 'status', 'page', 's', 'totals' ) as $name ) { + if ( ! array_key_exists( $name, $this->original_globals ) ) { + unset( $GLOBALS[ $name ] ); + } + } + + $this->remove_plugin(); + + parent::tear_down(); + } + + /** + * Tests the Network Deactivate link of a network-active plugin. + * + * @ticket 65819 + */ + public function test_should_link_network_deactivate_for_network_active_plugin() { + $this->network_activate(); + + $this->assertSame( + array( + 'deactivate' => 'Network Deactivate', + ), + $this->get_actions() + ); + } + + /** + * Tests that a network-active plugin that other active plugins require cannot be deactivated. + * + * @ticket 65819 + */ + public function test_should_not_link_network_deactivate_for_plugin_with_active_dependents() { + $this->set_dependent(); + $this->network_activate(); + + $this->assertSame( + array( + 'deactivate' => 'Network DeactivateYou cannot deactivate this plugin as other plugins require it.', + ), + $this->get_actions() + ); + } + + /** + * Tests that an inactive dependent does not block Network Deactivate. + * + * @ticket 65819 + */ + public function test_should_link_network_deactivate_when_dependent_is_inactive() { + $this->set_dependent( false ); + $this->network_activate(); + + $this->assertSame( + array( + 'deactivate' => 'Network Deactivate', + ), + $this->get_actions() + ); + } + + /** + * Tests the Network Activate and Delete links of a plugin that is not network active. + * + * @ticket 65819 + */ + public function test_should_link_network_activate_and_delete() { + $this->assertSame( + array( + 'activate' => 'Network Activate', + 'delete' => 'Delete', + ), + $this->get_actions() + ); + } + + /** + * Tests that a plugin that is active on the current site cannot be deleted. + * + * @ticket 65819 + */ + public function test_should_not_link_delete_for_plugin_active_on_site() { + update_option( 'active_plugins', array( $this->get_file() ) ); + + $this->assertSame( array( 'activate' ), array_keys( $this->get_actions() ) ); + } + + /** + * Tests that a plugin whose requirements are not met cannot be network activated. + * + * @ticket 65819 + * + * @dataProvider data_unmet_requirements + * + * @param array $plugin_data The plugin's requirement headers. + */ + public function test_should_not_network_activate_plugin_with_unmet_requirements( $plugin_data ) { + $this->assertSame( 'Cannot Activate', $this->get_actions( $plugin_data )['activate'] ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_unmet_requirements() { + return array( + 'PHP version' => array( array( 'RequiresPHP' => '99.0' ) ), + 'WordPress version' => array( array( 'RequiresWP' => '99.0' ) ), + ); + } + + /** + * Tests that a plugin with unmet dependencies cannot be network activated. + * + * @ticket 65819 + * + * @dataProvider data_unmet_dependencies + * + * @param string|false $filepath The filepath of the dependency. + */ + public function test_should_not_network_activate_plugin_with_unmet_dependencies( $filepath ) { + if ( false !== $filepath ) { + $this->set_property_value( 'plugins', array( $filepath => array( 'Name' => 'Dependency' ) ) ); + } + + $this->set_property_value( 'dependencies', array( $this->get_file() => array( 'dependency' ) ) ); + $this->set_property_value( 'dependency_filepaths', array( 'dependency' => $filepath ) ); + + $this->assertSame( + 'Network ActivateYou cannot activate this plugin as it has unmet requirements.', + $this->get_actions()['activate'] + ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_unmet_dependencies() { + return array( + 'missing dependency' => array( false ), + 'installed, inactive dependency' => array( 'dependency/dependency.php' ), + ); + } + + /** + * Tests that a plugin that other plugins require cannot be deleted, unless the dependency is circular. + * + * @ticket 65819 + * + * @dataProvider data_circular_dependencies + * + * @param bool $circular Whether the dependency is circular. + */ + public function test_delete_link_for_plugin_with_dependents( $circular ) { + $this->set_dependent( false ); + + if ( $circular ) { + $this->set_property_value( + 'dependencies', + array( + 'dependent/dependent.php' => array( $this->slug ), + $this->get_file() => array( 'dependent' ), + ) + ); + $this->set_property_value( 'circular_dependencies_slugs', array( $this->slug, 'dependent' ) ); + } + + $this->assertSame( + $circular + ? 'Delete' + : 'DeleteYou cannot delete this plugin as other plugins require it.', + $this->get_actions()['delete'] + ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_circular_dependencies() { + return array( + 'regular dependency' => array( false ), + 'circular dependency' => array( true ), + ); + } + + /** + * Tests that a site administrator gets no action links on the network screen. + * + * @ticket 65819 + * + * @dataProvider data_network_active_states + * + * @param bool $network_active Whether the plugin is network active. + */ + public function test_should_not_add_links_for_user_without_network_capabilities( $network_active ) { + wp_set_current_user( self::$admin_id ); + + if ( $network_active ) { + $this->network_activate(); + } + + $this->assertSame( array(), $this->get_actions() ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_network_active_states() { + return array( + 'network-active plugin' => array( true ), + 'inactive plugin' => array( false ), + ); + } + + /** + * Tests that only the network filters receive the links, with the plugin file, data and context. + * + * @ticket 65819 + */ + public function test_should_pass_plugin_and_context_to_network_filters() { + $network_filter = new MockAction(); + $file_filter = new MockAction(); + $site_filter = new MockAction(); + add_filter( 'network_admin_plugin_action_links', array( $network_filter, 'filter' ), 10, 4 ); + add_filter( "network_admin_plugin_action_links_{$this->get_file()}", array( $file_filter, 'filter' ), 10, 4 ); + add_filter( 'plugin_action_links', array( $site_filter, 'filter' ) ); + + $distinctive_link = 'Distinctive Network Link'; + add_filter( + "network_admin_plugin_action_links_{$this->get_file()}", + static function ( $actions ) use ( $distinctive_link ) { + $actions['distinctive'] = $distinctive_link; + return $actions; + }, + 20 + ); + + $this->get_actions(); + + $args = $network_filter->get_args(); + + $this->assertCount( 1, $args, 'The general network filter should run once.' ); + + $this->assertSame( $this->get_file(), $args[0][1], 'The filter should receive the plugin file.' ); + $this->assertSame( 'My Plugin', $args[0][2]['Name'], 'The filter should receive the plugin data.' ); + $this->assertSame( 'all', $args[0][3], 'The filter should receive the context.' ); + $this->assertSame( $args, $file_filter->get_args(), 'The plugin-specific filter should receive the same actions, plugin file, plugin data and context.' ); + $this->assertSame( 0, $site_filter->get_call_count(), 'The site filter should not run.' ); + + $this->assertStringContainsString( + $distinctive_link, + $this->row_output, + 'The rendered row should contain action links added by filters.' + ); + } + + /** + * Captures the actions passed to the network_admin_plugin_action_links filter. + * + * @param array $actions The action links. + * @return array The unchanged action links. + */ + public function capture_actions( $actions ) { + $this->actions = $actions; + + return $actions; + } + + /** + * Renders the row of the test plugin and returns its action links. + * + * @param array $plugin_data The plugin data to add. + * @return array The action links. + */ + private function get_actions( $plugin_data = array() ) { + if ( ! is_writable( WP_PLUGIN_DIR ) ) { + $this->markTestSkipped( 'WP_PLUGIN_DIR is not writable.' ); + } + + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + $this->remove_plugin(); + $this->assertTrue( mkdir( $dir ), 'The test plugin directory should be created.' ); + $this->assertNotFalse( file_put_contents( $dir . '/' . $this->slug . '.php', " 'plugins-network' ) ); + + $this->row_output = get_echo( + array( $table, 'single_row' ), + array( + array( + $this->get_file(), + array_merge( + array( + 'Name' => 'My Plugin', + 'slug' => $this->slug, + 'Description' => '', + 'Version' => '1.0', + 'Author' => '', + 'AuthorURI' => '', + 'PluginURI' => '', + ), + $plugin_data + ), + ), + ) + ); + + $this->assertIsArray( $this->actions, 'The action links filter should run.' ); + + return $this->actions; + } + + /** + * Returns the plugin file of the test plugin. + * + * @return string The plugin file. + */ + private function get_file() { + return "{$this->slug}/{$this->slug}.php"; + } + + /** + * Returns the expected URL of an action. + * + * @param string $action The action. + * @param string $nonce The nonce action. + * @return string The escaped URL. + */ + private function get_url( $action, $nonce ) { + return "plugins.php?action={$action}&plugin={$this->slug}%2F{$this->slug}.php&plugin_status=all&paged=1&s&_wpnonce=" . wp_create_nonce( $nonce ); + } + + /** + * Returns the expected Delete URL. + * + * @return string The escaped URL. + */ + private function get_delete_url() { + return "plugins.php?action=delete-selected&checked%5B0%5D={$this->slug}%2F{$this->slug}.php&plugin_status=all&paged=1&s&_wpnonce=" . wp_create_nonce( 'bulk-plugins' ); + } + + /** + * Activates the test plugin network-wide. + */ + private function network_activate() { + $active = get_site_option( 'active_sitewide_plugins', array() ); + $active[ $this->get_file() ] = time(); + update_site_option( 'active_sitewide_plugins', $active ); + } + + /** + * Sets a dependent plugin for the test plugin. + * + * @param bool $active Whether the dependent plugin should be network active. Default true. + */ + private function set_dependent( $active = true ) { + $this->set_property_value( 'plugins', array( 'dependent/dependent.php' => array( 'Name' => 'Dependent' ) ) ); + $this->set_property_value( 'dependencies', array( 'dependent/dependent.php' => array( $this->slug ) ) ); + $this->set_property_value( 'dependency_slugs', array( $this->slug ) ); + + if ( $active ) { + $active_plugins = get_site_option( 'active_sitewide_plugins', array() ); + $active_plugins['dependent/dependent.php'] = time(); + update_site_option( 'active_sitewide_plugins', $active_plugins ); + } + } + + /** + * Removes the test plugin, including one left over by an interrupted run. + */ + private function remove_plugin() { + $dir = WP_PLUGIN_DIR . '/' . $this->slug; + + if ( is_dir( $dir ) ) { + $this->rmdir( $dir ); + $this->delete_folders( $dir ); + } + } +} From 18911b8abbdf30c36486c1794e2a2dbfa16abf9c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:37:17 +0000 Subject: [PATCH 113/481] Tests: Cover admin configuration helpers. Add coverage for IIS rewrite rules, plugin file trees, and admin color-scheme settings. Developed in: https://github.com/WordPress/wordpress-develop/pull/11720, https://github.com/WordPress/wordpress-develop/pull/11724, https://github.com/WordPress/wordpress-develop/pull/11741 Props pbearne. See #65172, #65176, #65185. git-svn-id: https://develop.svn.wordpress.org/trunk@65119 602fd350-edb4-49c9-b593-d223f7449a82 --- .../includes/misc/iis7AddRewriteRule.php | 134 ++++++++++++++++++ .../includes/misc/wpColorSchemeSettings.php | 128 +++++++++++++++++ .../includes/misc/wpMakePluginFileTree.php | 89 ++++++++++++ 3 files changed, 351 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php create mode 100644 tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php create mode 100644 tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php diff --git a/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php b/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php new file mode 100644 index 0000000000000..52b4f7c61fd57 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php @@ -0,0 +1,134 @@ +temp_file = wp_tempnam( 'web.config' ); + } + + /** + * Clean up the test environment. + */ + public function tear_down() { + if ( file_exists( $this->temp_file ) ) { + unlink( $this->temp_file ); + } + parent::tear_down(); + } + + /** + * Tests that iis7_add_rewrite_rule() correctly adds WordPress rules. + * + * @ticket 65172 + * + * @dataProvider data_iis7_add_rewrite_rule + * + * @param string $initial_content The initial XML content of the file. + * @param string $rewrite_rule The rule to add. + * @param string $expected_content The expected XML content after adding. + */ + public function test_iis7_add_rewrite_rule( $initial_content, $rewrite_rule, $expected_content ) { + if ( null !== $initial_content ) { + file_put_contents( $this->temp_file, $initial_content ); + } else { + if ( file_exists( $this->temp_file ) ) { + unlink( $this->temp_file ); + } + } + + $result = iis7_add_rewrite_rule( $this->temp_file, $rewrite_rule ); + + $this->assertTrue( $result, 'iis7_add_rewrite_rule() should return true on success.' ); + $this->assertXmlStringEqualsXmlFile( $this->temp_file, $expected_content, 'The XML content should match the expected output.' ); + } + + /** + * Data provider for test_iis7_add_rewrite_rule. + * + * @return array + */ + public function data_iis7_add_rewrite_rule(): array { + $rule = ''; + + return array( + 'File does not exist' => array( + 'initial_content' => null, + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Empty configuration' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Existing system.webServer' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Existing rewrite' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Existing rules' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Existing other rule' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '' . $rule . '', + ), + 'Rule already exists (lowercase)' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '', + ), + 'Rule already exists (CamelCase)' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '', + ), + 'Rule with same prefix already exists' => array( + 'initial_content' => '', + 'rewrite_rule' => $rule, + 'expected_content' => '', + ), + ); + } + + /** + * Tests that iis7_add_rewrite_rule() returns false for invalid XML. + * + * @ticket 65172 + */ + public function test_iis7_add_rewrite_rule_invalid_xml() { + file_put_contents( $this->temp_file, 'Not XML' ); + $rule = ''; + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + $this->assertFalse( @iis7_add_rewrite_rule( $this->temp_file, $rule ), 'Should return false for invalid XML.' ); + } +} diff --git a/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php b/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php new file mode 100644 index 0000000000000..dd1969d620b31 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php @@ -0,0 +1,128 @@ +orig_wp_admin_css_colors = $_wp_admin_css_colors; + } + + public function tear_down() { + global $_wp_admin_css_colors; + $_wp_admin_css_colors = $this->orig_wp_admin_css_colors; + parent::tear_down(); + } + + /** + * Test wp_color_scheme_settings() with a valid color scheme. + */ + public function test_wp_color_scheme_settings_valid_scheme() { + global $_wp_admin_css_colors; + + $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + update_user_option( $user_id, 'admin_color', 'blue' ); + + $_wp_admin_css_colors = array( + 'blue' => (object) array( + 'icon_colors' => array( + 'base' => '#e5f8ff', + 'focus' => '#fff', + 'current' => '#fff', + ), + ), + ); + + ob_start(); + wp_color_scheme_settings(); + $output = ob_get_clean(); + + $expected = array( + 'icons' => array( + 'base' => '#e5f8ff', + 'focus' => '#fff', + 'current' => '#fff', + ), + ); + + $this->assertStringContainsString( 'var _wpColorScheme = ' . wp_json_encode( $expected ), $output ); + } + + /** + * Test wp_color_scheme_settings() with an invalid color scheme (fallback to modern). + */ + public function test_wp_color_scheme_settings_invalid_scheme_fallback_to_modern() { + global $_wp_admin_css_colors; + + $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + update_user_option( $user_id, 'admin_color', 'non-existent' ); + + $_wp_admin_css_colors = array( + 'modern' => (object) array( + 'icon_colors' => array( + 'base' => '#f0f0f1', + 'focus' => '#fff', + 'current' => '#fff', + ), + ), + ); + + ob_start(); + wp_color_scheme_settings(); + $output = ob_get_clean(); + + $expected = array( + 'icons' => array( + 'base' => '#f0f0f1', + 'focus' => '#fff', + 'current' => '#fff', + ), + ); + + $this->assertStringContainsString( 'var _wpColorScheme = ' . wp_json_encode( $expected ), $output ); + } + + /** + * Test wp_color_scheme_settings() with no icon colors defined (fallback to defaults). + */ + public function test_wp_color_scheme_settings_no_icon_colors_fallback() { + global $_wp_admin_css_colors; + + $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + update_user_option( $user_id, 'admin_color', 'empty-scheme' ); + + $_wp_admin_css_colors = array( + 'empty-scheme' => (object) array(), + 'modern' => (object) array(), + ); + + ob_start(); + wp_color_scheme_settings(); + $output = ob_get_clean(); + + $expected = array( + 'icons' => array( + 'base' => '#a7aaad', + 'focus' => '#72aee6', + 'current' => '#fff', + ), + ); + + $this->assertStringContainsString( 'var _wpColorScheme = ' . wp_json_encode( $expected ), $output ); + } +} diff --git a/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php b/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php new file mode 100644 index 0000000000000..7489ce44a498e --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php @@ -0,0 +1,89 @@ +assertSame( $expected, wp_make_plugin_file_tree( $plugin_editable_files ) ); + } + + /** + * Data provider for test_wp_make_plugin_file_tree. + * + * @return array, + * expected: array, + * }> + */ + public function data_wp_make_plugin_file_tree(): array { + return array( + 'empty_list' => array( + 'plugin_editable_files' => array(), + 'expected' => array(), + ), + 'flat_list' => array( + 'plugin_editable_files' => array( + 'plugin/plugin.php', + 'plugin/readme.txt', + ), + 'expected' => array( + 'plugin.php' => 'plugin/plugin.php', + 'readme.txt' => 'plugin/readme.txt', + ), + ), + 'nested_list' => array( + 'plugin_editable_files' => array( + 'plugin/plugin.php', + 'plugin/includes/class-plugin.php', + 'plugin/includes/functions.php', + ), + 'expected' => array( + 'plugin.php' => 'plugin/plugin.php', + 'includes' => array( + 'class-plugin.php' => 'plugin/includes/class-plugin.php', + 'functions.php' => 'plugin/includes/functions.php', + ), + ), + ), + 'deeply_nested_list' => array( + 'plugin_editable_files' => array( + 'plugin/plugin.php', + 'plugin/src/components/button/index.js', + ), + 'expected' => array( + 'plugin.php' => 'plugin/plugin.php', + 'src' => array( + 'components' => array( + 'button' => array( + 'index.js' => 'plugin/src/components/button/index.js', + ), + ), + ), + ), + ), + 'multiple_base_names' => array( + 'plugin_editable_files' => array( + 'plugin-a/plugin.php', + 'plugin-b/plugin.php', + ), + 'expected' => array( + 'plugin.php' => 'plugin-b/plugin.php', // Note: wp_make_plugin_file_tree replaces the file name if multiple base paths exist but result in same relative path. + ), + ), + ); + } +} From 5dfb970a525e20d2a9e7d8aeded4d75e2aebfb82 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:38:49 +0000 Subject: [PATCH 114/481] Tests: Cover logged-out Heartbeat requests. Verify the default response and the receive, send, and tick hooks in `wp_ajax_nopriv_heartbeat()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/11826 Props pbearne. See #65236. git-svn-id: https://develop.svn.wordpress.org/trunk@65120 602fd350-edb4-49c9-b593-d223f7449a82 --- .../ajax-actions/wpAjaxNoprivHeartbeat.php | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxNoprivHeartbeat.php diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxNoprivHeartbeat.php b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxNoprivHeartbeat.php new file mode 100644 index 0000000000000..7b83b240f5e1e --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxNoprivHeartbeat.php @@ -0,0 +1,171 @@ + 'nopriv_heartbeat', + 'screen_id' => 'front', + 'data' => array( + 'test_data' => 'test_value', + ), + ); + + // Make the request. + try { + $this->_handleAjax( 'nopriv_heartbeat' ); + } catch ( WPAjaxDieContinueException $e ) { + // Expected exception. + unset( $e ); + } catch ( WPAjaxDieStopException $e ) { + // Expected exception. + unset( $e ); + } catch ( Exception $e ) { + $this->fail( 'Unexpected exception: ' . $e->getMessage() ); + } + + if ( empty( $this->_last_response ) ) { + $this->fail( 'Ajax response was empty' ); + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertIsArray( $response ); + $this->assertArrayHasKey( 'server_time', $response ); + $this->assertIsInt( $response['server_time'] ); + } + + /** + * Tests the 'heartbeat_nopriv_received' filter. + * + * @ticket 65236 + */ + public function test_heartbeat_nopriv_received_filter(): void { + wp_set_current_user( 0 ); + + $_POST = array( + 'action' => 'nopriv_heartbeat', + 'screen_id' => 'test_screen', + 'data' => array( + 'foo' => 'bar', + ), + ); + + add_filter( + 'heartbeat_nopriv_received', + function ( $response, $data, $screen_id ) { + $response['received_data'] = $data; + $response['received_screen'] = $screen_id; + return $response; + }, + 10, + 3 + ); + + try { + $this->_handleAjax( 'nopriv_heartbeat' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertSame( array( 'foo' => 'bar' ), $response['received_data'] ); + $this->assertSame( 'test_screen', $response['received_screen'] ); + } + + /** + * Tests the 'heartbeat_nopriv_send' filter. + * + * @ticket 65236 + */ + public function test_heartbeat_nopriv_send_filter(): void { + wp_set_current_user( 0 ); + + $_POST = array( + 'action' => 'nopriv_heartbeat', + ); + + add_filter( + 'heartbeat_nopriv_send', + function ( $response, $screen_id ) { + $response['sent_screen'] = $screen_id; + return $response; + }, + 10, + 2 + ); + + try { + $this->_handleAjax( 'nopriv_heartbeat' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $response = json_decode( $this->_last_response, true ); + + // Default screen_id is 'front'. + $this->assertSame( 'front', $response['sent_screen'] ); + } + + /** + * Tests the 'heartbeat_nopriv_tick' action. + * + * @ticket 65236 + */ + public function test_heartbeat_nopriv_tick_action(): void { + wp_set_current_user( 0 ); + + $_POST = array( + 'action' => 'nopriv_heartbeat', + ); + + $action_called = false; + add_action( + 'heartbeat_nopriv_tick', + function ( $response, $screen_id ) use ( &$action_called ) { + $action_called = true; + }, + 10, + 2 + ); + + try { + $this->_handleAjax( 'nopriv_heartbeat' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } catch ( WPAjaxDieStopException $e ) { + unset( $e ); + } + + $this->assertTrue( $action_called ); + } +} From 78ec0a7809061b3ca34a25f0b9d6c6e0d1a8a33e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:39:57 +0000 Subject: [PATCH 115/481] Tests: Cover image sizes and embedded media. Verify registered image dimensions, crop settings, and filtering, alongside embedded-media extraction and type filtering. Developed in: https://github.com/WordPress/wordpress-develop/pull/12749, https://github.com/WordPress/wordpress-develop/pull/13222 Props irozum, khokansardar. See #65751, #65931. git-svn-id: https://develop.svn.wordpress.org/trunk@65121 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/media.php | 65 +++++++++++ .../tests/media/getMediaEmbeddedInContent.php | 105 ++++++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 tests/phpunit/tests/media/getMediaEmbeddedInContent.php diff --git a/tests/phpunit/tests/media.php b/tests/phpunit/tests/media.php index dd4af48d2bf4d..4cc8e35623609 100644 --- a/tests/phpunit/tests/media.php +++ b/tests/phpunit/tests/media.php @@ -1744,6 +1744,71 @@ public function test_has_image_size() { remove_image_size( 'test-size' ); } + /** + * @ticket 65751 + */ + public function test_wp_get_registered_image_subsizes_includes_custom_size() { + add_image_size( 'test-size', 200, 600 ); + + $sizes = wp_get_registered_image_subsizes(); + + // Clean up. + remove_image_size( 'test-size' ); + + $this->assertArrayHasKey( 'test-size', $sizes ); + $this->assertSame( 200, $sizes['test-size']['width'] ); + $this->assertSame( 600, $sizes['test-size']['height'] ); + $this->assertFalse( $sizes['test-size']['crop'] ); + } + + /** + * @ticket 65751 + */ + public function test_wp_get_registered_image_subsizes_preserves_crop_position() { + add_image_size( 'test-size', 200, 600, array( 'center', 'top' ) ); + + $sizes = wp_get_registered_image_subsizes(); + + // Clean up. + remove_image_size( 'test-size' ); + + $this->assertSame( array( 'center', 'top' ), $sizes['test-size']['crop'] ); + } + + /** + * @ticket 65751 + */ + public function test_wp_get_registered_image_subsizes_omits_size_with_no_dimensions() { + add_image_size( 'test-size', 0, 0 ); + + $sizes = wp_get_registered_image_subsizes(); + + // Clean up. + remove_image_size( 'test-size' ); + + $this->assertArrayNotHasKey( 'test-size', $sizes ); + } + + /** + * @ticket 65751 + */ + public function test_wp_get_registered_image_subsizes_honors_intermediate_image_sizes_filter() { + add_image_size( 'test-size', 200, 600 ); + + $exclude_test_size = static function ( $sizes ) { + return array_diff( $sizes, array( 'test-size' ) ); + }; + add_filter( 'intermediate_image_sizes', $exclude_test_size ); + + $sizes = wp_get_registered_image_subsizes(); + + // Clean up. + remove_filter( 'intermediate_image_sizes', $exclude_test_size ); + remove_image_size( 'test-size' ); + + $this->assertArrayNotHasKey( 'test-size', $sizes ); + } + /** * @ticket 30346 */ diff --git a/tests/phpunit/tests/media/getMediaEmbeddedInContent.php b/tests/phpunit/tests/media/getMediaEmbeddedInContent.php new file mode 100644 index 0000000000000..3b146ac3e427f --- /dev/null +++ b/tests/phpunit/tests/media/getMediaEmbeddedInContent.php @@ -0,0 +1,105 @@ +assertSame( $expected, get_media_embedded_in_content( $content, $types ) ); + } + + /** + * Data provider for test_returns_expected_media. + * + * @return array[] + */ + public function data_content() { + $audio = ''; + $video = ''; + $iframe = ''; + $embed = ''; + $object = ''; + + return array( + 'no types given' => array( + "

Before.

$object$embed$iframe$audio$video

After.

", + null, + array( $object, $embed, $iframe, $audio, $video ), + ), + 'an empty array of types' => array( + "

Before.

$audio

After.

", + array(), + array( $audio ), + ), + 'repeated elements of one type' => array( + "
$iframe

Between.

$iframe
", + 'iframe', + array( $iframe, $iframe ), + ), + 'both self-closing forms' => array( + '
', + 'embed', + array( '', '' ), + ), + 'an element left open' => array( + '
', + 'audio', + array(), + ), + 'a less-than sign in an attribute' => array( + '
', + 'iframe', + array(), + ), + ); + } + + /** + * @ticket 65931 + */ + public function test_allowed_types_filter_can_narrow_the_types() { + $video = ''; + + add_filter( + 'media_embedded_in_content_allowed_types', + static function () { + return array( 'video' ); + } + ); + + $this->assertSame( + array( $video ), + get_media_embedded_in_content( '
' . $video . '
' ) + ); + } + + /** + * @ticket 65931 + */ + public function test_allowed_types_filter_can_add_a_type() { + $img = ''; + + add_filter( + 'media_embedded_in_content_allowed_types', + static function ( $allowed_media_types ) { + $allowed_media_types[] = 'img'; + return $allowed_media_types; + } + ); + + $this->assertSame( array( $img ), get_media_embedded_in_content( "

Text.

$img" ) ); + } +} From 6b3cdb89dba8a103fe8fa5f8093a6cf27943b07e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:41:03 +0000 Subject: [PATCH 116/481] Tests: Strengthen object-cache assertions. Verify cache-group separation, missing entries, and bulk deletion. Cover empty and populated term relationship caches, including invalidation during deferred term counting. Developed in: https://github.com/WordPress/wordpress-develop/pull/12642, https://github.com/WordPress/wordpress-develop/pull/13226 Props jorgelopezrepiso, sainathpoojary. See #65693, #49799. git-svn-id: https://develop.svn.wordpress.org/trunk@65122 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/cache.php | 16 +++- tests/phpunit/tests/term/getTheTerms.php | 102 +++++++++++++++++++++-- 2 files changed, 106 insertions(+), 12 deletions(-) diff --git a/tests/phpunit/tests/cache.php b/tests/phpunit/tests/cache.php index a21d672938ebf..7ca6de5ec8eda 100644 --- a/tests/phpunit/tests/cache.php +++ b/tests/phpunit/tests/cache.php @@ -458,14 +458,16 @@ public function test_wp_cache_set_multiple() { public function test_wp_cache_get_multiple() { wp_cache_set( 'foo1', 'bar', 'group1' ); wp_cache_set( 'foo2', 'bar', 'group1' ); - wp_cache_set( 'foo1', 'bar', 'group2' ); + wp_cache_set( 'foo3', 'bar', 'group2' ); + wp_cache_set( 'foo1', 'bar2', 'group2' ); - $found = wp_cache_get_multiple( array( 'foo1', 'foo2', 'foo3' ), 'group1' ); + $found = wp_cache_get_multiple( array( 'foo1', 'foo2', 'foo3', 'foo4' ), 'group1' ); $expected = array( 'foo1' => 'bar', 'foo2' => 'bar', 'foo3' => false, + 'foo4' => false, ); $this->assertSame( $expected, $found ); @@ -480,7 +482,7 @@ public function test_wp_cache_delete_multiple() { wp_cache_set( 'foo3', 'bar', 'group2' ); $found = wp_cache_delete_multiple( - array( 'foo1', 'foo2', 'foo3' ), + array( 'foo1', 'foo2', 'foo3', 'foo4' ), 'group1' ); @@ -488,8 +490,16 @@ public function test_wp_cache_delete_multiple() { 'foo1' => true, 'foo2' => true, 'foo3' => false, + 'foo4' => false, ); $this->assertSame( $expected, $found ); + + // Verify that foo1 and foo2 were actually deleted from group1. + $this->assertFalse( wp_cache_get( 'foo1', 'group1' ) ); + $this->assertFalse( wp_cache_get( 'foo2', 'group1' ) ); + + // Verify that foo3 in group2 was untouched. + $this->assertSame( 'bar', wp_cache_get( 'foo3', 'group2' ) ); } } diff --git a/tests/phpunit/tests/term/getTheTerms.php b/tests/phpunit/tests/term/getTheTerms.php index fb1bb02aeec9f..b2bfe7f54605b 100644 --- a/tests/phpunit/tests/term/getTheTerms.php +++ b/tests/phpunit/tests/term/getTheTerms.php @@ -225,8 +225,13 @@ public function test_uncached_terms_should_not_be_primed_with_a_single_query_by_ /** * @ticket 40306 + * @ticket 49799 + * + * @dataProvider data_term_cache_priming_functions + * + * @param string $priming_function Function used to prime the empty relationship cache. */ - public function test_term_cache_should_be_invalidated_on_set_object_terms() { + public function test_term_cache_should_be_invalidated_on_set_object_terms( $priming_function ) { register_taxonomy( 'wptests_tax', 'post' ); // Temporarily disable term counting, which performs its own cache invalidation. @@ -241,18 +246,42 @@ public function test_term_cache_should_be_invalidated_on_set_object_terms() { $post_id = self::factory()->post->create(); - // Prime cache. - get_the_terms( $post_id, 'wptests_tax' ); + try { + // Prime cache with an empty array. + if ( 'update_object_term_cache' === $priming_function ) { + update_object_term_cache( array( $post_id ), array( 'post' ) ); + } else { + get_the_terms( $post_id, 'wptests_tax' ); + } - wp_set_object_terms( $post_id, $term_id, 'wptests_tax' ); + $cached = wp_cache_get( $post_id, 'wptests_tax_relationships' ); + $this->assertIsArray( $cached ); + $this->assertEmpty( $cached ); - $terms = get_the_terms( $post_id, 'wptests_tax' ); + wp_set_object_terms( $post_id, $term_id, 'wptests_tax' ); - // Re-activate term counting so this doesn't affect other tests. - wp_defer_term_counting( false ); + $this->assertFalse( wp_cache_get( $post_id, 'wptests_tax_relationships' ) ); - $this->assertIsArray( $terms ); - $this->assertSame( array( $term_id ), wp_list_pluck( $terms, 'term_id' ) ); + $terms = get_the_terms( $post_id, 'wptests_tax' ); + + $this->assertIsArray( $terms ); + $this->assertSame( array( $term_id ), wp_list_pluck( $terms, 'term_id' ) ); + } finally { + // Re-activate term counting so this doesn't affect other tests. + wp_defer_term_counting( false ); + } + } + + /** + * Data provider for test_term_cache_should_be_invalidated_on_set_object_terms(). + * + * @return array[] + */ + public static function data_term_cache_priming_functions() { + return array( + 'get_the_terms' => array( 'get_the_terms' ), + 'update_object_term_cache' => array( 'update_object_term_cache' ), + ); } /** @@ -289,4 +318,59 @@ public function test_term_cache_should_be_invalidated_on_remove_object_terms() { $this->assertIsArray( $terms ); $this->assertSame( array( $term_ids[1] ), wp_list_pluck( $terms, 'term_id' ) ); } + + /** + * Tests that get_the_terms() returns false for a post with no terms even when + * update_object_term_cache() has primed the cache with an empty array. + * + * @ticket 49799 + */ + public function test_get_the_terms_returns_false_for_post_with_no_terms_when_cache_primed() { + register_taxonomy( 'wptests_tax', 'post' ); + + $post_id = self::factory()->post->create(); + + // Prime cache with an empty array. + update_object_term_cache( array( $post_id ), array( 'post' ) ); + + $cached = wp_cache_get( $post_id, 'wptests_tax_relationships' ); + $this->assertIsArray( $cached ); + $this->assertEmpty( $cached ); + + $num_queries_before = get_num_queries(); + $terms = get_the_terms( $post_id, 'wptests_tax' ); + + $this->assertSame( 0, get_num_queries() - $num_queries_before ); + $this->assertFalse( $terms ); + } + + /** + * Tests that get_the_terms() returns correct terms after update_object_term_cache() + * is called following term assignment. + * + * @ticket 49799 + */ + public function test_get_the_terms_returns_correct_terms_when_cache_primed_after_assignment() { + register_taxonomy( 'wptests_tax', 'post' ); + + $post_id = self::factory()->post->create(); + $term_id = self::factory()->term->create( array( 'taxonomy' => 'wptests_tax' ) ); + + wp_set_object_terms( $post_id, $term_id, 'wptests_tax' ); + + // Prime cache after assignment. + update_object_term_cache( array( $post_id ), array( 'post' ) ); + + $cached = wp_cache_get( $post_id, 'wptests_tax_relationships' ); + $this->assertIsArray( $cached ); + $this->assertNotEmpty( $cached ); + + $num_queries_before = get_num_queries(); + $terms = get_the_terms( $post_id, 'wptests_tax' ); + + $this->assertSame( 0, get_num_queries() - $num_queries_before ); + $this->assertIsArray( $terms ); + $this->assertCount( 1, $terms ); + $this->assertSame( $term_id, (int) $terms[0]->term_id ); + } } From 4b866649a546870cb637efd11ae5a0e50101be4c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:42:20 +0000 Subject: [PATCH 117/481] Tests: Clarify post-date data providers. Improve dataset labels and provider documentation for post-date tests. Developed in: https://github.com/WordPress/wordpress-develop/pull/10481 Props mukesh27, westonruter. See #26798. git-svn-id: https://develop.svn.wordpress.org/trunk@65123 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post.php | 298 +++++++++++++++++------------------ 1 file changed, 147 insertions(+), 151 deletions(-) diff --git a/tests/phpunit/tests/post.php b/tests/phpunit/tests/post.php index b8bac29c1e039..a10d34b32a575 100644 --- a/tests/phpunit/tests/post.php +++ b/tests/phpunit/tests/post.php @@ -827,21 +827,25 @@ public function test_use_block_editor_for_post() { } /** + * Tests that invalid dates do not cause PHP errors when wp_insert_post() + * is called, and that the posts are not actually "inserted" (created). + * * @ticket 26798 * + * @covers ::wp_insert_post + * * @dataProvider data_wp_insert_post_handle_malformed_post_date * - * The purpose of this test is to ensure that invalid dates do not - * cause PHP errors when wp_insert_post() is called, and that the - * posts are not actually "inserted" (created). + * @param string $date The input post_date value. + * @param bool $expected Whether the post is expected to be inserted. */ - public function test_wp_insert_post_handle_malformed_post_date( $input, $expected ) { + public function test_wp_insert_post_handle_malformed_post_date( $date, $expected ) { $post = array( 'post_author' => self::$user_ids['editor'], 'post_status' => 'publish', 'post_content' => 'content', 'post_title' => 'title', - 'post_date' => $input, + 'post_date' => $date, ); // Inserting the post should fail gracefully. @@ -853,110 +857,107 @@ public function test_wp_insert_post_handle_malformed_post_date( $input, $expecte } /** - * @ticket 26798 + * Data provider for test_wp_insert_post_handle_malformed_post_date(). + * + * @return array */ - public function data_wp_insert_post_handle_malformed_post_date() { + public static function data_wp_insert_post_handle_malformed_post_date(): array { return array( - array( - '2012-01-01', - true, + 'date only' => array( + 'date' => '2012-01-01', + 'expected' => true, ), - // 24-hour time format. - array( - '2012-01-01 13:00:00', - true, + '24-hour time format' => array( + 'date' => '2012-01-01 13:00:00', + 'expected' => true, ), - // ISO8601 date with timezone. - array( - '2016-01-16T00:00:00Z', - true, + 'ISO8601 date with timezone' => array( + 'date' => '2016-01-16T00:00:00Z', + 'expected' => true, ), - // ISO8601 date with timezone offset. - array( - '2016-01-16T00:00:00+0100', - true, + 'ISO8601 date with timezone offset' => array( + 'date' => '2016-01-16T00:00:00+0100', + 'expected' => true, ), - // RFC3339 Format. - array( - '1970-01-01T01:00:00+01:00', - true, + 'RFC3339 format' => array( + 'date' => '1970-01-01T01:00:00+01:00', + 'expected' => true, ), - // RSS Format - array( - '1970-01-01T01:00:00+0100', - true, + 'RSS format' => array( + 'date' => '1970-01-01T01:00:00+0100', + 'expected' => true, ), - // Leap year. - array( - '2012-02-29', - true, + 'leap year' => array( + 'date' => '2012-02-29', + 'expected' => true, ), - // Strange formats. - array( - '2012-01-01 0', - true, + 'single digit hour' => array( + 'date' => '2012-01-01 0', + 'expected' => true, ), - array( - '2012-01-01 25:00:00', - true, + 'hour out of range' => array( + 'date' => '2012-01-01 25:00:00', + 'expected' => true, ), - array( - '2012-01-01 00:60:00', - true, + 'minute out of range' => array( + 'date' => '2012-01-01 00:60:00', + 'expected' => true, ), - // Dates without leading zeros (valid but malformed format). - array( - '2012-08-1', - true, + 'day without leading zero' => array( + 'date' => '2012-08-1', + 'expected' => true, ), - array( - '2012-1-08 00:00:00', - true, + 'month without leading zero with time' => array( + 'date' => '2012-1-08 00:00:00', + 'expected' => true, ), - array( - '2012-01-8 00:00:00', - true, + 'day without leading zero with time' => array( + 'date' => '2012-01-8 00:00:00', + 'expected' => true, ), - // Failures. - array( - '2012-08-0z', - false, + 'invalid character in day' => array( + 'date' => '2012-08-0z', + 'expected' => false, ), - array( - '201-01-08 00:00:00', - false, + 'three digit year' => array( + 'date' => '201-01-08 00:00:00', + 'expected' => false, ), - array( - '201-01-08 00:60:00', - false, + 'three digit year with minute out of range' => array( + 'date' => '201-01-08 00:60:00', + 'expected' => false, ), - array( - '201a-01-08 00:00:00', - false, + 'invalid character in year' => array( + 'date' => '201a-01-08 00:00:00', + 'expected' => false, ), - array( - '2012-31-08 00:00:00', - false, + 'month out of range' => array( + 'date' => '2012-31-08 00:00:00', + 'expected' => false, ), - array( - '2012-01-48 00:00:00', - false, + 'day out of range' => array( + 'date' => '2012-01-48 00:00:00', + 'expected' => false, ), - // Not a leap year. - array( - '2011-02-29', - false, + 'not a leap year' => array( + 'date' => '2011-02-29', + 'expected' => false, ), ); } /** + * Tests the regex inside of wp_resolve_post_date(), with + * the emphasis on the date format (not the time). + * * @ticket 26798 * + * @covers ::wp_resolve_post_date + * * @dataProvider data_wp_resolve_post_date_regex * - * Tests the regex inside of wp_resolve_post_date(), with - * the emphasis on the date format (not the time). + * @param string $date The input post_date value. + * @param string|false $expected The expected resolved post date, or false if invalid. */ public function test_wp_resolve_post_date_regex( $date, $expected ) { // Attempt to resolve post date. @@ -967,100 +968,95 @@ public function test_wp_resolve_post_date_regex( $date, $expected ) { } /** - * @ticket 26798 + * Data provider for test_wp_resolve_post_date_regex(). + * + * @return array */ - public function data_wp_resolve_post_date_regex() { + public static function data_wp_resolve_post_date_regex(): array { return array( - array( - '2012-01-01', - '2012-01-01', + 'date only' => array( + 'date' => '2012-01-01', + 'expected' => '2012-01-01', ), - array( - '2012-01-01 00:00:00', - '2012-01-01 00:00:00', + 'date with midnight time' => array( + 'date' => '2012-01-01 00:00:00', + 'expected' => '2012-01-01 00:00:00', ), - // ISO8601 date with timezone. - array( - '2016-01-16T00:00:00Z', - '2016-01-16T00:00:00Z', + 'ISO8601 date with timezone' => array( + 'date' => '2016-01-16T00:00:00Z', + 'expected' => '2016-01-16T00:00:00Z', ), - // ISO8601 date with timezone offset. - array( - '2016-01-16T00:00:00+0100', - '2016-01-16T00:00:00+0100', + 'ISO8601 date with timezone offset' => array( + 'date' => '2016-01-16T00:00:00+0100', + 'expected' => '2016-01-16T00:00:00+0100', ), - // RFC3339 Format. - array( - '1970-01-01T01:00:00+01:00', - '1970-01-01T01:00:00+01:00', + 'RFC3339 format' => array( + 'date' => '1970-01-01T01:00:00+01:00', + 'expected' => '1970-01-01T01:00:00+01:00', ), - // RSS Format - array( - '1970-01-01T01:00:00+0100', - '1970-01-01T01:00:00+0100', + 'RSS format' => array( + 'date' => '1970-01-01T01:00:00+0100', + 'expected' => '1970-01-01T01:00:00+0100', ), - // 24-hour time format. - array( - '2012-01-01 13:00:00', - '2012-01-01 13:00:00', + '24-hour time format' => array( + 'date' => '2012-01-01 13:00:00', + 'expected' => '2012-01-01 13:00:00', ), - array( - '2016-01-16T00:0', - '2016-01-16T00:0', + 'ISO8601 date with partial time' => array( + 'date' => '2016-01-16T00:0', + 'expected' => '2016-01-16T00:0', ), - array( - '2012-01-01 0', - '2012-01-01 0', + 'single digit hour' => array( + 'date' => '2012-01-01 0', + 'expected' => '2012-01-01 0', ), - array( - '2012-01-01 00:00', - '2012-01-01 00:00', + 'time without seconds' => array( + 'date' => '2012-01-01 00:00', + 'expected' => '2012-01-01 00:00', ), - array( - '2012-01-01 25:00:00', - '2012-01-01 25:00:00', + 'hour out of range' => array( + 'date' => '2012-01-01 25:00:00', + 'expected' => '2012-01-01 25:00:00', ), - array( - '2012-01-01 00:60:00', - '2012-01-01 00:60:00', + 'minute out of range' => array( + 'date' => '2012-01-01 00:60:00', + 'expected' => '2012-01-01 00:60:00', ), - array( - '2012-01-01 00:00:60', - '2012-01-01 00:00:60', + 'second out of range' => array( + 'date' => '2012-01-01 00:00:60', + 'expected' => '2012-01-01 00:00:60', ), - // Dates without leading zeros (valid but malformed format). - array( - '2012-1-08', - '2012-1-08', + 'month without leading zero' => array( + 'date' => '2012-1-08', + 'expected' => '2012-1-08', ), - array( - '2012-01-8', - '2012-01-8', + 'day without leading zero' => array( + 'date' => '2012-01-8', + 'expected' => '2012-01-8', ), - array( - '201-01-08', - false, + 'three digit year' => array( + 'date' => '201-01-08', + 'expected' => false, ), - array( - '201a-01-08', - false, + 'invalid character in year' => array( + 'date' => '201a-01-08', + 'expected' => false, ), - array( - '2012-31-08', - false, + 'month out of range' => array( + 'date' => '2012-31-08', + 'expected' => false, ), - array( - '2012-01-48 00:00:00', - false, + 'day out of range' => array( + 'date' => '2012-01-48 00:00:00', + 'expected' => false, ), - // Leap year. - array( - '2012-02-29', - '2012-02-29', + 'leap year' => array( + 'date' => '2012-02-29', + 'expected' => '2012-02-29', ), - array( - '2011-02-29', - false, + 'not a leap year' => array( + 'date' => '2011-02-29', + 'expected' => false, ), ); } From 7374a0ebd8b299d771a8c029f16d7dab62493344 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:43:18 +0000 Subject: [PATCH 118/481] Build/Test Tools: Document Windows Docker setup. Document WSL integration and Linux containers for the local development environment on Windows. Developed in: https://github.com/WordPress/wordpress-develop/pull/13499 Props micahele. See #62196. git-svn-id: https://develop.svn.wordpress.org/trunk@65124 602fd350-edb4-49c9-b593-d223f7449a82 --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index cb64a35538457..0e2f34af366b7 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,14 @@ You will also need a container environment such as [Docker Desktop](https://www. **Note:** WordPress currently only officially supports Docker but several container environments are available and should generally be compatible, such as [Colima](https://github.com/abiosoft/colima), [OrbStack](https://orbstack.dev/), [Podman Desktop](https://podman-desktop.io/), and [Rancher Desktop](https://rancherdesktop.io/). +#### Windows-specific instructions + +For development on Windows, [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) is recommended. This provides a Linux environment where the general development instructions can be used without modification. + +After installing Docker Desktop, enable Docker's WSL integration under **Settings > Resources > WSL integration**. This only needs to be configured once. + +If you use Docker Desktop directly from Windows without WSL, make sure it is using Linux containers. Right-click the Docker icon in the system tray and select **Switch to Linux containers...**. If that option is not available, or the menu shows **Switch to Windows containers...**, Docker is already using Linux containers. You can switch between container types later if another project requires Windows containers. + ### Development Environment Commands Ensure your container environment is running before using these commands. From 3dd9af210325467a2f367e630f94fdea0e76bb61 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:45:53 +0000 Subject: [PATCH 119/481] Build/Test Tools: Restore contributor welcome comments. Use `actions/github-script` to welcome first-time contributors. Check previous contributions and existing comments to avoid duplicate greetings. Developed in: https://github.com/WordPress/wordpress-develop/pull/14715 Props devmuhib. See #65432. git-svn-id: https://develop.svn.wordpress.org/trunk@65125 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/pull-request-comments.yml | 90 +++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/.github/workflows/pull-request-comments.yml b/.github/workflows/pull-request-comments.yml index 6c56326774b8d..cffc5d7aecb59 100644 --- a/.github/workflows/pull-request-comments.yml +++ b/.github/workflows/pull-request-comments.yml @@ -20,6 +20,96 @@ concurrency: permissions: {} jobs: + # Comments on a pull request when the author is a first time contributor. + post-welcome-message: + name: Post a welcome comment for first-time contributors + runs-on: ubuntu-24.04 + permissions: + issues: write + pull-requests: write + timeout-minutes: 5 + if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name == 'pull_request_target' && github.event.action == 'opened' }} + steps: + - name: Post welcome comment + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { owner, repo } = context.repo; + const pr = context.payload.pull_request; + const author = pr.user.login; + + // Only comment for first-time contributors. + const authorAssociation = pr.author_association; + const isFirstTimer = authorAssociation === 'FIRST_TIME_CONTRIBUTOR' || authorAssociation === 'FIRST_TIMER'; + + if ( ! isFirstTimer ) { + core.info( `Author @${ author } has author association "${ authorAssociation }". Skipping welcome comment.` ); + return; + } + + // Check if the author has opened other pull requests in the repository. + const query = `repo:${ owner }/${ repo } is:pr author:${ author }`; + const searchResults = await github.rest.search.issuesAndPullRequests( { + q: query, + per_page: 5, + } ); + + const otherPRs = searchResults.data.items.filter( ( item ) => item.number !== pr.number ); + if ( otherPRs.length > 0 ) { + core.info( `Author @${ author } has already opened other pull requests. Skipping welcome comment.` ); + return; + } + + // Check if a welcome comment already exists to avoid duplicate comments. + const comments = await github.paginate( github.rest.issues.listComments, { + owner, + repo, + issue_number: pr.number, + per_page: 100, + } ); + + const hasWelcomeComment = comments.some( ( comment ) => + comment.user && comment.user.type === 'Bot' && comment.body.includes( 'first pull request to `wordpress-develop`' ) + ); + + if ( hasWelcomeComment ) { + core.info( 'A welcome comment already exists on this pull request.' ); + return; + } + + const welcomeLines = [ + `Hi @${ author }! 👋`, + 'Thank you for your contribution to WordPress! 💖', + 'It looks like this is your first pull request to `wordpress-develop`. Here are a few things to be aware of that may help you out!', + '**No one monitors this repository for new pull requests.** Pull requests **must** be attached to a Trac ticket to be considered for inclusion in WordPress Core. To attach a pull request to a Trac ticket, please include the ticket\'s full URL in your pull request description.', + '**Pull requests are never merged on GitHub.** The WordPress codebase continues to be managed through the SVN repository that this GitHub repository mirrors. Please feel free to open pull requests to work on any contribution you are making.', + 'More information about how GitHub pull requests can be used to contribute to WordPress can be found in [the Core Handbook](https://make.wordpress.org/core/handbook/contribute/git/github-pull-requests-for-code-review/).', + '**Please include automated tests.** Including tests in your pull request is one way to help your patch be considered faster. To learn about WordPress\' test suites, visit the [Automated Testing](https://make.wordpress.org/core/handbook/testing/automated-testing/) page in the handbook.', + 'If you have not had a chance, please review the [Contribute with Code page](https://make.wordpress.org/core/handbook/contribute/) in the [WordPress Core Handbook](https://make.wordpress.org/core/handbook/).', + 'The [Developer Hub](https://developer.wordpress.org/) also documents the various [coding standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/) that are followed:\n- [PHP Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/)\n- [CSS Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/css/)\n- [HTML Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/html/)\n- [JavaScript Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/javascript/)\n- [Accessibility Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/accessibility/)\n- [Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/)', + 'Thank you,\nThe WordPress Project', + ]; + + await github.rest.issues.createComment( { + owner, + repo, + issue_number: pr.number, + body: welcomeLines.join( '\n\n' ), + } ); + + try { + await github.rest.reactions.createForIssue( { + owner, + repo, + issue_number: pr.number, + content: 'hooray', + } ); + } catch ( error ) { + core.info( `Could not add reaction: ${ error.message }` ); + } + + core.notice( `Created welcome comment for pull request: ${ pr.html_url }` ); + # Leaves a comment on a pull request with a link to test the changes in a WordPress Playground instance. playground-details: name: Comment on a pull request with Playground details From 16790ba99262b362f1d50e848522114b584192b7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:47:18 +0000 Subject: [PATCH 120/481] Tests: Preserve registered metadata between tests. Capture and restore metadata registrations and their hooks around test methods and class fixtures. Preserve bootstrap registrations without rerunning registration filters, and explicitly clear the registry in tests that require an empty baseline. Developed in: https://github.com/WordPress/wordpress-develop/pull/14774 Props salvatorecorsi. See #48300. git-svn-id: https://develop.svn.wordpress.org/trunk@65126 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/includes/abstract-testcase.php | 78 ++++++- .../phpunit/tests/includes/registeredMeta.php | 212 ++++++++++++++++++ tests/phpunit/tests/meta/registerMeta.php | 7 + tests/phpunit/tests/post/meta.php | 7 + tests/phpunit/tests/term/meta.php | 3 + 5 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/tests/includes/registeredMeta.php diff --git a/tests/phpunit/includes/abstract-testcase.php b/tests/phpunit/includes/abstract-testcase.php index aaf0c8aa57b5e..4b343666819db 100644 --- a/tests/phpunit/includes/abstract-testcase.php +++ b/tests/phpunit/includes/abstract-testcase.php @@ -32,6 +32,20 @@ abstract class WP_UnitTestCase_Base extends PHPUnit_Adapter_TestCase { protected static $hooks_saved = array(); protected static $ignore_files; + /** + * Metadata state before each class's fixtures are created, keyed by class. + * + * @var array[] + */ + private static $meta_before_class = array(); + + /** + * Metadata state before the current test, or null when setup was bypassed. + * + * @var array|null + */ + private $original_meta_state; + /** * The value of $GLOBALS['locale'] before each test, or null if it was unset. * @@ -95,7 +109,8 @@ public static function set_up_before_class() { $wpdb->db_connect(); ini_set( 'display_errors', 1 ); - $class = get_called_class(); + $class = get_called_class(); + self::$meta_before_class[ $class ] = self::backup_meta_state(); if ( method_exists( $class, 'wpSetUpBeforeClass' ) ) { call_user_func( array( $class, 'wpSetUpBeforeClass' ), static::factory() ); @@ -114,6 +129,11 @@ public static function tear_down_after_class() { call_user_func( array( $class, 'wpTearDownAfterClass' ) ); } + if ( isset( self::$meta_before_class[ $class ] ) ) { + self::restore_meta_state( self::$meta_before_class[ $class ] ); + unset( self::$meta_before_class[ $class ] ); + } + _delete_all_data(); self::flush_cache(); @@ -142,6 +162,8 @@ public function set_up() { $this->_backup_hooks(); } + $this->original_meta_state = self::backup_meta_state(); + $this->clean_up_global_scope(); $this->original_locale = $GLOBALS['locale'] ?? null; @@ -268,6 +290,9 @@ public function tear_down() { remove_filter( 'query', array( $this, '_drop_temporary_tables' ) ); remove_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) ); $this->_restore_hooks(); + if ( null !== $this->original_meta_state ) { + self::restore_meta_state( $this->original_meta_state ); + } wp_set_current_user( 0 ); // Restore the locale captured in set_up(); skip it for tests that bypass parent::set_up(). @@ -512,6 +537,57 @@ public static function flush_cache() { wp_cache_add_non_persistent_groups( array( 'counts', 'plugins', 'theme_json' ) ); } + /** + * Captures registrations and their hooks without re-registering metadata. + * + * The hooks also include legacy registrations without a registry entry and + * callbacks added independently of register_meta(). + * + * @return array Metadata registry and cloned metadata hooks. + */ + private static function backup_meta_state() { + $state = array( + 'keys' => $GLOBALS['wp_meta_keys'] ?? array(), + 'hooks' => array(), + ); + + foreach ( $GLOBALS['wp_filter'] as $name => $hook ) { + if ( self::is_meta_hook( $name ) ) { + $state['hooks'][ $name ] = clone $hook; + } + } + + return $state; + } + + /** + * Restores metadata hooks after the ordinary hook baseline has been restored. + * + * @param array $state Metadata state captured before the test or class. + */ + private static function restore_meta_state( $state ) { + $GLOBALS['wp_meta_keys'] = $state['keys']; + + foreach ( array_keys( $GLOBALS['wp_filter'] ) as $name ) { + if ( self::is_meta_hook( $name ) ) { + unset( $GLOBALS['wp_filter'][ $name ] ); + } + } + foreach ( $state['hooks'] as $name => $hook ) { + $GLOBALS['wp_filter'][ $name ] = clone $hook; + } + } + + /** + * Identifies the dynamic hooks used by metadata registrations and defaults. + * + * @param string $name Hook name. + * @return bool Whether the hook belongs to the metadata state. + */ + private static function is_meta_hook( $name ) { + return (bool) preg_match( '/^(?:sanitize|auth)_.+_meta_|^default_.+_metadata$/', $name ); + } + /** * Cleans up any registered meta keys. * diff --git a/tests/phpunit/tests/includes/registeredMeta.php b/tests/phpunit/tests/includes/registeredMeta.php new file mode 100644 index 0000000000000..53e6b3d23114a --- /dev/null +++ b/tests/phpunit/tests/includes/registeredMeta.php @@ -0,0 +1,212 @@ + $object_subtype, + 'single' => true, + 'default' => 'Original default', + 'sanitize_callback' => 'sanitize_text_field', + 'auth_callback' => '__return_true', + ); + register_meta( $object_type, $key, $args ); + $expected = get_registered_meta_keys( $object_type, $object_subtype )[ $key ]; + $case = $this->create_test_case(); + $class = get_class( $case ); + $class::set_up_before_class(); + + try { + $case->set_up(); + try { + if ( $unregister ) { + unregister_meta_key( $object_type, $key, $object_subtype ); + } else { + register_meta( + $object_type, + $key, + array_merge( + $args, + array( + 'default' => 'Changed default', + 'auth_callback' => '__return_false', + ) + ) + ); + } + register_meta( $object_type, '_test_temporary_meta', $args ); + } finally { + $case->tear_down(); + } + + $next_case = new $class( 'test_second' ); + $next_case->set_up(); + try { + $registered = get_registered_meta_keys( $object_type, $object_subtype ); + $this->assertArrayHasKey( $key, $registered ); + $this->assertSame( $expected, $registered[ $key ] ); + $this->assertSame( 'Example', sanitize_meta( $key, 'Example', $object_type, $object_subtype ) ); + $hook = "auth_{$object_type}_meta_{$key}"; + if ( $object_subtype ) { + $hook .= "_for_{$object_subtype}"; + } + $this->assertTrue( apply_filters( $hook, false, $key, 1, 1, 'edit_post_meta', array() ) ); + $this->assertFalse( registered_meta_key_exists( $object_type, '_test_temporary_meta', $object_subtype ) ); + } finally { + $next_case->tear_down(); + } + } finally { + $class::tear_down_after_class(); + } + } + + /** + * @return array[] + */ + public static function data_registered_metadata() { + // Each case boots WordPress separately. Cover the scopes and mutation modes + // without repeating their full cross-product in isolated processes. + return array( + 'post replaced' => array( 'post', '', false ), + 'post subtype removed' => array( 'post', 'page', true ), + 'term subtype replaced' => array( 'term', 'category', false ), + 'user removed' => array( 'user', '', true ), + ); + } + + public function test_restores_class_registrations_and_their_callbacks() { + // Capture the ordinary hook baseline before the class fixture exists. + $previous_case = $this->create_test_case(); + $previous_case->set_up(); + $previous_case->tear_down(); + + register_post_meta( 'post', '_test_plugin_meta', array( 'default' => 'Plugin default' ) ); + $case = new class( 'test_first' ) extends WP_UnitTestCase { + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { + register_post_meta( + 'post', + '_test_class_meta', + array( + 'default' => 'Class default', + 'sanitize_callback' => 'sanitize_text_field', + 'auth_callback' => '__return_true', + ) + ); + register_post_meta( 'post', '_test_plugin_meta', array( 'default' => 'Class override' ) ); + // Old-style registrations have callbacks but no registry entry. + register_meta( 'post', '_test_legacy_meta', 'sanitize_text_field' ); + } + + public function test_first() {} + public function test_second() {} + }; + $class = get_class( $case ); + $class::set_up_before_class(); + + try { + foreach ( array( $case, new $class( 'test_second' ) ) as $test_case ) { + $test_case->set_up(); + try { + $registered = get_registered_meta_keys( 'post', 'post' ); + $this->assertArrayHasKey( '_test_class_meta', $registered ); + $this->assertArrayHasKey( '_test_plugin_meta', $registered ); + $this->assertSame( 'Class default', $registered['_test_class_meta']['default'] ); + $this->assertSame( 'Class override', $registered['_test_plugin_meta']['default'] ); + $this->assertSame( 'Example', sanitize_meta( '_test_class_meta', 'Example', 'post', 'post' ) ); + $this->assertSame( 'Example', sanitize_meta( '_test_legacy_meta', 'Example', 'post' ) ); + unregister_post_meta( 'post', '_test_class_meta' ); + remove_filter( 'sanitize_post_meta__test_legacy_meta', 'sanitize_text_field' ); + } finally { + $test_case->tear_down(); + } + } + } finally { + $class::tear_down_after_class(); + } + + $this->assertFalse( registered_meta_key_exists( 'post', '_test_class_meta', 'post' ) ); + $registered = get_registered_meta_keys( 'post', 'post' ); + $this->assertArrayHasKey( '_test_plugin_meta', $registered ); + $this->assertSame( 'Plugin default', $registered['_test_plugin_meta']['default'] ); + $this->assertSame( 'Example', sanitize_meta( '_test_legacy_meta', 'Example', 'post' ) ); + $this->assertFalse( has_filter( 'sanitize_post_meta__test_class_meta_for_post' ) ); + } + + public function test_restores_defaults_sanitization_and_authorization_for_real_posts() { + register_post_meta( + 'post', + '_test_post_meta', + array( + 'single' => true, + 'default' => 'Original default', + 'sanitize_callback' => 'sanitize_text_field', + 'auth_callback' => '__return_true', + ) + ); + $case = new class( 'test_first' ) extends WP_UnitTestCase { + public static $author_id; + public static $post_id; + + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { + self::$author_id = $factory->user->create( array( 'role' => 'author' ) ); + self::$post_id = $factory->post->create( array( 'post_author' => self::$author_id ) ); + } + + public function test_first() {} + public function test_second() {} + }; + $class = get_class( $case ); + $class::set_up_before_class(); + + try { + foreach ( array( $case, new $class( 'test_second' ) ) as $test_case ) { + $test_case->set_up(); + try { + wp_set_current_user( $class::$author_id ); + $this->assertTrue( current_user_can( 'edit_post_meta', $class::$post_id, '_test_post_meta' ) ); + $this->assertSame( 'Original default', get_post_meta( $class::$post_id, '_test_post_meta', true ) ); + update_post_meta( $class::$post_id, '_test_post_meta', 'Example' ); + $this->assertSame( 'Example', get_post_meta( $class::$post_id, '_test_post_meta', true ) ); + register_post_meta( 'post', '_test_post_meta', array( 'auth_callback' => '__return_false' ) ); + $this->assertFalse( current_user_can( 'edit_post_meta', $class::$post_id, '_test_post_meta' ) ); + } finally { + $test_case->tear_down(); + } + } + } finally { + $class::tear_down_after_class(); + } + } + + /** + * Creates a test case with valid method names for the real setup routines. + * + * @return WP_UnitTestCase + */ + private function create_test_case() { + return new class( 'test_first' ) extends WP_UnitTestCase { + public function test_first() {} + public function test_second() {} + }; + } +} diff --git a/tests/phpunit/tests/meta/registerMeta.php b/tests/phpunit/tests/meta/registerMeta.php index 968ce82794525..d869fec493dd7 100644 --- a/tests/phpunit/tests/meta/registerMeta.php +++ b/tests/phpunit/tests/meta/registerMeta.php @@ -10,6 +10,13 @@ class Tests_Meta_Register_Meta extends WP_UnitTestCase { protected static $user_id; protected static $blog_id; + public function set_up() { + parent::set_up(); + + // These tests inspect the complete registry, independently of bootstrap registrations. + $this->unregister_all_meta_keys(); + } + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { self::$post_id = $factory->post->create( array( 'post_type' => 'page' ) ); self::$term_id = $factory->term->create( array( 'taxonomy' => 'category' ) ); diff --git a/tests/phpunit/tests/post/meta.php b/tests/phpunit/tests/post/meta.php index 9df764f148224..2a2ed65e7b138 100644 --- a/tests/phpunit/tests/post/meta.php +++ b/tests/phpunit/tests/post/meta.php @@ -16,6 +16,13 @@ class Tests_Post_Meta extends WP_UnitTestCase { protected static $post_id; protected static $post_id_2; + public function set_up() { + parent::set_up(); + + // These tests inspect the complete registry, independently of bootstrap registrations. + $this->unregister_all_meta_keys(); + } + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { self::$author = $factory->user->create_and_get( array( 'role' => 'editor' ) ); diff --git a/tests/phpunit/tests/term/meta.php b/tests/phpunit/tests/term/meta.php index 0f911f9766499..09923556e3de0 100644 --- a/tests/phpunit/tests/term/meta.php +++ b/tests/phpunit/tests/term/meta.php @@ -15,6 +15,9 @@ class Tests_Term_Meta extends WP_UnitTestCase { public function set_up() { parent::set_up(); + + // These tests inspect the complete registry, independently of bootstrap registrations. + $this->unregister_all_meta_keys(); register_taxonomy( 'wptests_tax', 'post' ); } From f53c7549aaae4ac7146053fd8600a8d89169df20 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 16:59:39 +0000 Subject: [PATCH 121/481] Tests: Make REST API data providers static. Declare the remaining 13 data providers in `tests/phpunit/tests/rest-api.php` as `public static` for PHPUnit compatibility. Preserve existing datasets and assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15299 Props rejaulalomkhan, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65127 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/rest-api.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php index f8494573f5126..dfa3bf1433b6b 100644 --- a/tests/phpunit/tests/rest-api.php +++ b/tests/phpunit/tests/rest-api.php @@ -991,7 +991,7 @@ public function test_jsonp_callback_check( $callback, $expected ) { $this->assertSame( $expected, wp_check_jsonp_callback( $callback ) ); } - public function data_jsonp_callback_check() { + public static function data_jsonp_callback_check() { return array( // Standard names. array( 'Springfield', true ), @@ -1016,7 +1016,7 @@ public function test_rest_parse_date( $date, $expected ) { $this->assertSame( $expected, rest_parse_date( $date ) ); } - public function data_rest_parse_date() { + public static function data_rest_parse_date() { return array( // Valid dates with timezones. array( '2017-01-16T11:30:00-05:00', gmmktime( 11, 30, 0, 1, 16, 2017 ) + 5 * HOUR_IN_SECONDS ), @@ -1048,7 +1048,7 @@ public function test_rest_parse_date_force_utc( $date, $expected ) { $this->assertSame( $expected, rest_parse_date( $date, true ) ); } - public function data_rest_parse_date_force_utc() { + public static function data_rest_parse_date_force_utc() { return array( // Valid dates with timezones. array( '2017-01-16T11:30:00-05:00', gmmktime( 11, 30, 0, 1, 16, 2017 ) ), @@ -1162,7 +1162,7 @@ public function test_rest_parse_embed_param( $expected, $embed ) { $this->assertSame( $expected, rest_parse_embed_param( $embed ) ); } - public function data_rest_parse_embed_param() { + public static function data_rest_parse_embed_param() { return array( array( true, '' ), array( true, null ), @@ -1280,7 +1280,7 @@ public function test_register_route_with_missing_permission_callback_multiple_wr $this->assertTrue( $registered ); } - public function data_rest_filter_response_by_context() { + public static function data_rest_filter_response_by_context() { return array( 'default' => array( array( @@ -1973,7 +1973,7 @@ public function test_rest_ensure_response_returns_instance_of_wp_rest_response( * * @return array */ - public function data_rest_ensure_response_returns_instance_of_wp_rest_response() { + public static function data_rest_ensure_response_returns_instance_of_wp_rest_response() { return array( array( null, null ), array( array( 'chocolate' => 'cookies' ), array( 'chocolate' => 'cookies' ) ), @@ -2198,7 +2198,7 @@ public function test_rest_is_object( $expected, $value ) { } } - public function data_rest_is_object() { + public static function data_rest_is_object() { return array( array( true, @@ -2256,7 +2256,7 @@ public function test_rest_sanitize_object( $expected, $value ) { $this->assertSame( $expected, $sanitized ); } - public function data_rest_sanitize_object() { + public static function data_rest_sanitize_object() { return array( array( array(), @@ -2319,7 +2319,7 @@ public function test_rest_is_array( $expected, $value ) { } } - public function data_rest_is_array() { + public static function data_rest_is_array() { return array( array( true, @@ -2385,7 +2385,7 @@ public function test_rest_sanitize_array( $expected, $value ) { $this->assertSame( $expected, $sanitized ); } - public function data_rest_sanitize_array() { + public static function data_rest_sanitize_array() { return array( array( array(), @@ -2502,7 +2502,7 @@ public function test_rest_is_integer( bool $expected_is_integer, $value, ?int $e * 2?: int, // $expected_sanitized * }> */ - public function data_rest_is_integer(): array { + public static function data_rest_is_integer(): array { return array( array( true, @@ -2720,7 +2720,7 @@ public function test_get_best_type_for_value( $expected, $value, $types ) { $this->assertSame( $expected, rest_get_best_type_for_value( $value, $types ) ); } - public function data_get_best_type_for_value() { + public static function data_get_best_type_for_value() { return array( array( 'array', @@ -2856,7 +2856,7 @@ public function test_rest_preload_api_request_embeds_links( $embed, $expected, $ } } - public function data_rest_preload_api_request_embeds_links() { + public static function data_rest_preload_api_request_embeds_links() { return array( array( '_embed=wp:term,author', array( 'wp:term', 'author' ), array( 'replies' ) ), array( '_embed[]=wp:term&_embed[]=author', array( 'wp:term', 'author' ), array( 'replies' ) ), From 36d9aa8fac6c10ab5a3258ed7a61288a961cc94e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:02:37 +0000 Subject: [PATCH 122/481] Tests: Make block and pluggable data providers static. Convert the remaining providers and fixture callbacks to static methods. Preserve datasets, expectations, and the already-landed provider cleanup. Developed in: https://github.com/WordPress/wordpress-develop/pull/14970, https://github.com/WordPress/wordpress-develop/pull/15176, https://github.com/WordPress/wordpress-develop/pull/15180 Props rejaulalomkhan, shailu25, mukesh27. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65128 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/block-bindings/patternOverridesSource.php | 4 ++-- tests/phpunit/tests/blocks/editor.php | 4 ++-- tests/phpunit/tests/blocks/render.php | 10 +++++----- tests/phpunit/tests/blocks/supportedStyles.php | 2 +- tests/phpunit/tests/blocks/wpBlock.php | 4 ++-- tests/phpunit/tests/blocks/wpBlockParser.php | 10 +++++----- tests/phpunit/tests/blocks/wpBlockType.php | 2 +- tests/phpunit/tests/pluggable/signatures.php | 4 ++-- tests/phpunit/tests/pluggable/wpRand.php | 4 ++-- 9 files changed, 22 insertions(+), 22 deletions(-) diff --git a/tests/phpunit/tests/block-bindings/patternOverridesSource.php b/tests/phpunit/tests/block-bindings/patternOverridesSource.php index b24946e4b7e05..233e2758d656a 100644 --- a/tests/phpunit/tests/block-bindings/patternOverridesSource.php +++ b/tests/phpunit/tests/block-bindings/patternOverridesSource.php @@ -79,7 +79,7 @@ public function test_get_value_returns_null_when_metadata_name_empty( array $att * * @return array[] */ - public function data_empty_metadata_names() { + public static function data_empty_metadata_names() { return array( 'empty attributes' => array( array() ), 'empty metadata array' => array( array( 'metadata' => array() ) ), @@ -224,7 +224,7 @@ public function test_get_value_handles_different_data_types( $expected ) { * * @return array[] */ - public function data_override_values_and_types() { + public static function data_override_values_and_types() { return array( 'empty string' => array( '' ), 'zero integer' => array( 0 ), diff --git a/tests/phpunit/tests/blocks/editor.php b/tests/phpunit/tests/blocks/editor.php index c5755ff434b82..5055aab4d999e 100644 --- a/tests/phpunit/tests/blocks/editor.php +++ b/tests/phpunit/tests/blocks/editor.php @@ -375,7 +375,7 @@ public function test_get_default_block_editor_settings_auto_attach_media_enabled * * @return array[] */ - public function data_get_default_block_editor_settings_auto_attach_media_enabled() { + public static function data_get_default_block_editor_settings_auto_attach_media_enabled() { return array( 'attachment pages disabled' => array( 0, true ), 'attachment pages enabled' => array( 1, false ), @@ -831,7 +831,7 @@ public function test_get_classic_theme_supports_block_editor_settings() { * * @return array */ - public function data_block_editor_rest_api_preload_adds_missing_leading_slash() { + public static function data_block_editor_rest_api_preload_adds_missing_leading_slash() { return array( 'a string without a slash' => array( 'preload_paths' => array( 'wp/v2/blocks' ), diff --git a/tests/phpunit/tests/blocks/render.php b/tests/phpunit/tests/blocks/render.php index 7b20dac147601..7791c7d7c94e7 100644 --- a/tests/phpunit/tests/blocks/render.php +++ b/tests/phpunit/tests/blocks/render.php @@ -183,7 +183,7 @@ public function test_blocks_arent_autopeed() { /** * @ticket 45109 */ - public function data_do_block_test_filenames() { + public static function data_do_block_test_filenames() { self::$fixtures_dir = DIR_TESTDATA . '/blocks/fixtures'; $fixture_filenames = array_merge( @@ -194,14 +194,14 @@ public function data_do_block_test_filenames() { $fixture_filenames = array_values( array_unique( array_map( - array( $this, 'clean_fixture_filename' ), + array( __CLASS__, 'clean_fixture_filename' ), $fixture_filenames ) ) ); return array_map( - array( $this, 'pass_parser_fixture_filenames' ), + array( __CLASS__, 'pass_parser_fixture_filenames' ), $fixture_filenames ); } @@ -476,7 +476,7 @@ public function test_dynamic_block_gets_rendered_inner_dynamic_blocks() { * @param string $filename The filename to clean. * @return string The cleaned fixture name. */ - protected function clean_fixture_filename( $filename ) { + protected static function clean_fixture_filename( $filename ) { $filename = wp_basename( $filename ); $filename = preg_replace( '/\..+$/', '', $filename ); return $filename; @@ -490,7 +490,7 @@ protected function clean_fixture_filename( $filename ) { * @param string $filename The cleaned fixture name. * @return array The input and expected output filenames for that fixture. */ - protected function pass_parser_fixture_filenames( $filename ) { + protected static function pass_parser_fixture_filenames( $filename ) { return array( "$filename.html", "$filename.server.html", diff --git a/tests/phpunit/tests/blocks/supportedStyles.php b/tests/phpunit/tests/blocks/supportedStyles.php index a6fd8b598a28f..6f7d11bdc015a 100644 --- a/tests/phpunit/tests/blocks/supportedStyles.php +++ b/tests/phpunit/tests/blocks/supportedStyles.php @@ -800,7 +800,7 @@ public function test_get_block_wrapper_attributes_merge_and_override( array $blo * expected_attribute: string * }> Array of test cases. */ - public function data_get_block_wrapper_attributes_merge_or_override(): array { + public static function data_get_block_wrapper_attributes_merge_or_override(): array { return array( 'extra style attributes are merged with block values' => array( 'block_type_settings' => array( diff --git a/tests/phpunit/tests/blocks/wpBlock.php b/tests/phpunit/tests/blocks/wpBlock.php index ab75616a7ec3a..3095400b9262c 100644 --- a/tests/phpunit/tests/blocks/wpBlock.php +++ b/tests/phpunit/tests/blocks/wpBlock.php @@ -365,7 +365,7 @@ public function test_render_applies_dynamic_render_block_filter() { * * @return array */ - public function data_provider_test_render_enqueues_scripts_and_styles(): array { + public static function data_provider_test_render_enqueues_scripts_and_styles(): array { $block_markup = <<<'HTML'
@@ -1508,7 +1508,7 @@ public function test_block_has_support_string( $block_data, $support, $expected, /** * Data provider for test_block_has_support_string */ - public function data_block_has_support_string() { + public static function data_block_has_support_string() { return array( array( array(), diff --git a/tests/phpunit/tests/blocks/wpBlockParser.php b/tests/phpunit/tests/blocks/wpBlockParser.php index e9cc62bcf5d62..07fdb556efcc4 100644 --- a/tests/phpunit/tests/blocks/wpBlockParser.php +++ b/tests/phpunit/tests/blocks/wpBlockParser.php @@ -156,7 +156,7 @@ public function test_default_parser_output( $html_filename, $parsed_json_filenam /** * @ticket 45109 */ - public function data_parsing_test_filenames() { + public static function data_parsing_test_filenames() { self::$fixtures_dir = DIR_TESTDATA . '/blocks/fixtures'; $fixture_filenames = array_merge( @@ -167,14 +167,14 @@ public function data_parsing_test_filenames() { $fixture_filenames = array_values( array_unique( array_map( - array( $this, 'clean_fixture_filename' ), + array( __CLASS__, 'clean_fixture_filename' ), $fixture_filenames ) ) ); return array_map( - array( $this, 'pass_parser_fixture_filenames' ), + array( __CLASS__, 'pass_parser_fixture_filenames' ), $fixture_filenames ); } @@ -187,7 +187,7 @@ public function data_parsing_test_filenames() { * @param string $filename The filename to clean. * @return string The cleaned fixture name. */ - protected function clean_fixture_filename( $filename ) { + protected static function clean_fixture_filename( $filename ) { $filename = wp_basename( $filename ); $filename = preg_replace( '/\..+$/', '', $filename ); return $filename; @@ -201,7 +201,7 @@ protected function clean_fixture_filename( $filename ) { * @param string $filename The cleaned fixture name. * @return array The input and expected output filenames for that fixture. */ - protected function pass_parser_fixture_filenames( $filename ) { + protected static function pass_parser_fixture_filenames( $filename ) { return array( "$filename.html", "$filename.parsed.json", diff --git a/tests/phpunit/tests/blocks/wpBlockType.php b/tests/phpunit/tests/blocks/wpBlockType.php index 95e6ddbb51a33..a87c5973d13e3 100644 --- a/tests/phpunit/tests/blocks/wpBlockType.php +++ b/tests/phpunit/tests/blocks/wpBlockType.php @@ -444,7 +444,7 @@ public function test_block_version( $content, $expected ) { * } * } */ - public function data_block_version() { + public static function data_block_version() { return array( // Null. array( null, 0 ), diff --git a/tests/phpunit/tests/pluggable/signatures.php b/tests/phpunit/tests/pluggable/signatures.php index 68b511b9d0d2d..1fa54ef7d0ad0 100644 --- a/tests/phpunit/tests/pluggable/signatures.php +++ b/tests/phpunit/tests/pluggable/signatures.php @@ -57,7 +57,7 @@ public function test_pluggable_function_signatures_match( $function_name ) { */ public function test_all_pluggable_functions_exist() { - $defined = wp_list_pluck( $this->get_defined_pluggable_functions(), 0 ); + $defined = wp_list_pluck( self::get_defined_pluggable_functions(), 0 ); $expected = $this->get_pluggable_function_signatures(); foreach ( $expected as $function => $sig ) { @@ -72,7 +72,7 @@ public function test_all_pluggable_functions_exist() { * * @return array Data provider array of pluggable function names. */ - public function get_defined_pluggable_functions() { + public static function get_defined_pluggable_functions() { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; diff --git a/tests/phpunit/tests/pluggable/wpRand.php b/tests/phpunit/tests/pluggable/wpRand.php index a6bcf347f85f3..0d97c7bd2055b 100644 --- a/tests/phpunit/tests/pluggable/wpRand.php +++ b/tests/phpunit/tests/pluggable/wpRand.php @@ -35,7 +35,7 @@ public function test_wp_rand_should_return_a_non_negative_integer( $min, $max ) * * @return array */ - public function data_wp_rand_should_return_a_non_negative_integer() { + public static function data_wp_rand_should_return_a_non_negative_integer() { return array( '1 and 99' => array( 'min' => 1, @@ -82,7 +82,7 @@ public function test_wp_rand_should_return_zero_when_min_and_max_are_zero( $min, * * @return array */ - public function data_wp_rand_should_return_zero_when_min_and_max_are_zero() { + public static function data_wp_rand_should_return_zero_when_min_and_max_are_zero() { return array( 'min and max as 0' => array( 'min' => 0, From c43a229f69f229674bf3bae795a66edf63898c08 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:03:31 +0000 Subject: [PATCH 123/481] Tests: Cover REST color parsing and avatar sizes. Verify accepted and rejected hexadecimal colors, and filtered avatar sizes and their URL parameters. Developed in: https://github.com/WordPress/wordpress-develop/pull/15244, https://github.com/WordPress/wordpress-develop/pull/15250 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65129 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/restGetAvatarSizes.php | 47 ++++++++++++++ .../tests/rest-api/restParseHexColor.php | 62 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restGetAvatarSizes.php create mode 100644 tests/phpunit/tests/rest-api/restParseHexColor.php diff --git a/tests/phpunit/tests/rest-api/restGetAvatarSizes.php b/tests/phpunit/tests/rest-api/restGetAvatarSizes.php new file mode 100644 index 0000000000000..e0ea0b8012772 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restGetAvatarSizes.php @@ -0,0 +1,47 @@ +assertSame( array( 32, 64 ), array_keys( $urls ) ); + + foreach ( array( 32, 64 ) as $size ) { + $this->assertStringContainsString( + 'https://secure.gravatar.com/avatar/' . $hash, + $urls[ $size ], + "Avatar URL for size {$size} should include the Gravatar path for the email." + ); + + $query = array(); + wp_parse_str( wp_parse_url( $urls[ $size ], PHP_URL_QUERY ), $query ); + + $this->assertSame( + (string) $size, + $query['s'] ?? null, + "Avatar URL for size {$size} should request that exact pixel size." + ); + } + } +} diff --git a/tests/phpunit/tests/rest-api/restParseHexColor.php b/tests/phpunit/tests/rest-api/restParseHexColor.php new file mode 100644 index 0000000000000..e2dc0ffc28634 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restParseHexColor.php @@ -0,0 +1,62 @@ +assertSame( $color, rest_parse_hex_color( $color ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_valid_hex_colors() { + return array( + '3-digit mixed case' => array( '#aBc' ), + '6-digit mixed case' => array( '#aBcDeF' ), + ); + } + + /** + * Tests that invalid color values return false. + * + * @ticket 65819 + * + * @dataProvider data_invalid_hex_colors + * + * @param mixed $color Invalid color value. + */ + public function test_returns_false_for_invalid_hex_color( $color ) { + $this->assertFalse( rest_parse_hex_color( $color ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_invalid_hex_colors() { + return array( + 'missing hash' => array( 'abcdef' ), + 'unsupported length' => array( '#ab' ), + 'non-hex characters' => array( '#ggg' ), + ); + } +} From e7ee7007ca7069ace928f522609152ea3adaaf8c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:07:11 +0000 Subject: [PATCH 124/481] Tests: Cover the MediaElement fallback output. Verify escaped fallback links and the output filter in `wp_mediaelement_fallback()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15248 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65130 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/media/wpMediaelementFallback.php | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tests/phpunit/tests/media/wpMediaelementFallback.php diff --git a/tests/phpunit/tests/media/wpMediaelementFallback.php b/tests/phpunit/tests/media/wpMediaelementFallback.php new file mode 100644 index 0000000000000..308283261c7b2 --- /dev/null +++ b/tests/phpunit/tests/media/wpMediaelementFallback.php @@ -0,0 +1,62 @@ +assertSame( + 'https://example.com/audio.mp3', + wp_mediaelement_fallback( $url ) + ); + } + + /** + * @ticket 65819 + */ + public function test_escapes_url_in_markup() { + $url = 'https://example.com/audio.mp3?foo=1&bar=2">'; + + $this->assertSame( + 'https://example.com/audio.mp3?foo=1&bar=2scriptalert(1)/script', + wp_mediaelement_fallback( $url ) + ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_generated_output_and_url_and_can_replace_output() { + $url = 'https://example.com/audio.mp3?foo=1&bar=2'; + $received_args = array(); + + add_filter( + 'wp_mediaelement_fallback', + static function ( $output, $media_url ) use ( &$received_args ) { + $received_args = array( $output, $media_url ); + return 'filtered-fallback'; + }, + 10, + 2 + ); + + $this->assertSame( 'filtered-fallback', wp_mediaelement_fallback( $url ) ); + $this->assertSame( + array( + 'https://example.com/audio.mp3?foo=1&bar=2', + $url, + ), + $received_args + ); + } +} From 0650e513124c27702bd9f83f4f45a9ccf92407a3 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:08:45 +0000 Subject: [PATCH 125/481] Tests: Cover comment types and author IP output. Verify comment-type normalization, global comment lookup, filters, and escaped author IP output. Developed in: https://github.com/WordPress/wordpress-develop/pull/15253, https://github.com/WordPress/wordpress-develop/pull/15254 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65131 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/comment/getCommentAuthorIP.php | 76 ++++++++++ .../phpunit/tests/comment/getCommentType.php | 143 ++++++++++++++++++ 2 files changed, 219 insertions(+) create mode 100644 tests/phpunit/tests/comment/getCommentAuthorIP.php create mode 100644 tests/phpunit/tests/comment/getCommentType.php diff --git a/tests/phpunit/tests/comment/getCommentAuthorIP.php b/tests/phpunit/tests/comment/getCommentAuthorIP.php new file mode 100644 index 0000000000000..9e7e3b8f907be --- /dev/null +++ b/tests/phpunit/tests/comment/getCommentAuthorIP.php @@ -0,0 +1,76 @@ +post->create(); + self::$comment = $factory->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author_IP' => '192.0.2.10', + ) + ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_IP + */ + public function test_returns_comment_author_ip() { + $this->assertSame( '192.0.2.10', get_comment_author_IP( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_IP + */ + public function test_filter_can_modify_ip() { + add_filter( + 'get_comment_author_IP', + static function () { + return '203.0.113.5'; + } + ); + + $this->assertSame( '203.0.113.5', get_comment_author_IP( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_author_IP + * @covers ::get_comment_author_IP + */ + public function test_comment_author_ip_echoes_escaped_value() { + add_filter( + 'get_comment_author_IP', + static function () { + return '192.0.2.10'; + } + ); + + $this->expectOutputString( '<b>192.0.2.10</b>' ); + comment_author_IP( self::$comment->comment_ID ); + } +} diff --git a/tests/phpunit/tests/comment/getCommentType.php b/tests/phpunit/tests/comment/getCommentType.php new file mode 100644 index 0000000000000..22d65f579e9f4 --- /dev/null +++ b/tests/phpunit/tests/comment/getCommentType.php @@ -0,0 +1,143 @@ +post->create(); + } + + public function tear_down() { + unset( $GLOBALS['comment'] ); + parent::tear_down(); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_type + */ + public function test_empty_type_normalizes_to_comment() { + $comment = self::factory()->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => 'pingback', + ) + ); + + // Bypass wp_insert_comment() normalization so get_comment_type() is exercised. + $comment->comment_type = ''; + + $this->assertSame( 'comment', get_comment_type( $comment ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_type + */ + public function test_filter_can_modify_comment_type() { + $comment_id = self::factory()->comment->create( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => 'comment', + ) + ); + + add_filter( + 'get_comment_type', + static function () { + return 'filtered-type'; + } + ); + + $this->assertSame( 'filtered-type', get_comment_type( $comment_id ) ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_type + * @covers ::get_comment_type + * + * @dataProvider data_default_labels + * + * @param string $comment_type Comment type fixture. + * @param string $expected Expected echoed label. + */ + public function test_comment_type_echoes_default_labels( $comment_type, $expected ) { + $comment = self::factory()->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => $comment_type, + ) + ); + + $GLOBALS['comment'] = $comment; + + $this->expectOutputString( $expected ); + comment_type(); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_default_labels() { + return array( + 'comment' => array( 'comment', 'Comment' ), + 'pingback' => array( 'pingback', 'Pingback' ), + 'trackback' => array( 'trackback', 'Trackback' ), + ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_type + * @covers ::get_comment_type + * + * @dataProvider data_custom_labels + * + * @param string $comment_type Comment type fixture. + * @param string $expected Expected echoed label. + */ + public function test_comment_type_echoes_custom_labels( $comment_type, $expected ) { + $comment = self::factory()->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_type' => $comment_type, + ) + ); + + $GLOBALS['comment'] = $comment; + + $this->expectOutputString( $expected ); + comment_type( 'Custom Comment', 'Custom Trackback', 'Custom Pingback' ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_custom_labels() { + return array( + 'comment' => array( 'comment', 'Custom Comment' ), + 'pingback' => array( 'pingback', 'Custom Pingback' ), + 'trackback' => array( 'trackback', 'Custom Trackback' ), + ); + } +} From 8f0d05348d344e353250b07313694abead41c28e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:11:54 +0000 Subject: [PATCH 126/481] Tests: Cover canonical redirect regressions. Verify encoded query keys on a static front page and prevent redirect guesses from exposing a private post type mixed with a public one. Developed in: https://github.com/WordPress/wordpress-develop/pull/13654, https://github.com/WordPress/wordpress-develop/pull/12941 Props faisalahammad, huzaifaalmesbah, irozum. See #44899, #44964. git-svn-id: https://develop.svn.wordpress.org/trunk@65132 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/canonical.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/phpunit/tests/canonical.php b/tests/phpunit/tests/canonical.php index 55e6bdd873f11..06379361887c2 100644 --- a/tests/phpunit/tests/canonical.php +++ b/tests/phpunit/tests/canonical.php @@ -396,6 +396,7 @@ public static function data_redirect_guess_404_permalink_with_custom_statuses() * * @ticket 43056 * @ticket 59795 + * @ticket 44964 * * @dataProvider data_redirect_guess_404_permalink_post_types */ @@ -431,6 +432,10 @@ public static function data_redirect_guess_404_permalink_post_types() { 'original_url' => '/?name=private-cpt-po&post_type[]=wp_tests_private', 'expected' => '/?name=private-cpt-po&post_type[]=wp_tests_private', ), + 'do not leak private post type mixed in with a public one' => array( + 'original_url' => '/?name=private-cpt-po&post_type[]=page&post_type[]=wp_tests_private', + 'expected' => '/?name=private-cpt-po&post_type[]=page&post_type[]=wp_tests_private', + ), ); } @@ -614,6 +619,30 @@ public function test_utf8_query_keys_canonical() { $this->assertNull( $redirect ); } + /** + * Ensure encoded query string keys do not trigger a redirect on the front page. + * + * @ticket 44899 + */ + public function test_encoded_query_string_keys_on_front_page() { + $p = self::factory()->post->create( + array( + 'post_type' => 'page', + ) + ); + update_option( 'show_on_front', 'page' ); + update_option( 'page_on_front', $p ); + + $this->go_to( get_permalink( $p ) ); + + $url = site_url( '/?xtor=AD-4970-%5BSocial%5D-%5B%5D-%5BPPL%5D-%5BFacebook%5D-%5B228284160&105478095%5D-%5B0%5D' ); + $redirect = redirect_canonical( $url, false ); + + delete_option( 'page_on_front' ); + + $this->assertNull( $redirect ); + } + /** * Ensure NOT EXISTS queries do not trigger not-countable or undefined array key errors. * From 05b0971dcc755603b02ea6497582dee831d9e387 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 17:12:56 +0000 Subject: [PATCH 127/481] Tests: Cover serialization of queued attribute updates. Verify that `WP_HTML_Processor::serialize_token()` reflects attribute additions and removals before the updated HTML is retrieved. Developed in: https://github.com/WordPress/wordpress-develop/pull/12947 Props motylanogha, irozum. See #64567. git-svn-id: https://develop.svn.wordpress.org/trunk@65133 602fd350-edb4-49c9-b593-d223f7449a82 --- .../html-api/wpHtmlProcessor-serialize.php | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/phpunit/tests/html-api/wpHtmlProcessor-serialize.php b/tests/phpunit/tests/html-api/wpHtmlProcessor-serialize.php index 6617d691224ab..3fd234b56785c 100644 --- a/tests/phpunit/tests/html-api/wpHtmlProcessor-serialize.php +++ b/tests/phpunit/tests/html-api/wpHtmlProcessor-serialize.php @@ -853,4 +853,39 @@ public static function data_provider_normalize_special_leading_newline_cases(): ), ); } + + /** + * Ensures that serialize_token() reflects enqueued attribute updates instead + * of emitting removed attributes as value-less attributes or omitting added ones. + * + * serialize_token() iterates the names from get_attribute_names_with_prefix( '' ) + * but reads each value through get_attribute(). Before #64567 the name list did not + * reflect enqueued updates while the values did, so a removed attribute survived in + * the output as a boolean attribute and an added attribute was dropped entirely. + * + * @ticket 64567 + * + * @covers WP_HTML_Processor::serialize_token + */ + public function test_serialize_token_reflects_enqueued_attribute_updates() { + $processor = WP_HTML_Processor::create_fragment( '
Text
' ); + $processor->next_tag(); + $processor->remove_attribute( 'onclick' ); + + $this->assertSame( + '
', + $processor->serialize_token(), + 'An attribute enqueued for removal was serialized as a value-less attribute.' + ); + + $processor = WP_HTML_Processor::create_fragment( '
Text
' ); + $processor->next_tag(); + $processor->set_attribute( 'id', 'new' ); + + $this->assertSame( + '
', + $processor->serialize_token(), + 'An attribute enqueued via set_attribute() was not serialized. A newly added attribute is emitted before the existing ones.' + ); + } } From bc8d7f7cdaf96083e3293cdd482d454ab69c06df Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 18:18:06 +0000 Subject: [PATCH 128/481] Build/Test Tools: Update the performance test baseline to 7.1. Use WordPress 7.1 as the default release baseline for performance comparisons by updating `BASE_TAG` to `7.1.0`. Developed in: https://github.com/WordPress/wordpress-develop/pull/13154 Props desrosj. See #65845. git-svn-id: https://develop.svn.wordpress.org/trunk@65134 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/reusable-performance-test-v2.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-performance-test-v2.yml b/.github/workflows/reusable-performance-test-v2.yml index bc40646871e0d..a4a9021510c1c 100644 --- a/.github/workflows/reusable-performance-test-v2.yml +++ b/.github/workflows/reusable-performance-test-v2.yml @@ -21,7 +21,7 @@ on: description: 'The version being used for baseline measurements.' required: false type: 'string' - default: '7.0.0' + default: '7.1.0' TARGET_SHA: description: 'SHA hash of the target commit used for "before" measurements.' required: true From 236bbaa84d689afa79ae8c57f52cf8007300c943 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 18:29:38 +0000 Subject: [PATCH 129/481] Docs: Correct wording in contributor documentation. Correct hyphenation and clarify configuration and QUnit build instructions in `README.md`. Add the missing preposition in `.github/pull_request_template.md`. Developed in: https://github.com/WordPress/wordpress-develop/pull/10749, https://github.com/WordPress/wordpress-develop/pull/14293 Props jenish1234. Unlinked contributors: Abhishek Mane (abhishekmanegit). Fixes #66431. git-svn-id: https://develop.svn.wordpress.org/trunk@65135 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/pull_request_template.md | 2 +- README.md | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b8bcf4f4eff2c..1fe1d87fc130f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,7 +3,7 @@ Hi there! Thanks for contributing to WordPress! Pull Requests in this GitHub repository **must** be linked to a ticket in the WordPress Core Trac instance (https://core.trac.wordpress.org), and are only used for code review. **No pull requests will be merged on GitHub.** -See the WordPress Handbook page on using PRs for Code Review more information: https://make.wordpress.org/core/handbook/contribute/git/github-pull-requests-for-code-review/ +See the WordPress Handbook page on using PRs for Code Review for more information: https://make.wordpress.org/core/handbook/contribute/git/github-pull-requests-for-code-review/ If this is your first time contributing, you may also find reviewing these guides first to be helpful: - FAQs for New Contributors: https://make.wordpress.org/core/handbook/tutorials/faq-for-new-contributors/ diff --git a/README.md b/README.md index 0e2f34af366b7..637e24359f034 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Welcome to the WordPress development repository! Please check out the [contribut ### Local development -WordPress is a PHP, MySQL, and JavaScript based project, and uses Node for its JavaScript dependencies. A local development environment is available to quickly get up and running. +WordPress is a PHP, MySQL, and JavaScript-based project, and uses Node for its JavaScript dependencies. A local development environment is available to quickly get up and running. You will need a basic understanding of how to use the command line on your computer. This will allow you to set up the local development environment, to start it and stop it when necessary, and to run the tests. @@ -64,8 +64,7 @@ npm run build:dev npm run env:start npm run env:install ``` - -Your WordPress site will be accessible at http://localhost:8889. You can see or change configurations in the `.env` file located at the root of the project directory. +Your WordPress site will be accessible at http://localhost:8889. You can view or change the configuration settings in the `.env` file located in the root directory of the project. #### To watch for changes @@ -111,10 +110,7 @@ To run the JavaScript (QUnit) tests: npm run grunt qunit:compiled ``` -`qunit:compiled` builds first, then runs the suite. The QUnit runner loads -scripts from the built `build/` directory, so a plain `npm run grunt qunit` -requires a completed `npm run build` first without a build, every test fails -with a `jQuery is not defined` error. +`qunit:compiled` builds first, then runs the suite. The QUnit runner loads scripts from the built `build/` directory, so a plain `npm run grunt qunit` requires a completed `npm run build` first; without a build, every test fails with a `jQuery is not defined` error. #### To lint the workflow files From b10c5714bda2c35c42c8f999f23df9f6b649beac Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:00:04 +0000 Subject: [PATCH 130/481] Tests: Cover REST IP address helper return values. Verify that `rest_is_ip_address()` returns valid IPv4 and IPv6 addresses unchanged and returns `false` for invalid addresses. Developed in: https://github.com/WordPress/wordpress-develop/pull/15271 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65136 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/restIsIpAddress.php | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restIsIpAddress.php diff --git a/tests/phpunit/tests/rest-api/restIsIpAddress.php b/tests/phpunit/tests/rest-api/restIsIpAddress.php new file mode 100644 index 0000000000000..765a68ff88c67 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restIsIpAddress.php @@ -0,0 +1,62 @@ +assertSame( $ip, rest_is_ip_address( $ip ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_valid_ip_addresses() { + return array( + 'ipv4' => array( '192.0.2.10' ), + 'ipv6' => array( '2001:db8::1' ), + ); + } + + /** + * Tests that invalid IP values return false. + * + * @ticket 65819 + * + * @dataProvider data_invalid_ip_addresses + * + * @param mixed $ip Invalid IP value. + */ + public function test_returns_false_for_invalid_ip_address( $ip ) { + $this->assertFalse( rest_is_ip_address( $ip ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_invalid_ip_addresses() { + return array( + 'empty string' => array( '' ), + 'out of range ipv4' => array( '256.0.0.1' ), + 'hostname' => array( 'example.com' ), + ); + } +} From 476aabf9565668986aa8377275df605fe2ba7e30 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:01:09 +0000 Subject: [PATCH 131/481] Tests: Cover comment author and ID helper output. Verify comment email, URL, and ID retrieval and display, including global comment handling and filtered output. Developed in: https://github.com/WordPress/wordpress-develop/pull/15274, https://github.com/WordPress/wordpress-develop/pull/15276, https://github.com/WordPress/wordpress-develop/pull/15280 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65137 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/comment/commentAuthorUrl.php | 118 +++++++++++++++++ .../tests/comment/getCommentAuthorEmail.php | 119 ++++++++++++++++++ tests/phpunit/tests/comment/getCommentID.php | 90 +++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 tests/phpunit/tests/comment/commentAuthorUrl.php create mode 100644 tests/phpunit/tests/comment/getCommentAuthorEmail.php create mode 100644 tests/phpunit/tests/comment/getCommentID.php diff --git a/tests/phpunit/tests/comment/commentAuthorUrl.php b/tests/phpunit/tests/comment/commentAuthorUrl.php new file mode 100644 index 0000000000000..91b65f9e02626 --- /dev/null +++ b/tests/phpunit/tests/comment/commentAuthorUrl.php @@ -0,0 +1,118 @@ +post->create(); + self::$comment = $factory->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author_url' => 'https://example.com/author', + ) + ); + } + + public function tear_down() { + unset( $GLOBALS['comment'] ); + parent::tear_down(); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_url + */ + public function test_returns_comment_author_url() { + $this->assertSame( 'https://example.com/author', get_comment_author_url( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_url + */ + public function test_accepts_comment_object() { + $this->assertSame( 'https://example.com/author', get_comment_author_url( self::$comment ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_url + */ + public function test_uses_global_comment_when_unspecified() { + $GLOBALS['comment'] = self::$comment; + + $this->assertSame( 'https://example.com/author', get_comment_author_url() ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_url + */ + public function test_returns_empty_string_when_url_missing() { + $comment_id = self::factory()->comment->create( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author_url' => '', + ) + ); + + $this->assertSame( '', get_comment_author_url( $comment_id ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_url + */ + public function test_filter_can_modify_url() { + add_filter( + 'get_comment_author_url', + static function () { + return 'https://filtered.example.com'; + } + ); + + $this->assertSame( 'https://filtered.example.com', get_comment_author_url( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_author_url + * @covers ::get_comment_author_url + */ + public function test_comment_author_url_echoes_value() { + add_filter( + 'comment_url', + function ( $url ) { + $this->assertSame( 'https://example.com/author', $url ); + return 'https://display.example.com'; + } + ); + + $this->expectOutputString( 'https://display.example.com' ); + comment_author_url( self::$comment->comment_ID ); + } +} diff --git a/tests/phpunit/tests/comment/getCommentAuthorEmail.php b/tests/phpunit/tests/comment/getCommentAuthorEmail.php new file mode 100644 index 0000000000000..76c9690dfe2c7 --- /dev/null +++ b/tests/phpunit/tests/comment/getCommentAuthorEmail.php @@ -0,0 +1,119 @@ +post->create(); + self::$comment = $factory->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author_email' => 'author@example.com', + ) + ); + } + + public function tear_down() { + unset( $GLOBALS['comment'] ); + parent::tear_down(); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_email + */ + public function test_returns_comment_author_email() { + $this->assertSame( 'author@example.com', get_comment_author_email( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_email + */ + public function test_accepts_comment_object() { + $this->assertSame( 'author@example.com', get_comment_author_email( self::$comment ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_email + */ + public function test_uses_global_comment_when_unspecified() { + $GLOBALS['comment'] = self::$comment; + + $this->assertSame( 'author@example.com', get_comment_author_email() ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_email + */ + public function test_returns_empty_string_when_email_missing() { + $comment_id = self::factory()->comment->create( + array( + 'comment_post_ID' => self::$post_id, + 'comment_author_email' => '', + ) + ); + + $this->assertSame( '', get_comment_author_email( $comment_id ) ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_author_email + */ + public function test_filter_can_modify_email() { + add_filter( + 'get_comment_author_email', + static function () { + return 'filtered@example.com'; + } + ); + + $this->assertSame( 'filtered@example.com', get_comment_author_email( self::$comment->comment_ID ) ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_author_email + * @covers ::get_comment_author_email + */ + public function test_comment_author_email_echoes_value() { + add_filter( + 'author_email', + function ( $email ) { + $this->assertSame( 'author@example.com', $email ); + + return 'display@example.com'; + } + ); + + $this->expectOutputString( 'display@example.com' ); + comment_author_email( self::$comment->comment_ID ); + } +} diff --git a/tests/phpunit/tests/comment/getCommentID.php b/tests/phpunit/tests/comment/getCommentID.php new file mode 100644 index 0000000000000..dee77be1b535c --- /dev/null +++ b/tests/phpunit/tests/comment/getCommentID.php @@ -0,0 +1,90 @@ +post->create(); + self::$comment = $factory->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + ) + ); + } + + public function tear_down() { + unset( $GLOBALS['comment'] ); + parent::tear_down(); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_ID + */ + public function test_returns_comment_id_from_global_comment() { + $GLOBALS['comment'] = self::$comment; + + $this->assertSame( (string) self::$comment->comment_ID, get_comment_ID() ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_ID + */ + public function test_returns_zero_when_no_comment() { + unset( $GLOBALS['comment'] ); + + $this->assertSame( '0', get_comment_ID() ); + } + + /** + * @ticket 65819 + * + * @covers ::get_comment_ID + */ + public function test_filter_can_modify_comment_id() { + $GLOBALS['comment'] = self::$comment; + + add_filter( + 'get_comment_ID', + static function () { + return '999'; + } + ); + + $this->assertSame( '999', get_comment_ID() ); + } + + /** + * @ticket 65819 + * + * @covers ::comment_ID + * @covers ::get_comment_ID + */ + public function test_comment_id_echoes_value() { + $GLOBALS['comment'] = self::$comment; + + $this->expectOutputString( (string) self::$comment->comment_ID ); + comment_ID(); + } +} From 3ddcd5b0e4217ca9b76ed7acb58ec638b9a79fdc Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:05:16 +0000 Subject: [PATCH 132/481] Tests: Cover post format labels and slugs. Verify `get_post_format_string()` handles standard, known, and unknown formats, and `get_post_format_slugs()` returns the expected keys and values. Developed in: https://github.com/WordPress/wordpress-develop/pull/15273 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65138 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/post/getPostFormatString.php | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 tests/phpunit/tests/post/getPostFormatString.php diff --git a/tests/phpunit/tests/post/getPostFormatString.php b/tests/phpunit/tests/post/getPostFormatString.php new file mode 100644 index 0000000000000..f35512d2f8bee --- /dev/null +++ b/tests/phpunit/tests/post/getPostFormatString.php @@ -0,0 +1,66 @@ +assertSame( $expected, get_post_format_string( $slug ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_post_format_strings() { + return array( + 'empty slug is standard' => array( '', 'Standard' ), + 'known slug' => array( 'aside', 'Aside' ), + 'unknown slug' => array( 'nonexistent', '' ), + ); + } + + /** + * Tests that get_post_format_slugs() returns slugs as both keys and values. + * + * @ticket 65819 + * + * @covers ::get_post_format_slugs + */ + public function test_get_post_format_slugs() { + $slugs = get_post_format_slugs(); + + $this->assertSameSetsWithIndex( + array( + 'standard' => 'standard', + 'aside' => 'aside', + 'chat' => 'chat', + 'gallery' => 'gallery', + 'link' => 'link', + 'image' => 'image', + 'quote' => 'quote', + 'status' => 'status', + 'video' => 'video', + 'audio' => 'audio', + ), + $slugs + ); + } +} From c9c642954f340f93e2ca074e418ffc3d528a1e71 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:06:40 +0000 Subject: [PATCH 133/481] Tests: Cover file extension groups. Verify `wp_get_ext_types()` includes representative extensions in the expected groups and respects the `ext2type` filter. Developed in: https://github.com/WordPress/wordpress-develop/pull/15275 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65139 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/functions/wpGetExtTypes.php | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 tests/phpunit/tests/functions/wpGetExtTypes.php diff --git a/tests/phpunit/tests/functions/wpGetExtTypes.php b/tests/phpunit/tests/functions/wpGetExtTypes.php new file mode 100644 index 0000000000000..1f289c842ce4e --- /dev/null +++ b/tests/phpunit/tests/functions/wpGetExtTypes.php @@ -0,0 +1,70 @@ +assertSameSets( + array( + 'image', + 'audio', + 'video', + 'document', + 'spreadsheet', + 'interactive', + 'text', + 'archive', + 'code', + ), + array_keys( $types ) + ); + } + + /** + * Tests representative extensions for a few file types. + * + * @ticket 65819 + */ + public function test_includes_representative_extensions() { + $types = wp_get_ext_types(); + + $this->assertContains( 'jpg', $types['image'] ); + $this->assertContains( 'mp3', $types['audio'] ); + $this->assertContains( 'mp4', $types['video'] ); + $this->assertContains( 'pdf', $types['document'] ); + $this->assertContains( 'zip', $types['archive'] ); + } + + /** + * Tests that the ext2type filter can modify the map. + * + * @ticket 65819 + */ + public function test_filter_can_modify_ext_types() { + add_filter( + 'ext2type', + static function ( $types ) { + $types['custom'] = array( 'xyz' ); + return $types; + } + ); + + $types = wp_get_ext_types(); + + $this->assertArrayHasKey( 'custom', $types ); + $this->assertSame( array( 'xyz' ), $types['custom'] ); + } +} From 2e460ac8790c65b8e43f0f34eed9b3789210a97e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:12:55 +0000 Subject: [PATCH 134/481] Tests: Cover REST discovery output. Verify the REST discovery link, RSD API element, and HTTP link header use the configured REST URL and are suppressed when that URL is disabled. Developed in: https://github.com/WordPress/wordpress-develop/pull/15282, https://github.com/WordPress/wordpress-develop/pull/15283, https://github.com/WordPress/wordpress-develop/pull/15284 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65140 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/restOutputLinkHeader.php | 56 +++++++++++++++++++ .../tests/rest-api/restOutputLinkWpHead.php | 32 +++++++++++ .../phpunit/tests/rest-api/restOutputRsd.php | 33 +++++++++++ 3 files changed, 121 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restOutputLinkHeader.php create mode 100644 tests/phpunit/tests/rest-api/restOutputLinkWpHead.php create mode 100644 tests/phpunit/tests/rest-api/restOutputRsd.php diff --git a/tests/phpunit/tests/rest-api/restOutputLinkHeader.php b/tests/phpunit/tests/rest-api/restOutputLinkHeader.php new file mode 100644 index 0000000000000..1eeb8936e6db7 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restOutputLinkHeader.php @@ -0,0 +1,56 @@ +assertSame( '', $output ); + } + + /** + * @ticket 65819 + * + * @requires function xdebug_get_headers + */ + public function test_returns_early_when_rest_url_is_empty() { + add_filter( 'rest_url', '__return_empty_string' ); + + $headers_before = xdebug_get_headers(); + + rest_output_link_header(); + + $this->assertSame( $headers_before, xdebug_get_headers() ); + } + + /** + * @ticket 65819 + * + * @requires function xdebug_get_headers + */ + public function test_sends_rest_api_link_header() { + $api_root = sanitize_url( get_rest_url() ); + + rest_output_link_header(); + + $headers = xdebug_get_headers(); + $expected = sprintf( 'Link: <%s>; rel="https://api.w.org/"', $api_root ); + + $this->assertContains( $expected, $headers ); + } +} diff --git a/tests/phpunit/tests/rest-api/restOutputLinkWpHead.php b/tests/phpunit/tests/rest-api/restOutputLinkWpHead.php new file mode 100644 index 0000000000000..24b9984413ca1 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restOutputLinkWpHead.php @@ -0,0 +1,32 @@ +', esc_url( $api_root ) ); + + $this->expectOutputString( $expected ); + rest_output_link_wp_head(); + } + + /** + * @ticket 65819 + */ + public function test_outputs_nothing_when_rest_url_is_empty() { + add_filter( 'rest_url', '__return_empty_string' ); + + $this->expectOutputString( '' ); + rest_output_link_wp_head(); + } +} diff --git a/tests/phpunit/tests/rest-api/restOutputRsd.php b/tests/phpunit/tests/rest-api/restOutputRsd.php new file mode 100644 index 0000000000000..6cecd7cb99789 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restOutputRsd.php @@ -0,0 +1,33 @@ +expectOutputRegex( + '##' + ); + rest_output_rsd(); + } + + /** + * @ticket 65819 + */ + public function test_outputs_nothing_when_rest_url_is_empty() { + add_filter( 'rest_url', '__return_empty_string' ); + + $this->expectOutputString( '' ); + rest_output_rsd(); + } +} From 9b29177f8ea7cc25f2dbecea341349aed4442501 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:13:59 +0000 Subject: [PATCH 135/481] Tests: Cover REST value comparison and request argument parsing. Verify nested REST value comparisons and request argument validation before sanitization, including numeric coercion and invalid-type errors. Developed in: https://github.com/WordPress/wordpress-develop/pull/15285, https://github.com/WordPress/wordpress-develop/pull/15292 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65141 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/restAreValuesEqual.php | 116 ++++++++++++++++++ .../tests/rest-api/restParseRequestArg.php | 55 +++++++++ 2 files changed, 171 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restAreValuesEqual.php create mode 100644 tests/phpunit/tests/rest-api/restParseRequestArg.php diff --git a/tests/phpunit/tests/rest-api/restAreValuesEqual.php b/tests/phpunit/tests/rest-api/restAreValuesEqual.php new file mode 100644 index 0000000000000..360620dae203b --- /dev/null +++ b/tests/phpunit/tests/rest-api/restAreValuesEqual.php @@ -0,0 +1,116 @@ +assertTrue( rest_are_values_equal( $value1, $value2 ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_equal_values() { + return array( + 'same strings' => array( 'hello', 'hello' ), + 'same integers' => array( 7, 7 ), + 'integer and float' => array( 1, 1.0 ), + 'float and integer' => array( 1.0, 1 ), + 'same booleans' => array( true, true ), + 'both null' => array( null, null ), + 'same lists' => array( array( 1, 2 ), array( 1, 2 ) ), + 'objects with null property' => array( + array( + 'a' => null, + 'b' => 1, + ), + array( + 'a' => null, + 'b' => 1, + ), + ), + 'same objects different key order' => array( + array( + 'a' => 1, + 'b' => 2, + ), + array( + 'b' => 2, + 'a' => 1, + ), + ), + 'nested coercion and key order' => array( + array( + 'items' => array( + 1, + array( + 'x' => 2, + 'y' => 3.0, + ), + ), + ), + array( + 'items' => array( + 1.0, + array( + 'y' => 3, + 'x' => 2.0, + ), + ), + ), + ), + ); + } + + /** + * @ticket 65819 + * + * @dataProvider data_unequal_values + * + * @param mixed $value1 First value. + * @param mixed $value2 Second value. + */ + public function test_returns_false_for_unequal_values( $value1, $value2 ) { + $this->assertFalse( rest_are_values_equal( $value1, $value2 ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_unequal_values() { + return array( + 'different strings' => array( 'hello', 'world' ), + 'string and integer' => array( '1', 1 ), + 'integer and float' => array( 1, 2.0 ), + 'float and integer' => array( 2.0, 1 ), + 'different list order' => array( array( 1, 2 ), array( 2, 1 ) ), + 'different counts' => array( array( 1 ), array( 1, 2 ) ), + 'missing object key' => array( + array( 'a' => 1 ), + array( 'b' => 1 ), + ), + 'nested mismatch' => array( + array( 'items' => array( 1, 2 ) ), + array( 'items' => array( 1, 3 ) ), + ), + ); + } +} diff --git a/tests/phpunit/tests/rest-api/restParseRequestArg.php b/tests/phpunit/tests/rest-api/restParseRequestArg.php new file mode 100644 index 0000000000000..24f42545538f6 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restParseRequestArg.php @@ -0,0 +1,55 @@ +request = new WP_REST_Request( + 'GET', + '/wp/v2/testroute', + array( + 'args' => array( + 'someinteger' => array( + 'type' => 'integer', + ), + 'someboolean' => array( + 'type' => 'boolean', + ), + ), + ) + ); + } + + /** + * @ticket 65819 + */ + public function test_returns_sanitized_value_when_valid() { + $this->assertSame( 123, rest_parse_request_arg( '123', $this->request, 'someinteger' ) ); + $this->assertFalse( rest_parse_request_arg( 'false', $this->request, 'someboolean' ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_wp_error_when_invalid() { + $result = rest_parse_request_arg( 'abc', $this->request, 'someinteger' ); + + $this->assertWPError( $result ); + $this->assertSame( 'rest_invalid_type', $result->get_error_code() ); + } +} From d1a99965620480d60524fc97f2c2ed6ee2fd4784 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:16:17 +0000 Subject: [PATCH 136/481] Tests: Cover REST routes for queried resources. Verify `rest_get_queried_resource_route()` identifies singular posts, categories, and authors, handles requests without a resource, and respects its filter. Developed in: https://github.com/WordPress/wordpress-develop/pull/15291 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65142 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/restGetQueriedResourceRoute.php | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restGetQueriedResourceRoute.php diff --git a/tests/phpunit/tests/rest-api/restGetQueriedResourceRoute.php b/tests/phpunit/tests/rest-api/restGetQueriedResourceRoute.php new file mode 100644 index 0000000000000..e6f522d64c354 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restGetQueriedResourceRoute.php @@ -0,0 +1,74 @@ +post->create(); + + $this->go_to( get_permalink( $post_id ) ); + + $this->assertSame( '/wp/v2/posts/' . $post_id, rest_get_queried_resource_route() ); + } + + /** + * @ticket 65819 + */ + public function test_returns_route_for_category_archive() { + $term_id = self::factory()->category->create(); + + $this->go_to( get_term_link( $term_id ) ); + + $this->assertSame( '/wp/v2/categories/' . $term_id, rest_get_queried_resource_route() ); + } + + /** + * @ticket 65819 + */ + public function test_returns_route_for_author_archive() { + $user_id = self::factory()->user->create(); + + $this->go_to( get_author_posts_url( $user_id ) ); + + $this->assertSame( '/wp/v2/users/' . $user_id, rest_get_queried_resource_route() ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_when_no_resource_identified() { + $this->go_to( home_url( '/' ) ); + + $this->assertSame( '', rest_get_queried_resource_route() ); + } + + /** + * @ticket 65819 + */ + public function test_filter_can_modify_route() { + $post_id = self::factory()->post->create(); + + $this->go_to( get_permalink( $post_id ) ); + + $received = null; + add_filter( + 'rest_queried_resource_route', + static function ( $route ) use ( &$received ) { + $received = $route; + return '/custom/queried-route'; + } + ); + + $this->assertSame( '/custom/queried-route', rest_get_queried_resource_route() ); + $this->assertSame( '/wp/v2/posts/' . $post_id, $received ); + } +} From f57dee8c4ccd509e480cff6cffcc26c6992fbf9f Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:20:41 +0000 Subject: [PATCH 137/481] Tests: Cover REST authentication cookie status. Verify `rest_cookie_collect_status()` records successful authentication and the failure status associated with cookie validation actions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15293 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65143 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/restCookieCollectStatus.php | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restCookieCollectStatus.php diff --git a/tests/phpunit/tests/rest-api/restCookieCollectStatus.php b/tests/phpunit/tests/rest-api/restCookieCollectStatus.php new file mode 100644 index 0000000000000..530c3d1bfe7cc --- /dev/null +++ b/tests/phpunit/tests/rest-api/restCookieCollectStatus.php @@ -0,0 +1,53 @@ +assertTrue( $GLOBALS['wp_rest_auth_cookie'] ); + } + + /** + * @ticket 65819 + * + * @dataProvider data_auth_cookie_failure_actions + * + * @param string $action Auth cookie action name. + * @param string $expected Stored failure status. + */ + public function test_stores_failure_status_from_action( $action, $expected ) { + do_action( $action ); + + $this->assertSame( $expected, $GLOBALS['wp_rest_auth_cookie'] ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_auth_cookie_failure_actions() { + return array( + 'malformed' => array( 'auth_cookie_malformed', 'malformed' ), + 'expired' => array( 'auth_cookie_expired', 'expired' ), + 'bad username' => array( 'auth_cookie_bad_username', 'bad_username' ), + 'bad hash' => array( 'auth_cookie_bad_hash', 'bad_hash' ), + ); + } +} From 9049f6cb3f472f392743a921ac78e4f91d7d57f6 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:21:56 +0000 Subject: [PATCH 138/481] Tests: Cover emoji style enqueueing. Check that `wp_enqueue_emoji_styles()` removes the legacy style-printing callback and emits the expected inline emoji styles. Developed in: https://github.com/WordPress/wordpress-develop/pull/5912 Props pbearne. See #60301. git-svn-id: https://develop.svn.wordpress.org/trunk@65144 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/formatting/wpEnqueueEmojiStyles.php | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 tests/phpunit/tests/formatting/wpEnqueueEmojiStyles.php diff --git a/tests/phpunit/tests/formatting/wpEnqueueEmojiStyles.php b/tests/phpunit/tests/formatting/wpEnqueueEmojiStyles.php new file mode 100644 index 0000000000000..92b7303af294b --- /dev/null +++ b/tests/phpunit/tests/formatting/wpEnqueueEmojiStyles.php @@ -0,0 +1,27 @@ +assertSame( 10, has_action( 'wp_print_styles', 'print_emoji_styles' ) ); + + wp_enqueue_emoji_styles(); + + $this->assertFalse( has_action( 'wp_print_styles', 'print_emoji_styles' ) ); + + $styles = get_echo( 'wp_print_styles' ); + $this->assertStringContainsString( 'wp-emoji-styles-inline-css', $styles ); + $this->assertStringContainsString( 'img.wp-smiley, img.emoji', $styles ); + } +} From 6a3df0e80eef3e1574831f8ee382dce241f87f52 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:24:45 +0000 Subject: [PATCH 139/481] Tests: Cover equivalent post-meta return values. Check that `update_post_meta()` returns `false` when stored numeric strings are updated with equivalent integer or boolean values. Developed in: https://github.com/WordPress/wordpress-develop/pull/8780 Props vishalkakadiya, mukesh27. See #59361. git-svn-id: https://develop.svn.wordpress.org/trunk@65145 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/meta.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/phpunit/tests/post/meta.php b/tests/phpunit/tests/post/meta.php index 2a2ed65e7b138..72271925da01a 100644 --- a/tests/phpunit/tests/post/meta.php +++ b/tests/phpunit/tests/post/meta.php @@ -134,6 +134,22 @@ public function test_update_post_meta() { $this->assertSame( array( 'new' ), get_post_meta( self::$post_id, 'unique_update', false ) ); $this->assertSame( 'new', get_post_meta( self::$post_id, 'nonunique_update', true ) ); $this->assertSame( array( 'new', 'another new' ), get_post_meta( self::$post_id, 'nonunique_update', false ) ); + + // Checks "1" == 1 == true + $this->assertIsInt( add_post_meta( self::$post_id, 'unique_type_true', '1' ) ); + // Checking asserting false to confirm that the post meta is not updating unnecessary as "1" and 1 is same in meta_value. + $this->assertFalse( update_post_meta( self::$post_id, 'unique_type_true', 1 ) ); + $this->assertFalse( update_post_meta( self::$post_id, 'unique_type_true', true ) ); + + // Check "21" == 21 + $this->assertIsInt( add_post_meta( self::$post_id, 'unique_type_integer', '21' ) ); + // Checking asserting false to confirm that the post meta is not updating unnecessary as "21" and 21 is same in meta_value. + $this->assertFalse( update_post_meta( self::$post_id, 'unique_type_integer', 21 ) ); + + // Check "0" == 0 + $this->assertIsInt( add_post_meta( self::$post_id, 'unique_type_false', '0' ) ); + // Checking asserting false to confirm that the post meta is not updating unnecessary as "0" and 0 is same in meta_value. + $this->assertFalse( update_post_meta( self::$post_id, 'unique_type_false', 0 ) ); } public function test_delete_post_meta() { From 62884f0f76ec629c2a8ed8854e1b5f1bfd43c1a2 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:26:27 +0000 Subject: [PATCH 140/481] Tests: Add focused coverage for utility functions. Cover PHP update annotations, post-preview script output, backtrace class filtering and frame counts, hierarchy loop traversal, and the non-IIS permalink-support result and filter invocation. Developed in: https://github.com/WordPress/wordpress-develop/pull/5545, https://github.com/WordPress/wordpress-develop/pull/5599, https://github.com/WordPress/wordpress-develop/pull/5631, https://github.com/WordPress/wordpress-develop/pull/5668, https://github.com/WordPress/wordpress-develop/pull/5733 Props pbearne. Fixes #59699, #59775, #59829, #60024. See #59901. git-svn-id: https://develop.svn.wordpress.org/trunk@65146 602fd350-edb4-49c9-b593-d223f7449a82 --- .../functions/iis7SupportsPermalinks.php | 29 +++++++++ .../functions/wpDebugBacktraceSummary.php | 60 +++++++++++++++++++ .../tests/functions/wpFindHierarchyLoop.php | 46 ++++++++++++++ .../functions/wpGetUpdatePhpAnnotation.php | 41 +++++++++++++ .../tests/functions/wpPostPreviewJs.php | 45 ++++++++++++++ 5 files changed, 221 insertions(+) create mode 100644 tests/phpunit/tests/functions/iis7SupportsPermalinks.php create mode 100644 tests/phpunit/tests/functions/wpDebugBacktraceSummary.php create mode 100644 tests/phpunit/tests/functions/wpFindHierarchyLoop.php create mode 100644 tests/phpunit/tests/functions/wpGetUpdatePhpAnnotation.php create mode 100644 tests/phpunit/tests/functions/wpPostPreviewJs.php diff --git a/tests/phpunit/tests/functions/iis7SupportsPermalinks.php b/tests/phpunit/tests/functions/iis7SupportsPermalinks.php new file mode 100644 index 0000000000000..3f6a428cb3b8d --- /dev/null +++ b/tests/phpunit/tests/functions/iis7SupportsPermalinks.php @@ -0,0 +1,29 @@ +assertFalse( iis7_supports_permalinks() ); + + $this->assertSame( 1, $filter->get_call_count() ); + } + } +} diff --git a/tests/phpunit/tests/functions/wpDebugBacktraceSummary.php b/tests/phpunit/tests/functions/wpDebugBacktraceSummary.php new file mode 100644 index 0000000000000..a87d00b281a6f --- /dev/null +++ b/tests/phpunit/tests/functions/wpDebugBacktraceSummary.php @@ -0,0 +1,60 @@ +assertStringContainsString( 'Tests_functions_wpDebugBacktraceSummary', $backtrace ); + } + + /** + * Test we get an array back + * + * @ticket 59829 + */ + public function test_wp_debug_backtrace_summary_returns_array() { + + $backtrace = wp_debug_backtrace_summary( null, 0, false ); + + $this->assertIsArray( $backtrace ); + } + + /** + * Test that we can skip a class + * + * @ticket 59829 + */ + public function test_wp_debug_backtrace_summary_skips_class() { + + $backtrace = wp_debug_backtrace_summary( 'Tests_functions_wpDebugBacktraceSummary' ); + + $this->assertStringNotContainsString( 'Tests_functions_wpDebugBacktraceSummary', $backtrace ); + } + + /** + * Test that we can skip the results of functions + * + * @ticket 59829 + */ + public function test_wp_debug_backtrace_summary_skips() { + + $backtrace = wp_debug_backtrace_summary( null, 0, false ); + $backtrace_skiped = wp_debug_backtrace_summary( null, 2, false ); + + $this->assertSame( count( $backtrace ) - 2, count( $backtrace_skiped ) ); + } +} diff --git a/tests/phpunit/tests/functions/wpFindHierarchyLoop.php b/tests/phpunit/tests/functions/wpFindHierarchyLoop.php new file mode 100644 index 0000000000000..12621844b4609 --- /dev/null +++ b/tests/phpunit/tests/functions/wpFindHierarchyLoop.php @@ -0,0 +1,46 @@ + true, + 2 => true, + ); + $this->assertSame( $expected, $result ); + } + + /** + * @ticket 59901 + */ + public function test_wp_find_hierarchy_loop_null_parent() { + $result = wp_find_hierarchy_loop( + static function ( $id ) { + return 1; + }, + 1, + null + ); + $expected = array( + 1 => true, + ); + $this->assertSame( $expected, $result ); + } +} diff --git a/tests/phpunit/tests/functions/wpGetUpdatePhpAnnotation.php b/tests/phpunit/tests/functions/wpGetUpdatePhpAnnotation.php new file mode 100644 index 0000000000000..a3d2bbb5d5c6b --- /dev/null +++ b/tests/phpunit/tests/functions/wpGetUpdatePhpAnnotation.php @@ -0,0 +1,41 @@ +assertEquals( '', wp_get_update_php_annotation() ); + } + + /** + * Test that the annotation is return if the URLs are different + * + * @ticket 59699 + */ + public function test_wp_get_update_php_annotation_dif_url() { + // add filter to change the URL for the PHP updates from wordpress.org + add_filter( 'wp_update_php_url', array( $this, 'filter_diff_url' ) ); + $this->assertStringContainsString( 'This resource is provided by your web host', wp_get_update_php_annotation() ); + } + + /** + * Filter to change the URL + * @param $url + * + * @return string + */ + public function filter_diff_url() { + + return 'diff_url.com'; + } +} diff --git a/tests/phpunit/tests/functions/wpPostPreviewJs.php b/tests/phpunit/tests/functions/wpPostPreviewJs.php new file mode 100644 index 0000000000000..fec104ab96f2a --- /dev/null +++ b/tests/phpunit/tests/functions/wpPostPreviewJs.php @@ -0,0 +1,45 @@ +assertEmpty( get_echo( 'wp_post_preview_js' ) ); + } + + /** + * @ticket 59775 + */ + public function test_wp_post_preview_js_working() { + global $post, $wp_query; + $post = self::factory()->post->create_and_get(); + $wp_query->is_preview = true; + + $output = get_echo( 'wp_post_preview_js' ); + $this->assertStringContainsString( 'wp-preview-' . $post->ID, $output ); + $this->assertStringStartsWith( 'assertStringContainsString( '', $output ); + } + + /** + * Check that both priveiw and post needed to return script block + * + * @ticket 59775 + */ + public function test_wp_post_preview_js_not_preview() { + global $post; + $post = self::factory()->post->create_and_get(); + + $this->assertEmpty( get_echo( 'wp_post_preview_js' ) ); + } +} From a9c8ccda4624f513fb7e8fca899695175b208da2 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 19:28:00 +0000 Subject: [PATCH 141/481] Tests: Add bookmark rendering coverage. Cover bookmark markup and display options in `_walk_bookmarks()`, plus categorized and uncategorized output, filtering, visibility, and echo behavior in `wp_list_bookmarks()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/13256 Props pbearne. See #65957. git-svn-id: https://develop.svn.wordpress.org/trunk@65147 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/bookmark-template/walkBookmarks.php | 272 ++++++++++++ .../bookmark-template/wpListBookmarks.php | 397 ++++++++++++++++++ 2 files changed, 669 insertions(+) create mode 100644 tests/phpunit/tests/bookmark-template/walkBookmarks.php create mode 100644 tests/phpunit/tests/bookmark-template/wpListBookmarks.php diff --git a/tests/phpunit/tests/bookmark-template/walkBookmarks.php b/tests/phpunit/tests/bookmark-template/walkBookmarks.php new file mode 100644 index 0000000000000..b957b6213f010 --- /dev/null +++ b/tests/phpunit/tests/bookmark-template/walkBookmarks.php @@ -0,0 +1,272 @@ +assertSame( $expected, _walk_bookmarks( $bookmarks, $args ) ); + } + + /** + * Data provider for test_walk_bookmarks. + * + * @return array>, + * args: array|string, + * expected: string, + * }> + */ + public function data_walk_bookmarks(): array { + return array( + 'empty bookmarks array' => array( + 'bookmarks_data' => array(), + 'args' => array(), + 'expected' => '', + ), + 'default arguments with standard bookmark' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 1, + 'link_name' => 'Example Site', + 'link_url' => 'https://example.org', + 'link_description' => 'A great website', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array(), + 'expected' => "
  • Example Site
  • \n", + ), + 'empty link_url falls back to hash' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 2, + 'link_name' => 'No URL Link', + 'link_url' => '', + 'link_description' => '', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array(), + 'expected' => "
  • No URL Link
  • \n", + ), + 'with link_rel and link_target' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 3, + 'link_name' => 'External Link', + 'link_url' => 'https://example.com', + 'link_description' => 'External resource', + 'link_image' => '', + 'link_target' => '_blank', + 'link_rel' => 'nofollow noopener', + 'link_rating' => 0, + ), + ), + 'args' => array(), + 'expected' => "
  • External Link
  • \n", + ), + 'show_description and show_rating with custom between' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 4, + 'link_name' => 'Rated Link', + 'link_url' => 'https://example.org/rated', + 'link_description' => 'High quality site', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 5, + ), + ), + 'args' => array( + 'show_description' => 1, + 'show_rating' => 1, + 'between' => ' - ', + ), + 'expected' => "
  • Rated Link - High quality site - 5
  • \n", + ), + 'show_images with absolute http url and show_name disabled' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 5, + 'link_name' => 'Image Link', + 'link_url' => 'https://example.org/img', + 'link_description' => 'Site with logo', + 'link_image' => 'https://example.org/logo.png', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array( + 'show_images' => 1, + 'show_name' => 0, + ), + 'expected' => "
  • \"Image
  • \n", + ), + 'show_images with absolute http url and show_name enabled' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 6, + 'link_name' => 'Image Link With Name', + 'link_url' => 'https://example.org/img2', + 'link_description' => '', + 'link_image' => 'https://example.org/logo2.png', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array( + 'show_images' => 1, + 'show_name' => 1, + ), + 'expected' => "
  • \"Image Image Link With Name
  • \n", + ), + 'show_images disabled when image exists' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 7, + 'link_name' => 'Text Only Link', + 'link_url' => 'https://example.org/text', + 'link_description' => '', + 'link_image' => 'https://example.org/logo.png', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array( + 'show_images' => 0, + ), + 'expected' => "
  • Text Only Link
  • \n", + ), + 'custom before, after, link_before, and link_after wrappers' => array( + 'bookmarks_data' => array( + array( + 'link_id' => 8, + 'link_name' => 'Wrapped Link', + 'link_url' => 'https://example.org/wrapped', + 'link_description' => '', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ), + ), + 'args' => array( + 'before' => '
    ', + 'after' => '
    ', + 'link_before' => '', + 'link_after' => '', + ), + 'expected' => "\n", + ), + ); + } + + /** + * Tests show_images with a relative image URL. + * + * @ticket 65957 + */ + public function test_walk_bookmarks_relative_image_url(): void { + $bookmark = (object) array( + 'link_id' => 10, + 'link_name' => 'Relative Image Link', + 'link_url' => 'https://example.org', + 'link_description' => '', + 'link_image' => '/images/logo.png', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + ); + + $expected = '
  • Relative Image Link
  • ' . "\n"; + + $this->assertSame( $expected, _walk_bookmarks( array( $bookmark ), array( 'show_images' => 1 ) ) ); + } + + /** + * Tests show_updated functionality with recently_updated bookmarks. + * + * @ticket 65957 + */ + public function test_walk_bookmarks_show_updated(): void { + $timestamp = strtotime( '2026-08-24 12:00:00' ); + + $bookmark_recent = (object) array( + 'link_id' => 11, + 'link_name' => 'Recent Link', + 'link_url' => 'https://example.org/recent', + 'link_description' => 'Description', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + 'recently_updated' => true, + 'link_updated_f' => (string) $timestamp, + ); + + $bookmark_not_recent = (object) array( + 'link_id' => 12, + 'link_name' => 'Old Link', + 'link_url' => 'https://example.org/old', + 'link_description' => '', + 'link_image' => '', + 'link_target' => '', + 'link_rel' => '', + 'link_rating' => 0, + 'recently_updated' => false, + 'link_updated_f' => '0000-00-00 00:00:00', + ); + + $date_format = get_option( 'links_updated_date_format' ); + $gmt_offset = (int) ( (float) get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ); + $expected_date = gmdate( $date_format, $timestamp + $gmt_offset ); + + $output = _walk_bookmarks( + array( $bookmark_recent, $bookmark_not_recent ), + array( + 'show_updated' => 1, + ) + ); + + $this->assertStringContainsString( 'assertStringContainsString( 'Last updated: ' . $expected_date, $output ); + $this->assertStringContainsString( '', $output ); + $this->assertStringNotContainsString( 'term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Alpha Category', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Alpha Site', + 'link_url' => 'https://alpha.example.org', + 'link_category' => array( $cat_id ), + ) + ); + + $args['echo'] = 0; + $output = wp_list_bookmarks( $args ); + + foreach ( $expected as $needle ) { + $needle = str_replace( '%cat_id%', (string) $cat_id, $needle ); + $this->assertStringContainsString( $needle, $output ); + } + } + + /** + * Data provider for test_wp_list_bookmarks_categorized. + * + * @return array, + * expected: string[], + * }> + */ + public function data_wp_list_bookmarks_categorized(): array { + return array( + 'default categorized output' => array( + 'args' => array( + 'categorize' => 1, + ), + 'expected' => array( + '
  • ', + '

    Alpha Category

    ', + "
    ', + '
  • ', + ), + ), + 'custom category class and wrappers' => array( + 'args' => array( + 'categorize' => 1, + 'class' => 'custom-bookmarks-class', + 'title_before' => '

    ', + 'title_after' => '

    ', + 'category_before' => '
    ', + 'category_after' => '
    ', + ), + 'expected' => array( + '
    ', + '

    Alpha Category

    ', + "
      ", + '
    ', + ), + ), + 'array of classes' => array( + 'args' => array( + 'categorize' => 1, + 'class' => array( 'class-one', 'class-two' ), + ), + 'expected' => array( + 'class="class-one class-two"', + ), + ), + ); + } + + /** + * Tests uncategorized bookmarks listing. + * + * @ticket 65957 + * + * @dataProvider data_wp_list_bookmarks_uncategorized + * + * @param array $args Arguments for wp_list_bookmarks. + * @param array $expected Substrings expected in the output. + * @param array $not_expected Substrings not expected in the output. + */ + public function test_wp_list_bookmarks_uncategorized( array $args, array $expected, array $not_expected ): void { + $cat_id = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Uncategorized Group', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Single Site', + 'link_url' => 'https://single.example.org', + 'link_category' => array( $cat_id ), + ) + ); + + $args['echo'] = 0; + $output = wp_list_bookmarks( $args ); + + foreach ( $expected as $needle ) { + $this->assertStringContainsString( $needle, $output ); + } + + foreach ( $not_expected as $needle ) { + $this->assertStringNotContainsString( $needle, $output ); + } + } + + /** + * Data provider for test_wp_list_bookmarks_uncategorized. + * + * @return array, + * expected: string[], + * not_expected: string[], + * }> + */ + public function data_wp_list_bookmarks_uncategorized(): array { + return array( + 'uncategorized with default title_li' => array( + 'args' => array( + 'categorize' => 0, + 'title_li' => 'Custom Bookmarks Title', + ), + 'expected' => array( + '

    Custom Bookmarks Title

    ', + "
      ", + '
    • ', + ), + 'not_expected' => array( + 'Uncategorized Group', + ), + ), + 'uncategorized with empty title_li' => array( + 'args' => array( + 'categorize' => 0, + 'title_li' => '', + ), + 'expected' => array( + '
    • ', + ), + 'not_expected' => array( + '

      ', + '

      ', + "
        ", + ), + ), + ); + } + + /** + * Tests echo parameter behavior. + * + * @ticket 65957 + */ + public function test_wp_list_bookmarks_echo(): void { + $cat_id = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Echo Category', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Echo Site', + 'link_url' => 'https://echo.example.org', + 'link_category' => array( $cat_id ), + ) + ); + + ob_start(); + $echo_result = wp_list_bookmarks( + array( + 'echo' => 1, + 'category' => $cat_id, + ) + ); + $echoed = ob_get_clean(); + + $return_result = wp_list_bookmarks( + array( + 'echo' => 0, + 'category' => $cat_id, + ) + ); + + $this->assertNull( $echo_result ); + $this->assertSame( $echoed, $return_result ); + $this->assertStringContainsString( 'Echo Site', $echoed ); + } + + /** + * Tests filtering bookmarks by category include, exclude, and category_name. + * + * @ticket 65957 + */ + public function test_wp_list_bookmarks_category_filtering(): void { + $cat_a = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Alpha Group', + ) + ); + $cat_b = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Beta Group', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Alpha Site', + 'link_url' => 'https://alpha.example.org', + 'link_category' => array( $cat_a ), + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Beta Site', + 'link_url' => 'https://beta.example.org', + 'link_category' => array( $cat_b ), + ) + ); + + // Test category inclusion. + $included_output = wp_list_bookmarks( + array( + 'echo' => 0, + 'category' => $cat_a, + ) + ); + $this->assertStringContainsString( 'Alpha Site', $included_output ); + $this->assertStringNotContainsString( 'Beta Site', $included_output ); + + // Test category exclusion. + $excluded_output = wp_list_bookmarks( + array( + 'echo' => 0, + 'exclude_category' => $cat_a, + ) + ); + $this->assertStringNotContainsString( 'Alpha Site', $excluded_output ); + $this->assertStringContainsString( 'Beta Site', $excluded_output ); + + // Test category_name filter. + $name_filter_output = wp_list_bookmarks( + array( + 'echo' => 0, + 'category_name' => 'Beta Group', + ) + ); + $this->assertStringNotContainsString( 'Alpha Site', $name_filter_output ); + $this->assertStringContainsString( 'Beta Site', $name_filter_output ); + } + + /** + * Tests link_category and wp_list_bookmarks filter hooks. + * + * @ticket 65957 + */ + public function test_wp_list_bookmarks_filters(): void { + $cat_id = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Original Category Name', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Filtered Site', + 'link_url' => 'https://filtered.example.org', + 'link_category' => array( $cat_id ), + ) + ); + + $filter_cat_name = static function ( $name ) { + return 'Modified Category: ' . $name; + }; + + $filter_html = static function ( $html ) { + return '' . $html . ''; + }; + + add_filter( 'link_category', $filter_cat_name ); + add_filter( 'wp_list_bookmarks', $filter_html ); + + $output = wp_list_bookmarks( + array( + 'echo' => 0, + 'category' => $cat_id, + ) + ); + + remove_filter( 'link_category', $filter_cat_name ); + remove_filter( 'wp_list_bookmarks', $filter_html ); + + $this->assertStringContainsString( 'Modified Category: Original Category Name', $output ); + $this->assertStringStartsWith( '', $output ); + $this->assertStringEndsWith( '', $output ); + } + + /** + * Tests hide_invisible argument. + * + * @ticket 65957 + */ + public function test_wp_list_bookmarks_hide_invisible(): void { + $cat_id = self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Visibility Category', + ) + ); + + self::factory()->bookmark->create( + array( + 'link_name' => 'Invisible Link', + 'link_url' => 'https://invisible.example.org', + 'link_visible' => 'N', + 'link_category' => array( $cat_id ), + ) + ); + + $hidden_output = wp_list_bookmarks( + array( + 'echo' => 0, + 'hide_invisible' => 1, + 'category' => $cat_id, + ) + ); + $this->assertStringNotContainsString( 'Invisible Link', $hidden_output ); + + $visible_output = wp_list_bookmarks( + array( + 'echo' => 0, + 'hide_invisible' => 0, + 'category' => $cat_id, + ) + ); + $this->assertStringContainsString( 'Invisible Link', $visible_output ); + } + + /** + * Tests when no bookmarks are found. + * + * @ticket 65957 + */ + public function test_wp_list_bookmarks_empty(): void { + $output = wp_list_bookmarks( + array( + 'echo' => 0, + 'category' => 999999, + ) + ); + + $this->assertSame( '', $output ); + } +} From c82c6cbdb5f38ce689755333c5e2914d03a5fddb Mon Sep 17 00:00:00 2001 From: lancewillett Date: Sat, 31 Oct 2026 20:06:01 +0000 Subject: [PATCH 142/481] Tests: Cover IIS rewrite-rule detection. Verify `iis7_rewrite_rule_exists()` with temporary XML fixtures for matching and missing rules, invalid configuration, and nonexistent files. Developed in: https://github.com/WordPress/wordpress-develop/pull/11672 Props pbearne. Fixes #65148. git-svn-id: https://develop.svn.wordpress.org/trunk@65148 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/misc.php | 1 - .../includes/misc/iis7RewriteRuleExists.php | 100 ++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php diff --git a/src/wp-admin/includes/misc.php b/src/wp-admin/includes/misc.php index 51409d945b7a5..d71ea1a8e607d 100644 --- a/src/wp-admin/includes/misc.php +++ b/src/wp-admin/includes/misc.php @@ -833,7 +833,6 @@ function iis7_rewrite_rule_exists( $filename ) { } $doc = new DOMDocument(); - if ( $doc->load( $filename ) === false ) { return false; } diff --git a/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php b/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php new file mode 100644 index 0000000000000..83532b1f51983 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php @@ -0,0 +1,100 @@ +temp_file = wp_tempnam( 'web.config' ); + } + + public function tear_down() { + if ( file_exists( $this->temp_file ) ) { + unlink( $this->temp_file ); + } + + parent::tear_down(); + } + + /** + * Tests that iis7_rewrite_rule_exists() correctly identifies the existence of rules. + * + * @ticket 65148 + * + * @dataProvider data_iis7_rewrite_rule_exists + * + * @phpstan-return array + * + * @param bool $expected Whether the rule is expected to exist. + * @param string $content The XML content of the file. + */ + public function test_iis7_rewrite_rule_exists( $expected, $content ) { + if ( 'Not XML' === $content ) { + file_put_contents( $this->temp_file, $content ); + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + $this->assertSame( $expected, @iis7_rewrite_rule_exists( $this->temp_file ) ); + } else { + file_put_contents( $this->temp_file, $content ); + $this->assertSame( $expected, iis7_rewrite_rule_exists( $this->temp_file ) ); + } + } + + /** + * Data provider for test_iis7_rewrite_rule_exists. + * + * @return array + */ + public function data_iis7_rewrite_rule_exists(): array { + return array( + 'Rule with name starting with "wordpress" exists' => array( + 'expected' => true, + 'content' => '', + ), + 'Rule with name "wordpress" exists' => array( + 'expected' => true, + 'content' => '', + ), + 'Rule with name "WordPress" exists' => array( + 'expected' => true, + 'content' => '', + ), + 'Rule does not exist' => array( + 'expected' => false, + 'content' => '', + ), + 'Empty configuration' => array( + 'expected' => false, + 'content' => '', + ), + 'Invalid XML' => array( + 'expected' => false, + 'content' => 'Not XML', + ), + ); + } + + /** + * Tests that iis7_rewrite_rule_exists() returns false if the file does not exist. + * + * @ticket 65148 + */ + public function test_iis7_rewrite_rule_exists_non_existent_file() { + $this->assertFalse( iis7_rewrite_rule_exists( '/non/existent/file' ) ); + } +} From 094ed92c85f5f3b98b91539e671d561cdfa43b63 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 20:07:14 +0000 Subject: [PATCH 143/481] Build/Test Tools: Retire resolved PHPStan baselines. Clarify pointer, metadata, and REST array types. Simplify equivalent Site Health, timezone, and upload checks while preserving the theme filter re-evaluation. Remove the resolved `empty.offset`, `booleanAnd.rightAlwaysTrue`, and `identical.alwaysTrue` baselines and the related unreachable-code entry. Developed in: https://github.com/WordPress/wordpress-develop/pull/14027, https://github.com/WordPress/wordpress-develop/pull/14031, https://github.com/WordPress/wordpress-develop/pull/14032 Props huzaifaalmesbah. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65149 602fd350-edb4-49c9-b593-d223f7449a82 --- phpstan.neon.dist | 3 -- .../includes/class-file-upload-upgrader.php | 4 +-- .../includes/class-wp-internal-pointers.php | 2 ++ .../includes/class-wp-site-health.php | 3 +- src/wp-admin/includes/media.php | 1 + .../themes/twentynineteen/header.php | 2 +- src/wp-includes/functions.php | 6 ++-- src/wp-includes/rest-api.php | 1 + .../baselines/booleanAnd.rightAlwaysTrue.neon | 35 ------------------- .../baselines/deadCode.unreachable.neon | 5 --- tests/phpstan/baselines/empty.offset.neon | 30 ---------------- .../baselines/identical.alwaysTrue.neon | 30 ---------------- 12 files changed, 10 insertions(+), 112 deletions(-) delete mode 100644 tests/phpstan/baselines/booleanAnd.rightAlwaysTrue.neon delete mode 100644 tests/phpstan/baselines/empty.offset.neon delete mode 100644 tests/phpstan/baselines/identical.alwaysTrue.neon diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 1932f7edcdb0f..55097717df3ee 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -28,18 +28,15 @@ includes: - tests/phpstan/baselines/binaryOp.invalid.neon - tests/phpstan/baselines/booleanAnd.alwaysFalse.neon - tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon - - tests/phpstan/baselines/booleanAnd.rightAlwaysTrue.neon - tests/phpstan/baselines/booleanNot.alwaysFalse.neon - tests/phpstan/baselines/booleanNot.alwaysTrue.neon - tests/phpstan/baselines/class.notFound.neon - tests/phpstan/baselines/deadCode.unreachable.neon - - tests/phpstan/baselines/empty.offset.neon - tests/phpstan/baselines/empty.property.neon - tests/phpstan/baselines/empty.variable.neon - tests/phpstan/baselines/function.alreadyNarrowedType.neon - tests/phpstan/baselines/function.resultUnused.neon - tests/phpstan/baselines/identical.alwaysFalse.neon - - tests/phpstan/baselines/identical.alwaysTrue.neon - tests/phpstan/baselines/if.alwaysFalse.neon - tests/phpstan/baselines/if.alwaysTrue.neon - tests/phpstan/baselines/isset.offset.neon diff --git a/src/wp-admin/includes/class-file-upload-upgrader.php b/src/wp-admin/includes/class-file-upload-upgrader.php index 48e1aac721d1d..0f52516a0e2cd 100644 --- a/src/wp-admin/includes/class-file-upload-upgrader.php +++ b/src/wp-admin/includes/class-file-upload-upgrader.php @@ -80,9 +80,7 @@ public function __construct( $form, $urlholder ) { __( 'Return to the Plugin Installer' ) ); wp_die( __( 'Incompatible Archive.' ) . '
        ' . $plugins_page ); - } - - if ( 'themezip' === $form ) { + } else { $themes_page = sprintf( '
        %s', self_admin_url( 'theme-install.php' ), diff --git a/src/wp-admin/includes/class-wp-internal-pointers.php b/src/wp-admin/includes/class-wp-internal-pointers.php index 22233884b4beb..448e7af914c08 100644 --- a/src/wp-admin/includes/class-wp-internal-pointers.php +++ b/src/wp-admin/includes/class-wp-internal-pointers.php @@ -48,6 +48,7 @@ public static function enqueue_scripts( $hook_suffix ) { * 'themes.php' => 'wp390_widgets' * ) */ + /** @var array $registered_pointers */ $registered_pointers = array( // None currently. ); @@ -72,6 +73,7 @@ public static function enqueue_scripts( $hook_suffix ) { * 'wp390_widgets' => array( 'edit_theme_options' ) * ) */ + /** @var array $caps_required */ $caps_required = array( // None currently. ); diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index de0d7cd8da332..b9ce4f472834f 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -528,7 +528,6 @@ public function get_test_theme_version() { $has_default_theme = false; $has_unused_themes = false; - $show_unused_themes = true; $using_default_theme = false; // Populate a list of all themes available in the install. @@ -622,7 +621,7 @@ public function get_test_theme_version() { } } - if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) { + if ( $has_unused_themes && ! is_multisite() ) { // This is a child theme, so we want to be a bit more explicit in our messages. if ( $active_theme->parent() ) { diff --git a/src/wp-admin/includes/media.php b/src/wp-admin/includes/media.php index ee4c2add91e65..896af458eb408 100644 --- a/src/wp-admin/includes/media.php +++ b/src/wp-admin/includes/media.php @@ -3677,6 +3677,7 @@ function wp_read_video_metadata( $file ) { return false; } + /** @var array $metadata */ $metadata = array(); if ( ! defined( 'GETID3_TEMP_DIR' ) ) { diff --git a/src/wp-content/themes/twentynineteen/header.php b/src/wp-content/themes/twentynineteen/header.php index 483355892799e..0212e46d34311 100644 --- a/src/wp-content/themes/twentynineteen/header.php +++ b/src/wp-content/themes/twentynineteen/header.php @@ -41,7 +41,7 @@ responses ) > 0 ) { diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 5307e33eed02c..d3493594cb7f6 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -6880,9 +6880,9 @@ function wp_timezone_choice( $selected_zone, $locale = null ) { // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later. $exists = array( - 0 => ( isset( $zone[0] ) && $zone[0] ), - 1 => ( isset( $zone[1] ) && $zone[1] ), - 2 => ( isset( $zone[2] ) && $zone[2] ), + 0 => ! empty( $zone[0] ), + 1 => ! empty( $zone[1] ), + 2 => ! empty( $zone[2] ), ); $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] ); $exists[4] = ( $exists[1] && $exists[3] ); diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index 9fe15fb1180a5..f40021f4d06cd 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -1072,6 +1072,7 @@ function rest_filter_response_fields( $response, $server, $request ) { $fields = array_map( 'trim', $fields ); // Create nested array of accepted field hierarchy. + /** @var array $fields_as_keyed */ $fields_as_keyed = array(); foreach ( $fields as $field ) { $parts = explode( '.', $field ); diff --git a/tests/phpstan/baselines/booleanAnd.rightAlwaysTrue.neon b/tests/phpstan/baselines/booleanAnd.rightAlwaysTrue.neon deleted file mode 100644 index 99d44e7b84f43..0000000000000 --- a/tests/phpstan/baselines/booleanAnd.rightAlwaysTrue.neon +++ /dev/null @@ -1,35 +0,0 @@ -# PHPStan baseline for the `booleanAnd.rightAlwaysTrue` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/booleanAnd.rightAlwaysTrue -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=booleanAnd.rightAlwaysTrue -# -# which reruns the analysis with this file suppressed so the errors surface again. - -parameters: - ignoreErrors: - - - message: '#^Right side of && is always true\.$#' - identifier: booleanAnd.rightAlwaysTrue - count: 1 - path: ../../../src/wp-admin/includes/class-wp-site-health.php - - - message: '#^Right side of && is always true\.$#' - identifier: booleanAnd.rightAlwaysTrue - count: 1 - path: ../../../src/wp-content/themes/twentynineteen/header.php - - - message: '#^Right side of && is always true\.$#' - identifier: booleanAnd.rightAlwaysTrue - count: 1 - path: ../../../src/wp-includes/functions.php diff --git a/tests/phpstan/baselines/deadCode.unreachable.neon b/tests/phpstan/baselines/deadCode.unreachable.neon index 74e77b7dffb79..ef8ca56577602 100644 --- a/tests/phpstan/baselines/deadCode.unreachable.neon +++ b/tests/phpstan/baselines/deadCode.unreachable.neon @@ -33,11 +33,6 @@ parameters: identifier: deadCode.unreachable count: 3 path: ../../../src/wp-admin/includes/ajax-actions.php - - - message: '#^Unreachable statement \- code above always terminates\.$#' - identifier: deadCode.unreachable - count: 1 - path: ../../../src/wp-admin/includes/class-wp-internal-pointers.php - message: '#^Unreachable statement \- code above always terminates\.$#' identifier: deadCode.unreachable diff --git a/tests/phpstan/baselines/empty.offset.neon b/tests/phpstan/baselines/empty.offset.neon deleted file mode 100644 index ac1410fad0869..0000000000000 --- a/tests/phpstan/baselines/empty.offset.neon +++ /dev/null @@ -1,30 +0,0 @@ -# PHPStan baseline for the `empty.offset` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/empty.offset -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=empty.offset -# -# which reruns the analysis with this file suppressed so the errors surface again. - -parameters: - ignoreErrors: - - - message: '#^Offset mixed on array\{\} in empty\(\) does not exist\.$#' - identifier: empty.offset - count: 1 - path: ../../../src/wp-admin/includes/class-wp-internal-pointers.php - - - message: '#^Offset ''created_timestamp'' on array\{\}\|array\{lossless\?\: mixed, bitrate\?\: int, bitrate_mode\?\: mixed, filesize\?\: int, mime_type\?\: mixed, length\?\: int, length_formatted\?\: mixed, width\?\: int, \.\.\.\} in empty\(\) does not exist\.$#' - identifier: empty.offset - count: 1 - path: ../../../src/wp-admin/includes/media.php diff --git a/tests/phpstan/baselines/identical.alwaysTrue.neon b/tests/phpstan/baselines/identical.alwaysTrue.neon deleted file mode 100644 index 347c3326fc5fe..0000000000000 --- a/tests/phpstan/baselines/identical.alwaysTrue.neon +++ /dev/null @@ -1,30 +0,0 @@ -# PHPStan baseline for the `identical.alwaysTrue` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/identical.alwaysTrue -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=identical.alwaysTrue -# -# which reruns the analysis with this file suppressed so the errors surface again. - -parameters: - ignoreErrors: - - - message: '#^Strict comparison using \=\=\= between ''themezip'' and ''themezip'' will always evaluate to true\.$#' - identifier: identical.alwaysTrue - count: 1 - path: ../../../src/wp-admin/includes/class-file-upload-upgrader.php - - - message: '#^Strict comparison using \=\=\= between true and true will always evaluate to true\.$#' - identifier: identical.alwaysTrue - count: 1 - path: ../../../src/wp-includes/rest-api.php From 26953711e91c251b54f033b4c8bb149ef8bd596e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:07:40 +0000 Subject: [PATCH 144/481] Build/Test Tools: Explain Composer failures during environment startup. Run `composer update -W` through the shared Compose retry helper in `start.js`. Report a focused Composer error after exhausted retries, preserving startup ordering and the failing exit status. Developed in: https://github.com/WordPress/wordpress-develop/pull/9360 Props iamadisingh, azaozz, r1k0. Fixes #62807. git-svn-id: https://develop.svn.wordpress.org/trunk@65150 602fd350-edb4-49c9-b593-d223f7449a82 --- package.json | 2 +- tools/local-env/scripts/start.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index e506c964d7de7..a0b92003074e8 100644 --- a/package.json +++ b/package.json @@ -140,7 +140,7 @@ "lint:jsdoc": "wp-scripts lint-js", "lint:jsdoc:fix": "wp-scripts lint-js --fix", "typecheck:js": "tsc --build", - "env:start": "node ./tools/local-env/scripts/start.js && node ./tools/local-env/scripts/docker.js run -T --rm php composer update -W", + "env:start": "node ./tools/local-env/scripts/start.js", "env:stop": "node ./tools/local-env/scripts/docker.js down", "env:restart": "npm run env:stop && npm run env:start", "env:clean": "node ./tools/local-env/scripts/docker.js down -v --remove-orphans", diff --git a/tools/local-env/scripts/start.js b/tools/local-env/scripts/start.js index 984e06bee5617..d811ca11ecbe8 100644 --- a/tools/local-env/scripts/start.js +++ b/tools/local-env/scripts/start.js @@ -93,3 +93,14 @@ if ( process.env.DOCKER_TOOLBOX_INSTALL_PATH ) { { stdio: 'inherit' } ); } + +// `composer update` reaches repo.packagist.org, so it is re-attempted for the same reasons as `up`. +const composer = local_env_utils.compose_with_retry( [ 'run', '-T', '--rm', 'php', 'composer', 'update', '-W' ], 3 ); + +if ( composer.status !== 0 ) { + console.error( '\nThere was an error while running PHP Composer update.' ); + console.error( 'This is often caused by network issues or Packagist.org downtime.' ); + console.error( 'Please check your internet connection and try again.' ); + + process.exit( composer.status ?? 1 ); +} From 890e607284112193dcd1a96d114c02ce5ff65e97 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:08:36 +0000 Subject: [PATCH 145/481] Posts, Post Types: Allow boundary post lookups outside single posts. Allow `get_boundary_post()` to return the first or last post on non-singular pages. Retain the missing-post guard when `$in_same_term` needs a current post, and continue rejecting unknown taxonomies. Add coverage for non-singular lookups and the missing-post case. Developed in: https://github.com/WordPress/wordpress-develop/pull/9200, https://github.com/WordPress/wordpress-develop/pull/9040 Props pathawks, sirlouen, iamadisingh, mukesh27, devasheeshkaul. Fixes #22957. git-svn-id: https://develop.svn.wordpress.org/trunk@65151 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/link-template.php | 6 +- tests/phpunit/tests/link/getBoundaryPost.php | 153 +++++++++++++++++++ 2 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/tests/link/getBoundaryPost.php diff --git a/src/wp-includes/link-template.php b/src/wp-includes/link-template.php index f6bd62e0e3ca5..aabf7bc69db79 100644 --- a/src/wp-includes/link-template.php +++ b/src/wp-includes/link-template.php @@ -2209,9 +2209,13 @@ function prev_post_rel_link( $title = '%title', $in_same_term = false, $excluded * @return array|null Array containing the boundary post object if successful, null otherwise. */ function get_boundary_post( $in_same_term = false, $excluded_terms = '', $start = true, $taxonomy = 'category' ) { + if ( ! taxonomy_exists( $taxonomy ) ) { + return null; + } + $post = get_post(); - if ( ! $post || ! is_single() || is_attachment() || ! taxonomy_exists( $taxonomy ) ) { + if ( $in_same_term && ! $post ) { return null; } diff --git a/tests/phpunit/tests/link/getBoundaryPost.php b/tests/phpunit/tests/link/getBoundaryPost.php new file mode 100644 index 0000000000000..ac8160cee06ea --- /dev/null +++ b/tests/phpunit/tests/link/getBoundaryPost.php @@ -0,0 +1,153 @@ + $factory->post->create( array( 'post_date' => '2020-01-01 12:00:00' ) ), + 'middle' => $factory->post->create( array( 'post_date' => '2021-01-01 12:00:00' ) ), + 'last' => $factory->post->create( array( 'post_date' => '2022-01-01 12:00:00' ) ), + ); + } + + /** + * @ticket 22957 + */ + public function test_should_work_on_non_singular_pages() { + // Navigate to the homepage, which is not a single post page. + $this->go_to( home_url( '/' ) ); + $this->assertFalse( is_single(), 'This test should be running on a non-single page.' ); + + // Test for the first post ($start = true, $in_same_term = false). + $first_boundary_post = get_boundary_post( false, '', true ); + $this->assertIsArray( $first_boundary_post, 'get_boundary_post() should return an array for the first post.' ); + $this->assertNotEmpty( $first_boundary_post, 'get_boundary_post() should not return an empty value for the first post.' ); + $this->assertSame( self::$post_ids['first'], $first_boundary_post[0]->ID, 'The first boundary post ID is incorrect.' ); + + // Test for the last post ($start = false, $in_same_term = false). + $last_boundary_post = get_boundary_post( false, '', false ); + $this->assertIsArray( $last_boundary_post, 'get_boundary_post() should return an array for the last post.' ); + $this->assertNotEmpty( $last_boundary_post, 'get_boundary_post() should not return an empty value for the last post.' ); + $this->assertSame( self::$post_ids['last'], $last_boundary_post[0]->ID, 'The last boundary post ID is incorrect.' ); + } + + /** + * @ticket 22957 + */ + public function test_should_return_null_for_in_same_term_without_current_post() { + // Navigate to a search results page with no matches, so there is no current post. + $this->go_to( home_url( '/?s=no-matching-posts' ) ); + $this->assertNull( get_post(), 'This test should be running without a current post.' ); + + $this->assertNull( get_boundary_post( true ) ); + } + + /** + * @ticket 22957 + */ + public function test_should_still_work_on_single_pages() { + // Navigate to a single post page. + $this->go_to( get_permalink( self::$post_ids['middle'] ) ); + $this->assertTrue( is_single(), 'This test should be running on a single page.' ); + + // Test for the first post ($start = true). + $first_boundary_post = get_boundary_post( false, '', true ); + $this->assertIsArray( $first_boundary_post, 'get_boundary_post() should return an array on a single page.' ); + $this->assertNotEmpty( $first_boundary_post, 'get_boundary_post() should not return an empty value for the first post on a single page.' ); + $this->assertSame( self::$post_ids['first'], $first_boundary_post[0]->ID, 'The first boundary post ID is incorrect on a single page.' ); + + // Test for the last post ($start = false). + $last_boundary_post = get_boundary_post( false, '', false ); + $this->assertIsArray( $last_boundary_post, 'get_boundary_post() should return an array for the last post on a single page.' ); + $this->assertNotEmpty( $last_boundary_post, 'get_boundary_post() should not return an empty value for the last post on a single page.' ); + $this->assertSame( self::$post_ids['last'], $last_boundary_post[0]->ID, 'The last boundary post ID is incorrect on a single page.' ); + } + + /** + * @ticket 22957 + */ + public function test_should_work_on_archive_pages() { + // Create a category and assign posts to test archive functionality. + $cat_id = self::factory()->category->create(); + wp_set_post_categories( self::$post_ids['first'], array( $cat_id ) ); + wp_set_post_categories( self::$post_ids['last'], array( $cat_id ) ); + + // Navigate to a category archive page. + $this->go_to( get_category_link( $cat_id ) ); + $this->assertTrue( is_category(), 'This test should be running on a category archive page.' ); + + // Test boundary posts work on archive pages. + $first_boundary_post = get_boundary_post( false, '', true ); + $this->assertIsArray( $first_boundary_post ); + $this->assertNotEmpty( $first_boundary_post ); + $this->assertSame( self::$post_ids['first'], $first_boundary_post[0]->ID ); + + $last_boundary_post = get_boundary_post( false, '', false ); + $this->assertIsArray( $last_boundary_post ); + $this->assertNotEmpty( $last_boundary_post ); + $this->assertSame( self::$post_ids['last'], $last_boundary_post[0]->ID ); + } + + /** + * @ticket 22957 + */ + public function test_should_respect_in_same_term_parameter() { + // Create categories. + $cat1 = self::factory()->category->create(); + $cat2 = self::factory()->category->create(); + + // Assign different categories to posts. + wp_set_post_categories( self::$post_ids['first'], array( $cat1 ) ); + wp_set_post_categories( self::$post_ids['middle'], array( $cat1 ) ); + wp_set_post_categories( self::$post_ids['last'], array( $cat2 ) ); + + // Navigate to the middle post to provide current post context. + $this->go_to( get_permalink( self::$post_ids['middle'] ) ); + $this->assertTrue( is_single(), 'This test should be running on a single page.' ); + + // Test with $in_same_term = true (should find posts in same category as current post). + $first_boundary_post = get_boundary_post( true, '', true ); + $this->assertIsArray( $first_boundary_post ); + $this->assertSame( self::$post_ids['first'], $first_boundary_post[0]->ID, 'Should find first post in same category.' ); + + $last_boundary_post = get_boundary_post( true, '', false ); + $this->assertIsArray( $last_boundary_post ); + $this->assertSame( self::$post_ids['middle'], $last_boundary_post[0]->ID, 'Should find middle post as last in same category.' ); + + // Test with $in_same_term = false (should work normally across all posts). + $first_boundary_post_all = get_boundary_post( false, '', true ); + $this->assertIsArray( $first_boundary_post_all ); + $this->assertSame( self::$post_ids['first'], $first_boundary_post_all[0]->ID ); + + $last_boundary_post_all = get_boundary_post( false, '', false ); + $this->assertIsArray( $last_boundary_post_all ); + $this->assertSame( self::$post_ids['last'], $last_boundary_post_all[0]->ID ); + } + + /** + * @ticket 22957 + */ + public function test_should_return_null_for_invalid_taxonomy() { + $this->go_to( home_url( '/' ) ); + + $boundary_post = get_boundary_post( false, '', true, 'nonexistent_taxonomy' ); + $this->assertNull( $boundary_post, 'get_boundary_post() should return null for non-existent taxonomy.' ); + } +} From 6ea8c0a3d76d7808c8298bb7a07126665a280aba Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:15:08 +0000 Subject: [PATCH 146/481] Tests: Cover AJAX menu, editor and preference actions. Verify menu metabox output and saved menu locations, dismissed pointers, fullscreen post updates, and post-lock ownership and expiry. Cover relevant permission and nonce rejection paths. Developed in: https://github.com/WordPress/wordpress-develop/pull/11897, https://github.com/WordPress/wordpress-develop/pull/11899, https://github.com/WordPress/wordpress-develop/pull/12138 Props pbearne, ugyensupport. See #65252. git-svn-id: https://develop.svn.wordpress.org/trunk@65152 602fd350-edb4-49c9-b593-d223f7449a82 --- .../includes/ajax-actions/menuGetMetabox.php | 172 ++++++++++++++++++ .../ajax-actions/menuLocationsSave.php | 141 ++++++++++++++ .../wp_ajax_dismiss_wp_pointer.php | 87 +++++++++ .../wp_ajax_wp_fullscreen_save_post.php | 73 ++++++++ .../wp_ajax_wp_remove_post_lock.php | 79 ++++++++ 5 files changed, 552 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/menuGetMetabox.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/menuLocationsSave.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_dismiss_wp_pointer.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_fullscreen_save_post.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_remove_post_lock.php diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/menuGetMetabox.php b/tests/phpunit/tests/admin/includes/ajax-actions/menuGetMetabox.php new file mode 100644 index 0000000000000..fba5408041c43 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/menuGetMetabox.php @@ -0,0 +1,172 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + } + + /** + * Tests retrieval of post type metabox. + * + * @ticket 65252 + */ + public function test_menu_get_metabox_post_type(): void { + wp_set_current_user( self::$admin_id ); + + self::factory()->post->create( + array( + 'post_title' => 'Post Metabox Test', + ) + ); + + $_POST = array( + 'action' => 'menu-get-metabox', + 'item-type' => 'post_type', + 'item-object' => 'post', + ); + + try { + $this->_handleAjax( 'menu-get-metabox' ); + } catch ( WPAjaxDieContinueException $e ) { + // We expect the function to die after echoing JSON. + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertIsArray( $response ); + $this->assertSame( 'posttype-post', $response['replace-id'] ); + $this->assertStringContainsString( 'id="posttype-post"', $response['markup'] ); + $this->assertStringContainsString( 'Post', $response['markup'] ); + } + + /** + * Tests retrieval of taxonomy metabox. + * + * @ticket 65252 + */ + public function test_menu_get_metabox_taxonomy(): void { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'menu-get-metabox', + 'item-type' => 'taxonomy', + 'item-object' => 'category', + ); + + try { + $this->_handleAjax( 'menu-get-metabox' ); + } catch ( WPAjaxDieContinueException $e ) { + // We expect the function to die after echoing JSON. + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertIsArray( $response ); + $this->assertSame( 'taxonomy-category', $response['replace-id'] ); + $this->assertStringContainsString( 'id="taxonomy-category"', $response['markup'] ); + $this->assertStringContainsString( 'Categories', $response['markup'] ); + } + + /** + * Tests failure due to insufficient permissions. + * + * @ticket 65252 + */ + public function test_menu_get_metabox_insufficient_permissions(): void { + wp_set_current_user( self::$subscriber_id ); + + $_POST = array( + 'action' => 'menu-get-metabox', + 'item-type' => 'post_type', + 'item-object' => 'post', + ); + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'menu-get-metabox' ); + } + + /** + * Tests behavior with invalid item-type. + * + * @ticket 65252 + */ + public function test_menu_get_metabox_invalid_item_type(): void { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'menu-get-metabox', + 'item-type' => 'invalid', + 'item-object' => 'post', + ); + + try { + $this->_handleAjax( 'menu-get-metabox' ); + } catch ( WPAjaxDieStopException $e ) { + // We expect it to die without outputting anything if item-type is invalid. + } + + $this->assertEmpty( $this->_last_response ); + } + + /** + * Tests behavior with invalid item-object. + * + * @ticket 65252 + */ + public function test_menu_get_metabox_invalid_item_object(): void { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'menu-get-metabox', + 'item-type' => 'post_type', + 'item-object' => 'non_existent_post_type', + ); + + try { + $this->_handleAjax( 'menu-get-metabox' ); + } catch ( WPAjaxDieStopException $e ) { + // We expect it to die without outputting anything if item-object is invalid. + } + + $this->assertEmpty( $this->_last_response ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/menuLocationsSave.php b/tests/phpunit/tests/admin/includes/ajax-actions/menuLocationsSave.php new file mode 100644 index 0000000000000..12e1c2b67523b --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/menuLocationsSave.php @@ -0,0 +1,141 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + } + + /** + * Tests successful saving of menu locations. + * + * @ticket 65252 + */ + public function test_menu_locations_save_success(): void { + wp_set_current_user( self::$admin_id ); + + $menu_id = self::factory()->term->create( + array( + 'name' => 'Test Menu', + 'taxonomy' => 'nav_menu', + ) + ); + + $_POST = array( + 'action' => 'menu-locations-save', + 'menu-settings-column-nonce' => wp_create_nonce( 'add-menu_item' ), + 'menu-locations' => array( + 'primary' => $menu_id, + ), + ); + + try { + $this->_handleAjax( 'menu-locations-save' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '1', $e->getMessage(), 'The AJAX response should be 1.' ); + } + + $locations = get_theme_mod( 'nav_menu_locations' ); + $this->assertIsArray( $locations ); + $this->assertSame( $menu_id, $locations['primary'] ); + } + + /** + * Tests failure due to invalid nonce. + * + * @ticket 65252 + */ + public function test_menu_locations_save_invalid_nonce(): void { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'menu-locations-save', + 'menu-settings-column-nonce' => 'invalid-nonce', + 'menu-locations' => array( + 'primary' => 1, + ), + ); + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'menu-locations-save' ); + } + + /** + * Tests failure due to missing menu-locations. + * + * @ticket 65252 + */ + public function test_menu_locations_save_missing_locations(): void { + wp_set_current_user( self::$admin_id ); + + $_POST = array( + 'action' => 'menu-locations-save', + 'menu-settings-column-nonce' => wp_create_nonce( 'add-menu_item' ), + ); + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '0' ); + + $this->_handleAjax( 'menu-locations-save' ); + } + + /** + * Tests failure due to insufficient permissions. + * + * @ticket 65252 + */ + public function test_menu_locations_save_insufficient_permissions(): void { + wp_set_current_user( self::$subscriber_id ); + + $_POST = array( + 'action' => 'menu-locations-save', + 'menu-settings-column-nonce' => wp_create_nonce( 'add-menu_item' ), + 'menu-locations' => array( + 'primary' => 1, + ), + ); + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'menu-locations-save' ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_dismiss_wp_pointer.php b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_dismiss_wp_pointer.php new file mode 100644 index 0000000000000..1f59866e492ad --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_dismiss_wp_pointer.php @@ -0,0 +1,87 @@ +user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $pointer = 'test-pointer'; + + $_POST = array( + 'pointer' => $pointer, + ); + + try { + $this->_handleAjax( 'dismiss-wp-pointer' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '1', $e->getMessage() ); + } + + $dismissed = explode( ',', (string) get_user_meta( $user_id, 'dismissed_wp_pointers', true ) ); + $this->assertContains( $pointer, $dismissed ); + } + + /** + * @covers ::wp_ajax_dismiss_wp_pointer + * @ticket 65252 + */ + public function test_wp_ajax_dismiss_wp_pointer_invalid_pointer() { + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $_POST = array( + 'pointer' => 'invalid pointer with spaces', + ); + + try { + $this->_handleAjax( 'dismiss-wp-pointer' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '0', $e->getMessage() ); + } + + $dismissed = get_user_meta( $user_id, 'dismissed_wp_pointers', true ); + $this->assertEmpty( $dismissed ); + } + + /** + * @covers ::wp_ajax_dismiss_wp_pointer + * @ticket 65252 + */ + public function test_wp_ajax_dismiss_wp_pointer_already_dismissed() { + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $pointer = 'test-pointer'; + update_user_meta( $user_id, 'dismissed_wp_pointers', $pointer ); + + $_POST = array( + 'pointer' => $pointer, + ); + + try { + $this->_handleAjax( 'dismiss-wp-pointer' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '0', $e->getMessage() ); + } + + $dismissed = get_user_meta( $user_id, 'dismissed_wp_pointers', true ); + $this->assertSame( $pointer, $dismissed ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_fullscreen_save_post.php b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_fullscreen_save_post.php new file mode 100644 index 0000000000000..72e2641d93a26 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_fullscreen_save_post.php @@ -0,0 +1,73 @@ +post->create( + array( + 'post_title' => 'Original Title', + 'post_content' => 'Original Content', + ) + ); + + $this->_setRole( 'administrator' ); + + $_POST = array( + 'post_ID' => $post_id, + 'post_title' => 'Updated Title', + 'post_content' => 'Updated Content', + '_wpnonce' => wp_create_nonce( 'update-post_' . $post_id ), + ); + + try { + $this->_handleAjax( 'wp-fullscreen-save-post' ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertTrue( $response['success'] ); + $this->assertArrayHasKey( 'last_edited', $response['data'] ); + + $post = get_post( $post_id ); + $this->assertSame( 'Updated Title', $post->post_title ); + $this->assertSame( 'Updated Content', $post->post_content ); + } + + /** + * @covers ::wp_ajax_wp_fullscreen_save_post + * @ticket 65252 + */ + public function test_wp_ajax_wp_fullscreen_save_post_invalid_nonce() { + $post_id = self::factory()->post->create(); + + $this->_setRole( 'administrator' ); + + $_POST = array( + 'post_ID' => $post_id, + '_wpnonce' => 'invalid-nonce', + ); + + $this->expectException( 'WPAjaxDieStopException' ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'wp-fullscreen-save-post' ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_remove_post_lock.php b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_remove_post_lock.php new file mode 100644 index 0000000000000..3cb96b009b882 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wp_ajax_wp_remove_post_lock.php @@ -0,0 +1,79 @@ +user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $post_id = self::factory()->post->create(); + + $lock_time = time() - 100; + $active_lock = $lock_time . ':' . $user_id; + update_post_meta( $post_id, '_edit_lock', $active_lock ); + + $_POST = array( + 'post_ID' => $post_id, + 'active_post_lock' => $active_lock, + '_ajax_nonce' => wp_create_nonce( 'update-post_' . $post_id ), + ); + + try { + $this->_handleAjax( 'wp-remove-post-lock' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '1', $e->getMessage() ); + } + + $new_lock = get_post_meta( $post_id, '_edit_lock', true ); + $this->assertNotSame( $active_lock, $new_lock ); + $parts = explode( ':', $new_lock ); + $this->assertSame( (string) $user_id, $parts[1] ); + $this->assertLessThanOrEqual( time() - 145, (int) $parts[0] ); + } + + /** + * @covers ::wp_ajax_wp_remove_post_lock + * @ticket 65252 + */ + public function test_wp_ajax_wp_remove_post_lock_wrong_user() { + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + $other_user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $post_id = self::factory()->post->create(); + + $lock_time = time() - 100; + $active_lock = $lock_time . ':' . $other_user_id; + update_post_meta( $post_id, '_edit_lock', $active_lock ); + + $_POST = array( + 'post_ID' => $post_id, + 'active_post_lock' => $active_lock, + '_ajax_nonce' => wp_create_nonce( 'update-post_' . $post_id ), + ); + + try { + $this->_handleAjax( 'wp-remove-post-lock' ); + } catch ( WPAjaxDieStopException $e ) { + $this->assertSame( '0', $e->getMessage() ); + } + + $this->assertSame( $active_lock, get_post_meta( $post_id, '_edit_lock', true ) ); + } +} From bc2512f15fe5dabbaf2fca0eeba41c2544129f30 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:16:02 +0000 Subject: [PATCH 147/481] Tests: Verify the frame options response header. Assert that `send_frame_options_header()` sends `X-Frame-Options: SAMEORIGIN`, using Xdebug header inspection in an isolated process. Developed in: https://github.com/WordPress/wordpress-develop/pull/5638 Props pbearne, swissspidy. See #59851. git-svn-id: https://develop.svn.wordpress.org/trunk@65153 602fd350-edb4-49c9-b593-d223f7449a82 --- .../functions/sendFrameOptionsHeader.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tests/phpunit/tests/functions/sendFrameOptionsHeader.php diff --git a/tests/phpunit/tests/functions/sendFrameOptionsHeader.php b/tests/phpunit/tests/functions/sendFrameOptionsHeader.php new file mode 100644 index 0000000000000..d006f2f1df1d1 --- /dev/null +++ b/tests/phpunit/tests/functions/sendFrameOptionsHeader.php @@ -0,0 +1,30 @@ +assertContains( 'X-Frame-Options: SAMEORIGIN', $headers ); + } +} From d16d2fa837501e6188b2302a0784ce1f2e3e7cb0 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:16:47 +0000 Subject: [PATCH 148/481] Tests: Cover generated image filename collisions. Test `_wp_check_existing_file_names()` against image dimensions, scaled and rotated suffixes, and filenames without a basename or extension. Developed in: https://github.com/WordPress/wordpress-develop/pull/2332 Props pbearne, azouamauriac, costdev. Fixes #55192. git-svn-id: https://develop.svn.wordpress.org/trunk@65154 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 1 + .../functions/_wpCheckExistingFileNames.php | 82 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 tests/phpunit/tests/functions/_wpCheckExistingFileNames.php diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index d3493594cb7f6..0745f0b891f9b 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -2912,6 +2912,7 @@ function _wp_check_existing_file_names( $filename, $files ) { // Edge case, file names like `.ext`. if ( empty( $fname ) ) { + return false; } diff --git a/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php b/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php new file mode 100644 index 0000000000000..13d6fee1d79d0 --- /dev/null +++ b/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php @@ -0,0 +1,82 @@ +assertSame( $expected, _wp_check_existing_file_names( $filename, $files ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public function data_wp_check_existing_file_names() { + return array( + 'no size' => array( + 'filename' => 'filename.php', + 'files' => array( 'filename.php' ), + 'expected' => false, + ), + '1x1' => array( + 'filename' => 'filename.png', + 'files' => array( 'filename-1x1.png' ), + 'expected' => true, + ), + '1x999999999999' => array( + 'filename' => 'filename.png', + 'files' => array( 'filename-1x999999999999.png' ), + 'expected' => true, + ), + 'scaled' => array( + 'filename' => 'filename.png', + 'files' => array( 'filename-scaled.png' ), + 'expected' => true, + ), + 'three matches' => array( + 'filename' => 'filename.ext', + 'files' => array( 'filename-1x1.ext', 'filename-scaled.ext', 'filename-rotated.ext' ), + 'expected' => true, + ), + 'rotated' => array( + 'filename' => 'filename.png', + 'files' => array( 'filename-rotated.png' ), + 'expected' => true, + ), + 'no extension' => array( + 'filename' => 'filename', + 'files' => array( 'filename-1x1.png' ), + 'expected' => false, + ), + 'no filename' => array( + 'filename' => '.htaccess', + 'files' => array( 'filename-1x1.png' ), + 'expected' => false, + ), + 'found file with no extension' => array( + 'filename' => 'filename', + 'files' => array( 'filename' ), + 'expected' => false, + ), + 'found file with no filename' => array( + 'filename' => '.htaccess', + 'files' => array( '.htaccess' ), + 'expected' => false, + ), + ); + } +} From 7b4e9b1b649918b431600c954a42f278e5943cf9 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:17:45 +0000 Subject: [PATCH 149/481] Tests: Use explicit database charsets in charset fixtures. Use `utf8mb3` where fixtures require three-byte UTF-8, and explicit `utf8mb4` collations for the connection test. This avoids relying on the `utf8` alias, which resolves to `utf8mb4` by default in MariaDB 13.1. Developed in: https://github.com/WordPress/wordpress-develop/pull/13497 Props micahele. Fixes #66072. git-svn-id: https://develop.svn.wordpress.org/trunk@65155 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/db/charset.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/phpunit/tests/db/charset.php b/tests/phpunit/tests/db/charset.php index f57119d103ccf..8fb905f8ab970 100644 --- a/tests/phpunit/tests/db/charset.php +++ b/tests/phpunit/tests/db/charset.php @@ -749,7 +749,7 @@ public function test_strip_invalid_text_for_column() { ), ), array( - 'definition' => '( a VARCHAR(50) CHARACTER SET utf8, b TEXT CHARACTER SET utf8mb4 )', + 'definition' => '( a VARCHAR(50) CHARACTER SET utf8mb3, b TEXT CHARACTER SET utf8mb4 )', 'table_expected' => 'utf8', 'column_expected' => array( 'a' => 'utf8', @@ -786,6 +786,7 @@ public static function data_get_table_charset() { /** * @dataProvider data_get_table_charset * @ticket 21212 + * @ticket 66072 * * @covers wpdb::get_table_charset */ @@ -822,6 +823,7 @@ public static function data_get_column_charset() { /** * @dataProvider data_get_column_charset * @ticket 21212 + * @ticket 66072 * * @covers wpdb::get_col_charset */ @@ -907,7 +909,7 @@ public static function data_strip_invalid_text_from_query() { ), 'utf8 + utf8mb4' => array( // utf8/utf8mb4 tables default to utf8. - 'create' => '( a VARCHAR(50) CHARACTER SET utf8, b VARCHAR(50) CHARACTER SET utf8mb4 )', + 'create' => '( a VARCHAR(50) CHARACTER SET utf8mb3, b VARCHAR(50) CHARACTER SET utf8mb4 )', 'query' => "('foo\xf0\x9f\x98\x88bar', 'foo')", 'expected' => "('foobar', 'foo')", ), @@ -931,6 +933,7 @@ public static function data_strip_invalid_text_from_query() { /** * @dataProvider data_strip_invalid_text_from_query * @ticket 21212 + * @ticket 66072 * * @covers wpdb::strip_invalid_text_from_query */ @@ -1155,14 +1158,15 @@ public function test_no_db_charset_defined() { /** * @ticket 36649 + * @ticket 66072 * * @covers wpdb::set_charset */ public function test_set_charset_changes_the_connection_collation() { - self::$_wpdb->set_charset( self::$_wpdb->dbh, 'utf8', 'utf8_general_ci' ); - $results = self::$_wpdb->get_results( "SHOW VARIABLES WHERE Variable_name='collation_connection'" ); - $expected = self::$utf8_is_utf8mb3 ? 'utf8mb3_general_ci' : 'utf8_general_ci'; - $this->assertSame( $expected, $results[0]->Value, "Collation should be set to $expected." ); + // Avoid the `utf8` alias: it resolves to utf8mb3 or utf8mb4 depending on the server version. + self::$_wpdb->set_charset( self::$_wpdb->dbh, 'utf8mb4', 'utf8mb4_general_ci' ); + $results = self::$_wpdb->get_results( "SHOW VARIABLES WHERE Variable_name='collation_connection'" ); + $this->assertSame( 'utf8mb4_general_ci', $results[0]->Value, 'Collation should be set to utf8mb4_general_ci.' ); self::$_wpdb->set_charset( self::$_wpdb->dbh, 'utf8mb4', 'utf8mb4_unicode_ci' ); $results = self::$_wpdb->get_results( "SHOW VARIABLES WHERE Variable_name='collation_connection'" ); From 4f9947beb0c7385b51be467284813cf3922bd322 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:19:08 +0000 Subject: [PATCH 150/481] Tests: Cover the Apache rewrite fallback and filter. Verify `got_mod_rewrite()` uses the server flag for its CLI fallback and passes that detected value to `got_rewrite`. Check that the filter can override the result and restore the server flag after each test. Developed in: https://github.com/WordPress/wordpress-develop/pull/11656 Props pbearne, westonruter. Fixes #65134. git-svn-id: https://develop.svn.wordpress.org/trunk@65156 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/includes/misc/gotModRewrite.php | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/misc/gotModRewrite.php diff --git a/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php b/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php new file mode 100644 index 0000000000000..b53219cdb9d35 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php @@ -0,0 +1,101 @@ +original_is_apache = $is_apache; + } + + /** + * Restores the `$is_apache` global. + * + * @global bool|null $is_apache + */ + public function tear_down() { + $GLOBALS['is_apache'] = $this->original_is_apache; + parent::tear_down(); + } + + /** + * Tests that got_mod_rewrite() depends on whether the server is Apache, and that the filter overrides it. + * + * @ticket 65134 + * + * @dataProvider data_got_mod_rewrite + * + * @param bool $is_apache Whether the server is Apache. + * @param bool $filter_value Value to return via the 'got_rewrite' filter. + */ + public function test_got_mod_rewrite( bool $is_apache, bool $filter_value ): void { + $GLOBALS['is_apache'] = $is_apache; + + /* + * On Apache, apache_mod_loaded() falls back to the default of true when the module list + * cannot be determined (as in the CLI), and it always returns false for other servers. + * So this covers the server check and the default value, not actual module detection, + * which would require apache_get_modules() to be available. + */ + $this->assertSame( $is_apache, got_mod_rewrite(), 'Expected the unfiltered result to be true on Apache (via the default value) and false otherwise.' ); + + $filtered_value = null; + add_filter( + 'got_rewrite', + static function ( $got_rewrite ) use ( $filter_value, &$filtered_value ) { + $filtered_value = $got_rewrite; + return $filter_value; + } + ); + + $this->assertSame( $filter_value, got_mod_rewrite(), 'Expected the filter to override the detected value.' ); + $this->assertSame( $is_apache, $filtered_value, 'Expected the filter to receive the detected value.' ); + } + + /** + * Data provider for {@see self::test_got_mod_rewrite()}. + * + * @return array + */ + public function data_got_mod_rewrite(): array { + return array( + 'Apache, filter returns true' => array( + 'is_apache' => true, + 'filter_value' => true, + ), + 'Apache, filter returns false' => array( + 'is_apache' => true, + 'filter_value' => false, + ), + 'Non-Apache, filter returns true' => array( + 'is_apache' => false, + 'filter_value' => true, + ), + 'Non-Apache, filter returns false' => array( + 'is_apache' => false, + 'filter_value' => false, + ), + ); + } +} From cb185940d958525ca3e1f528bfe0af8e7fd603d0 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:25:13 +0000 Subject: [PATCH 151/481] Tests: Correct HTML processor assertion capitalization. Use `assertSame()` consistently in the HTML processor semantic rules test. Developed in: https://github.com/WordPress/wordpress-develop/pull/15300 Props denisej25, rejaulalomkhan. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65157 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/html-api/wpHtmlProcessorSemanticRules.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/phpunit/tests/html-api/wpHtmlProcessorSemanticRules.php b/tests/phpunit/tests/html-api/wpHtmlProcessorSemanticRules.php index da6d959eb75e0..8448735b12a3e 100644 --- a/tests/phpunit/tests/html-api/wpHtmlProcessorSemanticRules.php +++ b/tests/phpunit/tests/html-api/wpHtmlProcessorSemanticRules.php @@ -446,6 +446,6 @@ public function test_table_form_element_immediately_popped() { // Followed by the comment token. $this->assertTrue( $processor->next_token() ); $this->assertSame( '#comment', $processor->get_token_name() ); - $this->assertsame( array( 'HTML', 'BODY', 'TABLE', '#comment' ), $processor->get_breadcrumbs() ); + $this->assertSame( array( 'HTML', 'BODY', 'TABLE', '#comment' ), $processor->get_breadcrumbs() ); } } From 392df1963a6b1018b04bbb310f67e7a40b28f1a0 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sat, 31 Oct 2026 21:28:01 +0000 Subject: [PATCH 152/481] Build/Test Tools: Preserve precise video metadata type inference. Remove the broad `$metadata` annotation and the always-true `created_timestamp` guard in `wp_read_video_metadata()`. Preserve the timestamp helper call and strict `false` check. Combine the pointer array type annotations with their explanatory docblocks. Follow-up to [65149]. Developed in: https://github.com/WordPress/wordpress-develop/pull/15303 Props westonruter. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65158 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/class-wp-internal-pointers.php | 10 ++++++---- src/wp-admin/includes/media.php | 10 +++------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/wp-admin/includes/class-wp-internal-pointers.php b/src/wp-admin/includes/class-wp-internal-pointers.php index 448e7af914c08..0e11d759a9b0e 100644 --- a/src/wp-admin/includes/class-wp-internal-pointers.php +++ b/src/wp-admin/includes/class-wp-internal-pointers.php @@ -35,7 +35,7 @@ final class WP_Internal_Pointers { * @param string $hook_suffix The current admin page. */ public static function enqueue_scripts( $hook_suffix ) { - /* + /** * Register feature pointers * * Format: @@ -47,8 +47,9 @@ public static function enqueue_scripts( $hook_suffix ) { * array( * 'themes.php' => 'wp390_widgets' * ) + * + * @var array $registered_pointers */ - /** @var array $registered_pointers */ $registered_pointers = array( // None currently. ); @@ -60,7 +61,7 @@ public static function enqueue_scripts( $hook_suffix ) { $pointers = (array) $registered_pointers[ $hook_suffix ]; - /* + /** * Specify required capabilities for feature pointers * * Format: @@ -72,8 +73,9 @@ public static function enqueue_scripts( $hook_suffix ) { * array( * 'wp390_widgets' => array( 'edit_theme_options' ) * ) + * + * @var array $caps_required */ - /** @var array $caps_required */ $caps_required = array( // None currently. ); diff --git a/src/wp-admin/includes/media.php b/src/wp-admin/includes/media.php index 896af458eb408..9f5b87ce85f93 100644 --- a/src/wp-admin/includes/media.php +++ b/src/wp-admin/includes/media.php @@ -3677,7 +3677,6 @@ function wp_read_video_metadata( $file ) { return false; } - /** @var array $metadata */ $metadata = array(); if ( ! defined( 'GETID3_TEMP_DIR' ) ) { @@ -3751,12 +3750,9 @@ function wp_read_video_metadata( $file ) { $metadata['audio'] = $data['audio']; } - if ( empty( $metadata['created_timestamp'] ) ) { - $created_timestamp = wp_get_media_creation_timestamp( $data ); - - if ( false !== $created_timestamp ) { - $metadata['created_timestamp'] = $created_timestamp; - } + $created_timestamp = wp_get_media_creation_timestamp( $data ); + if ( false !== $created_timestamp ) { + $metadata['created_timestamp'] = $created_timestamp; } wp_add_id3_tag_data( $metadata, $data ); From 15e95f3530db532da0791c78273325a8a5faca52 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sat, 31 Oct 2026 23:39:24 +0000 Subject: [PATCH 153/481] Menus: Simplify redundant conditions in `wp-includes/nav-menu.php` Simplifies redundant conditional logic: 1. In `wp_update_nav_menu_object()`: The preceding `if ( ! $_menu || is_wp_error( $_menu ) )` block handles non-existing menu creation and returns, so $_menu is guaranteed truthy. Dropped the redundant `! $_menu` check before `isset( $_menu->term_id )`. 2. In `wp_update_nav_menu_item()`: In the `elseif ( 0 === (int) $args['menu-item-position'] )` block, `$menu_id` is guaranteed non-zero because the preceding `if ( 0 === $menu_id )` block already handled `$menu_id === 0`. Removed the redundant `if ( 0 !== $menu_id )` check. 3. In `wp_map_nav_menu_locations()`: $slug is an alphanumeric theme location key string; comparing non-string types with $slug is strictly always true. Simplified `is_numeric(...) && ... !== $slug` to `! is_string(...)`. This resolves all `notIdentical.alwaysTrue` and `booleanNot.alwaysFalse` occurrences in `wp-includes/nav-menu.php`. Developed in https://github.com/WordPress/wordpress-develop/pull/14931. Props huzaifaalmesbah. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65159 602fd350-edb4-49c9-b593-d223f7449a82 --- phpstan.neon.dist | 1 - src/wp-includes/nav-menu.php | 12 +++------ .../baselines/booleanNot.alwaysFalse.neon | 25 ------------------- .../baselines/notIdentical.alwaysTrue.neon | 10 -------- 4 files changed, 4 insertions(+), 44 deletions(-) delete mode 100644 tests/phpstan/baselines/booleanNot.alwaysFalse.neon diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 55097717df3ee..52ac7ab489adf 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -28,7 +28,6 @@ includes: - tests/phpstan/baselines/binaryOp.invalid.neon - tests/phpstan/baselines/booleanAnd.alwaysFalse.neon - tests/phpstan/baselines/booleanAnd.leftAlwaysTrue.neon - - tests/phpstan/baselines/booleanNot.alwaysFalse.neon - tests/phpstan/baselines/booleanNot.alwaysTrue.neon - tests/phpstan/baselines/class.notFound.neon - tests/phpstan/baselines/deadCode.unreachable.neon diff --git a/src/wp-includes/nav-menu.php b/src/wp-includes/nav-menu.php index ed49892ac0eb6..40612d5b8d937 100644 --- a/src/wp-includes/nav-menu.php +++ b/src/wp-includes/nav-menu.php @@ -374,7 +374,7 @@ function wp_update_nav_menu_object( $menu_id = 0, $menu_data = array() ) { return (int) $_menu['term_id']; } - if ( ! $_menu || ! isset( $_menu->term_id ) ) { + if ( ! isset( $_menu->term_id ) ) { return 0; } @@ -458,11 +458,7 @@ function wp_update_nav_menu_item( $menu_id = 0, $menu_item_db_id = 0, $menu_item if ( 0 === $menu_id ) { $args['menu-item-position'] = 1; } elseif ( 0 === (int) $args['menu-item-position'] ) { - $menu_items = array(); - - if ( 0 !== $menu_id ) { - $menu_items = (array) wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) ); - } + $menu_items = (array) wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) ); $last_item = array_pop( $menu_items ); @@ -1281,7 +1277,7 @@ function wp_map_nav_menu_locations( $new_nav_menu_locations, $old_nav_menu_locat // ...actually match! if ( is_string( $new_location ) && false === stripos( $new_location, $slug ) && false === stripos( $slug, $new_location ) ) { continue; - } elseif ( is_numeric( $new_location ) && $new_location !== $slug ) { + } elseif ( ! is_string( $new_location ) ) { continue; } @@ -1294,7 +1290,7 @@ function wp_map_nav_menu_locations( $new_nav_menu_locations, $old_nav_menu_locat // ... have a match as well. if ( is_string( $location ) && false === stripos( $location, $slug ) && false === stripos( $slug, $location ) ) { continue; - } elseif ( is_numeric( $location ) && $location !== $slug ) { + } elseif ( ! is_string( $location ) ) { continue; } diff --git a/tests/phpstan/baselines/booleanNot.alwaysFalse.neon b/tests/phpstan/baselines/booleanNot.alwaysFalse.neon deleted file mode 100644 index 93f05e16c3ef3..0000000000000 --- a/tests/phpstan/baselines/booleanNot.alwaysFalse.neon +++ /dev/null @@ -1,25 +0,0 @@ -# PHPStan baseline for the `booleanNot.alwaysFalse` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/booleanNot.alwaysFalse -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=booleanNot.alwaysFalse -# -# which reruns the analysis with this file suppressed so the errors surface again. - -parameters: - ignoreErrors: - - - message: '#^Negated boolean expression is always false\.$#' - identifier: booleanNot.alwaysFalse - count: 1 - path: ../../../src/wp-includes/nav-menu.php diff --git a/tests/phpstan/baselines/notIdentical.alwaysTrue.neon b/tests/phpstan/baselines/notIdentical.alwaysTrue.neon index ed00a5e7f8fe6..f4daf4d4ebc01 100644 --- a/tests/phpstan/baselines/notIdentical.alwaysTrue.neon +++ b/tests/phpstan/baselines/notIdentical.alwaysTrue.neon @@ -23,16 +23,6 @@ parameters: identifier: notIdentical.alwaysTrue count: 1 path: ../../../src/wp-includes/functions.php - - - message: '#^Strict comparison using \!\=\= between 0 and int\\|int\<1, max\> will always evaluate to true\.$#' - identifier: notIdentical.alwaysTrue - count: 1 - path: ../../../src/wp-includes/nav-menu.php - - - message: '#^Strict comparison using \!\=\= between float\|int\|numeric\-string and ''bottom''\|''footer''\|''header''\|''main''\|''menu\-1''\|''menu\-2''\|''navigation''\|''primary''\|''secondary''\|''social''\|''subsidiary''\|''top'' will always evaluate to true\.$#' - identifier: notIdentical.alwaysTrue - count: 2 - path: ../../../src/wp-includes/nav-menu.php - message: '#^Strict comparison using \!\=\= between false and int will always evaluate to true\.$#' identifier: notIdentical.alwaysTrue From 0d4a0ee7254a4afa255cb25b66671182d9bd83ca Mon Sep 17 00:00:00 2001 From: John James Jacoby Date: Sun, 1 Nov 2026 03:10:29 +0000 Subject: [PATCH 154/481] Networks and Sites: Remove view modes from the Network Sites and Users list tables. The list and excerpt modes on these screens differ only by timestamps and optional site title and tagline output. Remove both view switchers and their request handling, and stop reading and writing the related user settings. Use the former excerpt-mode date format as the canonical display. Remove the site title and tagline output to avoid additional per-row option reads. Update the screen help text and add focused multisite tests. Developed in https://github.com/WordPress/wordpress-develop/pull/13120. Props afercia, johnjamesjacoby, realloc, sukhendu2002. Fixes #43899. git-svn-id: https://develop.svn.wordpress.org/trunk@65160 602fd350-edb4-49c9-b593-d223f7449a82 --- .../includes/class-wp-ms-sites-list-table.php | 67 +---------------- .../includes/class-wp-ms-users-list-table.php | 41 +--------- src/wp-admin/network/sites.php | 2 +- src/wp-admin/network/users.php | 2 +- .../tests/multisite/wpMsSitesListTable.php | 75 +++++++++++++++++++ .../tests/multisite/wpMsUsersListTable.php | 34 +++++++++ 6 files changed, 116 insertions(+), 105 deletions(-) diff --git a/src/wp-admin/includes/class-wp-ms-sites-list-table.php b/src/wp-admin/includes/class-wp-ms-sites-list-table.php index a12954827ee55..2738856f8889b 100644 --- a/src/wp-admin/includes/class-wp-ms-sites-list-table.php +++ b/src/wp-admin/includes/class-wp-ms-sites-list-table.php @@ -65,19 +65,11 @@ public function ajax_user_can() { * * @since 3.1.0 * - * @global string $mode List table view mode. * @global string $s Search string. * @global wpdb $wpdb WordPress database abstraction object. */ public function prepare_items() { - global $mode, $s, $wpdb; - - if ( ! empty( $_REQUEST['mode'] ) ) { - $mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list'; - set_user_setting( 'sites_list_mode', $mode ); - } else { - $mode = get_user_setting( 'sites_list_mode', 'list' ); - } + global $s, $wpdb; $per_page = $this->get_items_per_page( 'sites_network_per_page' ); @@ -310,27 +302,6 @@ protected function get_bulk_actions() { return $actions; } - /** - * Displays the pagination. - * - * @since 3.1.0 - * - * @global string $mode List table view mode. - * - * @param string $which The location of the pagination nav markup: Either 'top' or 'bottom'. - * - * @phpstan-param 'top'|'bottom' $which - */ - protected function pagination( $which ) { - global $mode; - - parent::pagination( $which ); - - if ( 'top' === $which ) { - $this->view_switcher( $mode ); - } - } - /** * Displays extra controls between bulk actions and pagination. * @@ -474,13 +445,9 @@ public function column_id( $blog ) { * * @since 4.3.0 * - * @global string $mode List table view mode. - * * @param array $blog Current site. */ public function column_blogname( $blog ) { - global $mode; - $blogname = untrailingslashit( $blog['domain'] . $blog['path'] ); ?> @@ -496,18 +463,6 @@ public function column_blogname( $blog ) { ?>
        '; - printf( - /* translators: 1: Site title, 2: Site tagline. */ - __( '%1$s – %2$s' ), - get_option( 'blogname' ), - '' . get_option( 'blogdescription' ) . '' - ); - echo '

        '; - restore_current_blog(); - } } /** @@ -515,18 +470,10 @@ public function column_blogname( $blog ) { * * @since 4.3.0 * - * @global string $mode List table view mode. - * * @param array $blog Current site. */ public function column_lastupdated( $blog ) { - global $mode; - - if ( 'list' === $mode ) { - $date = __( 'Y/m/d' ); - } else { - $date = __( 'Y/m/d g:i:s a' ); - } + $date = __( 'Y/m/d g:i:s a' ); if ( '0000-00-00 00:00:00' === $blog['last_updated'] ) { _e( 'Never' ); @@ -540,18 +487,10 @@ public function column_lastupdated( $blog ) { * * @since 4.3.0 * - * @global string $mode List table view mode. - * * @param array $blog Current site. */ public function column_registered( $blog ) { - global $mode; - - if ( 'list' === $mode ) { - $date = __( 'Y/m/d' ); - } else { - $date = __( 'Y/m/d g:i:s a' ); - } + $date = __( 'Y/m/d g:i:s a' ); if ( '0000-00-00 00:00:00' === $blog['registered'] ) { echo '—'; diff --git a/src/wp-admin/includes/class-wp-ms-users-list-table.php b/src/wp-admin/includes/class-wp-ms-users-list-table.php index 8e7c98372e184..eaf6a8df47bfb 100644 --- a/src/wp-admin/includes/class-wp-ms-users-list-table.php +++ b/src/wp-admin/includes/class-wp-ms-users-list-table.php @@ -31,19 +31,11 @@ public function ajax_user_can() { * * @since 3.1.0 * - * @global string $mode List table view mode. * @global string $usersearch User search query. * @global string $role The user role to filter by. Only 'super' (super admins) is supported. */ public function prepare_items() { - global $mode, $usersearch, $role; - - if ( ! empty( $_REQUEST['mode'] ) ) { - $mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list'; - set_user_setting( 'network_users_list_mode', $mode ); - } else { - $mode = get_user_setting( 'network_users_list_mode', 'list' ); - } + global $usersearch, $role; $usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : ''; @@ -189,27 +181,6 @@ protected function get_views() { return $this->get_views_links( $role_links ); } - /** - * Generates the list table pagination. - * - * @since 3.1.0 - * - * @global string $mode List table view mode. - * - * @param string $which The location of the pagination: Either 'top' or 'bottom'. - * - * @phpstan-param 'top'|'bottom' $which - */ - protected function pagination( $which ) { - global $mode; - - parent::pagination( $which ); - - if ( 'top' === $which ) { - $this->view_switcher( $mode ); - } - } - /** * Gets the list of columns for the users list table. * @@ -370,18 +341,10 @@ public function column_email( $user ) { * * @since 4.3.0 * - * @global string $mode List table view mode. - * * @param WP_User $user The current WP_User object. */ public function column_registered( $user ) { - global $mode; - if ( 'list' === $mode ) { - $date = __( 'Y/m/d' ); - } else { - $date = __( 'Y/m/d g:i:s a' ); - } - echo mysql2date( $date, $user->user_registered ); + echo mysql2date( __( 'Y/m/d g:i:s a' ), $user->user_registered ); } /** diff --git a/src/wp-admin/network/sites.php b/src/wp-admin/network/sites.php index b4d266f2b9050..5c2b72086b101 100644 --- a/src/wp-admin/network/sites.php +++ b/src/wp-admin/network/sites.php @@ -29,7 +29,7 @@ 'title' => __( 'Overview' ), 'content' => '

        ' . __( 'Add Site takes you to the screen for adding a new site to the network. You can search for a site by Name, ID number, or IP address. Screen Options allows you to choose how many sites to display on one page.' ) . '

        ' . - '

        ' . __( 'This is the main table of all sites on this network. Switch between list and excerpt views by using the icons above the right side of the table.' ) . '

        ' . + '

        ' . __( 'This is the main table of all sites on this network.' ) . '

        ' . '

        ' . __( 'Hovering over each site reveals seven options (three for the primary site):' ) . '

        ' . '
        • ' . __( 'An Edit link to a separate Edit Site screen.' ) . '
        • ' . '
        • ' . __( 'Dashboard leads to the Dashboard for that site.' ) . '
        • ' . diff --git a/src/wp-admin/network/users.php b/src/wp-admin/network/users.php index 144f98d0f90d8..c7b63b4360295 100644 --- a/src/wp-admin/network/users.php +++ b/src/wp-admin/network/users.php @@ -286,7 +286,7 @@ '

          ' . __( 'This table shows all users across the network and the sites to which they are assigned.' ) . '

          ' . '

          ' . __( 'Hover over any user on the list to make the edit links appear. The Edit link on the left will take you to their Edit User profile page; the Edit link on the right by any site name goes to an Edit Site screen for that site.' ) . '

          ' . '

          ' . __( 'You can also go to the user’s profile page by clicking on the individual username.' ) . '

          ' . - '

          ' . __( 'You can sort the table by clicking on any of the table headings and switch between list and excerpt views by using the icons above the users list.' ) . '

          ' . + '

          ' . __( 'You can sort the table by clicking on any of the table headings.' ) . '

          ' . '

          ' . __( 'The bulk action will permanently delete selected users, or mark/unmark those selected as spam. Spam users will have posts removed and will be unable to sign up again with the same email addresses.' ) . '

          ' . '

          ' . __( 'You can make an existing user an additional super admin by going to the Edit User profile page and checking the box to grant that privilege.' ) . '

          ', ) diff --git a/tests/phpunit/tests/multisite/wpMsSitesListTable.php b/tests/phpunit/tests/multisite/wpMsSitesListTable.php index e485cd3bbefef..e27adb1b9aad8 100644 --- a/tests/phpunit/tests/multisite/wpMsSitesListTable.php +++ b/tests/phpunit/tests/multisite/wpMsSitesListTable.php @@ -242,4 +242,79 @@ public function test_get_views_should_return_views_by_default() { $this->assertSame( $expected, $this->table->get_views() ); } + + /** + * @ticket 43899 + */ + public function test_view_switcher_is_not_displayed() { + $pagination = new ReflectionMethod( $this->table, 'pagination' ); + if ( PHP_VERSION_ID < 80100 ) { + $pagination->setAccessible( true ); + } + + ob_start(); + $pagination->invoke( $this->table, 'top' ); + $output = ob_get_clean(); + + $this->assertStringNotContainsString( 'view-switch', $output ); + } + + /** + * @ticket 43899 + */ + public function test_site_details_are_not_displayed_without_switching_blog() { + $_REQUEST['mode'] = 'excerpt'; + $this->table->prepare_items(); + unset( $_REQUEST['mode'] ); + + $site_id = self::$site_ids['wordpress.org/foo/']; + update_blog_option( $site_id, 'blogname', 'Test site title' ); + update_blog_option( $site_id, 'blogdescription', 'Test site tagline' ); + + $switch_blog = new MockAction(); + add_action( 'switch_blog', array( $switch_blog, 'action' ) ); + + ob_start(); + $this->table->column_blogname( + array( + 'blog_id' => $site_id, + 'domain' => 'wordpress.org', + 'path' => '/foo/', + ) + ); + $output = ob_get_clean(); + + remove_action( 'switch_blog', array( $switch_blog, 'action' ) ); + + $this->assertStringNotContainsString( 'Test site title', $output ); + $this->assertStringNotContainsString( 'Test site tagline', $output ); + $this->assertSame( 0, $switch_blog->get_call_count() ); + } + + /** + * @ticket 43899 + */ + public function test_list_mode_request_does_not_change_site_date_format() { + $_REQUEST['mode'] = 'list'; + $this->table->prepare_items(); + unset( $_REQUEST['mode'] ); + + $date = '2025-01-02 03:04:05'; + $blog = array( + 'last_updated' => $date, + 'registered' => $date, + ); + + ob_start(); + $this->table->column_lastupdated( $blog ); + $last_updated = ob_get_clean(); + + ob_start(); + $this->table->column_registered( $blog ); + $registered = ob_get_clean(); + + $expected = mysql2date( __( 'Y/m/d g:i:s a' ), $date ); + $this->assertSame( $expected, $last_updated ); + $this->assertSame( $expected, $registered ); + } } diff --git a/tests/phpunit/tests/multisite/wpMsUsersListTable.php b/tests/phpunit/tests/multisite/wpMsUsersListTable.php index b918edc4cfad1..d18b4794d007a 100644 --- a/tests/phpunit/tests/multisite/wpMsUsersListTable.php +++ b/tests/phpunit/tests/multisite/wpMsUsersListTable.php @@ -104,4 +104,38 @@ public function test_get_views_should_return_views_by_default() { $this->assertSame( $expected, $this->table->get_views() ); } + + /** + * @ticket 43899 + */ + public function test_view_switcher_is_not_displayed() { + $pagination = new ReflectionMethod( $this->table, 'pagination' ); + if ( PHP_VERSION_ID < 80100 ) { + $pagination->setAccessible( true ); + } + + ob_start(); + $pagination->invoke( $this->table, 'top' ); + $output = ob_get_clean(); + + $this->assertStringNotContainsString( 'view-switch', $output ); + } + + /** + * @ticket 43899 + */ + public function test_list_mode_request_does_not_change_registered_date_format() { + $_REQUEST['mode'] = 'list'; + $this->table->prepare_items(); + unset( $_REQUEST['mode'] ); + + $user = new WP_User(); + $user->user_registered = '2025-01-02 03:04:05'; + + ob_start(); + $this->table->column_registered( $user ); + $output = ob_get_clean(); + + $this->assertSame( mysql2date( __( 'Y/m/d g:i:s a' ), $user->user_registered ), $output ); + } } From b3f903c1d13060dcfe9336a16fa452c41b8472d9 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Sun, 1 Nov 2026 05:58:25 +0000 Subject: [PATCH 155/481] Taxonomy: Fix tag cloud handling of float font sizes. The `smallest` and `largest` arguments of `wp_generate_tag_cloud()` were documented as integers, but they are only used in arithmetic, and the Tag Cloud block always passes them as floats so that its font size settings can be fractional. They are now documented as `int|float`. Accepting floats exposed a bug. The `aria-label` on each tag is meant to be omitted when all tags share one font size, which was checked by comparing the font spread against the integer `0`. With equal float sizes the spread is `0.0`, which is not identical to `0`, so the `aria-label` was output anyway, including for any Tag Cloud block whose smallest and largest sizes matched. The spread is now checked for being greater than zero; a negative spread was already clamped to `1`. Developed in https://github.com/WordPress/wordpress-develop/pull/15306. Follow-up to r40816. Props huzaifaalmesbah, westonruter. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65161 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/category-template.php | 66 ++++++++-------- .../phpunit/tests/term/wpGenerateTagCloud.php | 75 ++++++++++++++++++- 2 files changed, 107 insertions(+), 34 deletions(-) diff --git a/src/wp-includes/category-template.php b/src/wp-includes/category-template.php index dbb1ff8ab0d2c..f48ebe6adb3d7 100644 --- a/src/wp-includes/category-template.php +++ b/src/wp-includes/category-template.php @@ -819,38 +819,38 @@ function default_topic_count_scale( $count ) { * @param string|array $args { * Optional. Array or string of arguments for generating a tag cloud. * - * @type int $smallest Smallest font size used to display tags. Paired - * with the value of `$unit`, to determine CSS text - * size unit. Default 8 (pt). - * @type int $largest Largest font size used to display tags. Paired - * with the value of `$unit`, to determine CSS text - * size unit. Default 22 (pt). - * @type string $unit CSS text size unit to use with the `$smallest` - * and `$largest` values. Accepts any valid CSS text - * size unit. Default 'pt'. - * @type int $number The number of tags to return. Accepts any - * positive integer or zero to return all. - * Default 0. - * @type string $format Format to display the tag cloud in. Accepts 'flat' - * (tags separated with spaces), 'list' (tags displayed - * in an unordered list), or 'array' (returns an array). - * Default 'flat'. - * @type string $separator HTML or text to separate the tags. Default "\n" (newline). - * @type string $orderby Value to order tags by. Accepts 'name' or 'count'. - * Default 'name'. The {@see 'tag_cloud_sort'} filter - * can also affect how tags are sorted. - * @type string $order How to order the tags. Accepts 'ASC' (ascending), - * 'DESC' (descending), or 'RAND' (random). Default 'ASC'. - * @type int|bool $filter Whether to enable filtering of the final output - * via {@see 'wp_generate_tag_cloud'}. Default 1. - * @type array $topic_count_text Nooped plural text from _n_noop() to supply to - * tag counts. Default null. - * @type callable $topic_count_text_callback Callback used to generate nooped plural text for - * tag counts based on the count. Default null. - * @type callable $topic_count_scale_callback Callback used to determine the tag count scaling - * value. Default default_topic_count_scale(). - * @type bool|int $show_count Whether to display the tag counts. Default 0. Accepts - * 0, 1, or their bool equivalents. + * @type int|float $smallest Smallest font size used to display tags. Paired + * with the value of `$unit`, to determine CSS text + * size unit. Default 8 (pt). + * @type int|float $largest Largest font size used to display tags. Paired + * with the value of `$unit`, to determine CSS text + * size unit. Default 22 (pt). + * @type string $unit CSS text size unit to use with the `$smallest` + * and `$largest` values. Accepts any valid CSS text + * size unit. Default 'pt'. + * @type int $number The number of tags to return. Accepts any + * positive integer or zero to return all. + * Default 0. + * @type string $format Format to display the tag cloud in. Accepts 'flat' + * (tags separated with spaces), 'list' (tags displayed + * in an unordered list), or 'array' (returns an array). + * Default 'flat'. + * @type string $separator HTML or text to separate the tags. Default "\n" (newline). + * @type string $orderby Value to order tags by. Accepts 'name' or 'count'. + * Default 'name'. The {@see 'tag_cloud_sort'} filter + * can also affect how tags are sorted. + * @type string $order How to order the tags. Accepts 'ASC' (ascending), + * 'DESC' (descending), or 'RAND' (random). Default 'ASC'. + * @type int|bool $filter Whether to enable filtering of the final output + * via {@see 'wp_generate_tag_cloud'}. Default 1. + * @type array $topic_count_text Nooped plural text from _n_noop() to supply to + * tag counts. Default null. + * @type callable $topic_count_text_callback Callback used to generate nooped plural text for + * tag counts based on the count. Default null. + * @type callable $topic_count_scale_callback Callback used to determine the tag count scaling + * value. Default default_topic_count_scale(). + * @type bool|int $show_count Whether to display the tag counts. Default 0. Accepts + * 0, 1, or their bool equivalents. * } * @return string|string[] Tag cloud as a string or an array, depending on 'format' argument. * @@ -970,7 +970,7 @@ function wp_generate_tag_cloud( $tags, $args = '' ) { * - when the tag count is displayed (for example when users check the checkbox in the * Tag Cloud widget), regardless of the tags font size */ - if ( $args['show_count'] || 0 !== $font_spread ) { + if ( $args['show_count'] || $font_spread > 0 ) { $aria_label = true; } diff --git a/tests/phpunit/tests/term/wpGenerateTagCloud.php b/tests/phpunit/tests/term/wpGenerateTagCloud.php index e93e92eb2907a..29a00055d72c8 100644 --- a/tests/phpunit/tests/term/wpGenerateTagCloud.php +++ b/tests/phpunit/tests/term/wpGenerateTagCloud.php @@ -302,11 +302,84 @@ public function test_should_include_tag_link_position_class() { $this->assertSame( array( 1, 2, 3 ), array_map( 'intval', $matches[1] ) ); } + /** + * Tests that the aria-label is only output when font sizes differ or counts are shown. + * + * @ticket 65817 + * + * @covers ::wp_generate_tag_cloud + * + * @dataProvider data_aria_label_font_sizes + * + * @param int|float $smallest Smallest font size. + * @param int|float $largest Largest font size. + * @param int $show_count Whether to show tag counts. + * @param bool $expect_aria_label Whether an aria-label is expected. + */ + public function test_aria_label_font_sizes( $smallest, $largest, int $show_count, bool $expect_aria_label ) { + register_taxonomy( 'wptests_tax', 'post' ); + $term_ids = self::factory()->term->create_many( 2, array( 'taxonomy' => 'wptests_tax' ) ); + $posts = self::factory()->post->create_many( 2 ); + + wp_set_post_terms( $posts[0], $term_ids, 'wptests_tax' ); + wp_set_post_terms( $posts[1], array( $term_ids[1] ), 'wptests_tax' ); + + $term_objects = $this->retrieve_terms( + array( + 'include' => $term_ids, + ), + 'wptests_tax' + ); + + $actual = wp_generate_tag_cloud( + $term_objects, + array( + 'format' => 'array', + 'smallest' => $smallest, + 'largest' => $largest, + 'show_count' => $show_count, + ) + ); + + $this->assertCount( 2, $actual ); + + $expected_aria_labels = array( + $term_objects[0]->name . ' (1 item)', + $term_objects[1]->name . ' (2 items)', + ); + foreach ( $actual as $i => $link ) { + $processor = new WP_HTML_Tag_Processor( $link ); + $this->assertTrue( $processor->next_tag( 'A' ), 'Expected the tag cloud item to be a link.' ); + $this->assertSame( + $expect_aria_label ? $expected_aria_labels[ $i ] : null, + $processor->get_attribute( 'aria-label' ), + 'Expected the aria-label attribute to be ' . ( $expect_aria_label ? 'present' : 'absent' ) . '.' + ); + } + } + + /** + * Data provider for {@see self::test_aria_label_font_sizes()}. + * + * @return array + */ + public static function data_aria_label_font_sizes(): array { + return array( + 'equal int sizes' => array( 12, 12, 0, false ), + 'equal float sizes' => array( 1.2, 1.2, 0, false ), + 'equal integral float sizes' => array( 12.0, 12.0, 0, false ), + 'different int sizes' => array( 8, 22, 0, true ), + 'different float sizes' => array( 0.8, 1.5, 0, true ), + 'equal float sizes with count' => array( 1.2, 1.2, 1, true ), + 'smallest larger than largest' => array( 22.5, 8.5, 0, true ), + ); + } + /** * Helper method retrieve the created terms. * * @param array $get_terms_args Options passed to get_terms() - * @return array + * @return WP_Term[] */ protected function retrieve_terms( $get_terms_args, $taxonomy = 'post_tag' ) { $terms = get_terms( array( $taxonomy ), $get_terms_args ); From 321dc1f717402f1d03c4b567271f40d0e8180635 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:25:13 +0000 Subject: [PATCH 156/481] Tests: Make more data providers public and static. Update post, database, view configuration, bookmark, admin, media, metadata, and variable test providers for newer PHPUnit versions. Use static calls for the media dimension helpers without changing datasets or assertions. Developed in: https://github.com/WordPress/wordpress-develop/pull/15270, https://github.com/WordPress/wordpress-develop/pull/15308, https://github.com/WordPress/wordpress-develop/pull/15309, https://github.com/WordPress/wordpress-develop/pull/15310, https://github.com/WordPress/wordpress-develop/pull/15311 Props shailu25, rejaulalomkhan, devmuhib, huzaifaalmesbah. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65162 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/includes/misc/gotModRewrite.php | 2 +- .../includes/misc/iis7AddRewriteRule.php | 2 +- .../includes/misc/iis7RewriteRuleExists.php | 2 +- .../includes/misc/wpMakePluginFileTree.php | 2 +- .../tests/bookmark-template/walkBookmarks.php | 2 +- .../bookmark-template/wpListBookmarks.php | 4 +- tests/phpunit/tests/db.php | 28 ++-- .../functions/_wpCheckExistingFileNames.php | 2 +- tests/phpunit/tests/media.php | 120 +++++++++--------- .../tests/media/getMediaEmbeddedInContent.php | 2 +- tests/phpunit/tests/meta.php | 2 +- tests/phpunit/tests/post.php | 6 +- tests/phpunit/tests/vars.php | 2 +- tests/phpunit/tests/view-config.php | 4 +- 14 files changed, 90 insertions(+), 90 deletions(-) diff --git a/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php b/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php index b53219cdb9d35..8c10b1af77b69 100644 --- a/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php +++ b/tests/phpunit/tests/admin/includes/misc/gotModRewrite.php @@ -78,7 +78,7 @@ static function ( $got_rewrite ) use ( $filter_value, &$filtered_value ) { * filter_value: bool, * }> */ - public function data_got_mod_rewrite(): array { + public static function data_got_mod_rewrite(): array { return array( 'Apache, filter returns true' => array( 'is_apache' => true, diff --git a/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php b/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php index 52b4f7c61fd57..6b05e7959194d 100644 --- a/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php +++ b/tests/phpunit/tests/admin/includes/misc/iis7AddRewriteRule.php @@ -68,7 +68,7 @@ public function test_iis7_add_rewrite_rule( $initial_content, $rewrite_rule, $ex * expected_content: string, * }> */ - public function data_iis7_add_rewrite_rule(): array { + public static function data_iis7_add_rewrite_rule(): array { $rule = ''; return array( diff --git a/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php b/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php index 83532b1f51983..54c4fab750e84 100644 --- a/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php +++ b/tests/phpunit/tests/admin/includes/misc/iis7RewriteRuleExists.php @@ -60,7 +60,7 @@ public function test_iis7_rewrite_rule_exists( $expected, $content ) { * * @return array */ - public function data_iis7_rewrite_rule_exists(): array { + public static function data_iis7_rewrite_rule_exists(): array { return array( 'Rule with name starting with "wordpress" exists' => array( 'expected' => true, diff --git a/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php b/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php index 7489ce44a498e..577c7ba8e567a 100644 --- a/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php +++ b/tests/phpunit/tests/admin/includes/misc/wpMakePluginFileTree.php @@ -29,7 +29,7 @@ public function test_wp_make_plugin_file_tree( $plugin_editable_files, $expected * expected: array, * }> */ - public function data_wp_make_plugin_file_tree(): array { + public static function data_wp_make_plugin_file_tree(): array { return array( 'empty_list' => array( 'plugin_editable_files' => array(), diff --git a/tests/phpunit/tests/bookmark-template/walkBookmarks.php b/tests/phpunit/tests/bookmark-template/walkBookmarks.php index b957b6213f010..e9f4ea583009e 100644 --- a/tests/phpunit/tests/bookmark-template/walkBookmarks.php +++ b/tests/phpunit/tests/bookmark-template/walkBookmarks.php @@ -42,7 +42,7 @@ public function test_walk_bookmarks( array $bookmarks_data, $args, string $expec * expected: string, * }> */ - public function data_walk_bookmarks(): array { + public static function data_walk_bookmarks(): array { return array( 'empty bookmarks array' => array( 'bookmarks_data' => array(), diff --git a/tests/phpunit/tests/bookmark-template/wpListBookmarks.php b/tests/phpunit/tests/bookmark-template/wpListBookmarks.php index 0c7b4ab3381e9..ed830ea171d5c 100644 --- a/tests/phpunit/tests/bookmark-template/wpListBookmarks.php +++ b/tests/phpunit/tests/bookmark-template/wpListBookmarks.php @@ -56,7 +56,7 @@ public function test_wp_list_bookmarks_categorized( array $args, array $expected * expected: string[], * }> */ - public function data_wp_list_bookmarks_categorized(): array { + public static function data_wp_list_bookmarks_categorized(): array { return array( 'default categorized output' => array( 'args' => array( @@ -148,7 +148,7 @@ public function test_wp_list_bookmarks_uncategorized( array $args, array $expect * not_expected: string[], * }> */ - public function data_wp_list_bookmarks_uncategorized(): array { + public static function data_wp_list_bookmarks_uncategorized(): array { return array( 'uncategorized with default title_li' => array( 'args' => array( diff --git a/tests/phpunit/tests/db.php b/tests/phpunit/tests/db.php index 1f7194d1a85ac..50ab02b260d1d 100644 --- a/tests/phpunit/tests/db.php +++ b/tests/phpunit/tests/db.php @@ -134,7 +134,7 @@ public function test_esc_like( $input, $expected ) { $this->assertSame( $expected, $wpdb->esc_like( $input ) ); } - public function data_esc_like() { + public static function data_esc_like() { return array( 'single percent' => array( 'howdy%', @@ -177,7 +177,7 @@ public function test_like_query( $data, $like, $result ) { return $this->assertSame( $result, $wpdb->get_var( $wpdb->prepare( 'SELECT %s LIKE %s', $data, $wpdb->esc_like( $like ) ) ) ); } - public function data_like_query() { + public static function data_like_query() { return array( array( 'aaa', @@ -456,7 +456,7 @@ public function test_prepare_incorrect_arg_count( $query, $args, $expected ) { $this->assertSame( $expected, $prepared ); } - public function data_prepare_incorrect_arg_count() { + public static function data_prepare_incorrect_arg_count() { global $wpdb; $placeholder_escape = $wpdb->placeholder_escape(); @@ -681,7 +681,7 @@ public function test_get_col( $query, $expected, $last_result, $column ) { * @type array|string|null $last_result The value to assign to `$wpdb->last_result`. * @type int|string $column The column index to retrieve. */ - public function data_get_col() { + public static function data_get_col() { global $wpdb; return array( @@ -813,7 +813,7 @@ public function test_mysqli_flush_sync() { * @ticket 21212 * @ticket 32763 */ - public function data_get_table_from_query() { + public static function data_get_table_from_query() { $table = 'a_test_table_name'; $more_tables = array( // table_name => expected_value @@ -944,7 +944,7 @@ public function test_get_table_from_query( $query, $table ) { $this->assertSame( $table, self::$_wpdb->get_table_from_query( $query ) ); } - public function data_get_table_from_query_false() { + public static function data_get_table_from_query_false() { $table = 'a_test_table_name'; return array( array( "LOL THIS ISN'T EVEN A QUERY $table" ), @@ -962,7 +962,7 @@ public function test_get_table_from_query_false( $query ) { /** * @ticket 38751 */ - public function data_get_escaped_table_from_show_query() { + public static function data_get_escaped_table_from_show_query() { return array( // Equality. array( "SHOW TABLE STATUS WHERE Name = 'test_name'", 'test_name' ), @@ -989,7 +989,7 @@ public function test_get_escaped_table_from_show_query( $query, $table ) { /** * @ticket 21212 */ - public function data_process_field_formats() { + public static function data_process_field_formats() { $core_db_fields_no_format_specified = array( array( 'post_content' => 'foo', @@ -1281,7 +1281,7 @@ private function get_db_error_value_too_long( $errored_fields ) { * * @return array */ - public function data_process_single_field_invalid_data() { + public static function data_process_single_field_invalid_data() { return array( 'too long' => array( 'data' => array( 'post_status' => str_repeat( 'a', 21 ) ), @@ -1299,7 +1299,7 @@ public function data_process_single_field_invalid_data() { * * @return array */ - public function data_process_multiple_fields_invalid_data() { + public static function data_process_multiple_fields_invalid_data() { return array( 'too long' => array( 'data' => array( @@ -1599,7 +1599,7 @@ public function test_prepare_with_placeholders_and_array_args( $sql, $values, $i } } - public function data_prepare_with_placeholders() { + public static function data_prepare_with_placeholders() { global $wpdb; $placeholder_escape = $wpdb->placeholder_escape(); @@ -2078,7 +2078,7 @@ public function test_prepare_should_respect_the_allow_unsafe_unquoted_parameters * * @return array[] */ - public function data_prepare_should_respect_the_allow_unsafe_unquoted_parameters_property() { + public static function data_prepare_should_respect_the_allow_unsafe_unquoted_parameters_property() { global $wpdb; $placeholder_escape = $wpdb->placeholder_escape(); @@ -2183,7 +2183,7 @@ public function test_escape_and_prepare( $escape, $sql, $values, $incorrect_usag $this->assertSame( $expected, $actual ); } - public function data_escape_and_prepare() { + public static function data_escape_and_prepare() { global $wpdb; $placeholder_escape = $wpdb->placeholder_escape(); @@ -2306,7 +2306,7 @@ public function test_parse_db_host( $host_string, $expect_bail, $host, $port, $s } } - public function data_parse_db_host() { + public static function data_parse_db_host() { return array( array( '', // DB_HOST. diff --git a/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php b/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php index 13d6fee1d79d0..8c9482e593f7f 100644 --- a/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php +++ b/tests/phpunit/tests/functions/_wpCheckExistingFileNames.php @@ -25,7 +25,7 @@ public function test_wp_check_existing_file_names( $filename, $files, $expected * * @return array[] */ - public function data_wp_check_existing_file_names() { + public static function data_wp_check_existing_file_names() { return array( 'no size' => array( 'filename' => 'filename.php', diff --git a/tests/phpunit/tests/media.php b/tests/phpunit/tests/media.php index 4cc8e35623609..06f1fb448e971 100644 --- a/tests/phpunit/tests/media.php +++ b/tests/phpunit/tests/media.php @@ -542,7 +542,7 @@ public function test_autoembed_no_paragraphs_around_urls() { $this->assertSame( $content, $result ); } - public function data_autoembed() { + public static function data_autoembed() { return array( // Should embed. @@ -763,7 +763,7 @@ public function test_wp_prepare_attachment_for_js_with_a_usable_full_size() { * * @return array }> */ - public function data_wp_prepare_attachment_for_js_unusable_full_size(): array { + public static function data_wp_prepare_attachment_for_js_unusable_full_size(): array { return array( 'no full size' => array( array( @@ -889,7 +889,7 @@ public function test_wp_prepare_attachment_for_js_filesize( $filesize, ?int $exp * * @return array|null }> */ - public function data_wp_prepare_attachment_for_js_filesize(): array { + public static function data_wp_prepare_attachment_for_js_filesize(): array { return array( 'an integer' => array( 'filesize' => 12345, @@ -984,7 +984,7 @@ public function test_wp_prepare_attachment_for_js_filesize_falls_back_to_the_fil * * @return array */ - public function data_wp_prepare_attachment_for_js_filesize_falls_back_to_the_file(): array { + public static function data_wp_prepare_attachment_for_js_filesize_falls_back_to_the_file(): array { return array( 'a value smaller than a byte' => array( 'filesize' => 0.5 ), 'zero' => array( 'filesize' => 0 ), @@ -4141,7 +4141,7 @@ public function test_wp_get_attachment_image_fetchpriority_original_value_respec * * @return array[] */ - public function data_provider_fetchpriority_values() { + public static function data_provider_fetchpriority_values() { return self::text_array_to_dataprovider( array( 'high', 'low', 'auto' ) ); } @@ -4203,7 +4203,7 @@ public function test_wp_get_attachment_image_decoding_attr( $decoding, $expected * * @return array[] */ - public function data_wp_get_attachment_image_decoding_attr() { + public static function data_wp_get_attachment_image_decoding_attr() { return array( 'default' => array( 'decoding' => 'no value', @@ -4265,7 +4265,7 @@ public function test_wp_lazy_loading_enabled_tag_name_defaults( $tag_name, $expe } } - public function data_wp_lazy_loading_enabled_tag_name_defaults() { + public static function data_wp_lazy_loading_enabled_tag_name_defaults() { return array( 'img => true' => array( 'img', true ), 'iframe => true' => array( 'iframe', true ), @@ -4290,7 +4290,7 @@ public function test_wp_lazy_loading_enabled_context_defaults( $context, $expect } } - public function data_wp_lazy_loading_enabled_context_defaults() { + public static function data_wp_lazy_loading_enabled_context_defaults() { return array( 'wp_get_attachment_image => true' => array( 'wp_get_attachment_image', true ), 'the_content => true' => array( 'the_content', true ), @@ -4431,7 +4431,7 @@ public function test_attachment_permalinks_based_on_parent_status( $post_key, $e * $type bool $expected_404 Whether the page is expected to return a 404 result. * } */ - public function data_attachment_permalinks_based_on_parent_status() { + public static function data_attachment_permalinks_based_on_parent_status() { return array( array( 'draft-attachment', '/?attachment_id=%ID%', true ), array( 'publish-attachment', '/publish-post/publish-attachment', false ), @@ -4502,7 +4502,7 @@ public function test_wp_get_loading_attr_default( $context ) { /** * @return array */ - public function data_wp_get_loading_attr_default(): array { + public static function data_wp_get_loading_attr_default(): array { return array( array( 'the_content' ), array( 'the_post_thumbnail' ), @@ -4748,7 +4748,7 @@ public function test_wp_get_loading_attr_default_no_loop( $context ) { * * @return array[] */ - public function data_wp_get_loading_attr_default_before_and_no_loop() { + public static function data_wp_get_loading_attr_default_before_and_no_loop() { return array( array( 'wp_get_attachment_image' ), array( 'the_post_thumbnail' ), @@ -5046,7 +5046,7 @@ static function ( $content ) use ( &$result, $context ) { * * @return array[] */ - public function data_special_contexts_for_the_content() { + public static function data_special_contexts_for_the_content() { return array( 'widget_media_image' => array( 'context' => 'widget_media_image' ), 'the_post_thumbnail' => array( 'context' => 'the_post_thumbnail' ), @@ -5059,7 +5059,7 @@ public function data_special_contexts_for_the_content() { * * @return array[] */ - public function data_special_contexts_for_the_content_wp_get_loading_attr_default() { + public static function data_special_contexts_for_the_content_wp_get_loading_attr_default() { return array( 'the_post_thumbnail' => array( 'context' => 'the_post_thumbnail' ), 'wp_get_attachment_image' => array( 'context' => 'wp_get_attachment_image' ), @@ -5081,7 +5081,7 @@ public function data_special_contexts_for_the_content_wp_get_loading_attr_defaul * @param string $context */ public function test_wp_get_loading_optimization_attributes( string $context ): void { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Return 'lazy' by default. $this->assertSameSetsWithIndex( @@ -5217,7 +5217,7 @@ public function test_wp_get_loading_optimization_attributes( string $context ): * @param string $context */ public function test_wp_get_loading_optimization_attributes_with_fetchpriority_auto_for_lcp_candidate( string $context ): void { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Return 'lazy' by default. $this->assertSameSetsWithIndex( @@ -5352,7 +5352,7 @@ public function test_wp_get_loading_optimization_attributes_with_fetchpriority_a * @param string $context Context for the element for which the loading optimization attribute is requested. */ public function test_wp_get_loading_optimization_attributes_with_arbitrary_contexts_in_main_loop( $context ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertSameSetsWithIndex( array( @@ -5402,7 +5402,7 @@ public function test_wp_get_loading_optimization_attributes_with_arbitrary_conte * @param string $context Context for the element for which the loading optimization attribute is requested. */ public function test_wp_get_loading_optimization_attributes_with_arbitrary_contexts_before_main_query_loop( $context ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $query = $this->get_new_wp_query_for_published_post(); @@ -5447,7 +5447,7 @@ public function test_wp_get_loading_optimization_attributes_with_arbitrary_conte * * @return array[] */ - public function data_wp_get_loading_optimization_attributes_arbitrary_contexts() { + public static function data_wp_get_loading_optimization_attributes_arbitrary_contexts() { return array( array( 'wp_get_attachment_image' ), array( 'something_completely_arbitrary' ), @@ -5468,7 +5468,7 @@ public function test_wp_get_loading_optimization_attributes_should_return_empty_ add_filter( 'the_content', function ( $content ) use ( &$result ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $result = wp_get_loading_optimization_attributes( 'img', $attr, 'something_completely_arbitrary' ); return $content; } @@ -5488,7 +5488,7 @@ function ( $content ) use ( &$result ) { * @param string $context The context for the header. */ public function test_wp_get_loading_optimization_attributes_header_contexts( $context ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertArrayNotHasKey( 'loading', @@ -5515,7 +5515,7 @@ public function test_wp_get_loading_optimization_attributes_header_contexts( $co * * @return array[] */ - public function data_wp_get_loading_optimization_attributes_header_context() { + public static function data_wp_get_loading_optimization_attributes_header_context() { return array( array( 'template_part_' . WP_TEMPLATE_PART_AREA_HEADER ), array( 'get_header_image_tag' ), @@ -5528,7 +5528,7 @@ public function data_wp_get_loading_optimization_attributes_header_context() { * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_loading_optimization_force_header_contexts_filter() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); add_filter( 'wp_loading_optimization_force_header_contexts', @@ -5569,7 +5569,7 @@ public function test_wp_get_loading_optimization_attributes_before_loop_if_not_m do_action( 'get_header' ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Lazy if not main query. $this->assertSameSetsWithIndex( @@ -5602,7 +5602,7 @@ public function test_wp_get_loading_optimization_attributes_before_loop_in_main_ $wp_query = $this->get_new_wp_query_for_published_post(); $this->set_main_query( $wp_query ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Lazy if header not called. $this->assertSameSetsWithIndex( @@ -5635,7 +5635,7 @@ public function test_wp_get_loading_optimization_attributes_before_loop_if_main_ $this->set_main_query( $wp_query ); do_action( 'get_header' ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assert_fetchpriority_low_loading_attrs( $attr, $context ); @@ -5675,7 +5675,7 @@ public function test_wp_get_loading_optimization_attributes_after_loop( $context the_post(); } - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertSameSetsWithIndex( array( 'decoding' => 'async', @@ -5708,7 +5708,7 @@ public function test_wp_get_loading_optimization_attributes_no_loop( $context ) do_action( 'get_header' ); do_action( 'get_footer' ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Load lazy if the there is no loop and footer was called. $this->assertSameSetsWithIndex( @@ -5734,7 +5734,7 @@ public function test_wp_get_loading_optimization_attributes_no_loop( $context ) * @param string $context Context for the element for which the `loading` attribute value is requested. */ public function test_wp_get_loading_optimization_attributes_should_return_lazy_for_special_contexts_outside_of_the_content( $context ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertSameSetsWithIndex( array( 'decoding' => 'async', @@ -5763,7 +5763,7 @@ public function test_wp_get_loading_optimization_attributes_should_not_modify_im add_filter( 'the_content', function ( $content ) use ( &$result, $context ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $result = wp_get_loading_optimization_attributes( 'img', $attr, $context ); return $content; } @@ -6474,7 +6474,7 @@ public function test_wp_get_loading_optimization_attributes_min_required_attrs( * * @return array[] */ - public function data_wp_get_loading_optimization_attributes_min_required_attrs() { + public static function data_wp_get_loading_optimization_attributes_min_required_attrs() { return array( 'img_with_min_attrs' => array( 'img', @@ -6521,7 +6521,7 @@ public function data_wp_get_loading_optimization_attributes_min_required_attrs() * @param string $message Message to display if the test fails. */ public function test_wp_get_loading_optimization_attributes_check_allowed_tags( $tag_name, $expected, $message ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $context = 'the_post_thumbnail'; $this->assertSame( wp_get_loading_optimization_attributes( $tag_name, $attr, $context ), $expected, $message ); } @@ -6531,7 +6531,7 @@ public function test_wp_get_loading_optimization_attributes_check_allowed_tags( * * @return array[] */ - public function data_wp_get_loading_optimization_attributes_check_allowed_tags() { + public static function data_wp_get_loading_optimization_attributes_check_allowed_tags() { return array( 'img' => array( 'img', @@ -6563,7 +6563,7 @@ public function data_wp_get_loading_optimization_attributes_check_allowed_tags() * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_skip_for_block_template() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Skip logic if context is `template`. $this->assertSame( @@ -6579,7 +6579,7 @@ public function test_wp_get_loading_optimization_attributes_skip_for_block_templ * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_header_block_template() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Skip logic if context is `template`. $this->assertSameSetsWithIndex( @@ -6600,7 +6600,7 @@ public function test_wp_get_loading_optimization_attributes_header_block_templat * @expectedIncorrectUsage wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_incorrect_loading_attrs() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $attr['loading'] = 'lazy'; $attr['fetchpriority'] = 'high'; @@ -6621,7 +6621,7 @@ public function test_wp_get_loading_optimization_attributes_incorrect_loading_at * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_if_loading_attr_present() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $attr['loading'] = 'eager'; // Check fetchpriority high logic if loading attribute is present. @@ -6702,7 +6702,7 @@ public function test_wp_get_loading_optimization_attributes_low_res_image() { * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_in_shortcodes() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); // Shortcodes processed outside of content blobs like 'the_content' always get `loading="lazy"`. $this->assertSameSetsWithIndex( @@ -6734,7 +6734,7 @@ public function test_wp_get_loading_optimization_attributes_in_shortcodes_within add_filter( $filter_name, function ( $content ) use ( &$result ) { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $result = wp_get_loading_optimization_attributes( 'img', $attr, 'do_shortcode' ); return $content; } @@ -6754,7 +6754,7 @@ function ( $content ) use ( &$result ) { * * @return array[] */ - public function data_get_filters_with_do_shortcode_callback() { + public static function data_get_filters_with_do_shortcode_callback() { return self::text_array_to_dataprovider( array( 'the_content', @@ -6848,12 +6848,12 @@ public function test_wp_maybe_add_fetchpriority_high_attr( array $loading_attrs, * 4: bool, * }> */ - public function data_wp_maybe_add_fetchpriority_high_attr(): array { + public static function data_wp_maybe_add_fetchpriority_high_attr(): array { return array( 'small image' => array( array(), 'img', - $this->get_insufficient_width_height_for_high_priority(), + self::get_insufficient_width_height_for_high_priority(), null, true, ), @@ -6861,7 +6861,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { array(), 'img', array_merge( - $this->get_insufficient_width_height_for_high_priority(), + self::get_insufficient_width_height_for_high_priority(), array( 'fetchpriority' => 'auto' ) ), null, @@ -6870,7 +6870,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { 'large image' => array( array(), 'img', - $this->get_width_height_for_high_priority(), + self::get_width_height_for_high_priority(), 'high', false, ), @@ -6878,7 +6878,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { array(), 'img', array_merge( - $this->get_width_height_for_high_priority(), + self::get_width_height_for_high_priority(), array( 'fetchpriority' => 'auto' ) ), null, @@ -6890,14 +6890,14 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { 'decoding' => 'async', ), 'img', - $this->get_width_height_for_high_priority(), + self::get_width_height_for_high_priority(), null, true, ), 'image with loading=eager' => array( array( 'loading' => 'eager' ), 'img', - $this->get_width_height_for_high_priority(), + self::get_width_height_for_high_priority(), 'high', false, ), @@ -6905,7 +6905,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { array(), 'img', array_merge( - $this->get_insufficient_width_height_for_high_priority(), + self::get_insufficient_width_height_for_high_priority(), array( 'fetchpriority' => 'high' ) ), 'high', @@ -6915,7 +6915,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { array(), 'img', array_merge( - $this->get_insufficient_width_height_for_high_priority(), + self::get_insufficient_width_height_for_high_priority(), array( 'fetchpriority' => 'low' ) ), null, @@ -6924,7 +6924,7 @@ public function data_wp_maybe_add_fetchpriority_high_attr(): array { 'non-image element' => array( array(), 'video', - $this->get_width_height_for_high_priority(), + self::get_width_height_for_high_priority(), null, true, ), @@ -6964,7 +6964,7 @@ static function ( $res ) { * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_header_block_template_increase_media_count() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); wp_get_loading_optimization_attributes( 'img', $attr, 'template_part_' . WP_TEMPLATE_PART_AREA_HEADER ); // Images with a certain minimum size in the header of the page are also counted towards the threshold. @@ -6977,7 +6977,7 @@ public function test_wp_get_loading_optimization_attributes_header_block_templat * @covers ::wp_get_loading_optimization_attributes */ public function test_wp_get_loading_optimization_attributes_header_image_tag_increase_media_count() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); wp_get_loading_optimization_attributes( 'img', $attr, 'get_header_image_tag' ); // Images with a certain minimum size in the header of the page are also counted towards the threshold. @@ -7000,7 +7000,7 @@ public function test_wp_get_loading_optimization_attributes_image_before_loop_in $this->set_main_query( $wp_query ); do_action( 'get_header' ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); wp_get_loading_optimization_attributes( 'img', $attr, $context ); // Images with a certain minimum size in the header of the page are also counted towards the threshold. @@ -7028,7 +7028,7 @@ static function ( $loading_attrs ) { 1 ); - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertSameSetsWithIndex( array( 'fetchpriority' => 'high' ), @@ -7086,7 +7086,7 @@ static function ( $loading_attrs ) { * @ticket 58893 */ public function test_wp_get_loading_optimization_attributes_filter() { - $attr = $this->get_width_height_for_high_priority(); + $attr = self::get_width_height_for_high_priority(); $this->assertSameSetsWithIndex( array( @@ -7388,7 +7388,7 @@ static function ( $html ) use ( $initial_sizes ) { * * @return array Arguments for the test scenarios. */ - public function data_image_with_existing_auto_sizes() { + public static function data_image_with_existing_auto_sizes() { return array( 'not present' => array( '(max-width: 1024px) 100vw, 1024px', @@ -7446,7 +7446,7 @@ public function data_image_with_existing_auto_sizes() { * * @return array */ - public function data_provider_data_provider_to_test_wp_enqueue_img_auto_sizes_contain_css_fix(): array { + public static function data_provider_data_provider_to_test_wp_enqueue_img_auto_sizes_contain_css_fix(): array { return array( 'default' => array( 'set_up' => null, @@ -7556,7 +7556,7 @@ static function () { * * @return array */ - public function data_provider_to_test_wp_img_tag_add_auto_sizes() { + public static function data_provider_to_test_wp_img_tag_add_auto_sizes() { return array( 'expected_with_single_quoted_attributes' => array( 'input' => "", @@ -7715,7 +7715,7 @@ public function test_jpeg_image_converts_to_webp_when_filtered( bool $apply_big_ * * @return array[] */ - public function data_image_converted_to_other_format_has_correct_filename() { + public static function data_image_converted_to_other_format_has_correct_filename() { return array( 'do not scale image' => array( false ), 'scale image' => array( true ), @@ -7840,7 +7840,7 @@ public function set_main_query( $query ) { * * @return array{ width: int, height: int } Associative array with 'width' and 'height' keys. */ - private function get_width_height_for_high_priority(): array { + private static function get_width_height_for_high_priority(): array { /* * The product of width * height must be >50000 to qualify for high priority image. * 300 * 200 = 60000 @@ -7856,7 +7856,7 @@ private function get_width_height_for_high_priority(): array { * * @return array{ width: int, height: int } Associative array with 'width' and 'height' keys. */ - private function get_insufficient_width_height_for_high_priority(): array { + private static function get_insufficient_width_height_for_high_priority(): array { /* * The product of width * height must be >50000 to qualify for high priority image. * 200 * 100 = 20000 diff --git a/tests/phpunit/tests/media/getMediaEmbeddedInContent.php b/tests/phpunit/tests/media/getMediaEmbeddedInContent.php index 3b146ac3e427f..286abb8d7efb0 100644 --- a/tests/phpunit/tests/media/getMediaEmbeddedInContent.php +++ b/tests/phpunit/tests/media/getMediaEmbeddedInContent.php @@ -26,7 +26,7 @@ public function test_returns_expected_media( $content, $types, $expected ) { * * @return array[] */ - public function data_content() { + public static function data_content() { $audio = ''; $video = ''; $iframe = ''; diff --git a/tests/phpunit/tests/meta.php b/tests/phpunit/tests/meta.php index 50701b5e6d1b8..daf81b3c3d13c 100644 --- a/tests/phpunit/tests/meta.php +++ b/tests/phpunit/tests/meta.php @@ -542,7 +542,7 @@ public function test_get_metadata_with_non_existent_object_id( $expected, $args $this->assertSame( $expected, get_metadata( 'user', ...$args ) ); } - public function data_get_metadata_with_non_existent_object_id() { + public static function data_get_metadata_with_non_existent_object_id() { return array( 'should return empty array for default `$meta_key` and `$single` values' => array( 'expected' => array(), diff --git a/tests/phpunit/tests/post.php b/tests/phpunit/tests/post.php index a10d34b32a575..340ccde60e34b 100644 --- a/tests/phpunit/tests/post.php +++ b/tests/phpunit/tests/post.php @@ -621,7 +621,7 @@ public function test_stick_post_does_not_duplicate_post_ids( $stick ) { * @type mixed $stick Value to pass to stick_post(). * } */ - public function data_stick_post_does_not_duplicate_post_ids() { + public static function data_stick_post_does_not_duplicate_post_ids() { return array( array( 1 ), array( '1' ), @@ -665,7 +665,7 @@ public function test_stick_post_with_unexpected_sticky_posts_option( $starting_o * * @return array */ - public function data_stick_post_with_unexpected_sticky_posts_option() { + public static function data_stick_post_with_unexpected_sticky_posts_option() { return array( 'false' => array( false ), 'a string' => array( 'string' ), @@ -733,7 +733,7 @@ public function test_unstick_post_removes_duplicate_post_ids( $starting_option, * @type array $expected * } */ - public function data_unstick_post_removes_duplicate_post_ids() { + public static function data_unstick_post_removes_duplicate_post_ids() { return array( array( array( 1, 1 ), diff --git a/tests/phpunit/tests/vars.php b/tests/phpunit/tests/vars.php index c7634b780aaff..7d73618a42799 100644 --- a/tests/phpunit/tests/vars.php +++ b/tests/phpunit/tests/vars.php @@ -34,7 +34,7 @@ public function tear_down() { * * @return array */ - public function get_data_to_test_wp_is_mobile(): array { + public static function get_data_to_test_wp_is_mobile(): array { return array( 'mobile client hint' => array( 'headers' => array( diff --git a/tests/phpunit/tests/view-config.php b/tests/phpunit/tests/view-config.php index 28966f8c33f13..2e1f18e7a7817 100644 --- a/tests/phpunit/tests/view-config.php +++ b/tests/phpunit/tests/view-config.php @@ -131,7 +131,7 @@ public function test_default_form_groups_declare_summary( $post_type ) { * * @return array[] */ - public function data_default_form_post_types() { + public static function data_default_form_post_types() { return array( 'page' => array( 'page' ), 'post' => array( 'post' ), @@ -160,7 +160,7 @@ public function test_own_form_post_types_do_not_get_default_groups( $post_type ) * * @return array[] */ - public function data_post_types_with_own_form() { + public static function data_post_types_with_own_form() { return array( 'attachment' => array( 'attachment' ), 'wp_block' => array( 'wp_block' ), From 613a7548e696400bdcade8463e3bf2c4f0496caf Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:26:04 +0000 Subject: [PATCH 157/481] Tests: Use the static factory in color scheme tests. Replace deprecated `$this->factory` property access with `self::factory()` in the `wp_color_scheme_settings()` tests. Developed in: https://github.com/WordPress/wordpress-develop/pull/15326 Props soean. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65163 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/admin/includes/misc/wpColorSchemeSettings.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php b/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php index dd1969d620b31..59876f267fba5 100644 --- a/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php +++ b/tests/phpunit/tests/admin/includes/misc/wpColorSchemeSettings.php @@ -32,7 +32,7 @@ public function tear_down() { public function test_wp_color_scheme_settings_valid_scheme() { global $_wp_admin_css_colors; - $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); wp_set_current_user( $user_id ); update_user_option( $user_id, 'admin_color', 'blue' ); @@ -67,7 +67,7 @@ public function test_wp_color_scheme_settings_valid_scheme() { public function test_wp_color_scheme_settings_invalid_scheme_fallback_to_modern() { global $_wp_admin_css_colors; - $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); wp_set_current_user( $user_id ); update_user_option( $user_id, 'admin_color', 'non-existent' ); @@ -102,7 +102,7 @@ public function test_wp_color_scheme_settings_invalid_scheme_fallback_to_modern( public function test_wp_color_scheme_settings_no_icon_colors_fallback() { global $_wp_admin_css_colors; - $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) ); + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); wp_set_current_user( $user_id ); update_user_option( $user_id, 'admin_color', 'empty-scheme' ); From e6c93aed6ceaa94bfe738cd28a98c697c0bd9445 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:26:55 +0000 Subject: [PATCH 158/481] Tests: Expand MIME type and extension assertions. Add literal extension-to-type and MIME-to-extension expectations to the existing tests for `wp_ext2type()` and `wp_get_default_extension_for_mime_type()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15278, https://github.com/WordPress/wordpress-develop/pull/15279 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65164 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/functions.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/phpunit/tests/functions.php b/tests/phpunit/tests/functions.php index 9939678366265..64d84458c334f 100644 --- a/tests/phpunit/tests/functions.php +++ b/tests/phpunit/tests/functions.php @@ -1147,12 +1147,21 @@ public function test_wp_get_ext_types() { /** * @ticket 35987 + * @ticket 65819 + * @covers ::wp_ext2type */ public function test_wp_ext2type() { $extensions = wp_get_ext_types(); $this->assertNotEmpty( $extensions ); + // Literal mappings stay independent of the current registry contents. + $this->assertSame( 'image', wp_ext2type( 'jpg' ) ); + $this->assertSame( 'image', wp_ext2type( 'PNG' ) ); + $this->assertSame( 'audio', wp_ext2type( 'mp3' ) ); + $this->assertSame( 'video', wp_ext2type( 'mp4' ) ); + $this->assertSame( 'document', wp_ext2type( 'pdf' ) ); + foreach ( $extensions as $type => $extension_list ) { foreach ( $extension_list as $extension ) { $this->assertSame( $type, wp_ext2type( $extension ) ); @@ -2265,11 +2274,15 @@ public static function data_wp_is_json_media_type() { /** * @ticket 53668 + * @ticket 65819 + * @covers ::wp_get_default_extension_for_mime_type */ public function test_wp_get_default_extension_for_mime_type() { $this->assertSame( 'jpg', wp_get_default_extension_for_mime_type( 'image/jpeg' ), 'jpg not returned as default extension for "image/jpeg"' ); $this->assertNotSame( 'jpeg', wp_get_default_extension_for_mime_type( 'image/jpeg' ), 'jpeg should not be returned as default extension for "image/jpeg"' ); $this->assertSame( 'png', wp_get_default_extension_for_mime_type( 'image/png' ), 'png not returned as default extension for "image/png"' ); + $this->assertSame( 'pdf', wp_get_default_extension_for_mime_type( 'application/pdf' ), 'pdf not returned as default extension for "application/pdf"' ); + $this->assertSame( 'mp3', wp_get_default_extension_for_mime_type( 'audio/mpeg' ), 'mp3 not returned as default extension for "audio/mpeg"' ); $this->assertFalse( wp_get_default_extension_for_mime_type( 'wibble/wobble' ), 'false not returned for unrecognized mime type' ); $this->assertFalse( wp_get_default_extension_for_mime_type( '' ), 'false not returned when empty string as mime type supplied' ); $this->assertFalse( wp_get_default_extension_for_mime_type( ' ' ), 'false not returned when empty string as mime type supplied' ); From 601ae8a53b198b3f8ab37da6634c6447f5929b65 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:28:16 +0000 Subject: [PATCH 159/481] Tests: Cover REST resource route filters and collection routes. Extend the post and term route tests with filter assertions. Cover collection routes for post types and taxonomies, including REST visibility and custom route configuration. Developed in: https://github.com/WordPress/wordpress-develop/pull/15286, https://github.com/WordPress/wordpress-develop/pull/15287, https://github.com/WordPress/wordpress-develop/pull/15288, https://github.com/WordPress/wordpress-develop/pull/15289 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65165 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/rest-api.php | 33 +++++ .../rest-api/restGetRouteForPostTypeItems.php | 71 +++++++++ .../rest-api/restGetRouteForTaxonomyItems.php | 137 ++++++++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restGetRouteForPostTypeItems.php create mode 100644 tests/phpunit/tests/rest-api/restGetRouteForTaxonomyItems.php diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php index dfa3bf1433b6b..b9268daec2296 100644 --- a/tests/phpunit/tests/rest-api.php +++ b/tests/phpunit/tests/rest-api.php @@ -2086,6 +2086,22 @@ public function test_rest_get_route_for_post_id() { $this->assertSame( '/wp/v2/posts/' . $post->ID, rest_get_route_for_post( $post->ID ) ); } + /** + * @ticket 65819 + */ + public function test_rest_get_route_for_post_filter() { + $post = self::factory()->post->create_and_get(); + + add_filter( + 'rest_route_for_post', + static function () { + return '/custom/route'; + } + ); + + $this->assertSame( '/custom/route', rest_get_route_for_post( $post ) ); + } + /** * @ticket 49116 */ @@ -2136,6 +2152,23 @@ public function test_rest_get_route_for_term_id() { $this->assertSame( '/wp/v2/tags/' . $term->term_id, rest_get_route_for_term( $term->term_id ) ); } + /** + * @ticket 65819 + * @covers ::rest_get_route_for_term + */ + public function test_rest_get_route_for_term_filter() { + $term = self::factory()->category->create_and_get(); + + add_filter( + 'rest_route_for_term', + static function () { + return '/custom/term-route'; + } + ); + + $this->assertSame( '/custom/term-route', rest_get_route_for_term( $term ) ); + } + /** * @ticket 54267 */ diff --git a/tests/phpunit/tests/rest-api/restGetRouteForPostTypeItems.php b/tests/phpunit/tests/rest-api/restGetRouteForPostTypeItems.php new file mode 100644 index 0000000000000..b6063cb62ec0b --- /dev/null +++ b/tests/phpunit/tests/rest-api/restGetRouteForPostTypeItems.php @@ -0,0 +1,71 @@ +assertSame( '/wp/v2/posts', rest_get_route_for_post_type_items( 'post' ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_for_invalid_post_type() { + $this->assertSame( '', rest_get_route_for_post_type_items( 'not-a-real-type' ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_when_post_type_not_in_rest() { + register_post_type( + 'not-in-rest', + array( + 'public' => true, + 'show_in_rest' => false, + ) + ); + + $this->assertSame( '', rest_get_route_for_post_type_items( 'not-in-rest' ) ); + } + + /** + * @ticket 65819 + */ + public function test_uses_custom_rest_namespace_and_base() { + register_post_type( + 'with-rest-base', + array( + 'public' => true, + 'show_in_rest' => true, + 'rest_base' => 'custom-base', + 'rest_namespace' => 'my-plugin/v1', + ) + ); + + $this->assertSame( '/my-plugin/v1/custom-base', rest_get_route_for_post_type_items( 'with-rest-base' ) ); + } + + /** + * @ticket 65819 + */ + public function test_filter_can_modify_route() { + add_filter( + 'rest_route_for_post_type_items', + static function () { + return '/custom/post-type-route'; + } + ); + + $this->assertSame( '/custom/post-type-route', rest_get_route_for_post_type_items( 'post' ) ); + } +} diff --git a/tests/phpunit/tests/rest-api/restGetRouteForTaxonomyItems.php b/tests/phpunit/tests/rest-api/restGetRouteForTaxonomyItems.php new file mode 100644 index 0000000000000..96f1bae16fc09 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restGetRouteForTaxonomyItems.php @@ -0,0 +1,137 @@ +assertSame( '/wp/v2/categories', rest_get_route_for_taxonomy_items( 'category' ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_for_invalid_taxonomy() { + $this->assertSame( '', rest_get_route_for_taxonomy_items( 'not-a-real-taxonomy' ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_empty_string_when_taxonomy_not_in_rest() { + register_taxonomy( + 'not-in-rest', + 'post', + array( + 'public' => true, + 'show_in_rest' => false, + ) + ); + + $this->assertSame( '', rest_get_route_for_taxonomy_items( 'not-in-rest' ) ); + } + + /** + * @ticket 65819 + */ + public function test_uses_custom_rest_namespace_and_base() { + register_taxonomy( + 'with-rest-base', + 'post', + array( + 'public' => true, + 'show_in_rest' => true, + 'rest_base' => 'custom-terms', + 'rest_namespace' => 'my-plugin/v1', + ) + ); + + $this->assertSame( '/my-plugin/v1/custom-terms', rest_get_route_for_taxonomy_items( 'with-rest-base' ) ); + } + + /** + * @ticket 65819 + */ + public function test_uses_registration_defaults_for_rest_enabled_taxonomy() { + register_taxonomy( + 'fallback-tax', + 'post', + array( + 'public' => true, + 'show_in_rest' => true, + ) + ); + + $this->assertSame( '/wp/v2/fallback-tax', rest_get_route_for_taxonomy_items( 'fallback-tax' ) ); + } + + /** + * @ticket 65819 + */ + public function test_falls_back_to_taxonomy_name_when_rest_base_empty() { + register_taxonomy( + 'fallback-tax', + 'post', + array( + 'public' => true, + 'show_in_rest' => true, + 'rest_namespace' => 'my-plugin/v1', + ) + ); + + $taxonomy = get_taxonomy( 'fallback-tax' ); + $taxonomy->rest_base = ''; + + $this->assertSame( '/my-plugin/v1/fallback-tax', rest_get_route_for_taxonomy_items( 'fallback-tax' ) ); + } + + /** + * @ticket 65819 + */ + public function test_falls_back_to_default_namespace_when_rest_namespace_empty() { + register_taxonomy( + 'fallback-tax', + 'post', + array( + 'public' => true, + 'show_in_rest' => true, + 'rest_base' => 'custom-terms', + ) + ); + + $taxonomy = get_taxonomy( 'fallback-tax' ); + $taxonomy->rest_namespace = ''; + + $this->assertSame( '/wp/v2/custom-terms', rest_get_route_for_taxonomy_items( 'fallback-tax' ) ); + } + + /** + * @ticket 65819 + */ + public function test_filter_can_modify_route() { + $received = null; + + add_filter( + 'rest_route_for_taxonomy_items', + static function ( $route, $taxonomy ) use ( &$received ) { + $received = array( $route, $taxonomy ); + return '/custom/taxonomy-route'; + }, + 10, + 2 + ); + + $this->assertSame( '/custom/taxonomy-route', rest_get_route_for_taxonomy_items( 'category' ) ); + $this->assertSame( '/wp/v2/categories', $received[0] ); + $this->assertInstanceOf( 'WP_Taxonomy', $received[1] ); + $this->assertSame( 'category', $received[1]->name ); + } +} From 89f89d78232745eb18d7b2d8cc7c42cf6ab72840 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:29:02 +0000 Subject: [PATCH 160/481] Tests: Cover REST boolean and cookie authentication helpers. Cover `rest_is_boolean()` rejecting `null` and the authentication-state handling in `rest_cookie_check_errors()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15272, https://github.com/WordPress/wordpress-develop/pull/15294 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65166 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/rest-api/restCookieCheckErrors.php | 115 ++++++++++++++++++ .../tests/rest-api/restSanitizeBoolean.php | 22 ++++ 2 files changed, 137 insertions(+) create mode 100644 tests/phpunit/tests/rest-api/restCookieCheckErrors.php create mode 100644 tests/phpunit/tests/rest-api/restSanitizeBoolean.php diff --git a/tests/phpunit/tests/rest-api/restCookieCheckErrors.php b/tests/phpunit/tests/rest-api/restCookieCheckErrors.php new file mode 100644 index 0000000000000..81ad3a16be9a0 --- /dev/null +++ b/tests/phpunit/tests/rest-api/restCookieCheckErrors.php @@ -0,0 +1,115 @@ +assertSame( $result, rest_cookie_check_errors( $result ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_true_and_clears_user_when_nonce_missing() { + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + + $GLOBALS['wp_rest_auth_cookie'] = true; + + $this->assertTrue( rest_cookie_check_errors( null ) ); + $this->assertSame( 0, get_current_user_id() ); + } + + /** + * @ticket 65819 + * + * @dataProvider data_nonce_sources + * + * @param string $source Where the nonce is provided from. + */ + public function test_returns_error_for_invalid_nonce( $source ) { + $GLOBALS['wp_rest_auth_cookie'] = true; + $this->set_nonce_source( $source, 'invalid-nonce' ); + + $result = rest_cookie_check_errors( null ); + + $this->assertWPError( $result ); + $this->assertSame( 'rest_cookie_invalid_nonce', $result->get_error_code() ); + } + + /** + * @ticket 65819 + * + * @dataProvider data_nonce_sources + * + * @param string $source Where the nonce is provided from. + */ + public function test_returns_true_for_valid_nonce( $source ) { + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + + $GLOBALS['wp_rest_auth_cookie'] = true; + $this->set_nonce_source( $source, wp_create_nonce( 'wp_rest' ) ); + + $this->assertTrue( rest_cookie_check_errors( null ) ); + $this->assertSame( $user_id, get_current_user_id() ); + } + + /** + * @ticket 65819 + */ + public function test_skips_check_when_another_auth_method_is_in_use() { + $user_id = self::factory()->user->create(); + wp_set_current_user( $user_id ); + + $GLOBALS['wp_rest_auth_cookie'] = 'malformed'; + + $this->assertNull( rest_cookie_check_errors( null ) ); + $this->assertSame( $user_id, get_current_user_id() ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_nonce_sources() { + return array( + 'request param' => array( 'request' ), + 'header' => array( 'header' ), + ); + } + + /** + * Sets the nonce on the requested source. + * + * @param string $source Nonce source: 'request' or 'header'. + * @param string $nonce Nonce value. + */ + private function set_nonce_source( $source, $nonce ) { + if ( 'header' === $source ) { + $_SERVER['HTTP_X_WP_NONCE'] = $nonce; + return; + } + + $_REQUEST['_wpnonce'] = $nonce; + } +} diff --git a/tests/phpunit/tests/rest-api/restSanitizeBoolean.php b/tests/phpunit/tests/rest-api/restSanitizeBoolean.php new file mode 100644 index 0000000000000..9239f1aa8ac6e --- /dev/null +++ b/tests/phpunit/tests/rest-api/restSanitizeBoolean.php @@ -0,0 +1,22 @@ +assertFalse( rest_is_boolean( null ) ); + } +} From 98e9d67bad68db97dd6239e99cef2a8dfbaf916b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:30:11 +0000 Subject: [PATCH 161/481] Tests: Cover comment excerpt display. Verify `comment_excerpt()` output for explicit and current comments, using independent literal expectations and covering the display filter. Developed in: https://github.com/WordPress/wordpress-develop/pull/15281 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65167 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/comment/commentExcerpt.php | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 tests/phpunit/tests/comment/commentExcerpt.php diff --git a/tests/phpunit/tests/comment/commentExcerpt.php b/tests/phpunit/tests/comment/commentExcerpt.php new file mode 100644 index 0000000000000..6f4142e495ec6 --- /dev/null +++ b/tests/phpunit/tests/comment/commentExcerpt.php @@ -0,0 +1,82 @@ +post->create(); + self::$comment = $factory->comment->create_and_get( + array( + 'comment_post_ID' => self::$post_id, + 'comment_content' => 'Short comment excerpt text.', + ) + ); + } + + public function tear_down() { + unset( $GLOBALS['comment'] ); + parent::tear_down(); + } + + /** + * @ticket 65819 + */ + public function test_comment_excerpt_echoes_excerpt() { + $this->expectOutputString( 'Short comment excerpt text.' ); + comment_excerpt( self::$comment->comment_ID ); + } + + /** + * @ticket 65819 + */ + public function test_comment_excerpt_accepts_comment_object() { + $this->expectOutputString( 'Short comment excerpt text.' ); + comment_excerpt( self::$comment ); + } + + /** + * @ticket 65819 + */ + public function test_comment_excerpt_uses_global_comment_when_unspecified() { + $GLOBALS['comment'] = self::$comment; + + $this->expectOutputString( 'Short comment excerpt text.' ); + comment_excerpt(); + } + + /** + * @ticket 65819 + */ + public function test_comment_excerpt_filter_can_modify_output() { + add_filter( + 'comment_excerpt', + static function () { + return 'Filtered excerpt.'; + } + ); + + $this->expectOutputString( 'Filtered excerpt.' ); + comment_excerpt( self::$comment->comment_ID ); + } +} From ba236d8d5a1d092c49ac95f7a10c3f3bdbfac687 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:32:23 +0000 Subject: [PATCH 162/481] Tests: Cover post ID, excerpt, metadata, and GUID helpers. Cover display and missing-post behavior for post IDs, excerpt presence, scalar and multi-value custom metadata, and GUID retrieval and filtering. Developed in: https://github.com/WordPress/wordpress-develop/pull/15218, https://github.com/WordPress/wordpress-develop/pull/15219, https://github.com/WordPress/wordpress-develop/pull/15220, https://github.com/WordPress/wordpress-develop/pull/15221 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65168 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getTheGuid.php | 76 +++++++++++++++++++++++++ tests/phpunit/tests/post/hasExcerpt.php | 73 ++++++++++++++++++++++++ tests/phpunit/tests/post/postCustom.php | 64 +++++++++++++++++++++ tests/phpunit/tests/post/theId.php | 59 +++++++++++++++++++ 4 files changed, 272 insertions(+) create mode 100644 tests/phpunit/tests/post/getTheGuid.php create mode 100644 tests/phpunit/tests/post/hasExcerpt.php create mode 100644 tests/phpunit/tests/post/postCustom.php create mode 100644 tests/phpunit/tests/post/theId.php diff --git a/tests/phpunit/tests/post/getTheGuid.php b/tests/phpunit/tests/post/getTheGuid.php new file mode 100644 index 0000000000000..e95433cec88da --- /dev/null +++ b/tests/phpunit/tests/post/getTheGuid.php @@ -0,0 +1,76 @@ +post->create( + array( + 'guid' => self::$guid, + ) + ); + } + + /** + * Tests that get_the_guid() returns the guid for a post. + * + * @ticket 65819 + */ + public function test_get_the_guid() { + $this->assertSame( self::$guid, get_the_guid( self::$post_id ) ); + } + + /** + * Tests that get_the_guid() returns an empty string when the post does not exist. + * + * @ticket 65819 + */ + public function test_get_the_guid_returns_empty_string_for_non_existent_post() { + $this->assertSame( '', get_the_guid( 999999 ) ); + } + + /** + * Tests that the 'get_the_guid' filter receives expected arguments and modifies the return value. + * + * @ticket 65819 + */ + public function test_get_the_guid_filter() { + add_filter( + 'get_the_guid', + function ( $guid, $id ) { + $this->assertSame( self::$guid, $guid ); + $this->assertSame( self::$post_id, $id ); + return 'urn:uuid:12345-' . $id; + }, + 10, + 2 + ); + + $this->assertSame( 'urn:uuid:12345-' . self::$post_id, get_the_guid( self::$post_id ) ); + } +} diff --git a/tests/phpunit/tests/post/hasExcerpt.php b/tests/phpunit/tests/post/hasExcerpt.php new file mode 100644 index 0000000000000..a2060f99ba006 --- /dev/null +++ b/tests/phpunit/tests/post/hasExcerpt.php @@ -0,0 +1,73 @@ +post->create( + array( + 'post_title' => 'Post With Excerpt', + 'post_excerpt' => 'This is an explicit excerpt.', + ) + ); + + self::$post_without_excerpt = $factory->post->create( + array( + 'post_title' => 'Post Without Excerpt', + 'post_excerpt' => '', + ) + ); + } + + /** + * Tests that has_excerpt() returns true when passing a post with an excerpt. + * + * @ticket 65819 + */ + public function test_has_excerpt_returns_true_with_excerpt() { + $this->assertTrue( has_excerpt( self::$post_with_excerpt ) ); + } + + /** + * Tests that has_excerpt() returns false when a post has no excerpt. + * + * @ticket 65819 + */ + public function test_has_excerpt_returns_false_when_empty() { + $this->assertFalse( has_excerpt( self::$post_without_excerpt ) ); + } + + /** + * Tests that has_excerpt() returns false for a non-existent post ID. + * + * @ticket 65819 + */ + public function test_has_excerpt_returns_false_for_non_existent_post() { + $this->assertFalse( has_excerpt( 999999 ) ); + } +} diff --git a/tests/phpunit/tests/post/postCustom.php b/tests/phpunit/tests/post/postCustom.php new file mode 100644 index 0000000000000..984999d28387f --- /dev/null +++ b/tests/phpunit/tests/post/postCustom.php @@ -0,0 +1,64 @@ +post->create(); + + add_post_meta( self::$post_id, 'single_key', 'single_value' ); + add_post_meta( self::$post_id, 'multi_key', 'first_value' ); + add_post_meta( self::$post_id, 'multi_key', 'second_value' ); + } + + /** + * Tests that post_custom() returns a single value when the key has one entry. + * + * @ticket 65819 + */ + public function test_post_custom_returns_single_value() { + $GLOBALS['post'] = get_post( self::$post_id ); + + $this->assertSame( 'single_value', post_custom( 'single_key' ) ); + } + + /** + * Tests that post_custom() returns an array when the key has multiple entries. + * + * @ticket 65819 + */ + public function test_post_custom_returns_array_for_multiple_values() { + $GLOBALS['post'] = get_post( self::$post_id ); + + $this->assertSame( array( 'first_value', 'second_value' ), post_custom( 'multi_key' ) ); + } + + /** + * Tests that post_custom() returns false for a non-existent key. + * + * @ticket 65819 + */ + public function test_post_custom_returns_false_for_non_existent_key() { + $GLOBALS['post'] = get_post( self::$post_id ); + + $this->assertFalse( post_custom( 'non_existent_key' ) ); + } +} diff --git a/tests/phpunit/tests/post/theId.php b/tests/phpunit/tests/post/theId.php new file mode 100644 index 0000000000000..caf45810fed66 --- /dev/null +++ b/tests/phpunit/tests/post/theId.php @@ -0,0 +1,59 @@ +post->create(); + } + + /** + * Tests that get_the_ID() returns false when no post is in scope. + * + * @ticket 65819 + */ + public function test_get_the_id_returns_false_when_no_post() { + $this->assertFalse( get_the_ID() ); + } + + /** + * Tests that the_ID() displays the ID of the current post in the loop. + * + * @ticket 65819 + */ + public function test_the_id_displays_current_post_id() { + $GLOBALS['post'] = get_post( self::$post_id ); + + $this->expectOutputString( (string) self::$post_id ); + the_ID(); + } + + /** + * Tests that the_ID() produces no output when no post is in scope. + * + * @ticket 65819 + */ + public function test_the_id_produces_no_output_when_no_post() { + $this->expectOutputString( '' ); + the_ID(); + } +} From 9f978733aedd095946dddd785454950a95a646a2 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:33:17 +0000 Subject: [PATCH 163/481] Tests: Extend page template and term predicate coverage. Extend existing `is_page_template()` assertions for default and custom templates. Cover the global-post fallback and failure results in `has_term()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15222, https://github.com/WordPress/wordpress-develop/pull/15228 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65169 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/category/hasTerm.php | 77 ++++++++++++++++++++++ tests/phpunit/tests/query/conditionals.php | 8 +++ 2 files changed, 85 insertions(+) create mode 100644 tests/phpunit/tests/category/hasTerm.php diff --git a/tests/phpunit/tests/category/hasTerm.php b/tests/phpunit/tests/category/hasTerm.php new file mode 100644 index 0000000000000..5aa08ec4de03d --- /dev/null +++ b/tests/phpunit/tests/category/hasTerm.php @@ -0,0 +1,77 @@ +term = self::factory()->term->create_and_get( + array( + 'taxonomy' => self::TAXONOMY, + 'name' => 'Assigned Term', + 'slug' => 'assigned-term', + ) + ); + + $this->post = self::factory()->post->create_and_get(); + wp_set_object_terms( $this->post->ID, $this->term->term_id, self::TAXONOMY ); + } + + /** + * Tests that has_term() defaults to the global post when no post parameter is passed. + * + * @ticket 65819 + */ + public function test_has_term_falls_back_to_global_post() { + $GLOBALS['post'] = $this->post; + + $this->assertTrue( has_term( $this->term->term_id, self::TAXONOMY ) ); + } + + /** + * Tests that has_term() returns false when the post does not exist or no post is in scope. + * + * @ticket 65819 + */ + public function test_has_term_returns_false_for_missing_post() { + $this->assertFalse( has_term( $this->term->term_id, self::TAXONOMY, 99999999 ) ); + $this->assertFalse( has_term( $this->term->term_id, self::TAXONOMY ) ); + } + + /** + * Tests that has_term() returns false when an invalid or non-existent taxonomy is passed. + * + * @ticket 65819 + */ + public function test_has_term_returns_false_for_invalid_taxonomy() { + $this->assertFalse( has_term( $this->term->term_id, 'non_existent_tax', $this->post->ID ) ); + } +} diff --git a/tests/phpunit/tests/query/conditionals.php b/tests/phpunit/tests/query/conditionals.php index dad0357656004..f0f4d77988dbe 100644 --- a/tests/phpunit/tests/query/conditionals.php +++ b/tests/phpunit/tests/query/conditionals.php @@ -1255,25 +1255,32 @@ public function test_is_page_with_page_slug_that_begins_with_a_number_that_clash $this->assertFalse( $q->is_page( $p2 ) ); } + /** + * @ticket 65819 + */ public function test_is_page_template() { $post_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); update_post_meta( $post_id, '_wp_page_template', 'example.php' ); $this->go_to( "/?page_id=$post_id" ); $this->assertTrue( is_page_template( 'example.php' ) ); + $this->assertTrue( is_page_template() ); } /** * @ticket 31271 + * @ticket 65819 */ public function test_is_page_template_default() { $post_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); $this->go_to( "/?page_id=$post_id" ); $this->assertTrue( is_page_template( 'default' ) ); $this->assertTrue( is_page_template( array( 'random', 'default' ) ) ); + $this->assertFalse( is_page_template() ); } /** * @ticket 31271 + * @ticket 65819 */ public function test_is_page_template_array() { $post_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); @@ -1281,6 +1288,7 @@ public function test_is_page_template_array() { $this->go_to( "/?page_id=$post_id" ); $this->assertFalse( is_page_template( array( 'test.php' ) ) ); $this->assertTrue( is_page_template( array( 'test.php', 'example.php' ) ) ); + $this->assertFalse( is_page_template( array( 'default', 'test.php' ) ) ); } /** From e3508af3b8e2483118630e36a6652f81c7317384 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:34:03 +0000 Subject: [PATCH 164/481] Tests: Cover date display and calendar cache clearing. Cover XML date and weekday display with fixed dates. Extend weekday-date assertions for repeated output and filters, and verify `delete_get_calendar_cache()` targets the calendar cache entry. Developed in: https://github.com/WordPress/wordpress-develop/pull/15238, https://github.com/WordPress/wordpress-develop/pull/15239, https://github.com/WordPress/wordpress-develop/pull/15318 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65170 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/date/theDate.php | 19 +++++ .../tests/general/deleteGetCalendarCache.php | 41 ++++++++++ tests/phpunit/tests/general/theDateXml.php | 31 ++++++++ tests/phpunit/tests/general/theWeekday.php | 78 +++++++++++++++++++ 4 files changed, 169 insertions(+) create mode 100644 tests/phpunit/tests/general/deleteGetCalendarCache.php create mode 100644 tests/phpunit/tests/general/theDateXml.php create mode 100644 tests/phpunit/tests/general/theWeekday.php diff --git a/tests/phpunit/tests/date/theDate.php b/tests/phpunit/tests/date/theDate.php index e4bfaabf73db0..c87ac089e7add 100644 --- a/tests/phpunit/tests/date/theDate.php +++ b/tests/phpunit/tests/date/theDate.php @@ -128,6 +128,7 @@ public function test_the_date() { /** * @ticket 47354 + * @ticket 65819 */ public function test_the_weekday_date() { ob_start(); @@ -152,5 +153,23 @@ public function test_the_weekday_date() { $GLOBALS['previousweekday'] = '17.09.15'; the_weekday_date( 'before ', ' after' ); $this->assertSame( 'before Wednesday after', ob_get_clean() ); + + // Consecutive call on the same day should be suppressed. + ob_start(); + the_weekday_date( 'before ', ' after' ); + $this->assertSame( '', ob_get_clean() ); + + add_filter( + 'the_weekday_date', + static function ( $output ) { + return 'Filtered ' . $output; + } + ); + + ob_start(); + $GLOBALS['currentday'] = '19.09.15'; + $GLOBALS['previousweekday'] = '18.09.15'; + the_weekday_date(); + $this->assertSame( 'Filtered Wednesday', ob_get_clean() ); } } diff --git a/tests/phpunit/tests/general/deleteGetCalendarCache.php b/tests/phpunit/tests/general/deleteGetCalendarCache.php new file mode 100644 index 0000000000000..e4dd6b4d84f3e --- /dev/null +++ b/tests/phpunit/tests/general/deleteGetCalendarCache.php @@ -0,0 +1,41 @@ + 'calendar_content' ), 'calendar' ); + $this->assertSame( + array( 'sample_key' => 'calendar_content' ), + wp_cache_get( 'get_calendar', 'calendar' ) + ); + + delete_get_calendar_cache(); + + $this->assertFalse( wp_cache_get( 'get_calendar', 'calendar' ) ); + } + + /** + * Tests that delete_get_calendar_cache() executes without error when cache does not exist. + * + * @ticket 65819 + */ + public function test_delete_get_calendar_cache_when_empty() { + wp_cache_delete( 'get_calendar', 'calendar' ); + + delete_get_calendar_cache(); + + $this->assertFalse( wp_cache_get( 'get_calendar', 'calendar' ) ); + } +} diff --git a/tests/phpunit/tests/general/theDateXml.php b/tests/phpunit/tests/general/theDateXml.php new file mode 100644 index 0000000000000..3b28cb17862a6 --- /dev/null +++ b/tests/phpunit/tests/general/theDateXml.php @@ -0,0 +1,31 @@ +post->create_and_get( + array( + 'post_date' => '2026-05-15 12:30:00', + ) + ); + + $this->expectOutputString( '2026-05-15' ); + the_date_xml(); + } +} diff --git a/tests/phpunit/tests/general/theWeekday.php b/tests/phpunit/tests/general/theWeekday.php new file mode 100644 index 0000000000000..3f33a84e7dc5a --- /dev/null +++ b/tests/phpunit/tests/general/theWeekday.php @@ -0,0 +1,78 @@ +post->create( + array( + 'post_date' => '2026-05-15 12:00:00', + ) + ); + } + + /** + * Tests that the_weekday() outputs the localized weekday for the post. + * + * @ticket 65819 + */ + public function test_the_weekday_should_echo_localized_weekday() { + global $post; + + $post = get_post( self::$post_id ); + + $this->expectOutputString( 'Friday' ); + the_weekday(); + } + + /** + * Tests that the_weekday() returns early when there is no current post. + * + * @ticket 65819 + */ + public function test_the_weekday_without_post_should_return_early() { + global $post; + + $post = null; + + $this->expectOutputString( '' ); + the_weekday(); + } + + /** + * Tests that the 'the_weekday' filter is applied. + * + * @ticket 65819 + */ + public function test_the_weekday_filter_should_apply() { + global $post; + + $post = get_post( self::$post_id ); + + add_filter( + 'the_weekday', + static function ( $weekday ) { + return 'Custom ' . $weekday; + } + ); + + $this->expectOutputString( 'Custom Friday' ); + the_weekday(); + } +} From 6ce5e6015f43819f790f96632155d511cc01a81b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:35:00 +0000 Subject: [PATCH 165/481] Tests: Cover template and archive display helpers. Cover body-opening output, post type descriptions, archive descriptions and titles, and post type archive titles. Verify relevant display filters and return behavior. Developed in: https://github.com/WordPress/wordpress-develop/pull/15240, https://github.com/WordPress/wordpress-develop/pull/15241, https://github.com/WordPress/wordpress-develop/pull/15242, https://github.com/WordPress/wordpress-develop/pull/15315, https://github.com/WordPress/wordpress-develop/pull/15319 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65171 602fd350-edb4-49c9-b593-d223f7449a82 --- .../general/getThePostTypeDescription.php | 116 ++++++++++++++ .../tests/general/postTypeArchiveTitle.php | 95 ++++++++++++ .../tests/general/theArchiveDescription.php | 145 ++++++++++++++++++ .../phpunit/tests/general/theArchiveTitle.php | 79 ++++++++++ tests/phpunit/tests/general/wpBodyOpen.php | 36 +++++ 5 files changed, 471 insertions(+) create mode 100644 tests/phpunit/tests/general/getThePostTypeDescription.php create mode 100644 tests/phpunit/tests/general/postTypeArchiveTitle.php create mode 100644 tests/phpunit/tests/general/theArchiveDescription.php create mode 100644 tests/phpunit/tests/general/theArchiveTitle.php create mode 100644 tests/phpunit/tests/general/wpBodyOpen.php diff --git a/tests/phpunit/tests/general/getThePostTypeDescription.php b/tests/phpunit/tests/general/getThePostTypeDescription.php new file mode 100644 index 0000000000000..0145e380e2957 --- /dev/null +++ b/tests/phpunit/tests/general/getThePostTypeDescription.php @@ -0,0 +1,116 @@ + true, + 'description' => 'Test CPT description.', + ) + ); + + register_post_type( + self::POST_TYPE_WITHOUT_DESC, + array( + 'public' => true, + ) + ); + } + + /** + * Tests that get_the_post_type_description() returns an empty string when no post type is queried. + * + * @ticket 65819 + */ + public function test_get_the_post_type_description_without_queried_post_type() { + global $wp_query; + + $wp_query->query_vars = array(); + + $this->assertSame( '', get_the_post_type_description() ); + } + + /** + * Tests that get_the_post_type_description() returns the description of the queried post type. + * + * @ticket 65819 + */ + public function test_get_the_post_type_description_with_queried_post_type() { + global $wp_query; + + $wp_query->set( 'post_type', self::POST_TYPE_WITH_DESC ); + + $this->assertSame( "

          Test CPT description.

          \n", get_the_post_type_description() ); + } + + /** + * Tests that get_the_post_type_description() handles an array of post types. + * + * @ticket 65819 + */ + public function test_get_the_post_type_description_with_array_post_type() { + global $wp_query; + + $wp_query->set( 'post_type', array( self::POST_TYPE_WITH_DESC, 'post' ) ); + + $this->assertSame( "

          Test CPT description.

          \n", get_the_post_type_description() ); + } + + /** + * Tests that get_the_post_type_description() returns an empty string when the post type has no description. + * + * @ticket 65819 + */ + public function test_get_the_post_type_description_without_description() { + global $wp_query; + + $wp_query->set( 'post_type', self::POST_TYPE_WITHOUT_DESC ); + + $this->assertSame( '', get_the_post_type_description() ); + } + + /** + * Tests that the 'get_the_post_type_description' filter is applied. + * + * @ticket 65819 + */ + public function test_get_the_post_type_description_filter() { + global $wp_query; + + $wp_query->set( 'post_type', self::POST_TYPE_WITH_DESC ); + + $filter_received_obj = null; + + add_filter( + 'get_the_post_type_description', + static function ( $description, $post_type_obj ) use ( &$filter_received_obj ) { + $filter_received_obj = $post_type_obj; + return 'Filtered: ' . $description; + }, + 20, + 2 + ); + + $result = get_the_post_type_description(); + + $this->assertSame( "Filtered:

          Test CPT description.

          \n", $result ); + $this->assertInstanceOf( 'WP_Post_Type', $filter_received_obj ); + $this->assertSame( self::POST_TYPE_WITH_DESC, $filter_received_obj->name ); + } +} diff --git a/tests/phpunit/tests/general/postTypeArchiveTitle.php b/tests/phpunit/tests/general/postTypeArchiveTitle.php new file mode 100644 index 0000000000000..ae45852a2b517 --- /dev/null +++ b/tests/phpunit/tests/general/postTypeArchiveTitle.php @@ -0,0 +1,95 @@ + true, + 'has_archive' => true, + 'labels' => array( + 'name' => 'Custom Books', + ), + ) + ); + } + + /** + * Tests that post_type_archive_title() returns null when not on a post type archive. + * + * @ticket 65819 + */ + public function test_post_type_archive_title_returns_null_outside_archive() { + $this->go_to( '/' ); + + $this->assertNull( post_type_archive_title( '', false ) ); + } + + /** + * Tests that post_type_archive_title() displays the title on a post type archive. + * + * @ticket 65819 + */ + public function test_post_type_archive_title_should_display_on_archive() { + $this->go_to( '/?post_type=' . self::POST_TYPE ); + + $this->expectOutputString( 'Custom Books' ); + post_type_archive_title(); + } + + /** + * Tests that post_type_archive_title() returns the title when $display is false. + * + * @ticket 65819 + */ + public function test_post_type_archive_title_returns_when_display_is_false() { + $this->go_to( '/?post_type=' . self::POST_TYPE ); + + $this->assertSame( 'Custom Books', post_type_archive_title( '', false ) ); + } + + /** + * Tests that post_type_archive_title() prepends the prefix to the title. + * + * @ticket 65819 + */ + public function test_post_type_archive_title_prepends_prefix() { + $this->go_to( '/?post_type=' . self::POST_TYPE ); + + $this->expectOutputString( 'Archive: Custom Books' ); + post_type_archive_title( 'Archive: ' ); + } + + /** + * Tests that post_type_archive_title() respects the post_type_archive_title filter. + * + * @ticket 65819 + */ + public function test_post_type_archive_title_filter() { + $this->go_to( '/?post_type=' . self::POST_TYPE ); + + add_filter( + 'post_type_archive_title', + static function ( $title, $post_type ) { + return 'Filtered: ' . $title . ' (' . $post_type . ')'; + }, + 10, + 2 + ); + + $this->assertSame( 'Filtered: Custom Books (wptests_pt)', post_type_archive_title( '', false ) ); + } +} diff --git a/tests/phpunit/tests/general/theArchiveDescription.php b/tests/phpunit/tests/general/theArchiveDescription.php new file mode 100644 index 0000000000000..372209c6c4bc6 --- /dev/null +++ b/tests/phpunit/tests/general/theArchiveDescription.php @@ -0,0 +1,145 @@ + true, + 'has_archive' => true, + 'description' => 'Test CPT Archive description.', + ) + ); + } + + /** + * Tests get_the_archive_description() on author archives. + * + * @ticket 65819 + * + * @covers ::get_the_archive_description + */ + public function test_get_the_archive_description_on_author_archive() { + $author_id = self::factory()->user->create( + array( + 'description' => 'Author biography test.', + ) + ); + + $this->go_to( get_author_posts_url( $author_id ) ); + + $this->assertTrue( is_author() ); + $this->assertSame( 'Author biography test.', get_the_archive_description() ); + } + + /** + * Tests get_the_archive_description() on post type archives. + * + * @ticket 65819 + * + * @covers ::get_the_archive_description + */ + public function test_get_the_archive_description_on_post_type_archive() { + $this->go_to( get_post_type_archive_link( self::CPT_NAME ) ); + + $this->assertTrue( is_post_type_archive( self::CPT_NAME ) ); + $this->assertSame( "

          Test CPT Archive description.

          \n", get_the_archive_description() ); + } + + /** + * Tests get_the_archive_description() on term/category archives. + * + * @ticket 65819 + * + * @covers ::get_the_archive_description + */ + public function test_get_the_archive_description_on_term_archive() { + $term_id = self::factory()->category->create( + array( + 'description' => 'Category archive description.', + ) + ); + + $this->go_to( get_category_link( $term_id ) ); + + $this->assertTrue( is_category() ); + $this->assertSame( "

          Category archive description.

          \n", get_the_archive_description() ); + } + + /** + * Tests that the 'get_the_archive_description' filter is applied. + * + * @ticket 65819 + * + * @covers ::get_the_archive_description + */ + public function test_get_the_archive_description_filter() { + $author_id = self::factory()->user->create( + array( + 'description' => 'Author bio.', + ) + ); + + $this->go_to( get_author_posts_url( $author_id ) ); + + add_filter( + 'get_the_archive_description', + static function ( $description ) { + return 'Filtered: ' . $description; + } + ); + + $this->assertSame( 'Filtered: Author bio.', get_the_archive_description() ); + } + + /** + * Tests that the_archive_description() echoes the description with before and after strings. + * + * @ticket 65819 + * + * @covers ::the_archive_description + */ + public function test_the_archive_description_echoes_with_before_and_after() { + $author_id = self::factory()->user->create( + array( + 'description' => 'Author description.', + ) + ); + + $this->go_to( get_author_posts_url( $author_id ) ); + + $this->expectOutputString( '
          Author description.
          ' ); + the_archive_description( '
          ', '
          ' ); + } + + /** + * Tests that the_archive_description() echoes nothing when there is no description. + * + * @ticket 65819 + * + * @covers ::the_archive_description + */ + public function test_the_archive_description_echoes_nothing_when_empty() { + $author_id = self::factory()->user->create( + array( + 'description' => '', + ) + ); + + $this->go_to( get_author_posts_url( $author_id ) ); + + $this->expectOutputString( '' ); + the_archive_description( '
          ', '
          ' ); + } +} diff --git a/tests/phpunit/tests/general/theArchiveTitle.php b/tests/phpunit/tests/general/theArchiveTitle.php new file mode 100644 index 0000000000000..ba5b4c6bc37c3 --- /dev/null +++ b/tests/phpunit/tests/general/theArchiveTitle.php @@ -0,0 +1,79 @@ +category->create( + array( + 'name' => 'News', + ) + ); + } + + /** + * Tests that the_archive_title() displays the title on a category archive. + * + * @ticket 65819 + */ + public function test_the_archive_title_should_display_on_category_archive() { + $this->go_to( get_category_link( self::$category_id ) ); + + $this->expectOutputString( 'Category: News' ); + the_archive_title(); + } + + /** + * Tests that the_archive_title() outputs before and after markup when provided. + * + * @ticket 65819 + */ + public function test_the_archive_title_should_output_before_and_after_markup() { + $this->go_to( get_category_link( self::$category_id ) ); + + $this->expectOutputString( '

          Category: News

          ' ); + the_archive_title( '

          ', '

          ' ); + } + + /** + * Tests that the_archive_title() outputs the title without prefix when prefix is filtered to empty. + * + * @ticket 65819 + */ + public function test_the_archive_title_without_prefix() { + add_filter( 'get_the_archive_title_prefix', '__return_empty_string' ); + + $this->go_to( get_category_link( self::$category_id ) ); + + $this->expectOutputString( 'News' ); + the_archive_title(); + } + + /** + * Tests that the_archive_title() produces no output when the archive title is empty. + * + * @ticket 65819 + */ + public function test_the_archive_title_should_produce_no_output_when_title_is_empty() { + add_filter( 'get_the_archive_title', '__return_empty_string' ); + + $this->go_to( get_category_link( self::$category_id ) ); + + $this->expectOutputString( '' ); + the_archive_title( '

          ', '

          ' ); + } +} diff --git a/tests/phpunit/tests/general/wpBodyOpen.php b/tests/phpunit/tests/general/wpBodyOpen.php new file mode 100644 index 0000000000000..74028b801c0ec --- /dev/null +++ b/tests/phpunit/tests/general/wpBodyOpen.php @@ -0,0 +1,36 @@ +Hello
    '; + } + ); + + $this->expectOutputString( '
    Hello
    ' ); + wp_body_open(); + + $this->assertSame( 1, $action->get_call_count() ); + } +} From b8e6fbbea282be50e1ff76b3b8984320b0182d79 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:35:52 +0000 Subject: [PATCH 166/481] Tests: Cover generator output formats and filters. Verify `get_the_generator()` output formats and filtering, and the display behavior of `the_generator()` and `wp_generator()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15324 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65172 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/general/getTheGenerator.php | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 tests/phpunit/tests/general/getTheGenerator.php diff --git a/tests/phpunit/tests/general/getTheGenerator.php b/tests/phpunit/tests/general/getTheGenerator.php new file mode 100644 index 0000000000000..62100e9d1b2b7 --- /dev/null +++ b/tests/phpunit/tests/general/getTheGenerator.php @@ -0,0 +1,171 @@ +assertSame( sprintf( $expected, $version ), get_the_generator( $type ) ); + } + + /** + * Data provider for test_get_the_generator_types(). + * + * @return array[] + */ + public static function data_generator_types() { + return array( + 'html' => array( + 'html', + '', + ), + 'xhtml' => array( + 'xhtml', + '', + ), + 'atom' => array( + 'atom', + 'WordPress', + ), + 'rss2' => array( + 'rss2', + 'https://wordpress.org/?v=%s', + ), + 'rdf' => array( + 'rdf', + '', + ), + 'comment' => array( + 'comment', + '', + ), + ); + } + + /** + * Tests get_the_generator( 'export' ) formats export comment markup. + * + * @ticket 65819 + */ + public function test_get_the_generator_export() { + $output = get_the_generator( 'export' ); + $version = get_bloginfo_rss( 'version' ); + + $this->assertMatchesRegularExpression( + '/^$/', + $output + ); + } + + /** + * Tests that get_the_generator() returns null when $type is empty and no action hook is active. + * + * @ticket 65819 + */ + public function test_get_the_generator_returns_null_when_type_empty() { + $this->assertNull( get_the_generator() ); + $this->assertNull( get_the_generator( '' ) ); + } + + /** + * Tests that get_the_generator_$type filter modifies the generator markup. + * + * @ticket 65819 + */ + public function test_get_the_generator_filter() { + add_filter( + 'get_the_generator_xhtml', + static function ( $gen, $type ) { + return ''; + }, + 10, + 2 + ); + + $this->assertSame( '', get_the_generator( 'xhtml' ) ); + } + + /** + * Tests that the_generator() echoes generator markup with a newline. + * + * @ticket 65819 + */ + public function test_the_generator_echoes_with_newline() { + $expected = get_the_generator( 'xhtml' ) . "\n"; + + $this->expectOutputString( $expected ); + the_generator( 'xhtml' ); + } + + /** + * Tests that the the_generator filter modifies the displayed generator markup. + * + * @ticket 65819 + */ + public function test_the_generator_filter() { + add_filter( + 'the_generator', + static function ( $generator, $type ) { + return ''; + }, + 10, + 2 + ); + + $this->expectOutputString( "\n" ); + the_generator( 'html' ); + } + + /** + * Tests that wp_generator() displays the XHTML generator. + * + * @ticket 65819 + */ + public function test_wp_generator_displays_xhtml_generator() { + $expected = get_the_generator( 'xhtml' ) . "\n"; + + $this->expectOutputString( $expected ); + wp_generator(); + } + + /** + * Tests that the wp_generator_type filter changes the generator type used by wp_generator(). + * + * @ticket 65819 + */ + public function test_wp_generator_type_filter() { + add_filter( + 'wp_generator_type', + static function () { + return 'html'; + } + ); + + $expected = get_the_generator( 'html' ) . "\n"; + + $this->expectOutputString( $expected ); + wp_generator(); + } +} From aa8df15d581c1077690fea81bc45c7206e9084a0 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:37:15 +0000 Subject: [PATCH 167/481] Tests: Cover adjacent post relation link display. Verify that `next_post_rel_link()` and `prev_post_rel_link()` output the corresponding adjacent-post relation links. Developed in: https://github.com/WordPress/wordpress-develop/pull/15323 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65173 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/link/getAdjacentPostRelLink.php | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/link/getAdjacentPostRelLink.php b/tests/phpunit/tests/link/getAdjacentPostRelLink.php index 950780c7770c3..62b344deb20fd 100644 --- a/tests/phpunit/tests/link/getAdjacentPostRelLink.php +++ b/tests/phpunit/tests/link/getAdjacentPostRelLink.php @@ -1,12 +1,15 @@ expectOutputString( '' ); adjacent_posts_rel_link_wp_head(); } + + /** + * Tests next_post_rel_link() outputs relational link for next post. + * + * @ticket 65819 + * + * @covers ::next_post_rel_link + */ + public function test_next_post_rel_link() { + $this->set_permalink_structure( '' ); + $this->go_to( get_permalink( self::$post_ids[1] ) ); + + $expected = "\n"; + + $this->expectOutputString( $expected ); + next_post_rel_link(); + } + + /** + * Tests prev_post_rel_link() outputs relational link for previous post. + * + * @ticket 65819 + * + * @covers ::prev_post_rel_link + */ + public function test_prev_post_rel_link() { + $this->set_permalink_structure( '' ); + $this->go_to( get_permalink( self::$post_ids[1] ) ); + + $expected = "\n"; + + $this->expectOutputString( $expected ); + prev_post_rel_link(); + } } From 4ab88cf43e741acff868bcde36293b38364d47b5 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:38:08 +0000 Subject: [PATCH 168/481] Tests: Cover formatting values for editing. Verify the HTML escaping and format handling in `format_to_edit()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15317 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65174 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/formatting/formatToEdit.php | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/phpunit/tests/formatting/formatToEdit.php diff --git a/tests/phpunit/tests/formatting/formatToEdit.php b/tests/phpunit/tests/formatting/formatToEdit.php new file mode 100644 index 0000000000000..4cb55c8ae8768 --- /dev/null +++ b/tests/phpunit/tests/formatting/formatToEdit.php @@ -0,0 +1,53 @@ +"hello" & \'world\'
    '; + $expected = '<b>"hello" & 'world'</b>'; + + $this->assertSame( $expected, format_to_edit( $content ) ); + $this->assertSame( $expected, format_to_edit( $content, false ) ); + } + + /** + * Tests that format_to_edit() does not escape text when $rich_text is true. + * + * @ticket 65819 + */ + public function test_format_to_edit_does_not_escape_when_rich_text_is_true() { + $content = '"hello" & \'world\''; + + $this->assertSame( $content, format_to_edit( $content, true ) ); + } + + /** + * Tests that format_to_edit filter modifies content before escaping. + * + * @ticket 65819 + */ + public function test_format_to_edit_filter() { + add_filter( + 'format_to_edit', + static function ( $text ) { + return $text . ' & extra'; + } + ); + + $expected = 'original & <span>extra</span>'; + + $this->assertSame( $expected, format_to_edit( 'original' ) ); + } +} From 0fba29a13825251f3461fbade0ea81647918a156 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:39:01 +0000 Subject: [PATCH 169/481] Filesystem: Handle concurrent directory creation in `wp_mkdir_p()`. Accept a directory created by another process after `mkdir()` fails, without changing its permissions. Add coverage for directory creation, existing paths, traversal rejection, and the race fallback. Developed in: https://github.com/WordPress/wordpress-develop/pull/15033 Props pbearne, wildworks, dhrupo. See #57081. git-svn-id: https://develop.svn.wordpress.org/trunk@65175 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 6 +- .../wp-includes/functions/WpMkdirPTest.php | 246 ++++++++++++++++++ 2 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/tests/wp-includes/functions/WpMkdirPTest.php diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 0745f0b891f9b..d021b635ed60f 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -2137,7 +2137,11 @@ function wp_mkdir_p( $target ) { return true; } - return false; + /* + * Another process may have created the directory since the check above. Accept + * it, with the permissions that process set: this call did not create it. + */ + return is_dir( $target ); } /** diff --git a/tests/phpunit/tests/wp-includes/functions/WpMkdirPTest.php b/tests/phpunit/tests/wp-includes/functions/WpMkdirPTest.php new file mode 100644 index 0000000000000..e5b18ed75ebd8 --- /dev/null +++ b/tests/phpunit/tests/wp-includes/functions/WpMkdirPTest.php @@ -0,0 +1,246 @@ +created_dirs ) as $dir ) { + if ( is_dir( $dir ) ) { + rmdir( $dir ); + } + } + + parent::tear_down(); + } + + public function test_folder_is_made() { + $upload_dir = wp_upload_dir(); + $target = $upload_dir['basedir'] . '/wp-mkdir-p-test-' . wp_generate_password( 6, false ); + $this->created_dirs[] = $target; + + $this->assertTrue( wp_mkdir_p( $target ) ); + $this->assertDirectoryExists( $target ); + } + + public function test_if_file_with_name_exists() { + $this->assertFalse( wp_mkdir_p( ABSPATH . 'wp-admin/index.php' ) ); + } + + public function test_if_folder_with_name_exists() { + $this->assertTrue( wp_mkdir_p( ABSPATH . 'wp-admin' ) ); + } + + /** + * Do not allow path traversals. + * + * The targets are built from a unique component that is asserted missing first: + * wp_mkdir_p() returns for an existing path before it rejects traversal, so a + * target that happens to exist relative to the working directory would pass for + * the wrong reason. + */ + public function test_if_up_tree_in_target() { + $missing = 'wp-mkdir-p-missing-' . wp_generate_password( 6, false ); + + $this->assertFileDoesNotExist( ABSPATH . $missing, 'The target must not exist for this test to mean anything.' ); + + $this->assertFalse( wp_mkdir_p( ABSPATH . $missing . '/../' . $missing ) ); + $this->assertFalse( wp_mkdir_p( ABSPATH . $missing . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . $missing ) ); + $this->assertFalse( wp_mkdir_p( ABSPATH . $missing . '/../../' . $missing ) ); + + // Relative too: the unique component cannot exist relative to any directory. + $this->assertFalse( wp_mkdir_p( $missing . '/../' . $missing ) ); + $this->assertFalse( wp_mkdir_p( $missing . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . $missing ) ); + + $this->assertDirectoryDoesNotExist( ABSPATH . $missing, 'A rejected traversal must not create anything.' ); + } + + /** + * An existing target is accepted even though the path contains a traversal + * segment: wp_mkdir_p() reports an existing path before it rejects traversal. + */ + public function test_existing_target_with_a_traversal_segment_is_accepted() { + $this->assertTrue( wp_mkdir_p( ABSPATH . 'wp-admin/../wp-admin' ) ); + } + + public function test_permissions_are_set() { + $upload_dir = wp_upload_dir(); + $target = $upload_dir['basedir'] . '/wp-mkdir-p-perm-test-' . wp_generate_password( 6, false ); + $this->created_dirs[] = $target; + $parent_stat = stat( $upload_dir['basedir'] ); + + $this->assertTrue( wp_mkdir_p( $target ) ); + $target_stat = stat( $target ); + $this->assertSame( $parent_stat['mode'], $target_stat['mode'] ); + } + + /** + * A directory created by another process between the existence check and + * mkdir() is accepted, but its permissions are left alone: this call did not + * create it, so widening them could expose a directory another process made + * deliberately narrow. + * + * The race cannot be produced in-process on a real filesystem, so the target + * is a stream wrapper whose mkdir() fails and reports the directory present + * from that moment on, exactly as a losing race does. + * + * @ticket 57081 + */ + public function test_directory_created_by_another_process_keeps_its_permissions() { + stream_wrapper_register( 'wpmkdirprace', WpMkdirPRaceStream::class ); + WpMkdirPRaceStream::reset(); + + // A umask that alters the inherited bits, so the permission block is reached. + $previous_umask = umask( 0022 ); + + try { + $created = wp_mkdir_p( 'wpmkdirprace://bucket/parent/child' ); + } finally { + umask( $previous_umask ); + stream_wrapper_unregister( 'wpmkdirprace' ); + } + + $this->assertSame( 1, WpMkdirPRaceStream::$mkdir_calls, 'The race path was not exercised, so the rest of this test proves nothing.' ); + $this->assertTrue( $created, 'Losing the race is not a failure: the directory exists.' ); + $this->assertSame( 0, WpMkdirPRaceStream::$chmod_calls, 'wp_mkdir_p() must not change permissions on a directory it did not create.' ); + } +} + +/** + * Stream wrapper that loses the mkdir race. + * + * mkdir() reports failure and the target is present from that call onwards, which + * is the state wp_mkdir_p() sees when another process created the directory first. + * Permission changes are counted rather than applied. + */ +class WpMkdirPRaceStream { + + /** + * Number of permission changes attempted through this wrapper. + * + * @var int + */ + public static $chmod_calls = 0; + + /** + * Number of directory creations attempted through this wrapper. + * + * @var int + */ + public static $mkdir_calls = 0; + + /** + * Whether the target directory exists yet. + * + * @var bool + */ + public static $target_exists = false; + + /** + * The current context. + * + * @var resource|null + */ + public $context; + + /** + * Returns the wrapper to its starting state. + */ + public static function reset() { + self::$chmod_calls = 0; + self::$mkdir_calls = 0; + self::$target_exists = false; + } + + /** + * Reports the parent as an existing 0777 directory, and the target only once + * mkdir() has been attempted. + * + * @param string $path The path being stat'ed. + * @param int $flags Stat flags. + * @return array|false + */ + public function url_stat( $path, $flags ) { + $file = parse_url( $path, PHP_URL_PATH ); + + if ( '/parent' === $file ) { + return $this->directory_stat(); + } + + if ( '/parent/child' === $file && self::$target_exists ) { + return $this->directory_stat(); + } + + return false; + } + + /** + * Fails, and reports the directory present from now on. + * + * @param string $path The directory to create. + * @param int $mode Permissions. + * @param int $options Option flags. + * @return false + */ + public function mkdir( $path, $mode, $options ) { + ++self::$mkdir_calls; + self::$target_exists = true; + + return false; + } + + /** + * Counts permission changes instead of applying them. + * + * @param string $path The path being changed. + * @param int $option The metadata option. + * @param mixed $value The new value. + * @return bool + */ + public function stream_metadata( $path, $option, $value ) { + if ( STREAM_META_ACCESS === $option ) { + ++self::$chmod_calls; + } + + return true; + } + + /** + * A stat array describing a 0777 directory. + * + * @return array + */ + private function directory_stat() { + return array( + 'dev' => 0, + 'ino' => 0, + 'mode' => 040777, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => -1, + 'blocks' => -1, + ); + } +} From 0370b4b46f2c9bdae4dc5a392021eaa41676c685 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:40:33 +0000 Subject: [PATCH 170/481] Tests: Handle external version API availability failures. Skip recognized availability failures in the readme version checks while retaining failures for invalid requests and unexpected responses. Add deterministic response checks that distinguish skipped tests from assertion failures. Developed in: https://github.com/WordPress/wordpress-develop/pull/14683 Props devmuhib, huzaifaalmesbah. See #63914. git-svn-id: https://develop.svn.wordpress.org/trunk@65176 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/readme.php | 214 ++++++++++++++++++++++++++++++++- 1 file changed, 208 insertions(+), 6 deletions(-) diff --git a/tests/phpunit/tests/readme.php b/tests/phpunit/tests/readme.php index df60d140706f0..d3ce915ea3968 100644 --- a/tests/phpunit/tests/readme.php +++ b/tests/phpunit/tests/readme.php @@ -116,30 +116,82 @@ public function test_readme_mariadb_version() { } /** - * Helper function to retrieve the response body or skip the test on HTTP timeout. + * Helper function to retrieve the response body or skip the test on HTTP timeout or server unavailability. * * @param string $url The URL to retrieve the response from. * @return string The response body. */ public function get_response_body( $url ) { $response = $this->wp_remote_get( $url ); + return $this->parse_response_body( $response, $url ); + } - $this->assertNotWPError( $response ); + /** + * Processes the HTTP response, skipping on availability failures or returning the body. + * + * @param array|WP_Error $response The response from wp_remote_get(). + * @param string $url The URL retrieved. + * @return string The response body. + */ + public function parse_response_body( $response, $url ) { + $parsed_url = parse_url( $url ); + $host = isset( $parsed_url['host'] ) ? $parsed_url['host'] : $url; + + if ( is_wp_error( $response ) ) { + $error_message = $response->get_error_message(); + $is_availability_failure = false; + + if ( 'http_request_failed' === $response->get_error_code() ) { + $availability_patterns = array( + 'Could not resolve host', + 'Failed to connect', + 'Connection refused', + 'unable to connect to', + 'Connection timed out', + 'Network is unreachable', + 'Host is down', + 'getaddrinfo failed', + 'name or service not known', + 'temporary failure in name resolution', + 'Operation timed out', + 'fsocket timed out', + 'Could not connect to server', + 'Connection reset by peer', + ); + + foreach ( $availability_patterns as $pattern ) { + if ( false !== stripos( $error_message, $pattern ) ) { + $is_availability_failure = true; + break; + } + } + } + + if ( $is_availability_failure ) { + $this->markTestSkipped( + sprintf( + 'Could not contact %1$s to check versions: %2$s', + $host, + $error_message + ) + ); + } + + $this->assertNotWPError( $response ); + } $response_code = wp_remote_retrieve_response_code( $response ); $response_body = wp_remote_retrieve_body( $response ); if ( 200 !== $response_code ) { - $parsed_url = parse_url( $url ); - $error_message = sprintf( 'Could not contact %1$s to check versions. Response code: %2$s. Response body: %3$s', - $parsed_url['host'], + $host, $response_code, $response_body ); - if ( 503 === $response_code ) { + if ( in_array( $response_code, array( 429, 500, 502, 503, 504 ), true ) ) { $this->markTestSkipped( $error_message ); } @@ -148,4 +200,154 @@ public function get_response_body( $url ) { return $response_body; } + + /** + * Returns the version-appropriate SkippedTestError class name. + * + * @return string + */ + private function get_skipped_test_error_class() { + return class_exists( 'PHPUnit\Framework\SkippedTestError' ) + ? 'PHPUnit\Framework\SkippedTestError' + : 'PHPUnit_Framework_SkippedTestError'; + } + + /** + * @ticket 63914 + * + * @dataProvider data_availability_error_messages + * + * @param string $message Error message. + */ + public function test_get_response_body_skips_on_availability_failures( $message ) { + $error = new WP_Error( 'http_request_failed', $message ); + $skipped_class = $this->get_skipped_test_error_class(); + $skipped = false; + + try { + $this->parse_response_body( $error, 'https://endoflife.date/api/mysql.json' ); + } catch ( PHPUnit_Framework_AssertionFailedError $e ) { + if ( is_a( $e, $skipped_class ) ) { + $skipped = true; + $this->assertStringContainsString( 'Could not contact endoflife.date to check versions: ' . $message, $e->getMessage() ); + } + } + + $this->assertTrue( $skipped, 'Expected test to be skipped.' ); + } + + /** + * Data provider for availability failure messages. + * + * @return array[] + */ + public static function data_availability_error_messages() { + return array( + 'host resolution' => array( 'cURL error 6: Could not resolve host: endoflife.date' ), + 'fsocket timed out' => array( 'fsocket timed out' ), + 'could not connect to server' => array( 'cURL error 7: Could not connect to server' ), + 'connection reset by peer' => array( 'cURL error 35: Connection reset by peer' ), + ); + } + + /** + * @ticket 63914 + */ + public function test_get_response_body_fails_on_invalid_url() { + $error = new WP_Error( 'http_request_failed', 'A valid URL was not provided.' ); + $skipped_class = $this->get_skipped_test_error_class(); + $failed = false; + + try { + $this->parse_response_body( $error, 'https://endoflife.date/api/mysql.json' ); + } catch ( PHPUnit_Framework_AssertionFailedError $e ) { + $failed = true; + $this->assertNotInstanceOf( $skipped_class, $e, 'The request should fail rather than skip.' ); + } + + $this->assertTrue( $failed, 'Expected an assertion failure.' ); + } + + /** + * @ticket 63914 + */ + public function test_get_response_body_fails_on_request_not_executed() { + $error = new WP_Error( 'http_request_not_executed', 'User has blocked requests through HTTP.' ); + $skipped_class = $this->get_skipped_test_error_class(); + $failed = false; + + try { + $this->parse_response_body( $error, 'https://endoflife.date/api/mysql.json' ); + } catch ( PHPUnit_Framework_AssertionFailedError $e ) { + $failed = true; + $this->assertNotInstanceOf( $skipped_class, $e, 'The request should fail rather than skip.' ); + } + + $this->assertTrue( $failed, 'Expected an assertion failure.' ); + } + + /** + * @ticket 63914 + * + * @dataProvider data_availability_status_codes + * + * @param int $status_code The HTTP status code. + */ + public function test_get_response_body_skips_on_server_availability_status_codes( $status_code ) { + $response = array( + 'response' => array( 'code' => $status_code ), + 'body' => 'Service Unavailable', + ); + + $skipped_class = $this->get_skipped_test_error_class(); + $skipped = false; + + try { + $this->parse_response_body( $response, 'https://endoflife.date/api/mysql.json' ); + } catch ( PHPUnit_Framework_AssertionFailedError $e ) { + if ( is_a( $e, $skipped_class ) ) { + $skipped = true; + $this->assertStringContainsString( "Response code: $status_code", $e->getMessage() ); + } + } + + $this->assertTrue( $skipped, 'Expected test to be skipped.' ); + } + + /** + * Data provider for server availability status codes. + * + * @return array[] + */ + public static function data_availability_status_codes() { + return array( + '429 Too Many Requests' => array( 429 ), + '500 Server Error' => array( 500 ), + '502 Bad Gateway' => array( 502 ), + '503 Unavailable' => array( 503 ), + '504 Gateway Timeout' => array( 504 ), + ); + } + + /** + * @ticket 63914 + */ + public function test_get_response_body_fails_on_404_status_code() { + $response = array( + 'response' => array( 'code' => 404 ), + 'body' => 'Not Found', + ); + + $skipped_class = $this->get_skipped_test_error_class(); + $failed = false; + + try { + $this->parse_response_body( $response, 'https://endoflife.date/api/mysql.json' ); + } catch ( PHPUnit_Framework_AssertionFailedError $e ) { + $failed = true; + $this->assertNotInstanceOf( $skipped_class, $e, 'The request should fail rather than skip.' ); + } + + $this->assertTrue( $failed, 'Expected an assertion failure.' ); + } } From 2700c1f3e661925d99561714e020e0f373322a15 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 17:52:59 +0000 Subject: [PATCH 171/481] Tests: Isolate uploads in a dedicated test directory. Use `wp-content/test-suite-uploads` for test uploads and remove leftover files once at startup. This prevents interrupted runs from causing filename collisions in later media tests and keeps test files separate from normal uploads. Update upload URL expectations and run tests for the `upload_path` and `upload_url_path` options in separate processes without the `UPLOADS` constant. Developed in: https://github.com/WordPress/wordpress-develop/pull/13065 Props mrdollar4444. Fixes #63532. git-svn-id: https://develop.svn.wordpress.org/trunk@65177 602fd350-edb4-49c9-b593-d223f7449a82 --- .gitignore | 1 + tests/phpunit/includes/bootstrap.php | 35 ++++++++ tests/phpunit/includes/functions.php | 11 +++ .../tests/fonts/font-library/wpFontsDir.php | 4 +- .../wpRestFontFacesController.php | 2 +- tests/phpunit/tests/media.php | 68 +++++++------- .../tests/media/getAdjacentImageLink.php | 4 +- .../phpunit/tests/media/getNextImageLink.php | 2 +- .../phpunit/tests/media/getPostGalleries.php | 32 +++---- .../tests/media/getPreviousImageLink.php | 2 +- tests/phpunit/tests/media/nextImageLink.php | 2 +- .../phpunit/tests/media/previousImageLink.php | 2 +- .../tests/multisite/msFilesRewriting.php | 21 +++-- tests/phpunit/tests/multisite/site.php | 13 ++- .../wpGetSpeculationRules.php | 14 +-- tests/phpunit/tests/upload.php | 63 ++----------- .../phpunit/tests/upload/uploadDirOptions.php | 90 +++++++++++++++++++ 17 files changed, 232 insertions(+), 134 deletions(-) create mode 100644 tests/phpunit/tests/upload/uploadDirOptions.php diff --git a/.gitignore b/.gitignore index f96e379fbb304..94798d0a72702 100644 --- a/.gitignore +++ b/.gitignore @@ -88,6 +88,7 @@ wp-tests-config.php /src/wp-content/object-cache.php /src/wp-content/php-error.php /src/wp-content/sunrise.php +/src/wp-content/test-suite-uploads # Files and folders relating to wp-content build tools. /src/wp-content/themes/twentynineteen/node_modules diff --git a/tests/phpunit/includes/bootstrap.php b/tests/phpunit/includes/bootstrap.php index 37ae4b2384b58..41cc5e7fd7f95 100644 --- a/tests/phpunit/includes/bootstrap.php +++ b/tests/phpunit/includes/bootstrap.php @@ -251,6 +251,24 @@ define( 'REST_TESTS_IMPOSSIBLY_HIGH_NUMBER', 99999999 ); +/* + * Tests that cover the upload_path and upload_url_path options run in a separate process + * with WP_TESTS_SKIP_UPLOADS_CONSTANT set, as UPLOADS overrides those options. + */ +if ( ! defined( 'UPLOADS' ) && '1' !== getenv( 'WP_TESTS_SKIP_UPLOADS_CONSTANT' ) ) { + define( 'UPLOADS', 'wp-content/test-suite-uploads' ); + + /* + * Delete the test uploads dir exactly once per run, via an env var (we need it cos each + * @runInSeparateProcess test re-executes this in its own process). + */ + $delete_tests_uploads_dir = ( false === getenv( 'WP_TESTS_UPLOADS_RUN_ID' ) ); + + if ( $delete_tests_uploads_dir ) { + putenv( 'WP_TESTS_UPLOADS_RUN_ID=' . getmypid() . '-' . uniqid() ); + } +} + $PHP_SELF = '/index.php'; $GLOBALS['PHP_SELF'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; @@ -315,6 +333,23 @@ function wp_tests_options( $value ) { // Load WordPress. require_once ABSPATH . 'wp-settings.php'; +// Process delete wp-content/test-suite-uploads folder. +if ( ! empty( $delete_tests_uploads_dir ) ) { + $uploads_test_run_dir = ABSPATH . UPLOADS; + + if ( is_dir( $uploads_test_run_dir ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; + require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; + + // Use the direct transport, as WP_Filesystem() may pick FTP and fail without credentials. + $uploads_test_run_fs = new WP_Filesystem_Direct( null ); + $uploads_test_run_fs->delete( $uploads_test_run_dir, true ); + } + + unset( $uploads_test_run_dir, $uploads_test_run_fs ); +} +unset( $delete_tests_uploads_dir ); + // Override the PHPMailer. require_once __DIR__ . '/mock-mailer.php'; diff --git a/tests/phpunit/includes/functions.php b/tests/phpunit/includes/functions.php index 6aab0c80b7201..3bcf8db87e893 100644 --- a/tests/phpunit/includes/functions.php +++ b/tests/phpunit/includes/functions.php @@ -337,6 +337,17 @@ function _upload_dir_https( $uploads ) { return $uploads; } +/** + * Builds the upload base URL used throughout the test suite. + * + * @param string $path Path/filename to append after the uploads URL. No leading slash needed. + * @param string $scheme URL scheme, 'http' or 'https'. + * @return string The upload URL. + */ +function _upload_get_url( $path = '', $scheme = 'http' ) { + return $scheme . '://' . WP_TESTS_DOMAIN . '/' . trailingslashit( UPLOADS ) . ltrim( $path, '/' ); +} + /** * Use the Spy_REST_Server class for the REST server. * diff --git a/tests/phpunit/tests/fonts/font-library/wpFontsDir.php b/tests/phpunit/tests/fonts/font-library/wpFontsDir.php index 22208ca7b2e26..ce7f5d08ab295 100644 --- a/tests/phpunit/tests/fonts/font-library/wpFontsDir.php +++ b/tests/phpunit/tests/fonts/font-library/wpFontsDir.php @@ -52,10 +52,10 @@ public function test_fonts_dir_for_multisite() { $actual = wp_get_font_dir(); $expected = array( 'path' => untrailingslashit( $main_site_upload_dir['basedir'] ) . "/sites/{$blog_id}/fonts", - 'url' => untrailingslashit( $main_site_upload_dir['baseurl'] ) . "/sites/{$blog_id}/fonts", + 'url' => get_option( 'siteurl' ) . '/' . UPLOADS . "/sites/{$blog_id}/fonts", 'subdir' => '', 'basedir' => untrailingslashit( $main_site_upload_dir['basedir'] ) . "/sites/{$blog_id}/fonts", - 'baseurl' => untrailingslashit( $main_site_upload_dir['baseurl'] ) . "/sites/{$blog_id}/fonts", + 'baseurl' => get_option( 'siteurl' ) . '/' . UPLOADS . "/sites/{$blog_id}/fonts", 'error' => false, ); diff --git a/tests/phpunit/tests/fonts/font-library/wpRestFontFacesController.php b/tests/phpunit/tests/fonts/font-library/wpRestFontFacesController.php index eea334c927626..05af011f5cf0a 100644 --- a/tests/phpunit/tests/fonts/font-library/wpRestFontFacesController.php +++ b/tests/phpunit/tests/fonts/font-library/wpRestFontFacesController.php @@ -447,7 +447,7 @@ function ( $font_dir ) { 'The font_face_settings data should match the expected data.' ); - $expected_file_path = WP_CONTENT_DIR . '/uploads/fonts/subdir/' . reset( $files )['name']; + $expected_file_path = ABSPATH . '/' . UPLOADS . '/fonts/subdir/' . reset( $files )['name']; $expected_post_meta = 'subdir/' . reset( $files )['name']; $this->assertFileExists( $expected_file_path, 'The font file should exist in the expected subdirectory.' ); $this->assertSame( $expected_post_meta, get_post_meta( $data['id'], '_wp_font_face_file', true ), 'The post meta should match the expected subdirectory.' ); diff --git a/tests/phpunit/tests/media.php b/tests/phpunit/tests/media.php index 06f1fb448e971..76224d162f0c3 100644 --- a/tests/phpunit/tests/media.php +++ b/tests/phpunit/tests/media.php @@ -670,7 +670,7 @@ public function test_wp_prepare_attachment_for_js_without_image_sizes() { 'post_type' => 'attachment', 'post_parent' => 0, 'post_mime_type' => 'image/jpeg', - 'guid' => 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test-image.jpg', + 'guid' => _upload_get_url( 'test-image.jpg' ), ) ); @@ -1073,7 +1073,7 @@ public function test_post_galleries_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids1[] = $attachment_id; - $ids1_srcs[] = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $ids1_srcs[] = _upload_get_url( "image$i.jpg" ); } $ids2 = array(); @@ -1090,7 +1090,7 @@ public function test_post_galleries_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids2[] = $attachment_id; - $ids2_srcs[] = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $ids2_srcs[] = _upload_get_url( "image$i.jpg" ); } $ids1_joined = implode( ',', array_slice( $ids1, 0, 3 ) ); @@ -1124,7 +1124,7 @@ public function test_post_gallery_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids1[] = $attachment_id; - $ids1_srcs[] = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $ids1_srcs[] = _upload_get_url( "image$i.jpg" ); } $ids2 = array(); @@ -1141,7 +1141,7 @@ public function test_post_gallery_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids2[] = $attachment_id; - $ids2_srcs[] = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $ids2_srcs[] = _upload_get_url( "image$i.jpg" ); } $ids1_joined = implode( ',', $ids1 ); @@ -1174,7 +1174,7 @@ public function test_block_post_gallery_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; } @@ -1212,7 +1212,7 @@ public function test_block_post_gallery_images_json() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -1254,7 +1254,7 @@ public function test_mixed_post_gallery_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; } @@ -1297,7 +1297,7 @@ public function test_block_inner_post_gallery_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -1340,7 +1340,7 @@ public function test_block_post_gallery_innerblock_images() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -1823,7 +1823,7 @@ public function test_attachment_url_to_postid() { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path; + $image_url = _upload_get_url( $image_path ); $this->assertSame( $attachment_id, attachment_url_to_postid( $image_url ) ); } @@ -1841,7 +1841,7 @@ public function test_attachment_url_to_postid_with_different_scheme() { ) ); - $image_url = 'https://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path; + $image_url = _upload_get_url( $image_path, 'https' ); $this->assertSame( $attachment_id, attachment_url_to_postid( $image_url ) ); } @@ -1869,7 +1869,7 @@ public function test_attachment_url_to_postid_should_be_case_sensitive() { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path_upper_case; + $image_url = _upload_get_url( $image_path_upper_case ); $this->assertSame( $attachment_id_upper_case, attachment_url_to_postid( $image_url ) ); } @@ -2399,7 +2399,7 @@ public function test_wp_calculate_image_srcset() { $year_month = gmdate( 'Y/m' ); $image_meta = wp_get_attachment_metadata( self::$large_id ); - $uploads_dir_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/'; + $uploads_dir_url = _upload_get_url(); // Set up test cases for all expected size names. $intermediates = array( 'medium', 'medium_large', 'large', 'full' ); @@ -2453,7 +2453,7 @@ public function test_wp_calculate_image_srcset_no_date_uploads() { $id = self::factory()->attachment->create_upload_object( $filename ); $image_meta = wp_get_attachment_metadata( $id ); - $uploads_dir_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/'; + $uploads_dir_url = _upload_get_url(); // Set up test cases for all expected size names. $intermediates = array( 'medium', 'medium_large', 'large', 'full' ); @@ -2544,7 +2544,7 @@ public function test_wp_calculate_image_srcset_with_absolute_path_in_meta() { $year_month = gmdate( 'Y/m' ); $image_meta = wp_get_attachment_metadata( self::$large_id ); - $uploads_dir_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/'; + $uploads_dir_url = _upload_get_url(); // Set up test cases for all expected size names. $intermediates = array( 'medium', 'medium_large', 'large', 'full' ); @@ -2645,7 +2645,7 @@ public function test_wp_calculate_image_srcset_no_width() { public function test_wp_calculate_image_srcset_ratio_variance() { // Mock data for this test. $size_array = array( 218, 300 ); - $image_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test-768x1055-218x300.png'; + $image_src = _upload_get_url( '2015/12/test-768x1055-218x300.png' ); $image_meta = array( 'width' => 768, 'height' => 1055, @@ -2678,7 +2678,7 @@ public function test_wp_calculate_image_srcset_ratio_variance() { ), ); - $uploads_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/'; + $uploads_url = _upload_get_url( '2015/12/' ); $expected_srcset = $uploads_url . 'test-768x1055-218x300.png 218w, ' . $uploads_url . 'test-768x1055-600x824.png 600w, ' . @@ -2694,7 +2694,7 @@ public function test_wp_calculate_image_srcset_ratio_variance() { public function test_wp_calculate_image_srcset_include_src() { // Mock data for this test. $size_array = array( 2000, 1000 ); - $image_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test.png'; + $image_src = _upload_get_url( '2015/12/test.png' ); $image_meta = array( 'width' => 2000, 'height' => 1000, @@ -2727,7 +2727,7 @@ public function test_wp_calculate_image_srcset_include_src() { ), ); - $uploads_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/'; + $uploads_url = _upload_get_url( '2015/12/' ); $expected_srcset = $uploads_url . 'test.png 2000w, ' . $uploads_url . 'test-300x150.png 300w, ' . @@ -2742,7 +2742,7 @@ public function test_wp_calculate_image_srcset_include_src() { */ public function test_wp_calculate_image_srcset_corrupted_image_meta() { $size_array = array( 300, 150 ); - $image_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test-300x150.png'; + $image_src = _upload_get_url( '2015/12/test-300x150.png' ); $image_meta = array( 'width' => 1600, 'height' => 800, @@ -2776,10 +2776,10 @@ public function test_wp_calculate_image_srcset_corrupted_image_meta() { ); $srcset = array( - 300 => 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test-300x150.png 300w', - 768 => 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test-768x384.png 768w', - 1024 => 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test-1024x512.png 1024w', - 1600 => 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test.png 1600w', + 300 => _upload_get_url( '2015/12/test-300x150.png' ) . ' 300w', + 768 => _upload_get_url( '2015/12/test-768x384.png' ) . ' 768w', + 1024 => _upload_get_url( '2015/12/test-1024x512.png' ) . ' 1024w', + 1600 => _upload_get_url( '2015/12/test.png' ) . ' 1600w', ); // No sizes array. @@ -2816,7 +2816,7 @@ public function test_wp_calculate_image_srcset_corrupted_image_meta() { */ public function test_wp_calculate_image_srcset_with_spaces_in_filenames() { // Mock data for this test. - $image_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/test image-300x150.png'; + $image_src = _upload_get_url( '2015/12/test image-300x150.png' ); $image_meta = array( 'width' => 3000, 'height' => 1500, @@ -2849,7 +2849,7 @@ public function test_wp_calculate_image_srcset_with_spaces_in_filenames() { ), ); - $uploads_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/2015/12/'; + $uploads_url = _upload_get_url( '2015/12/' ); $expected_srcset = $uploads_url . 'test%20image-300x150.png 300w, ' . $uploads_url . 'test%20image-768x384.png 768w, ' . @@ -2871,7 +2871,7 @@ public function test_wp_get_attachment_image_srcset() { $srcset = wp_get_attachment_image_srcset( self::$large_id, $size_array, $image_meta ); $year_month = gmdate( 'Y/m' ); - $uploads_dir = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/'; + $uploads_dir = _upload_get_url(); // Set up test cases for all expected size names. $intermediates = array( 'medium', 'medium_large', 'large', 'full' ); @@ -3074,7 +3074,7 @@ public function test_wp_filter_content_tags_srcset_sizes_wrong() { $img = wp_img_tag_add_loading_optimization_attrs( $img, 'test' ); // Replace the src URL. - $image_wrong_src = preg_replace( '|src="[^"]+"|', 'src="http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/foo.jpg"', $img ); + $image_wrong_src = preg_replace( '|src="[^"]+"|', 'src="' . _upload_get_url( 'foo.jpg' ) . '"', $img ); $this->assertSame( $image_wrong_src, wp_filter_content_tags( $image_wrong_src ) ); } @@ -3203,8 +3203,8 @@ public function test_wp_calculate_image_srcset_animated_gifs() { ), ); - $full_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_meta['file']; - $large_src = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_meta['sizes']['large']['file']; + $full_src = _upload_get_url( $image_meta['file'] ); + $large_src = _upload_get_url( $image_meta['sizes']['large']['file'] ); // Test with soft resized size array. $size_array = array( 900, 450 ); @@ -3301,11 +3301,11 @@ public function test_wp_get_attachment_image_with_https_on() { // Test using the large file size. $size_array = array( 1024, 512 ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_meta['sizes']['large']['file']; + $image_url = _upload_get_url( $image_meta['sizes']['large']['file'] ); $_SERVER['HTTPS'] = 'on'; - $uploads_url = 'https://' . WP_TESTS_DOMAIN . '/wp-content/uploads/'; + $uploads_url = _upload_get_url( '', 'https' ); $expected = $uploads_url . 'test-1024x512.jpg 1024w, ' . $uploads_url . 'test-300x150.jpg 300w, ' . @@ -3434,7 +3434,7 @@ public function test_wp_get_attachment_image_should_use_wp_get_attachment_metada $basename = wp_basename( self::$large_filename, '.jpg' ); $year_month = gmdate( 'Y/m' ); - $uploads_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $year_month . '/'; + $uploads_url = _upload_get_url( $year_month . '/' ); $expected = ' array( 'current_attachment_index' => 3, 'expected_attachment_index' => 2, - 'expected' => '', + 'expected' => '', ), 'with text when has previous link' => array( 'current_attachment_index' => 3, @@ -43,7 +43,7 @@ public static function data_get_adjacent_image_link() { 'when has next link' => array( 'current_attachment_index' => 4, 'expected_attachment_index' => 5, - 'expected' => '', + 'expected' => '', 'args' => array( 'prev' => false ), ), 'with text when has next link' => array( diff --git a/tests/phpunit/tests/media/getNextImageLink.php b/tests/phpunit/tests/media/getNextImageLink.php index 6c9b00894b6c3..9a0a5094b2d47 100644 --- a/tests/phpunit/tests/media/getNextImageLink.php +++ b/tests/phpunit/tests/media/getNextImageLink.php @@ -31,7 +31,7 @@ public static function data_get_next_image_link() { 'when has next link' => array( 'current_attachment_index' => 4, 'expected_attachment_index' => 5, - 'expected' => '', + 'expected' => '', ), 'with text when has next link' => array( 'current_attachment_index' => 4, diff --git a/tests/phpunit/tests/media/getPostGalleries.php b/tests/phpunit/tests/media/getPostGalleries.php index e3b670f2c8be0..6b86b00dd1315 100644 --- a/tests/phpunit/tests/media/getPostGalleries.php +++ b/tests/phpunit/tests/media/getPostGalleries.php @@ -58,7 +58,7 @@ public function test_returns_only_galleries( $content, $needle ) { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg'; + $image_url = _upload_get_url( 'test.jpg' ); $content = str_replace( array( 'IMAGE_ID', 'IMAGE_URL' ), @@ -240,7 +240,7 @@ public function test_returns_no_srcs_with_block_v2_in_post_with_no_attached_imag ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg'; + $image_url = _upload_get_url( 'test.jpg' ); $blob = <<< BLOB @@ -330,7 +330,7 @@ public function test_returns_html_with_shortcode_gallery() { ) ); - $expected = 'src="http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg"'; + $expected = 'src="' . _upload_get_url( 'test.jpg' ) . '"'; $galleries = get_post_galleries( $post_id_two ); // The method can return an empty array. @@ -379,7 +379,7 @@ public function test_returns_html_with_block_gallery() { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg'; + $image_url = _upload_get_url( 'test.jpg' ); $blob = <<< BLOB @@ -393,7 +393,7 @@ public function test_returns_html_with_block_gallery() { ) ); - $expected = 'src="http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg"'; + $expected = 'src="' . _upload_get_url( 'test.jpg' ) . '"'; $galleries = get_post_galleries( $post_id_two ); // The method can return an empty array. @@ -435,7 +435,7 @@ public function test_returns_html_with_block_gallery_v2() { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg'; + $image_url = _upload_get_url( 'test.jpg' ); $blob = <<< BLOB @@ -461,7 +461,7 @@ class="wp-image-$image_id" ) ); - $expected = 'src="http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg"'; + $expected = 'src="' . _upload_get_url( 'test.jpg' ) . '"'; $galleries = get_post_galleries( $post_id ); // The method can return an empty array. @@ -514,7 +514,7 @@ public function test_respects_post_id_with_shortcode_gallery() { ) ); $expected_srcs = array( - 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg', + _upload_get_url( 'test.jpg' ), ); // Set the global $post context to the other post. @@ -569,7 +569,7 @@ public function test_respects_post_id_with_block_gallery() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -602,7 +602,7 @@ public function test_respects_post_id_with_block_gallery() { ) ); $expected_srcs = array( - 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg', + _upload_get_url( 'test.jpg' ), ); // Set the global $post context to the other post. @@ -656,7 +656,7 @@ public function test_respects_post_id_with_block_gallery_v2() { ) ); $metadata = array_merge( array( 'file' => 'image1.jpg' ), self::IMG_META ); - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . 'image1.jpg'; + $url = _upload_get_url( 'image1.jpg' ); $global_post_id = self::factory()->post->create( array( 'post_content' => 'Global Post', @@ -697,7 +697,7 @@ class="wp-image-$attachment_id" ) ); $expected_srcs = array( - 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg', + _upload_get_url( 'test.jpg' ), ); // Set the global $post context to the other post. @@ -761,7 +761,7 @@ public function test_respects_shortcode_id_attribute() { ) ); $expected_srcs = array( - 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg', + _upload_get_url( 'test.jpg' ), ); $galleries = get_post_galleries( $post_id_two, false ); @@ -838,7 +838,7 @@ public function test_respects_shortcode_and_block_id_attributes() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -901,7 +901,7 @@ public function test_respects_additional_shortcode_and_block_attributes() { $metadata = array_merge( array( 'file' => "image$i.jpg" ), self::IMG_META ); wp_update_attachment_metadata( $attachment_id, $metadata ); $ids[] = $attachment_id; - $url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . "image$i.jpg"; + $url = _upload_get_url( "image$i.jpg" ); $ids_srcs[] = $url; $imgs[] = '
    '; @@ -957,7 +957,7 @@ public function test_returns_srcs_from_html_with_block_with_no_json_blob() { ) ); - $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg'; + $image_url = _upload_get_url( 'test.jpg' ); $blob = <<< BLOB diff --git a/tests/phpunit/tests/media/getPreviousImageLink.php b/tests/phpunit/tests/media/getPreviousImageLink.php index b8a3ac6d1e9ba..eeca618f742a6 100644 --- a/tests/phpunit/tests/media/getPreviousImageLink.php +++ b/tests/phpunit/tests/media/getPreviousImageLink.php @@ -31,7 +31,7 @@ public static function data_get_previous_image_link() { 'when has previous link' => array( 'current_attachment_index' => 3, 'expected_attachment_index' => 2, - 'expected' => '', + 'expected' => '', ), 'with text when has previous link' => array( 'current_attachment_index' => 3, diff --git a/tests/phpunit/tests/media/nextImageLink.php b/tests/phpunit/tests/media/nextImageLink.php index d284138fd84e5..c288018e83559 100644 --- a/tests/phpunit/tests/media/nextImageLink.php +++ b/tests/phpunit/tests/media/nextImageLink.php @@ -30,7 +30,7 @@ public static function data_next_image_link() { 'when has next link' => array( 'current_attachment_index' => 4, 'expected_attachment_index' => 5, - 'expected' => '', + 'expected' => '', ), 'with text when has next link' => array( 'current_attachment_index' => 4, diff --git a/tests/phpunit/tests/media/previousImageLink.php b/tests/phpunit/tests/media/previousImageLink.php index 50528675bb0dc..df8a23d1ada18 100644 --- a/tests/phpunit/tests/media/previousImageLink.php +++ b/tests/phpunit/tests/media/previousImageLink.php @@ -30,7 +30,7 @@ public static function data_previous_image_link() { 'when has previous link' => array( 'current_attachment_index' => 3, 'expected_attachment_index' => 2, - 'expected' => '', + 'expected' => '', ), 'with text when has previous link' => array( 'current_attachment_index' => 3, diff --git a/tests/phpunit/tests/multisite/msFilesRewriting.php b/tests/phpunit/tests/multisite/msFilesRewriting.php index 396018ea918dd..a35c45efc5112 100644 --- a/tests/phpunit/tests/multisite/msFilesRewriting.php +++ b/tests/phpunit/tests/multisite/msFilesRewriting.php @@ -15,28 +15,39 @@ class Tests_Multisite_msFilesRewriting extends WP_UnitTestCase { public function set_up() { parent::set_up(); update_site_option( 'ms_files_rewriting', 1 ); + + // Legacy ms-files subsite uploads ignore UPLOADS, so keep them in the test dir. + if ( ! defined( 'UPLOADBLOGSDIR' ) ) { + define( 'UPLOADBLOGSDIR', UPLOADS . '/blogs.dir' ); + } + ms_upload_constants(); + + // The main site ignores UPLOADS with ms-files rewriting, so keep its legacy path in the test dir. + update_option( 'upload_path', UPLOADS ); + + // Refresh the upload dir cache, which was populated before ms-files rewriting was enabled. + wp_upload_dir( null, false, true ); } public function test_switch_upload_dir() { $this->assertTrue( is_main_site() ); - $site = get_current_site(); $date = date_format( date_create( 'now' ), 'Y/m' ); $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); $blog_id2 = self::factory()->blog->create( array( 'user_id' => $user_id ) ); $info = wp_upload_dir(); - $this->assertSame( 'http://' . $site->domain . '/wp-content/uploads/' . $date, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads/' . $date, $info['path'] ); + $this->assertSame( _upload_get_url( $date ), $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . '/' . $date, $info['path'] ); $this->assertSame( '/' . $date, $info['subdir'] ); $this->assertFalse( $info['error'] ); switch_to_blog( $blog_id2 ); $info2 = wp_upload_dir(); $this->assertNotSame( $info, $info2 ); - $this->assertSame( get_option( 'siteurl' ) . '/wp-content/blogs.dir/' . get_current_blog_id() . '/files/' . $date, $info2['url'] ); - $this->assertSame( ABSPATH . 'wp-content/blogs.dir/' . get_current_blog_id() . '/files/' . $date, $info2['path'] ); + $this->assertSame( get_option( 'siteurl' ) . '/' . UPLOADBLOGSDIR . '/' . get_current_blog_id() . '/files/' . $date, $info2['url'] ); + $this->assertSame( ABSPATH . UPLOADBLOGSDIR . '/' . get_current_blog_id() . '/files/' . $date, $info2['path'] ); $this->assertSame( '/' . $date, $info2['subdir'] ); $this->assertFalse( $info2['error'] ); restore_current_blog(); diff --git a/tests/phpunit/tests/multisite/site.php b/tests/phpunit/tests/multisite/site.php index d5f4630823dd4..3e40955c18920 100644 --- a/tests/phpunit/tests/multisite/site.php +++ b/tests/phpunit/tests/multisite/site.php @@ -565,12 +565,11 @@ public function test_is_main_site_is_false_after_switch_to_blog() { public function test_switch_upload_dir() { $this->assertTrue( is_main_site() ); - $site = get_current_site(); $date = date_format( date_create( 'now' ), 'Y/m' ); $info = wp_upload_dir(); - $this->assertSame( 'http://' . $site->domain . '/wp-content/uploads/' . $date, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads/' . $date, $info['path'] ); + $this->assertSame( _upload_get_url( $date ), $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . '/' . $date, $info['path'] ); $this->assertSame( '/' . $date, $info['subdir'] ); $this->assertFalse( $info['error'] ); @@ -578,15 +577,15 @@ public function test_switch_upload_dir() { switch_to_blog( $blog_id ); $info = wp_upload_dir(); - $this->assertSame( 'http://' . $site->domain . '/wp-content/uploads/sites/' . get_current_blog_id() . '/' . $date, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads/sites/' . get_current_blog_id() . '/' . $date, $info['path'] ); + $this->assertSame( trailingslashit( get_option( 'siteurl' ) ) . UPLOADS . '/sites/' . get_current_blog_id() . '/' . $date, $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . '/sites/' . get_current_blog_id() . '/' . $date, $info['path'] ); $this->assertSame( '/' . $date, $info['subdir'] ); $this->assertFalse( $info['error'] ); restore_current_blog(); $info = wp_upload_dir(); - $this->assertSame( 'http://' . $site->domain . '/wp-content/uploads/' . $date, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads/' . $date, $info['path'] ); + $this->assertSame( _upload_get_url( $date ), $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . '/' . $date, $info['path'] ); $this->assertSame( '/' . $date, $info['subdir'] ); $this->assertFalse( $info['error'] ); } diff --git a/tests/phpunit/tests/speculative-loading/wpGetSpeculationRules.php b/tests/phpunit/tests/speculative-loading/wpGetSpeculationRules.php index a4854db0e41d6..fd6a89c3fa8a8 100644 --- a/tests/phpunit/tests/speculative-loading/wpGetSpeculationRules.php +++ b/tests/phpunit/tests/speculative-loading/wpGetSpeculationRules.php @@ -216,7 +216,7 @@ function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -246,7 +246,7 @@ static function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -284,7 +284,7 @@ function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -333,7 +333,7 @@ function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -363,7 +363,7 @@ function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -409,7 +409,7 @@ function () { array( '/wp-*.php', '/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', @@ -467,7 +467,7 @@ function () { array( '/wp/wp-*.php', '/wp/wp-admin/*', - '/wp-content/uploads/*', + '/' . UPLOADS . '/*', '/wp-content/*', '/wp-content/plugins/*', '/wp-content/themes/stylesheet/*', diff --git a/tests/phpunit/tests/upload.php b/tests/phpunit/tests/upload.php index 46fcea7099097..c1394c54881f4 100644 --- a/tests/phpunit/tests/upload.php +++ b/tests/phpunit/tests/upload.php @@ -24,43 +24,8 @@ public function test_upload_dir_default() { $info = wp_upload_dir(); $subdir = date_format( date_create( 'now' ), '/Y/m' ); - $this->assertSame( get_option( 'siteurl' ) . '/wp-content/uploads' . $subdir, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads' . $subdir, $info['path'] ); - $this->assertSame( $subdir, $info['subdir'] ); - $this->assertFalse( $info['error'] ); - } - - public function test_upload_dir_relative() { - // wp_upload_dir() with a relative upload path that is not 'wp-content/uploads'. - update_option( 'upload_path', 'foo/bar' ); - $info = _wp_upload_dir(); - $subdir = date_format( date_create( 'now' ), '/Y/m' ); - - $this->assertSame( get_option( 'siteurl' ) . '/foo/bar' . $subdir, $info['url'] ); - $this->assertSame( ABSPATH . 'foo/bar' . $subdir, $info['path'] ); - $this->assertSame( $subdir, $info['subdir'] ); - $this->assertFalse( $info['error'] ); - } - - /** - * @ticket 5953 - */ - public function test_upload_dir_absolute() { - $path = get_temp_dir() . 'wp-unit-test'; - - // wp_upload_dir() with an absolute upload path. - update_option( 'upload_path', $path ); - - // Doesn't make sense to use an absolute file path without setting the url path. - update_option( 'upload_url_path', '/baz' ); - - // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. - // It doesn't create the /year/month directories. - $info = _wp_upload_dir(); - $subdir = date_format( date_create( 'now' ), '/Y/m' ); - - $this->assertSame( '/baz' . $subdir, $info['url'] ); - $this->assertSame( $path . $subdir, $info['path'] ); + $this->assertSame( _upload_get_url( $subdir ), $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . $subdir, $info['path'] ); $this->assertSame( $subdir, $info['subdir'] ); $this->assertFalse( $info['error'] ); } @@ -71,28 +36,14 @@ public function test_upload_dir_no_yearnum() { // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. $info = _wp_upload_dir(); - $this->assertSame( get_option( 'siteurl' ) . '/wp-content/uploads', $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads', $info['path'] ); + $this->assertSame( get_option( 'siteurl' ) . '/' . UPLOADS, $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS, $info['path'] ); $this->assertSame( '', $info['subdir'] ); $this->assertFalse( $info['error'] ); } - public function test_upload_path_absolute() { - update_option( 'upload_url_path', 'http://' . WP_TESTS_DOMAIN . '/asdf' ); - - // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. - // It doesn't create the /year/month directories. - $info = _wp_upload_dir(); - $subdir = date_format( date_create( 'now' ), '/Y/m' ); - - $this->assertSame( 'http://' . WP_TESTS_DOMAIN . '/asdf' . $subdir, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads' . $subdir, $info['path'] ); - $this->assertSame( $subdir, $info['subdir'] ); - $this->assertFalse( $info['error'] ); - } - public function test_upload_dir_empty() { - // Upload path setting is empty - it should default to 'wp-content/uploads'. + // Upload path setting is empty - it should default to UPLOADS. update_option( 'upload_path', '' ); // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. @@ -100,8 +51,8 @@ public function test_upload_dir_empty() { $info = _wp_upload_dir(); $subdir = date_format( date_create( 'now' ), '/Y/m' ); - $this->assertSame( get_option( 'siteurl' ) . '/wp-content/uploads' . $subdir, $info['url'] ); - $this->assertSame( ABSPATH . 'wp-content/uploads' . $subdir, $info['path'] ); + $this->assertSame( _upload_get_url( $subdir ), $info['url'] ); + $this->assertSame( ABSPATH . UPLOADS . $subdir, $info['path'] ); $this->assertSame( $subdir, $info['subdir'] ); $this->assertFalse( $info['error'] ); } diff --git a/tests/phpunit/tests/upload/uploadDirOptions.php b/tests/phpunit/tests/upload/uploadDirOptions.php new file mode 100644 index 0000000000000..bf1a9da67e7f1 --- /dev/null +++ b/tests/phpunit/tests/upload/uploadDirOptions.php @@ -0,0 +1,90 @@ +assertSame( get_option( 'siteurl' ) . '/foo/bar' . $subdir, $info['url'] ); + $this->assertSame( ABSPATH . 'foo/bar' . $subdir, $info['path'] ); + $this->assertSame( $subdir, $info['subdir'] ); + $this->assertFalse( $info['error'] ); + } + + /** + * @ticket 5953 + */ + public function test_upload_dir_absolute() { + $path = get_temp_dir() . 'wp-unit-test'; + + // wp_upload_dir() with an absolute upload path. + update_option( 'upload_path', $path ); + + // Doesn't make sense to use an absolute file path without setting the url path. + update_option( 'upload_url_path', '/baz' ); + + // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. + // It doesn't create the /year/month directories. + $info = _wp_upload_dir(); + $subdir = date_format( date_create( 'now' ), '/Y/m' ); + + $this->assertSame( '/baz' . $subdir, $info['url'] ); + $this->assertSame( $path . $subdir, $info['path'] ); + $this->assertSame( $subdir, $info['subdir'] ); + $this->assertFalse( $info['error'] ); + } + + public function test_upload_path_absolute() { + update_option( 'upload_url_path', 'http://' . WP_TESTS_DOMAIN . '/asdf' ); + + // Use `_wp_upload_dir()` directly to bypass caching and work with the changed options. + // It doesn't create the /year/month directories. + $info = _wp_upload_dir(); + $subdir = date_format( date_create( 'now' ), '/Y/m' ); + + $this->assertSame( 'http://' . WP_TESTS_DOMAIN . '/asdf' . $subdir, $info['url'] ); + $this->assertSame( ABSPATH . 'wp-content/uploads' . $subdir, $info['path'] ); + $this->assertSame( $subdir, $info['subdir'] ); + $this->assertFalse( $info['error'] ); + } +} From 4780928f956b9992a5789c75faeb1605792afaec Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 19:10:26 +0000 Subject: [PATCH 172/481] Tests: Cover attachment ordering and editor AJAX responses. Verify that `wp_ajax_save_attachment_order()` persists attachment menu orders and rejects invalid requests. Cover image and file responses from `wp_ajax_send_attachment_to_editor()`, including attachment parenting and the supplied file URL. Use the inherited AJAX test handlers and a static data provider. Developed in: https://github.com/WordPress/wordpress-develop/pull/12095 Props pbearne. See #65252. git-svn-id: https://develop.svn.wordpress.org/trunk@65178 602fd350-edb4-49c9-b593-d223f7449a82 --- .../ajax-actions/saveAttachmentOrder.php | 203 ++++++++++++++++++ .../ajax-actions/sendAttachmentToEditor.php | 174 +++++++++++++++ 2 files changed, 377 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/saveAttachmentOrder.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/sendAttachmentToEditor.php diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/saveAttachmentOrder.php b/tests/phpunit/tests/admin/includes/ajax-actions/saveAttachmentOrder.php new file mode 100644 index 0000000000000..86b91d8608699 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/saveAttachmentOrder.php @@ -0,0 +1,203 @@ +user->create( array( 'role' => 'administrator' ) ); + + self::$post_id = $factory->post->create(); + + self::$attachment_ids = array( + $factory->attachment->create_object( + array( + 'file' => 'test1.jpg', + 'post_parent' => self::$post_id, + 'menu_order' => 0, + ) + ), + $factory->attachment->create_object( + array( + 'file' => 'test2.jpg', + 'post_parent' => self::$post_id, + 'menu_order' => 0, + ) + ), + ); + } + + public function set_up(): void { + parent::set_up(); + add_action( 'wp_ajax_save-attachment-order', 'wp_ajax_save_attachment_order', 1 ); + } + + /** + * Tests success for wp_ajax_save_attachment_order(). + * + * @ticket 65252 + */ + public function test_save_attachment_order_success(): void { + wp_set_current_user( self::$admin_id ); + + $_POST['post_id'] = self::$post_id; + $_POST['nonce'] = wp_create_nonce( 'update-post_' . self::$post_id ); + $_POST['attachments'] = array( + self::$attachment_ids[0] => 10, + self::$attachment_ids[1] => 20, + ); + + try { + $this->_handleAjax( 'save-attachment-order' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertTrue( $response['success'], 'AJAX response should be successful' ); + + $this->assertEquals( 10, get_post( self::$attachment_ids[0] )->menu_order, 'First attachment menu_order should be 10' ); + $this->assertEquals( 20, get_post( self::$attachment_ids[1] )->menu_order, 'Second attachment menu_order should be 20' ); + } + + /** + * Tests failure with invalid nonce for wp_ajax_save_attachment_order(). + * + * @ticket 65252 + */ + public function test_save_attachment_order_invalid_nonce(): void { + wp_set_current_user( self::$admin_id ); + + $_POST['post_id'] = self::$post_id; + $_POST['nonce'] = 'invalid-nonce'; + $_POST['attachments'] = array( + self::$attachment_ids[0] => 10, + ); + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'save-attachment-order' ); + } + + /** + * Tests failure with insufficient permissions for wp_ajax_save_attachment_order(). + * + * @ticket 65252 + */ + public function test_save_attachment_order_insufficient_permissions(): void { + $subscriber_id = self::factory()->user->create( array( 'role' => 'subscriber' ) ); + wp_set_current_user( $subscriber_id ); + + $_POST['post_id'] = self::$post_id; + $_POST['nonce'] = wp_create_nonce( 'update-post_' . self::$post_id ); + $_POST['attachments'] = array( + self::$attachment_ids[0] => 10, + ); + + try { + $this->_handleAjax( 'save-attachment-order' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertFalse( $response['success'], 'AJAX response should be unsuccessful' ); + } + + /** + * Tests failure with missing parameters for wp_ajax_save_attachment_order(). + * + * @ticket 65252 + * + * @dataProvider data_missing_parameters + * + * @param array $post_data POST data. + */ + public function test_save_attachment_order_missing_parameters( array $post_data ): void { + wp_set_current_user( self::$admin_id ); + + $_POST = $post_data; + + try { + $this->_handleAjax( 'save-attachment-order' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertFalse( $response['success'], 'AJAX response should be unsuccessful' ); + } + + /** + * Data provider for missing parameters. + * + * @return array + */ + public static function data_missing_parameters(): array { + return array( + 'missing post_id' => array( + array( + 'attachments' => array( 1 => 10 ), + ), + ), + 'invalid post_id' => array( + array( + 'post_id' => 0, + 'attachments' => array( 1 => 10 ), + ), + ), + 'missing attachments' => array( + array( + 'post_id' => 1, + ), + ), + 'empty attachments' => array( + array( + 'post_id' => 1, + 'attachments' => array(), + ), + ), + ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/sendAttachmentToEditor.php b/tests/phpunit/tests/admin/includes/ajax-actions/sendAttachmentToEditor.php new file mode 100644 index 0000000000000..99fd34a269180 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/sendAttachmentToEditor.php @@ -0,0 +1,174 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$post_id = $factory->post->create(); + + self::$attachment_id = $factory->attachment->create_object( + array( + 'file' => 'test.jpg', + 'post_parent' => 0, + 'post_mime_type' => 'image/jpeg', + 'post_title' => 'Test Image', + 'post_content' => 'Test Description', + 'post_excerpt' => 'Test Caption', + ) + ); + } + + /** + * Tests success for wp_ajax_send_attachment_to_editor() with an image. + * + * @ticket 65252 + */ + public function test_send_attachment_to_editor_image_success(): void { + wp_set_current_user( self::$admin_id ); + + $_POST['nonce'] = wp_create_nonce( 'media-send-to-editor' ); + $_POST['post_id'] = self::$post_id; + $_POST['attachment'] = array( + 'id' => self::$attachment_id, + 'align' => 'left', + 'image-size' => 'medium', + 'image_alt' => 'Custom Alt', + 'post_excerpt' => 'Custom Caption', + 'url' => 'http://example.com/test.jpg', + ); + + try { + $this->_handleAjax( 'send-attachment-to-editor' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertTrue( $response['success'], 'AJAX response should be successful' ); + $this->assertStringContainsString( 'Custom Alt', $response['data'], 'HTML should contain custom alt text' ); + $this->assertStringContainsString( 'Custom Caption', $response['data'], 'HTML should contain custom caption' ); + $this->assertStringContainsString( 'alignleft', $response['data'], 'HTML should contain correct alignment class' ); + + // Verify that the attachment was attached to the post. + $attachment = get_post( self::$attachment_id ); + $this->assertEquals( self::$post_id, $attachment->post_parent, 'Attachment should be attached to the post' ); + } + + /** + * Tests success for wp_ajax_send_attachment_to_editor() with a non-image file. + * + * @ticket 65252 + */ + public function test_send_attachment_to_editor_file_success(): void { + wp_set_current_user( self::$admin_id ); + + $file_id = self::factory()->attachment->create_object( + array( + 'file' => 'test.pdf', + 'post_parent' => 0, + 'post_mime_type' => 'application/pdf', + 'post_title' => 'Test Document', + ) + ); + + $_POST['nonce'] = wp_create_nonce( 'media-send-to-editor' ); + $_POST['post_id'] = self::$post_id; + $_POST['attachment'] = array( + 'id' => $file_id, + 'post_title' => 'Custom Link Text', + 'url' => 'http://example.com/test.pdf', + ); + + try { + $this->_handleAjax( 'send-attachment-to-editor' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertTrue( $response['success'], 'AJAX response should be successful' ); + $this->assertStringContainsString( 'Custom Link Text', $response['data'], 'HTML should contain custom link text' ); + $this->assertStringContainsString( 'http://example.com/test.pdf', $response['data'], 'HTML should contain the correct URL' ); + } + + /** + * Tests failure with invalid nonce for wp_ajax_send_attachment_to_editor(). + * + * @ticket 65252 + */ + public function test_send_attachment_to_editor_invalid_nonce(): void { + wp_set_current_user( self::$admin_id ); + + $_POST['nonce'] = 'invalid-nonce'; + + $this->expectException( WPAjaxDieStopException::class ); + $this->expectExceptionMessage( '-1' ); + + $this->_handleAjax( 'send-attachment-to-editor' ); + } + + /** + * Tests failure with missing attachment for wp_ajax_send_attachment_to_editor(). + * + * @ticket 65252 + */ + public function test_send_attachment_to_editor_missing_attachment(): void { + wp_set_current_user( self::$admin_id ); + + $_POST['nonce'] = wp_create_nonce( 'media-send-to-editor' ); + $_POST['attachment'] = array( + 'id' => 999999, // Non-existent ID. + ); + + try { + $this->_handleAjax( 'send-attachment-to-editor' ); + } catch ( WPAjaxDieContinueException $e ) { + } + + $response = json_decode( $this->_last_response, true ); + + $this->assertFalse( $response['success'], 'AJAX response should be unsuccessful' ); + } +} From faa721c16dbbcb4520122e2436661323be5051c1 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 19:16:46 +0000 Subject: [PATCH 173/481] Tests: Cover terminating hierarchies and cycles reached from outside the loop. Verify that `wp_find_hierarchy_loop()` returns an empty array for a terminating chain and excludes a leading noncycle node from the returned cycle members. Preserve the existing loop cases and correct the `functions` group annotation. Developed in: https://github.com/WordPress/wordpress-develop/pull/8091 Props sukhendu2002. See #59901. git-svn-id: https://develop.svn.wordpress.org/trunk@65179 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/functions/wpFindHierarchyLoop.php | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/functions/wpFindHierarchyLoop.php b/tests/phpunit/tests/functions/wpFindHierarchyLoop.php index 12621844b4609..d9efc837bcac8 100644 --- a/tests/phpunit/tests/functions/wpFindHierarchyLoop.php +++ b/tests/phpunit/tests/functions/wpFindHierarchyLoop.php @@ -3,7 +3,7 @@ /** * Tests for the wp_find_hierarchy_loop function. * - * @group Functions.php + * @group functions * * @covers ::wp_find_hierarchy_loop */ @@ -43,4 +43,49 @@ static function ( $id ) { ); $this->assertSame( $expected, $result ); } + + /** + * @ticket 59901 + */ + public function test_wp_find_hierarchy_loop_no_loop() { + $hierarchy = array( + 1 => 2, + 2 => 3, + 3 => 0, + ); + + $result = wp_find_hierarchy_loop( + static function ( $id ) use ( $hierarchy ) { + return isset( $hierarchy[ $id ] ) ? $hierarchy[ $id ] : 0; + }, + 1, + null + ); + + $this->assertSame( array(), $result ); + } + + /** + * @ticket 59901 + */ + public function test_wp_find_hierarchy_loop_with_multiple_levels() { + $result = wp_find_hierarchy_loop( + static function ( $id ) { + return array( + 1 => 2, + 2 => 3, + 3 => 4, + 4 => 2, + )[ $id ] ?? null; + }, + 1, + null + ); + $expected = array( + 2 => true, + 3 => true, + 4 => true, + ); + $this->assertSame( $expected, $result ); + } } From 9fcf733449ccace01cf68db0ff6f1cd7c801c879 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 19:17:35 +0000 Subject: [PATCH 174/481] Tests: Cover emoji conversion in email messages. Verify plain-text preservation, HTML conversion, string and array headers, and content-type filter overrides in `wp_staticize_emoji_for_email()`. Control the emoji URL to avoid coupling expectations to the current CDN version. Developed in: https://github.com/WordPress/wordpress-develop/pull/5909 Props pbearne. See #60300. git-svn-id: https://develop.svn.wordpress.org/trunk@65180 602fd350-edb4-49c9-b593-d223f7449a82 --- .../formatting/wpStaticizeEmojiForEmail.php | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 tests/phpunit/tests/formatting/wpStaticizeEmojiForEmail.php diff --git a/tests/phpunit/tests/formatting/wpStaticizeEmojiForEmail.php b/tests/phpunit/tests/formatting/wpStaticizeEmojiForEmail.php new file mode 100644 index 0000000000000..a3311290e6896 --- /dev/null +++ b/tests/phpunit/tests/formatting/wpStaticizeEmojiForEmail.php @@ -0,0 +1,99 @@ +assertSame( $expected, wp_staticize_emoji_for_email( $email ) ); + } + + public static function data_wp_staticize_emoji_for_email() { + $png_cdn = 'https://example.org/emoji/'; + + return array( + 'emoji with default plain text' => array( + 'email' => array( 'message' => 'message 🙂' ), + 'expected' => array( 'message' => 'message 🙂' ), + ), + 'simply with emoji as plain text' => array( + 'email' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/plain', + ), + 'expected' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/plain', + ), + ), + 'simply with emoji with html' => array( + 'email' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/html', + ), + 'expected' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/html', + ), + ), + 'simply with emoji with headers array with charset' => array( + 'email' => array( + 'message' => 'message 🙂', + 'headers' => array( + 'content-type:text/html; charset=utf-8', + 'header:value', + ), + ), + 'expected' => array( + 'message' => 'message 🙂', + 'headers' => array( + 'content-type:text/html; charset=utf-8', + 'header:value', + ), + ), + ), + 'filtered to html' => array( + 'email' => array( 'message' => 'message 🙂' ), + 'expected' => array( 'message' => 'message 🙂' ), + 'filtered_content_type' => 'text/html', + ), + 'filtered to plain text' => array( + 'email' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/html', + ), + 'expected' => array( + 'message' => 'message 🙂', + 'headers' => 'content-type:text/html', + ), + 'filtered_content_type' => 'text/plain', + ), + ); + } +} From 1d977f31b97587da294b5e78abb50c3dd5116112 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 19:18:53 +0000 Subject: [PATCH 175/481] Tests: Cover saved and rejected screen options. Verify user metadata written by `set_screen_options()` for built-in and filtered custom options, rejection of an out-of-range value, and requests without screen-option data. Use the inherited die handler, a redirect interceptor, and a static data provider. Developed in: https://github.com/WordPress/wordpress-develop/pull/11739 Props pbearne. See #65183. git-svn-id: https://develop.svn.wordpress.org/trunk@65181 602fd350-edb4-49c9-b593-d223f7449a82 --- .../admin/includes/misc/setScreenOptions.php | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/misc/setScreenOptions.php diff --git a/tests/phpunit/tests/admin/includes/misc/setScreenOptions.php b/tests/phpunit/tests/admin/includes/misc/setScreenOptions.php new file mode 100644 index 0000000000000..b2441edd6639f --- /dev/null +++ b/tests/phpunit/tests/admin/includes/misc/setScreenOptions.php @@ -0,0 +1,161 @@ +assertNull( $result, 'set_screen_options should return null when wp_screen_options is not set in $_POST.' ); + } + + /** + * @ticket 65183 + * @dataProvider data_set_screen_options + * + * Tests saving various screen options, including those that require filters. + * + * @param string $option The option name. + * @param mixed $value The option value. + * @param mixed $expected The expected stored value in user meta. + */ + public function test_set_screen_options( $option, $value, $expected ) { + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $_POST['wp_screen_options'] = array( + 'option' => $option, + 'value' => $value, + ); + + // Mock request method. + $_SERVER['REQUEST_METHOD'] = 'POST'; + + // Set referer and nonce. + $_SERVER['HTTP_REFERER'] = admin_url( 'edit.php?pagenum=2' ); + $_POST['screenoptionnonce'] = wp_create_nonce( 'screen-options-nonce' ); + $_REQUEST['screenoptionnonce'] = $_POST['screenoptionnonce']; + $_REQUEST['_wp_http_referer'] = $_SERVER['HTTP_REFERER']; + + if ( 'my_custom_page' === $option || 'layout_columns' === $option ) { + add_filter( 'set-screen-option', array( $this, 'filter_set_screen_option_custom' ), 10, 3 ); + } + + // Intercept redirect to prevent exit. + add_filter( 'wp_redirect', array( $this, 'intercept_redirect' ) ); + + try { + set_screen_options(); + } catch ( Exception $e ) { + if ( 'Redirected' === $e->getMessage() ) { + // Success! + } else { + $this->fail( 'The function failed with message: ' . $e->getMessage() ); + } + } + + $meta = get_user_meta( $user_id, $option, true ); + $this->assertEquals( $expected, $meta ); + } + + public function intercept_redirect( $location ) { + throw new Exception( 'Redirected' ); + } + + public function filter_set_screen_option_custom( $status, $option, $value ) { + if ( 'my_custom_page' === $option || 'layout_columns' === $option ) { + return $value; + } + return $status; + } + + /** + * Data provider for test_set_screen_options. + * + * @return array + */ + public static function data_set_screen_options(): array { + return array( + 'edit_per_page' => array( + 'option' => 'edit_per_page', + 'value' => '20', + 'expected' => 20, + ), + 'edit_per_page_invalid' => array( + 'option' => 'edit_per_page', + 'value' => '1000', // Max is 999. + 'expected' => '', + ), + 'upload_per_page' => array( + 'option' => 'upload_per_page', + 'value' => '50', + 'expected' => 50, + ), + 'custom_option_with_filter' => array( + 'option' => 'my_custom_page', + 'value' => '10', + 'expected' => 10, + ), + 'layout_columns' => array( + 'option' => 'layout_columns', + 'value' => '2', + 'expected' => 2, + ), + ); + } + + /** + * @ticket 65183 + * + * Tests that set-screen-option filter is correctly applied for custom options. + */ + public function test_set_screen_options_with_filters() { + $user_id = self::factory()->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $user_id ); + + $_POST['wp_screen_options'] = array( + 'option' => 'custom_per_page', + 'value' => '25', + ); + $_SERVER['HTTP_REFERER'] = admin_url( 'admin.php' ); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_REQUEST['screenoptionnonce'] = wp_create_nonce( 'screen-options-nonce' ); + $_REQUEST['_wp_http_referer'] = $_SERVER['HTTP_REFERER']; + + // Intercept redirect to prevent exit. + add_filter( 'wp_redirect', array( $this, 'intercept_redirect' ) ); + + // Filter ending with _page. + add_filter( 'set-screen-option', array( $this, 'filter_set_screen_option' ), 10, 3 ); + + try { + set_screen_options(); + } catch ( Exception $e ) { + if ( 'Redirected' === $e->getMessage() ) { + // Success! + } else { + $this->fail( 'The function failed with message: ' . $e->getMessage() ); + } + } + + $this->assertEquals( 25, get_user_meta( $user_id, 'custom_per_page', true ) ); + } + + public function filter_set_screen_option( $status, $option, $value ) { + if ( 'custom_per_page' === $option ) { + return $value; + } + return $status; + } +} From 7c9c8b624927f0d966fc28546712ddc01090a92b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 19:19:44 +0000 Subject: [PATCH 176/481] I18N: Correct the documented return type of translation entries. Document `WP_Translation_File::entries()` as returning string values rather than arrays of strings. Remove the three PHPStan baseline suppressions resolved by this correction. Developed in: https://github.com/WordPress/wordpress-develop/pull/15330 Props abcd95. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65182 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/l10n/class-wp-translation-file.php | 2 +- tests/phpstan/baselines/assign.propertyType.neon | 5 ----- tests/phpstan/baselines/return.type.neon | 10 ---------- 3 files changed, 1 insertion(+), 16 deletions(-) diff --git a/src/wp-includes/l10n/class-wp-translation-file.php b/src/wp-includes/l10n/class-wp-translation-file.php index 199fdca4ab786..336b3a7814900 100644 --- a/src/wp-includes/l10n/class-wp-translation-file.php +++ b/src/wp-includes/l10n/class-wp-translation-file.php @@ -158,7 +158,7 @@ public function headers(): array { * * @since 6.5.0 * - * @return array Entries. + * @return array Entries. */ public function entries(): array { if ( ! $this->parsed ) { diff --git a/tests/phpstan/baselines/assign.propertyType.neon b/tests/phpstan/baselines/assign.propertyType.neon index be051c7781720..9d852663a7340 100644 --- a/tests/phpstan/baselines/assign.propertyType.neon +++ b/tests/phpstan/baselines/assign.propertyType.neon @@ -103,11 +103,6 @@ parameters: identifier: assign.propertyType count: 1 path: ../../../src/wp-includes/customize/class-wp-customize-header-image-control.php - - - message: '#^Property WP_Translation_File\:\:\$entries \(array\\) does not accept array\\>\.$#' - identifier: assign.propertyType - count: 1 - path: ../../../src/wp-includes/l10n/class-wp-translation-file.php - message: '#^Property WP_REST_Autosaves_Controller\:\:\$revisions_controller \(WP_REST_Revisions_Controller\) does not accept WP_REST_Controller\.$#' identifier: assign.propertyType diff --git a/tests/phpstan/baselines/return.type.neon b/tests/phpstan/baselines/return.type.neon index db2b0be300568..a395fbd5ca63a 100644 --- a/tests/phpstan/baselines/return.type.neon +++ b/tests/phpstan/baselines/return.type.neon @@ -68,16 +68,6 @@ parameters: identifier: return.type count: 1 path: ../../../src/wp-includes/fonts.php - - - message: '#^Method WP_Translation_Controller\:\:get_entries\(\) should return array\ but returns array\\>\.$#' - identifier: return.type - count: 1 - path: ../../../src/wp-includes/l10n/class-wp-translation-controller.php - - - message: '#^Method WP_Translation_File\:\:entries\(\) should return array\\> but returns array\\.$#' - identifier: return.type - count: 1 - path: ../../../src/wp-includes/l10n/class-wp-translation-file.php - message: '#^Function update_meta_cache\(\) should return array\|false but returns bool\.$#' identifier: return.type From 7a133c60d99dce9cc4acbafd399b9f79e05fbbbe Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Sun, 1 Nov 2026 23:44:17 +0000 Subject: [PATCH 177/481] Code Quality: Remove redundant array-offset checks. Simplify conditions in menu ordering, timezone selection, and REST revision queries where surrounding code already guarantees the checked offset exists. Remove the resolved `isset.offset` PHPStan baseline and its configuration include. Developed in: https://github.com/WordPress/wordpress-develop/pull/14035 Props huzaifaalmesbah. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65183 602fd350-edb4-49c9-b593-d223f7449a82 --- phpstan.neon.dist | 1 - src/wp-admin/nav-menus.php | 1 - src/wp-includes/functions.php | 2 +- .../class-wp-rest-revisions-controller.php | 2 +- tests/phpstan/baselines/isset.offset.neon | 35 ------------------- 5 files changed, 2 insertions(+), 39 deletions(-) delete mode 100644 tests/phpstan/baselines/isset.offset.neon diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 52ac7ab489adf..655bb9bbc807c 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -38,7 +38,6 @@ includes: - tests/phpstan/baselines/identical.alwaysFalse.neon - tests/phpstan/baselines/if.alwaysFalse.neon - tests/phpstan/baselines/if.alwaysTrue.neon - - tests/phpstan/baselines/isset.offset.neon - tests/phpstan/baselines/isset.property.neon - tests/phpstan/baselines/method.childParameterType.neon - tests/phpstan/baselines/method.unused.neon diff --git a/src/wp-admin/nav-menus.php b/src/wp-admin/nav-menus.php index 6a9925b0d4708..6f3b683817447 100644 --- a/src/wp-admin/nav-menus.php +++ b/src/wp-admin/nav-menus.php @@ -197,7 +197,6 @@ // If this menu item is a child of the previous. if ( ! empty( $menu_item_data['menu_item_parent'] ) && isset( $dbids_to_orders[ (int) $menu_item_data['menu_item_parent'] ] ) - && isset( $orders_to_dbids[ $dbids_to_orders[ $menu_item_id ] - 1 ] ) && ( (int) $menu_item_data['menu_item_parent'] === $orders_to_dbids[ $dbids_to_orders[ $menu_item_id ] - 1 ] ) ) { if ( in_array( (int) $menu_item_data['menu_item_parent'], $orders_to_dbids, true ) ) { diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index d021b635ed60f..f7baf953bcbcd 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -6955,7 +6955,7 @@ function wp_timezone_choice( $selected_zone, $locale = null ) { $structure[] = ''; // Close continent optgroup. - if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || ( isset( $zonen[ $key + 1 ] ) && $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) ) { + if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) { $structure[] = ''; } } diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php index 9abced65e68b2..a68f0cd5a513f 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php @@ -288,7 +288,7 @@ public function get_items( $request ) { } // For backward-compatibility, 'date' needs to resolve to 'date ID'. - if ( isset( $args['orderby'] ) && 'date' === $args['orderby'] ) { + if ( 'date' === $args['orderby'] ) { $args['orderby'] = 'date ID'; } diff --git a/tests/phpstan/baselines/isset.offset.neon b/tests/phpstan/baselines/isset.offset.neon deleted file mode 100644 index 701b260590e6f..0000000000000 --- a/tests/phpstan/baselines/isset.offset.neon +++ /dev/null @@ -1,35 +0,0 @@ -# PHPStan baseline for the `isset.offset` errors in WordPress core. -# -# https://phpstan.org/error-identifiers/isset.offset -# -# Each entry is scoped to a single file and carries an exact occurrence count, -# so that a new instance is reported as a new error rather than being absorbed -# silently. Fixing an occurrence therefore means decrementing or removing its -# entry here as part of the same change. -# -# The goal is to empty this file and delete it, along with the `includes` entry -# for it in phpstan.neon.dist. -# -# Generated by `composer phpstan:baselines`. Do not edit by hand; regenerate with -# -# composer phpstan:baselines -- --identifier=isset.offset -# -# which reruns the analysis with this file suppressed so the errors surface again. - -parameters: - ignoreErrors: - - - message: '#^Offset \(float\|int\) on non\-empty\-array\ in isset\(\) always exists and is not nullable\.$#' - identifier: isset.offset - count: 1 - path: ../../../src/wp-admin/nav-menus.php - - - message: '#^Offset int\<1, max\> on non\-empty\-list\ in isset\(\) always exists and is not nullable\.$#' - identifier: isset.offset - count: 1 - path: ../../../src/wp-includes/functions.php - - - message: '#^Offset ''orderby'' on array\{post_parent\: mixed, post_type\: ''revision'', post_status\: ''inherit'', posts_per_page\: mixed, orderby\: mixed, order\: mixed, suppress_filters\: true, post__not_in\?\: mixed, \.\.\.\} in isset\(\) always exists and is not nullable\.$#' - identifier: isset.offset - count: 1 - path: ../../../src/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php From 040bdd6b89913c4272bd4fdc61a79e8347cee21d Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sun, 1 Nov 2026 23:49:24 +0000 Subject: [PATCH 178/481] Twenty Fifteen: Hide menu toggle button when JavaScript is disabled. Uses the `no-js` class to hide the toggle button that expands and collapses the secondary container (with a menu and/or widgets). Developed in https://github.com/WordPress/wordpress-develop/pull/13719. Props sabernhardt, dboy1988. Fixes #66175. git-svn-id: https://develop.svn.wordpress.org/trunk@65184 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-content/themes/twentyfifteen/style.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wp-content/themes/twentyfifteen/style.css b/src/wp-content/themes/twentyfifteen/style.css index 58aef4e34bc2e..5e841f1d27a4e 100644 --- a/src/wp-content/themes/twentyfifteen/style.css +++ b/src/wp-content/themes/twentyfifteen/style.css @@ -716,6 +716,10 @@ a:focus { margin-top: 0.5em; } +.no-js .secondary-toggle { + display: none; +} + .no-js .main-navigation ul ul { display: block; } From 4dac54caab1e103be6d154466d2227f5219d8afc Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:38:40 +0000 Subject: [PATCH 179/481] Tests: Correct block template slug assertion argument order. Pass the expected slug before the actual value in `test_register_template()` so PHPUnit reports failures correctly. Developed in: https://github.com/WordPress/wordpress-develop/pull/15332 Props noruzzaman, rejaulalomkhan. See #64895. git-svn-id: https://develop.svn.wordpress.org/trunk@65185 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/block-templates/WpBlockTemplatesRegistry.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/phpunit/tests/block-templates/WpBlockTemplatesRegistry.php b/tests/phpunit/tests/block-templates/WpBlockTemplatesRegistry.php index ec227f3ad9dec..113fdc61ace88 100644 --- a/tests/phpunit/tests/block-templates/WpBlockTemplatesRegistry.php +++ b/tests/phpunit/tests/block-templates/WpBlockTemplatesRegistry.php @@ -29,7 +29,7 @@ public function test_register_template() { $template_name = 'test-plugin//test-template'; $template = self::$registry->register( $template_name ); - $this->assertSame( $template->slug, 'test-template' ); + $this->assertSame( 'test-template', $template->slug ); self::$registry->unregister( $template_name ); } From 0e08bebf460561004ebc5549b932c785e41e574e Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:39:49 +0000 Subject: [PATCH 180/481] Tests: Simplify post type removal in attachment permalink tests. Use `unregister_post_type()` instead of manually removing the registry entry when testing an attachment whose parent post type no longer exists. Remove the unused global declaration. Developed in: https://github.com/WordPress/wordpress-develop/pull/14950 Props rejaulalomkhan, mukesh27. See #65893. git-svn-id: https://develop.svn.wordpress.org/trunk@65186 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/link.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/tests/phpunit/tests/link.php b/tests/phpunit/tests/link.php index b9576a7a1a16a..ceb12d0c3900d 100644 --- a/tests/phpunit/tests/link.php +++ b/tests/phpunit/tests/link.php @@ -150,8 +150,6 @@ public function test_unattached_attachment_has_a_pretty_permalink() { * @ticket 1914 */ public function test_attachment_attached_to_non_existent_post_type_has_a_pretty_permalink() { - global $wp_post_types; - $this->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); register_post_type( 'not_a_post_type', array( 'public' => true ) ); @@ -175,12 +173,7 @@ public function test_attachment_attached_to_non_existent_post_type_has_a_pretty_ $this->assertSame( get_permalink( $post_id ) . user_trailingslashit( $attachment->post_name ), get_permalink( $attachment_id ) ); - foreach ( $wp_post_types as $id => $pt ) { - if ( 'not_a_post_type' === $pt->name ) { - unset( $wp_post_types[ $id ] ); - break; - } - } + unregister_post_type( 'not_a_post_type' ); $this->assertSame( home_url( "/?attachment_id={$attachment->ID}" ), get_permalink( $attachment_id ) ); // Visit permalink. From 05bb12bda0ac11241f246e041a9842b3b2e16019 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:48:15 +0000 Subject: [PATCH 181/481] REST API: Remove unreachable featured media update code. Remove the unreachable `featured_media` block from `WP_REST_Attachments_Controller::update_item()` and its PHPStan baseline entries. The local `$schema` variable is never assigned, and the parent controller already handles featured media updates. Developed in: https://github.com/WordPress/wordpress-develop/pull/13980 Props huzaifaalmesbah. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65187 602fd350-edb4-49c9-b593-d223f7449a82 --- .../endpoints/class-wp-rest-attachments-controller.php | 8 -------- tests/phpstan/baselines/booleanAnd.alwaysFalse.neon | 5 ----- tests/phpstan/baselines/empty.variable.neon | 5 ----- 3 files changed, 18 deletions(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php index 1be17d2dffbe0..bc6ba492a351c 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php @@ -1006,14 +1006,6 @@ public function update_item( $request ) { $attachment = get_post( $request['id'] ); - if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { - $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment->ID ); - - if ( is_wp_error( $thumbnail_update ) ) { - return $thumbnail_update; - } - } - $fields_update = $this->update_additional_fields_for_object( $attachment, $request ); if ( is_wp_error( $fields_update ) ) { diff --git a/tests/phpstan/baselines/booleanAnd.alwaysFalse.neon b/tests/phpstan/baselines/booleanAnd.alwaysFalse.neon index 4bbff3cdb566b..0580dee3a7f31 100644 --- a/tests/phpstan/baselines/booleanAnd.alwaysFalse.neon +++ b/tests/phpstan/baselines/booleanAnd.alwaysFalse.neon @@ -23,8 +23,3 @@ parameters: identifier: booleanAnd.alwaysFalse count: 1 path: ../../../src/wp-admin/themes.php - - - message: '#^Result of && is always false\.$#' - identifier: booleanAnd.alwaysFalse - count: 1 - path: ../../../src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php diff --git a/tests/phpstan/baselines/empty.variable.neon b/tests/phpstan/baselines/empty.variable.neon index c4e28ff1f0f03..ab74229ad5717 100644 --- a/tests/phpstan/baselines/empty.variable.neon +++ b/tests/phpstan/baselines/empty.variable.neon @@ -33,11 +33,6 @@ parameters: identifier: empty.variable count: 1 path: ../../../src/wp-includes/class-wp-query.php - - - message: '#^Variable \$schema in empty\(\) is never defined\.$#' - identifier: empty.variable - count: 1 - path: ../../../src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php - message: '#^Variable \$the_parent in empty\(\) always exists and is not falsy\.$#' identifier: empty.variable From d0c67b4638ea0b95b9493d99913f1b1c002415bb Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:49:03 +0000 Subject: [PATCH 182/481] Tests: Cover array preservation in string-only unslashing. Verify that `stripslashes_from_strings_only()` leaves an array containing a slashed string unchanged. The existing `stripslashes_deep()` tests exercise recursive processing instead of this direct-input contract. Developed in: https://github.com/WordPress/wordpress-develop/pull/15325 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65188 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/formatting/stripslashesDeep.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/phpunit/tests/formatting/stripslashesDeep.php b/tests/phpunit/tests/formatting/stripslashesDeep.php index b88966cc3427f..e090b41a3dc98 100644 --- a/tests/phpunit/tests/formatting/stripslashesDeep.php +++ b/tests/phpunit/tests/formatting/stripslashesDeep.php @@ -5,6 +5,7 @@ * @group slashes * * @covers ::stripslashes_deep + * @covers ::stripslashes_from_strings_only */ class Tests_Formatting_StripslashesDeep extends WP_UnitTestCase { /** @@ -55,4 +56,17 @@ public function test_permits_escaped_slash() { $this->assertSame( $txt, stripslashes_deep( "I can\'t see, isn\\\'t that it?" ) ); $this->assertSame( $txt, stripslashes_deep( "I can\'t see, isn\\\\\'t that it?" ) ); } + + /** + * Tests that stripslashes_from_strings_only() does not strip slashes from array elements. + * + * Unlike stripslashes_deep(), stripslashes_from_strings_only() does not recurse into arrays. + * + * @ticket 65819 + */ + public function test_stripslashes_from_strings_only_does_not_strip_array() { + $slashed_array = array( "I can\'t see", 'b' ); + + $this->assertSame( $slashed_array, stripslashes_from_strings_only( $slashed_array ) ); + } } From 24f9a3e424849ac0550db97df513336d183e3daf Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:53:05 +0000 Subject: [PATCH 183/481] Tests: Cover posts navigation output and custom arguments. Verify that `the_posts_navigation()` emits navigation with the supplied class, screen-reader text, and accessible label. Reuse the existing post fixture and derive expected links from the configured home URL. Developed in: https://github.com/WordPress/wordpress-develop/pull/15321 Props devmuhib, huzaifaalmesbah. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65189 602fd350-edb4-49c9-b593-d223f7449a82 --- .../tests/link/getThePostsNavigation.php | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/link/getThePostsNavigation.php b/tests/phpunit/tests/link/getThePostsNavigation.php index 0cb39b07453ee..f3e1077e81015 100644 --- a/tests/phpunit/tests/link/getThePostsNavigation.php +++ b/tests/phpunit/tests/link/getThePostsNavigation.php @@ -1,13 +1,14 @@ set_permalink_structure( '' ); + $this->go_to( home_url( '/' ) ); + + global $wp_query, $paged; + + $paged = 2; + $wp_query = new WP_Query( + array( + 'post_type' => 'post', + 'posts_per_page' => 1, + 'paged' => $paged, + ) + ); + + add_filter( + 'navigation_markup_template', + static function () { + return ''; + } + ); + + $expected = ''; + + $this->expectOutputString( $expected ); + the_posts_navigation( + array( + 'class' => 'echo-navigation', + 'screen_reader_text' => 'Echo Reader', + 'aria_label' => 'Echo ARIA', + ) + ); + } } From 9dfdf85f6911c32d22cfa61c4af2b4416bf401bf Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:54:19 +0000 Subject: [PATCH 184/481] Tests: Clean test uploads before loading WordPress. Delete the test uploads directory before loading plugins and themes. Calling `wp_upload_dir()` during loading can create and cache the directory; deleting it afterward leaves that cached path missing. Use PHP filesystem operations before WordPress functions are available, handle Windows directory symlinks, and report directory traversal exceptions. Follow-up to [65177]. Developed in: https://github.com/WordPress/wordpress-develop/pull/15368 Props oaratovskyi, adrianmoldovanwp. See #63532. git-svn-id: https://develop.svn.wordpress.org/trunk@65190 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/includes/bootstrap.php | 39 +++++++++++++++++++++------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/tests/phpunit/includes/bootstrap.php b/tests/phpunit/includes/bootstrap.php index 41cc5e7fd7f95..70de86b1b4e20 100644 --- a/tests/phpunit/includes/bootstrap.php +++ b/tests/phpunit/includes/bootstrap.php @@ -330,26 +330,45 @@ function wp_tests_options( $value ) { } } -// Load WordPress. -require_once ABSPATH . 'wp-settings.php'; - -// Process delete wp-content/test-suite-uploads folder. +/* + * Delete the wp-content/test-suite-uploads folder before WordPress loads. + * + * Plugins and themes may call wp_upload_dir() while loading, which creates the folder and + * caches it as created. Deleting it afterwards would leave a cached path that no longer exists. + * WordPress functions are not available yet, so this uses plain PHP. + */ if ( ! empty( $delete_tests_uploads_dir ) ) { $uploads_test_run_dir = ABSPATH . UPLOADS; if ( is_dir( $uploads_test_run_dir ) ) { - require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; - require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; + try { + $uploads_test_run_files = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator( $uploads_test_run_dir, FilesystemIterator::SKIP_DOTS ), + RecursiveIteratorIterator::CHILD_FIRST + ); - // Use the direct transport, as WP_Filesystem() may pick FTP and fail without credentials. - $uploads_test_run_fs = new WP_Filesystem_Direct( null ); - $uploads_test_run_fs->delete( $uploads_test_run_dir, true ); + foreach ( $uploads_test_run_files as $uploads_test_run_file ) { + // Windows removes symlinks to directories with rmdir(), not unlink(). + if ( $uploads_test_run_file->isDir() && ( ! $uploads_test_run_file->isLink() || 'Windows' === PHP_OS_FAMILY ) ) { + rmdir( $uploads_test_run_file->getPathname() ); + } else { + unlink( $uploads_test_run_file->getPathname() ); + } + } + + rmdir( $uploads_test_run_dir ); + } catch ( UnexpectedValueException $uploads_test_run_exception ) { + echo 'Could not delete the test uploads directory: ' . $uploads_test_run_exception->getMessage() . PHP_EOL; + } } - unset( $uploads_test_run_dir, $uploads_test_run_fs ); + unset( $uploads_test_run_dir, $uploads_test_run_files, $uploads_test_run_file, $uploads_test_run_exception ); } unset( $delete_tests_uploads_dir ); +// Load WordPress. +require_once ABSPATH . 'wp-settings.php'; + // Override the PHPMailer. require_once __DIR__ . '/mock-mailer.php'; From f159ff116a133cacbf4b6c6723211841c2b34a3b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 15:59:22 +0000 Subject: [PATCH 185/481] Build/Test Tools: Use release ZIPs for installation tests. Download WordPress release ZIP archives through `wp core download` to preserve long filenames during extraction. Keep nightly and trunk downloads unchanged. Pin WP-CLI to `2.12.0` for PHP `5.6`, `7.0`, and `7.1`, retaining the existing `2.4.0` pin for PHP `5.4` and `5.5`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15252 Props adrianmoldovanwp, lucatume. See #66403. git-svn-id: https://develop.svn.wordpress.org/trunk@65191 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/workflows/install-testing.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/install-testing.yml b/.github/workflows/install-testing.yml index 7bc7cab67856a..a1a634b6bac39 100644 --- a/.github/workflows/install-testing.yml +++ b/.github/workflows/install-testing.yml @@ -138,15 +138,15 @@ jobs: - name: Set up WP-CLI uses: $/.github/actions/setup-wp-cli with: - version: ${{ contains( fromJSON('["5.4", "5.5"]'), matrix.php ) && '2.4.0' || 'latest' }} + version: ${{ contains( fromJSON('["5.4", "5.5"]'), matrix.php ) && '2.4.0' || contains( fromJSON('["5.6", "7.0", "7.1"]'), matrix.php ) && '2.12.0' || 'latest' }} - # WP-CLI extracts tarballs with PharData, which truncates paths longer than 100 characters. - # Nightly builds are only available as a zip, which is not affected. + # WP-CLI 2.x extracts tarballs with PharData, which truncates paths longer than 100 characters. + # Zip archives are not affected, so download the zip for every version. - name: Download WordPress run: | case "${WP_VERSION}" in nightly|trunk) wp core download --version=nightly ;; - *) curl -fsSL "https://wordpress.org/wordpress-${WP_VERSION}.tar.gz" | tar xz --strip-components=1 ;; + *) wp core download "https://wordpress.org/wordpress-${WP_VERSION}.zip" ;; esac env: WP_VERSION: ${{ inputs.wp-version || 'nightly' }} From 46bb3912c21e7419495a2a692636f15050159378 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:03:09 +0000 Subject: [PATCH 186/481] Build/Test Tools: Correct nullable property documentation. Document that `WP_Locale::$word_count_type` and `WP_Post_Type::$template` can be `null`, and remove the corresponding PHPStan baseline entries. Cover the existing REST response normalization of a `null` post type template to an empty array. Developed in: https://github.com/WordPress/wordpress-develop/pull/13982 Props huzaifaalmesbah. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65192 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-locale.php | 2 +- src/wp-includes/class-wp-post-type.php | 2 +- .../baselines/nullCoalesce.property.neon | 10 --------- .../rest-api/rest-post-types-controller.php | 22 +++++++++++++++++++ 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/wp-includes/class-wp-locale.php b/src/wp-includes/class-wp-locale.php index b1e091e5196ca..3671c1b27927f 100644 --- a/src/wp-includes/class-wp-locale.php +++ b/src/wp-includes/class-wp-locale.php @@ -118,7 +118,7 @@ class WP_Locale { * Default is 'words'. * * @since 6.2.0 - * @var string + * @var string|null */ public $word_count_type; diff --git a/src/wp-includes/class-wp-post-type.php b/src/wp-includes/class-wp-post-type.php index 2924f2a02f80d..0767deeb34162 100644 --- a/src/wp-includes/class-wp-post-type.php +++ b/src/wp-includes/class-wp-post-type.php @@ -305,7 +305,7 @@ final class WP_Post_Type { * @link https://developer.wordpress.org/block-editor/developers/block-api/block-templates/ * * @since 5.0.0 - * @var array[] $template + * @var array[]|null $template */ public $template = array(); diff --git a/tests/phpstan/baselines/nullCoalesce.property.neon b/tests/phpstan/baselines/nullCoalesce.property.neon index 431dd45d9d3c9..0085e07d9614f 100644 --- a/tests/phpstan/baselines/nullCoalesce.property.neon +++ b/tests/phpstan/baselines/nullCoalesce.property.neon @@ -18,18 +18,8 @@ parameters: ignoreErrors: - - - message: '#^Property WP_Locale\:\:\$word_count_type \(string\) on left side of \?\? is not nullable\.$#' - identifier: nullCoalesce.property - count: 1 - path: ../../../src/wp-includes/class-wp-locale.php - message: '#^Property WP_Query\:\:\$max_num_pages \(int\) on left side of \?\? is not nullable\.$#' identifier: nullCoalesce.property count: 1 path: ../../../src/wp-includes/general-template.php - - - message: '#^Property WP_Post_Type\:\:\$template \(array\\) on left side of \?\? is not nullable\.$#' - identifier: nullCoalesce.property - count: 1 - path: ../../../src/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php diff --git a/tests/phpunit/tests/rest-api/rest-post-types-controller.php b/tests/phpunit/tests/rest-api/rest-post-types-controller.php index ede182995ec69..69f312a8eb3ed 100644 --- a/tests/phpunit/tests/rest-api/rest-post-types-controller.php +++ b/tests/phpunit/tests/rest-api/rest-post-types-controller.php @@ -189,6 +189,28 @@ public function test_get_item_template_cpt() { $this->check_post_type_object_response( 'view', $response, 'cpt_template' ); } + /** + * Tests that registering a post type with a null template normalizes to an empty array. + * + * @ticket 61477 + * @ticket 65817 + */ + public function test_get_item_template_null_cpt() { + register_post_type( + 'cpt_template_null', + array( + 'show_in_rest' => true, + 'template' => null, + ) + ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/types/cpt_template_null' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( array(), $data['template'] ); + } + public function test_get_item_page() { $request = new WP_REST_Request( 'GET', '/wp/v2/types/page' ); $response = rest_get_server()->dispatch( $request ); From 118dc5e4ad84fc414d03efe4c6f0ef29e4ae0e8c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:05:08 +0000 Subject: [PATCH 187/481] Build/Test Tools: Improve guidance for new contributors. Add responsible disclosure guidance to the pull request template and welcome message. Explain how to link GitHub and WordPress.org accounts for contribution credit, and clarify the Trac ticket requirement. Developed in: https://github.com/WordPress/wordpress-develop/pull/15353 Props yashjawale. See #56897. git-svn-id: https://develop.svn.wordpress.org/trunk@65193 602fd350-edb4-49c9-b593-d223f7449a82 --- .github/pull_request_template.md | 2 ++ .github/workflows/pull-request-comments.yml | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 1fe1d87fc130f..f867d4736a8e8 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,6 +5,8 @@ Pull Requests in this GitHub repository **must** be linked to a ticket in the Wo See the WordPress Handbook page on using PRs for Code Review for more information: https://make.wordpress.org/core/handbook/contribute/git/github-pull-requests-for-code-review/ +Do not open pull requests for security vulnerabilities. Please follow the responsible disclosure policy instead: https://make.wordpress.org/core/handbook/testing/reporting-security-vulnerabilities/ + If this is your first time contributing, you may also find reviewing these guides first to be helpful: - FAQs for New Contributors: https://make.wordpress.org/core/handbook/tutorials/faq-for-new-contributors/ - Contributing with Code Guide: https://make.wordpress.org/core/handbook/contribute/ diff --git a/.github/workflows/pull-request-comments.yml b/.github/workflows/pull-request-comments.yml index cffc5d7aecb59..f5df15e28df0f 100644 --- a/.github/workflows/pull-request-comments.yml +++ b/.github/workflows/pull-request-comments.yml @@ -81,9 +81,11 @@ jobs: `Hi @${ author }! 👋`, 'Thank you for your contribution to WordPress! 💖', 'It looks like this is your first pull request to `wordpress-develop`. Here are a few things to be aware of that may help you out!', - '**No one monitors this repository for new pull requests.** Pull requests **must** be attached to a Trac ticket to be considered for inclusion in WordPress Core. To attach a pull request to a Trac ticket, please include the ticket\'s full URL in your pull request description.', + '**Pull requests must be attached to a [Trac](https://core.trac.wordpress.org/) ticket.** WordPress Core does not use GitHub as an issue tracker. To ensure your pull request receives the necessary attention, please include the Trac ticket\'s full URL in your pull request description.', '**Pull requests are never merged on GitHub.** The WordPress codebase continues to be managed through the SVN repository that this GitHub repository mirrors. Please feel free to open pull requests to work on any contribution you are making.', 'More information about how GitHub pull requests can be used to contribute to WordPress can be found in [the Core Handbook](https://make.wordpress.org/core/handbook/contribute/git/github-pull-requests-for-code-review/).', + '> [!IMPORTANT]\n> If your pull request addresses a security issue, please close it. Security vulnerabilities must be reported privately and handled according to the project\'s responsible disclosure policy. See [Reporting Security Vulnerabilities](https://make.wordpress.org/core/handbook/testing/reporting-security-vulnerabilities/) in the Core Handbook for more information.', + '**Please link your WordPress.org account to GitHub.** To ensure your contribution is correctly credited in a WordPress release, [connect your GitHub account in your WordPress.org profile](https://profiles.wordpress.org/me/). If you do not have a WordPress.org account, you can [register one](https://login.wordpress.org/register). More information is available in [Associating GitHub accounts with WordPress.org profiles](https://make.wordpress.org/core/2020/03/19/associating-github-accounts-with-wordpress-org-profiles/).', '**Please include automated tests.** Including tests in your pull request is one way to help your patch be considered faster. To learn about WordPress\' test suites, visit the [Automated Testing](https://make.wordpress.org/core/handbook/testing/automated-testing/) page in the handbook.', 'If you have not had a chance, please review the [Contribute with Code page](https://make.wordpress.org/core/handbook/contribute/) in the [WordPress Core Handbook](https://make.wordpress.org/core/handbook/).', 'The [Developer Hub](https://developer.wordpress.org/) also documents the various [coding standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/) that are followed:\n- [PHP Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/)\n- [CSS Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/css/)\n- [HTML Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/html/)\n- [JavaScript Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/javascript/)\n- [Accessibility Coding Standards](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/accessibility/)\n- [Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/)', From ed3b80a5e6f2da000ddb5e6888359d1e8585af41 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:07:31 +0000 Subject: [PATCH 188/481] Build/Test Tools: Allow testing and packaging a selected default theme. Add a theme selector to manual workflow runs, retaining `all` as the default and for automatic runs. Derive checks, builds, and ZIP packaging from the selection. Reject unknown selections and missing selected themes, preserve packaging for themes without build scripts, and separate concurrent runs by branch and theme. Developed in: https://github.com/WordPress/wordpress-develop/pull/15196 Props abcd95, adrianmoldovanwp, lucatume. See #66405. git-svn-id: https://develop.svn.wordpress.org/trunk@65194 602fd350-edb4-49c9-b593-d223f7449a82 --- .../workflows/test-and-zip-default-themes.yml | 171 +++++++++++------- 1 file changed, 107 insertions(+), 64 deletions(-) diff --git a/.github/workflows/test-and-zip-default-themes.yml b/.github/workflows/test-and-zip-default-themes.yml index 6dc161b3b38b2..ba130c59b608b 100644 --- a/.github/workflows/test-and-zip-default-themes.yml +++ b/.github/workflows/test-and-zip-default-themes.yml @@ -44,12 +44,35 @@ on: required: true type: string default: 'trunk' + theme: + description: 'The theme to test and zip' + required: true + type: choice + default: 'all' + options: + - all + - ipsum + - twentytwentyfive + - twentytwentyfour + - twentytwentythree + - twentytwentytwo + - twentytwentyone + - twentytwenty + - twentynineteen + - twentyseventeen + - twentysixteen + - twentyfifteen + - twentyfourteen + - twentythirteen + - twentytwelve + - twentyeleven + - twentyten # Cancels all previous workflow runs for pull requests that have not completed. concurrency: # The concurrency group contains the workflow name and the branch name for pull requests - # or the commit hash for any other events. - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + # or the commit hash for any other events, plus the selected branch and theme. + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }}-${{ inputs.branch }}-${{ inputs.theme }} cancel-in-progress: true # Disable permissions for all available scopes by default. @@ -57,6 +80,69 @@ concurrency: permissions: {} jobs: + # Selects the themes to check, build, and package. + determine-themes: + name: Determine Themes + runs-on: ubuntu-24.04 + permissions: {} + timeout-minutes: 5 + if: | + github.repository == 'WordPress/wordpress-develop' || ( + github.event_name == 'pull_request' && ( + ! github.event.repository.private || + ! github.event.pull_request.draft || + contains( github.event.pull_request.labels.*.name, 'Draft Workflow Runs' ) + ) + ) + outputs: + themes: ${{ steps.set-themes.outputs.themes }} + build_themes: ${{ steps.set-themes.outputs.build_themes }} + has_build_themes: ${{ steps.set-themes.outputs.has_build_themes }} + steps: + - name: Determine themes to test and zip + id: set-themes + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const allThemes = [ + 'ipsum', + 'twentytwentyfive', + 'twentytwentyfour', + 'twentytwentythree', + 'twentytwentytwo', + 'twentytwentyone', + 'twentytwenty', + 'twentynineteen', + 'twentyseventeen', + 'twentysixteen', + 'twentyfifteen', + 'twentyfourteen', + 'twentythirteen', + 'twentytwelve', + 'twentyeleven', + 'twentyten', + ]; + const buildThemes = [ + 'twentytwentyfive', + 'twentytwentytwo', + 'twentytwentyone', + 'twentytwenty', + 'twentynineteen', + ]; + const selected = context.eventName === 'workflow_dispatch' ? ( context.payload.inputs?.theme || 'all' ) : 'all'; + + if ( selected !== 'all' && ! allThemes.includes( selected ) ) { + core.setFailed( 'Unknown theme selected.' ); + return; + } + + const themes = selected === 'all' ? allThemes : [ selected ]; + const filteredBuildThemes = buildThemes.filter( ( theme ) => themes.includes( theme ) ); + + core.setOutput( 'themes', JSON.stringify( themes ) ); + core.setOutput( 'build_themes', JSON.stringify( filteredBuildThemes ) ); + core.setOutput( 'has_build_themes', filteredBuildThemes.length > 0 ); + # Checks for zero-byte files. # # Occasionally, binary files such as images and fonts are added to themes incorrectly. @@ -70,36 +156,12 @@ jobs: runs-on: ubuntu-24.04 permissions: contents: read + needs: [ determine-themes ] timeout-minutes: 10 - if: | - github.repository == 'WordPress/wordpress-develop' || ( - github.event_name == 'pull_request' && ( - ! github.event.repository.private || - ! github.event.pull_request.draft || - contains( github.event.pull_request.labels.*.name, 'Draft Workflow Runs' ) - ) - ) strategy: fail-fast: false matrix: - theme: [ - 'ipsum', - 'twentytwentyfive', - 'twentytwentyfour', - 'twentytwentythree', - 'twentytwentytwo', - 'twentytwentyone', - 'twentytwenty', - 'twentynineteen', - 'twentyseventeen', - 'twentysixteen', - 'twentyfifteen', - 'twentyfourteen', - 'twentythirteen', - 'twentytwelve', - 'twentyeleven', - 'twentyten' - ] + theme: ${{ fromJson( needs.determine-themes.outputs.themes ) }} steps: - name: Checkout repository @@ -142,25 +204,14 @@ jobs: runs-on: ubuntu-24.04 permissions: contents: read + needs: [ determine-themes ] timeout-minutes: 10 - if: | - github.repository == 'WordPress/wordpress-develop' || ( - github.event_name == 'pull_request' && ( - ! github.event.repository.private || - ! github.event.pull_request.draft || - contains( github.event.pull_request.labels.*.name, 'Draft Workflow Runs' ) - ) - ) + # Skip this job before expanding an empty build matrix. + if: ${{ needs.determine-themes.outputs.has_build_themes == 'true' }} strategy: fail-fast: false matrix: - theme: [ - 'twentytwentyfive', - 'twentytwentytwo', - 'twentytwentyone', - 'twentytwenty', - 'twentynineteen', - ] + theme: ${{ fromJson( needs.determine-themes.outputs.build_themes ) }} defaults: run: @@ -249,30 +300,18 @@ jobs: runs-on: ubuntu-24.04 permissions: contents: read - needs: [ check-for-empty-files, test-build-scripts ] + needs: [ determine-themes, check-for-empty-files, test-build-scripts ] timeout-minutes: 10 - if: ${{ github.repository == 'WordPress/wordpress-develop' }} + if: | + ! cancelled() && + github.repository == 'WordPress/wordpress-develop' && + needs.determine-themes.result == 'success' && + needs.check-for-empty-files.result == 'success' && + ( needs.test-build-scripts.result == 'success' || needs.test-build-scripts.result == 'skipped' ) strategy: fail-fast: false matrix: - theme: [ - 'ipsum', - 'twentytwentyfive', - 'twentytwentyfour', - 'twentytwentythree', - 'twentytwentytwo', - 'twentytwentyone', - 'twentytwenty', - 'twentynineteen', - 'twentyseventeen', - 'twentysixteen', - 'twentyfifteen', - 'twentyfourteen', - 'twentythirteen', - 'twentytwelve', - 'twentyeleven', - 'twentyten' - ] + theme: ${{ fromJson( needs.determine-themes.outputs.themes ) }} steps: - name: Checkout repository @@ -291,9 +330,13 @@ jobs: else echo "exists=false" >> "$GITHUB_OUTPUT" echo "Theme ${THEME} does not exist on the selected branch." + if [[ "${SELECTED_THEME}" != 'all' ]]; then + exit 1 + fi fi env: THEME: ${{ matrix.theme }} + SELECTED_THEME: ${{ github.event_name == 'workflow_dispatch' && inputs.theme || 'all' }} - name: Set up Node.js for themes needing minification if: ${{ steps.theme-exists.outputs.exists == 'true' && ( matrix.theme == 'twentytwentytwo' || matrix.theme == 'twentytwentyfive' ) }} @@ -335,7 +378,7 @@ jobs: permissions: actions: read contents: read - needs: [ check-for-empty-files, bundle-theme, test-build-scripts ] + needs: [ determine-themes, check-for-empty-files, bundle-theme, test-build-scripts ] if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name != 'pull_request' && always() }} with: calling_status: ${{ contains( needs.*.result, 'cancelled' ) && 'cancelled' || contains( needs.*.result, 'failure' ) && 'failure' || 'success' }} From 1a955de9302c7f0beebae02c082b39a700ff8477 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:09:26 +0000 Subject: [PATCH 189/481] Code Quality: Declare existing admin globals and simplify variable checks. Document existing globals in user and plugin administration screens, initialize the remaining redirect and privacy management URL defaults, and remove a redundant old-user-data check from `wp_insert_user()`. Remove the corresponding PHPStan baseline entries. Developed in: https://github.com/WordPress/wordpress-develop/pull/11979 Props huzaifaalmesbah, noruzzaman. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65195 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/plugins.php | 8 +++ src/wp-admin/user-edit.php | 7 ++ src/wp-admin/user-new.php | 11 ++-- src/wp-admin/users.php | 12 +++- src/wp-includes/user.php | 3 +- tests/phpstan/baselines/empty.variable.neon | 5 -- .../phpstan/baselines/variable.undefined.neon | 65 ------------------- 7 files changed, 34 insertions(+), 77 deletions(-) diff --git a/src/wp-admin/plugins.php b/src/wp-admin/plugins.php index 520bd03dee20a..62e904accaac2 100644 --- a/src/wp-admin/plugins.php +++ b/src/wp-admin/plugins.php @@ -9,6 +9,14 @@ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; +/** + * @global string $status Current plugin status view, set by WP_Plugins_List_Table. + * @global int $page Current page number, set by WP_Plugins_List_Table. + * @global array $plugins Set by WP_Plugins_List_Table::prepare_items(). + * @global int $user_ID ID of the current user, set during authentication. + */ +global $status, $page, $plugins, $user_ID; + if ( ! current_user_can( 'activate_plugins' ) ) { wp_die( __( 'Sorry, you are not allowed to manage plugins for this site.' ) ); } diff --git a/src/wp-admin/user-edit.php b/src/wp-admin/user-edit.php index df72f7250b61d..d1f99690b8451 100644 --- a/src/wp-admin/user-edit.php +++ b/src/wp-admin/user-edit.php @@ -12,6 +12,13 @@ /** WordPress Translation Installation API */ require_once ABSPATH . 'wp-admin/includes/translation-install.php'; +/** + * @global wpdb $wpdb WordPress database abstraction object. + * @global array $_wp_admin_css_colors Registered admin color schemes. + * @global WP_Roles $wp_roles The roles object. + */ +global $wpdb, $_wp_admin_css_colors, $wp_roles; + $action = ! empty( $_REQUEST['action'] ) ? sanitize_text_field( $_REQUEST['action'] ) : ''; $user_id = ! empty( $_REQUEST['user_id'] ) ? absint( $_REQUEST['user_id'] ) : 0; $wp_http_referer = ! empty( $_REQUEST['wp_http_referer'] ) ? sanitize_url( $_REQUEST['wp_http_referer'] ) : ''; diff --git a/src/wp-admin/user-new.php b/src/wp-admin/user-new.php index 73d74aa6db9c7..920fa4b768d2d 100644 --- a/src/wp-admin/user-new.php +++ b/src/wp-admin/user-new.php @@ -9,6 +9,12 @@ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; +/** + * @global wpdb $wpdb WordPress database abstraction object. + * @global int $blog_id The current site (blog) ID on multisite. + */ +global $wpdb, $blog_id; + if ( is_multisite() ) { if ( ! current_user_can( 'create_users' ) && ! current_user_can( 'promote_users' ) ) { wp_die( @@ -240,11 +246,6 @@ ); if ( isset( $_POST['noconfirmation'] ) && current_user_can( 'manage_network_users' ) ) { - /** - * @global wpdb $wpdb WordPress database abstraction object. - */ - global $wpdb; - $key = $wpdb->get_var( $wpdb->prepare( "SELECT activation_key FROM {$wpdb->signups} WHERE user_login = %s AND user_email = %s", $new_user_login, $new_user_email ) ); $new_user = wpmu_activate_signup( $key ); if ( is_wp_error( $new_user ) ) { diff --git a/src/wp-admin/users.php b/src/wp-admin/users.php index 0af7a33c77f16..36689221565f6 100644 --- a/src/wp-admin/users.php +++ b/src/wp-admin/users.php @@ -10,6 +10,15 @@ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; +/** + * @global WP_User $current_user The current user, set during authentication. + * @global WP_Roles $wp_roles The roles object. + * @global wpdb $wpdb WordPress database abstraction object. + * @global string $usersearch User search query, set by WP_Users_List_Table. + * @global int $blog_id The current site (blog) ID on multisite. + */ +global $current_user, $wp_roles, $wpdb, $usersearch, $blog_id; + if ( ! current_user_can( 'list_users' ) ) { wp_die( '

    ' . __( 'You need a higher level of permission.' ) . '

    ' . @@ -93,7 +102,8 @@ ); if ( empty( $_REQUEST ) ) { - $referer = ''; + $redirect = ''; + $referer = ''; } elseif ( isset( $_REQUEST['wp_http_referer'] ) ) { $redirect = remove_query_arg( array( 'wp_http_referer', 'updated', 'delete_count' ), wp_unslash( $_REQUEST['wp_http_referer'] ) ); $referer = ''; diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index 915020f21e9ec..02a412b291a8e 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -2428,7 +2428,7 @@ function wp_insert_user( $userdata ) { * check if current email and new email are the same, and check `email_exists` * accordingly. */ - if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) ) + if ( ( ! $update || 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) && ! defined( 'WP_IMPORTING' ) && email_exists( $user_email ) ) { @@ -4326,6 +4326,7 @@ function _wp_privacy_send_request_confirmation_notification( $request_id ) { return; } + $manage_url = ''; if ( 'export_personal_data' === $request->action_name ) { $manage_url = admin_url( 'export-personal-data.php' ); } elseif ( 'remove_personal_data' === $request->action_name ) { diff --git a/tests/phpstan/baselines/empty.variable.neon b/tests/phpstan/baselines/empty.variable.neon index ab74229ad5717..8c3edbabae187 100644 --- a/tests/phpstan/baselines/empty.variable.neon +++ b/tests/phpstan/baselines/empty.variable.neon @@ -38,8 +38,3 @@ parameters: identifier: empty.variable count: 1 path: ../../../src/wp-includes/taxonomy.php - - - message: '#^Variable \$old_user_data in empty\(\) always exists and is not falsy\.$#' - identifier: empty.variable - count: 1 - path: ../../../src/wp-includes/user.php diff --git a/tests/phpstan/baselines/variable.undefined.neon b/tests/phpstan/baselines/variable.undefined.neon index c972075c1a0ed..96e30e716bf84 100644 --- a/tests/phpstan/baselines/variable.undefined.neon +++ b/tests/phpstan/baselines/variable.undefined.neon @@ -358,26 +358,6 @@ parameters: identifier: variable.undefined count: 1 path: ../../../src/wp-admin/options.php - - - message: '#^Variable \$page might not be defined\.$#' - identifier: variable.undefined - count: 18 - path: ../../../src/wp-admin/plugins.php - - - message: '#^Variable \$plugins might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/plugins.php - - - message: '#^Variable \$status might not be defined\.$#' - identifier: variable.undefined - count: 18 - path: ../../../src/wp-admin/plugins.php - - - message: '#^Variable \$user_ID might not be defined\.$#' - identifier: variable.undefined - count: 3 - path: ../../../src/wp-admin/plugins.php - message: '#^Variable \$typenow might not be defined\.$#' identifier: variable.undefined @@ -448,26 +428,11 @@ parameters: identifier: variable.undefined count: 1 path: ../../../src/wp-admin/upgrade.php - - - message: '#^Variable \$_wp_admin_css_colors might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/user-edit.php - message: '#^Variable \$user_login might not be defined\.$#' identifier: variable.undefined count: 1 path: ../../../src/wp-admin/user-edit.php - - - message: '#^Variable \$wp_roles might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/user-edit.php - - - message: '#^Variable \$blog_id might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/user-new.php - message: '#^Variable \$current_blog might not be defined\.$#' identifier: variable.undefined @@ -478,31 +443,6 @@ parameters: identifier: variable.undefined count: 2 path: ../../../src/wp-admin/user/admin.php - - - message: '#^Variable \$blog_id might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/users.php - - - message: '#^Variable \$current_user might not be defined\.$#' - identifier: variable.undefined - count: 7 - path: ../../../src/wp-admin/users.php - - - message: '#^Variable \$redirect might not be defined\.$#' - identifier: variable.undefined - count: 10 - path: ../../../src/wp-admin/users.php - - - message: '#^Variable \$usersearch might not be defined\.$#' - identifier: variable.undefined - count: 2 - path: ../../../src/wp-admin/users.php - - - message: '#^Variable \$wp_roles might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-admin/users.php - message: '#^Variable \$title might not be defined\.$#' identifier: variable.undefined @@ -783,11 +723,6 @@ parameters: identifier: variable.undefined count: 2 path: ../../../src/wp-includes/template.php - - - message: '#^Variable \$manage_url might not be defined\.$#' - identifier: variable.undefined - count: 1 - path: ../../../src/wp-includes/user.php - message: '#^Variable \$error might not be defined\.$#' identifier: variable.undefined From 97177c144ad975f02f426371ab7c0aae874e1d3c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:10:25 +0000 Subject: [PATCH 190/481] Tests: Cover extended post content parsing. Verify `get_extended()` splits content at the more marker, preserves custom more text, trims surrounding whitespace, and leaves an unrecognized marker unchanged. Developed in: https://github.com/WordPress/wordpress-develop/pull/15341 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65196 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getExtended.php | 72 ++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 tests/phpunit/tests/post/getExtended.php diff --git a/tests/phpunit/tests/post/getExtended.php b/tests/phpunit/tests/post/getExtended.php new file mode 100644 index 0000000000000..44cf3ffd40f5a --- /dev/null +++ b/tests/phpunit/tests/post/getExtended.php @@ -0,0 +1,72 @@ +assertSame( $expected, get_extended( $content ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_get_extended() { + return array( + 'no more tag' => array( + 'Hello world.', + array( + 'main' => 'Hello world.', + 'extended' => '', + 'more_text' => '', + ), + ), + 'basic more split' => array( + "Before.\n\nAfter.", + array( + 'main' => 'Before.', + 'extended' => 'After.', + 'more_text' => '', + ), + ), + 'custom more text' => array( + 'IntroRest', + array( + 'main' => 'Intro', + 'extended' => 'Rest', + 'more_text' => 'Continue Reading', + ), + ), + 'trims surrounding newlines' => array( + "\nBefore\n\nAfter\n", + array( + 'main' => 'Before', + 'extended' => 'After', + 'more_text' => 'Read', + ), + ), + 'spaced more marker ignored' => array( + 'BeforeAfter', + array( + 'main' => 'BeforeAfter', + 'extended' => '', + 'more_text' => '', + ), + ), + ); + } +} From ec154f9cf3ea28c1c006c87f7f92c2160ca2533b Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:21:11 +0000 Subject: [PATCH 191/481] Tests: Cover post field sanitization context forwarding. Verify that `get_post_field()` passes the requested context to post field sanitization, using one local post fixture and context-specific filters. Developed in: https://github.com/WordPress/wordpress-develop/pull/15335 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65197 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getPostField.php | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 tests/phpunit/tests/post/getPostField.php diff --git a/tests/phpunit/tests/post/getPostField.php b/tests/phpunit/tests/post/getPostField.php new file mode 100644 index 0000000000000..435e1f7c97148 --- /dev/null +++ b/tests/phpunit/tests/post/getPostField.php @@ -0,0 +1,39 @@ +post->create( + array( + 'post_title' => 'Example Title', + ) + ); + + add_filter( + 'post_title', + static function ( $value ) { + return $value . '|post_title'; + } + ); + add_filter( + 'edit_post_title', + static function ( $value ) { + return $value . '|edit_post_title'; + } + ); + + $this->assertSame( 'Example Title', get_post_field( 'post_title', $post_id, 'raw' ) ); + $this->assertSame( 'Example Title|post_title', get_post_field( 'post_title', $post_id, 'display' ) ); + $this->assertSame( 'Example Title|post_title', get_post_field( 'post_title', $post_id, 'attribute' ) ); + $this->assertSame( 'Example Title|edit_post_title', get_post_field( 'post_title', $post_id, 'edit' ) ); + } +} From 426cf9c4f1e11096c38181f5539b3b73642c5d82 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:25:28 +0000 Subject: [PATCH 192/481] Tests: Cover feed content types and content transformations. Cover MIME type mappings, unknown feed types, default-feed selection, and the `feed_content_type` filter. Verify content formatting, CDATA terminator escaping, and the arguments and returned value of `the_content_feed`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15337, https://github.com/WordPress/wordpress-develop/pull/15348 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65198 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/feed/feedContentType.php | 80 ++++++++++++ .../phpunit/tests/feed/getTheContentFeed.php | 117 ++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 tests/phpunit/tests/feed/feedContentType.php create mode 100644 tests/phpunit/tests/feed/getTheContentFeed.php diff --git a/tests/phpunit/tests/feed/feedContentType.php b/tests/phpunit/tests/feed/feedContentType.php new file mode 100644 index 0000000000000..30dc9bb98bc74 --- /dev/null +++ b/tests/phpunit/tests/feed/feedContentType.php @@ -0,0 +1,80 @@ +assertSame( $expected, feed_content_type( $type ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_known_feed_content_types() { + return array( + 'rss' => array( 'rss', 'application/rss+xml' ), + 'rss2' => array( 'rss2', 'application/rss+xml' ), + 'rss-http' => array( 'rss-http', 'text/xml' ), + 'atom' => array( 'atom', 'application/atom+xml' ), + 'rdf' => array( 'rdf', 'application/rdf+xml' ), + ); + } + + /** + * @ticket 65819 + */ + public function test_returns_octet_stream_for_unknown_feed_type() { + $this->assertSame( 'application/octet-stream', feed_content_type( 'foo' ) ); + } + + /** + * @ticket 65819 + */ + public function test_empty_type_uses_default_feed() { + $this->assertSame( 'application/rss+xml', feed_content_type() ); + $this->assertSame( 'application/rss+xml', feed_content_type( '' ) ); + } + + /** + * @ticket 65819 + */ + public function test_empty_type_respects_default_feed_filter() { + add_filter( + 'default_feed', + static function () { + return 'atom'; + } + ); + + $this->assertSame( 'application/atom+xml', feed_content_type() ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_content_type_and_type() { + $filter = new MockAction(); + add_filter( 'feed_content_type', array( $filter, 'filter_append' ), 10, 2 ); + + $result = feed_content_type( 'atom' ); + + $this->assertSame( 'application/atom+xml_append', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'application/atom+xml', 'atom' ), $filter->get_args()[0] ); + } +} diff --git a/tests/phpunit/tests/feed/getTheContentFeed.php b/tests/phpunit/tests/feed/getTheContentFeed.php new file mode 100644 index 0000000000000..e3b671424a637 --- /dev/null +++ b/tests/phpunit/tests/feed/getTheContentFeed.php @@ -0,0 +1,117 @@ +post->create( + array( + 'post_content' => 'Hello feed content', + ) + ); + } + + /** + * Set the global post for content lookups. + */ + public function set_up() { + parent::set_up(); + $GLOBALS['post'] = get_post( self::$post_id ); + setup_postdata( $GLOBALS['post'] ); + } + + /** + * @ticket 65819 + */ + public function test_returns_filtered_content_for_default_feed_type() { + $filter = new MockAction(); + add_filter( 'the_content_feed', array( $filter, 'filter' ), 10, 2 ); + + $this->assertSame( "

    Hello feed content

    \n", get_the_content_feed() ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( 'rss2', $filter->get_args()[0][1] ); + + $this->assertSame( "

    Hello feed content

    \n", get_the_content_feed( null ) ); + $this->assertSame( 2, $filter->get_call_count() ); + $this->assertSame( 'rss2', $filter->get_args()[1][1] ); + } + + /** + * @ticket 65819 + */ + public function test_escapes_cdata_end_marker() { + add_filter( + 'the_content', + static function () { + return 'Before ]]> After'; + }, + 999 + ); + + $filter = new MockAction(); + add_filter( 'the_content_feed', array( $filter, 'filter' ), 10, 2 ); + + $result = get_the_content_feed( 'rss2' ); + + $this->assertSame( 'Before ]]> After', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( + array( 'Before ]]> After', 'rss2' ), + $filter->get_args()[0] + ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_content_and_feed_type() { + $filter = new MockAction(); + add_filter( 'the_content_feed', array( $filter, 'filter_append' ), 10, 2 ); + + $result = get_the_content_feed( 'atom' ); + + $this->assertSame( "

    Hello feed content

    \n_append", $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( + array( "

    Hello feed content

    \n", 'atom' ), + $filter->get_args()[0] + ); + } + + /** + * @ticket 65819 + */ + public function test_null_feed_type_uses_default_feed() { + add_filter( + 'default_feed', + static function () { + return 'atom'; + } + ); + + $filter = new MockAction(); + add_filter( 'the_content_feed', array( $filter, 'filter' ), 10, 2 ); + + get_the_content_feed( null ); + + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( 'atom', $filter->get_args()[0][1] ); + } +} From 16f874b76002dd44735151e772fce55cdad608db Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:49:10 +0000 Subject: [PATCH 193/481] Tests: Cover comment feed GUID generation. Verify `get_comment_guid()` combines the post GUID with the comment anchor, accepts a comment object, and returns `false` for a nonexistent comment. Developed in: https://github.com/WordPress/wordpress-develop/pull/15339 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65199 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/feed/getCommentGuid.php | 73 +++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 tests/phpunit/tests/feed/getCommentGuid.php diff --git a/tests/phpunit/tests/feed/getCommentGuid.php b/tests/phpunit/tests/feed/getCommentGuid.php new file mode 100644 index 0000000000000..11b0db7891435 --- /dev/null +++ b/tests/phpunit/tests/feed/getCommentGuid.php @@ -0,0 +1,73 @@ +post->create( + array( + 'guid' => 'https://example.org/?p=123', + ) + ); + + self::$comment_id = $factory->comment->create( + array( + 'comment_post_ID' => self::$post_id, + ) + ); + } + + /** + * @ticket 65819 + */ + public function test_returns_false_for_invalid_comment() { + $this->assertFalse( get_comment_guid( PHP_INT_MAX ) ); + } + + /** + * @ticket 65819 + */ + public function test_returns_post_guid_with_comment_anchor() { + $this->assertSame( + 'https://example.org/?p=123#comment-' . self::$comment_id, + get_comment_guid( self::$comment_id ) + ); + } + + /** + * @ticket 65819 + */ + public function test_accepts_comment_object() { + $comment = get_comment( self::$comment_id ); + + $this->assertSame( + 'https://example.org/?p=123#comment-' . self::$comment_id, + get_comment_guid( $comment ) + ); + } +} From 682e705b77638767ef6e4b039e6d6827501310d8 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:50:12 +0000 Subject: [PATCH 194/481] Tests: Cover default feed selection and feed HTML types. Verify the default feed, legacy RSS normalization, and the `default_feed` filter. Cover how `html_type_rss()` maps HTML and XHTML content types to feed values. Developed in: https://github.com/WordPress/wordpress-develop/pull/15336, https://github.com/WordPress/wordpress-develop/pull/15342 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65200 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/feed/getDefaultFeed.php | 45 +++++++++++++++++++++ tests/phpunit/tests/feed/htmlTypeRss.php | 42 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 tests/phpunit/tests/feed/getDefaultFeed.php create mode 100644 tests/phpunit/tests/feed/htmlTypeRss.php diff --git a/tests/phpunit/tests/feed/getDefaultFeed.php b/tests/phpunit/tests/feed/getDefaultFeed.php new file mode 100644 index 0000000000000..c4579e641de11 --- /dev/null +++ b/tests/phpunit/tests/feed/getDefaultFeed.php @@ -0,0 +1,45 @@ +assertSame( 'rss2', get_default_feed() ); + } + + /** + * @ticket 65819 + */ + public function test_maps_legacy_rss_alias_to_rss2() { + add_filter( + 'default_feed', + static function () { + return 'rss'; + } + ); + + $this->assertSame( 'rss2', get_default_feed() ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_unfiltered_default() { + $filter = new MockAction(); + add_filter( 'default_feed', array( $filter, 'filter_append' ) ); + + $result = get_default_feed(); + + $this->assertSame( 'rss2_append', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'rss2' ), $filter->get_args()[0] ); + } +} diff --git a/tests/phpunit/tests/feed/htmlTypeRss.php b/tests/phpunit/tests/feed/htmlTypeRss.php new file mode 100644 index 0000000000000..8e5ca85403ec6 --- /dev/null +++ b/tests/phpunit/tests/feed/htmlTypeRss.php @@ -0,0 +1,42 @@ +expectOutputString( 'xhtml' ); + + html_type_rss(); + } + + /** + * @ticket 65819 + */ + public function test_echoes_html_for_non_xhtml_html_type() { + add_filter( + 'pre_option_html_type', + static function () { + return 'text/html'; + } + ); + + $this->expectOutputString( 'html' ); + + html_type_rss(); + } +} From 1128131aa40f40545d05cb8c6463964fb9d41503 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:52:13 +0000 Subject: [PATCH 195/481] Tests: Cover feed title filtering. Verify `get_the_title_rss()` passes the post title to `the_title_rss` and returns the filtered value. Use a local post fixture and retain existing integration coverage for ordinary feed titles. Developed in: https://github.com/WordPress/wordpress-develop/pull/15346 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65201 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/feed/getTheTitleRss.php | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tests/phpunit/tests/feed/getTheTitleRss.php diff --git a/tests/phpunit/tests/feed/getTheTitleRss.php b/tests/phpunit/tests/feed/getTheTitleRss.php new file mode 100644 index 0000000000000..9b5ca133487bf --- /dev/null +++ b/tests/phpunit/tests/feed/getTheTitleRss.php @@ -0,0 +1,30 @@ +post->create( + array( + 'post_title' => 'Hello Feed Title', + ) + ); + + $filter = new MockAction(); + add_filter( 'the_title_rss', array( $filter, 'filter_append' ) ); + + $result = get_the_title_rss( $post_id ); + + $this->assertSame( 'Hello Feed Title_append', $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( array( 'Hello Feed Title' ), $filter->get_args()[0] ); + } +} From 68b3ef7169111045e83f602fae79d2c3fb090137 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:53:45 +0000 Subject: [PATCH 196/481] Tests: Cover feed category output and filtering. Cover RDF category markup, deduplication of category and tag names, Atom attribute escaping, and the arguments and returned value of the `the_category_rss` filter. Developed in: https://github.com/WordPress/wordpress-develop/pull/15345 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65202 602fd350-edb4-49c9-b593-d223f7449a82 --- .../phpunit/tests/feed/getTheCategoryRss.php | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 tests/phpunit/tests/feed/getTheCategoryRss.php diff --git a/tests/phpunit/tests/feed/getTheCategoryRss.php b/tests/phpunit/tests/feed/getTheCategoryRss.php new file mode 100644 index 0000000000000..d841a35dfd4ce --- /dev/null +++ b/tests/phpunit/tests/feed/getTheCategoryRss.php @@ -0,0 +1,138 @@ +category->create_and_get( + array( + 'name' => 'News', + 'slug' => 'news', + ) + ); + + self::$post_id = $factory->post->create(); + wp_set_post_categories( self::$post_id, array( self::$category->term_id ) ); + } + + /** + * Set the global post for category lookups. + */ + public function set_up() { + parent::set_up(); + $GLOBALS['post'] = get_post( self::$post_id ); + setup_postdata( $GLOBALS['post'] ); + } + + /** + * @ticket 65819 + */ + public function test_returns_rdf_subject_markup() { + $expected = "\t\t\n"; + + $this->assertSame( $expected, get_the_category_rss( 'rdf' ) ); + } + + /** + * @ticket 65819 + */ + public function test_includes_tags_and_deduplicates_shared_names() { + $post_id = self::factory()->post->create(); + wp_set_object_terms( $post_id, array(), 'category' ); + + $tag_only = self::factory()->tag->create_and_get( + array( + 'name' => 'Featured', + 'slug' => 'featured', + ) + ); + $tag_dup = self::factory()->tag->create_and_get( + array( + 'name' => 'News', + 'slug' => 'news-tag', + ) + ); + + wp_set_post_tags( $post_id, array( $tag_only->term_id, $tag_dup->term_id ) ); + wp_set_post_categories( $post_id, array( self::$category->term_id ) ); + + $GLOBALS['post'] = get_post( $post_id ); + setup_postdata( $GLOBALS['post'] ); + + $expected = "\t\t\n"; + $expected .= "\t\t\n"; + + $this->assertSame( $expected, get_the_category_rss( 'rss2' ) ); + } + + /** + * @ticket 65819 + */ + public function test_atom_escapes_special_characters_in_term_attribute() { + $post_id = self::factory()->post->create(); + $category = self::factory()->category->create_and_get( + array( + 'name' => 'News "A" & B', + 'slug' => 'news-a-b', + ) + ); + + wp_set_object_terms( $post_id, array(), 'category' ); + wp_set_post_categories( $post_id, array( $category->term_id ) ); + + $GLOBALS['post'] = get_post( $post_id ); + setup_postdata( $GLOBALS['post'] ); + + add_filter( + 'pre_option_home', + static function () { + return 'https://example.org'; + } + ); + + $expected = ''; + + $this->assertSame( $expected, get_the_category_rss( 'atom' ) ); + } + + /** + * @ticket 65819 + */ + public function test_filter_receives_list_and_type() { + $filter = new MockAction(); + add_filter( 'the_category_rss', array( $filter, 'filter_append' ), 10, 2 ); + + $result = get_the_category_rss( 'rss2' ); + + $this->assertSame( "\t\t\n_append", $result ); + $this->assertSame( 1, $filter->get_call_count() ); + $this->assertSame( + array( "\t\t\n", 'rss2' ), + $filter->get_args()[0] + ); + } +} From a522bfca13e5998b5065d51ba6e67c9023af6ac7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:54:35 +0000 Subject: [PATCH 197/481] Tests: Cover post type lookup from the global post. Verify `get_post_type()` uses the global post when called without an argument. Use a local page fixture and rely on the existing test lifecycle to reset global state. Developed in: https://github.com/WordPress/wordpress-develop/pull/15343 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65203 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/post/getPostType.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/phpunit/tests/post/getPostType.php diff --git a/tests/phpunit/tests/post/getPostType.php b/tests/phpunit/tests/post/getPostType.php new file mode 100644 index 0000000000000..5405e778a69c4 --- /dev/null +++ b/tests/phpunit/tests/post/getPostType.php @@ -0,0 +1,19 @@ +post->create( array( 'post_type' => 'page' ) ) ); + + $this->assertSame( 'page', get_post_type() ); + } +} From 7ede52efdc638113fca341194a78eb689b1cb8f9 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 16:55:56 +0000 Subject: [PATCH 198/481] Tests: Cover image dimension attribute formatting. Verify `image_hwstring()` formats supplied dimensions, omits zero dimensions, and casts numeric strings to integers. Use five provider cases without additional fixtures. Developed in: https://github.com/WordPress/wordpress-develop/pull/15338 Props shailu25. See #65819. git-svn-id: https://develop.svn.wordpress.org/trunk@65204 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/tests/media/imageHwstring.php | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 tests/phpunit/tests/media/imageHwstring.php diff --git a/tests/phpunit/tests/media/imageHwstring.php b/tests/phpunit/tests/media/imageHwstring.php new file mode 100644 index 0000000000000..cb6ce16d9ef32 --- /dev/null +++ b/tests/phpunit/tests/media/imageHwstring.php @@ -0,0 +1,58 @@ +assertSame( $expected, image_hwstring( $width, $height ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_image_hwstring() { + return array( + 'both dimensions' => array( + 100, + 50, + 'width="100" height="50" ', + ), + 'width only' => array( + 100, + 0, + 'width="100" ', + ), + 'height only' => array( + 0, + 50, + 'height="50" ', + ), + 'both falsy' => array( + 0, + 0, + '', + ), + 'casts numeric strings' => array( + '100.9', + '50.1', + 'width="100" height="50" ', + ), + ); + } +} From 8833e46d2a7cda1d40754763348493d0afe78d68 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 17:04:27 +0000 Subject: [PATCH 199/481] Build/Test Tools: Restore Composer argument forwarding during environment startup. Forward arguments supplied to `npm run env:start -- ...` to `composer update -W`. This restores options such as `--dry-run`, which stopped reaching Composer when its invocation moved into `start.js`. Follow-up to [65150]. Developed in: https://github.com/WordPress/wordpress-develop/pull/15304 Props adrianmoldovanwp, lucatume. Fixes #62807. git-svn-id: https://develop.svn.wordpress.org/trunk@65205 602fd350-edb4-49c9-b593-d223f7449a82 --- tools/local-env/scripts/start.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/local-env/scripts/start.js b/tools/local-env/scripts/start.js index d811ca11ecbe8..970fc4b944ed6 100644 --- a/tools/local-env/scripts/start.js +++ b/tools/local-env/scripts/start.js @@ -95,7 +95,7 @@ if ( process.env.DOCKER_TOOLBOX_INSTALL_PATH ) { } // `composer update` reaches repo.packagist.org, so it is re-attempted for the same reasons as `up`. -const composer = local_env_utils.compose_with_retry( [ 'run', '-T', '--rm', 'php', 'composer', 'update', '-W' ], 3 ); +const composer = local_env_utils.compose_with_retry( [ 'run', '-T', '--rm', 'php', 'composer', 'update', '-W', ...process.argv.slice( 2 ) ], 3 ); if ( composer.status !== 0 ) { console.error( '\nThere was an error while running PHP Composer update.' ); From 35e092058a113d60dc7d2543480dc5d0ae2a7f55 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 17:38:15 +0000 Subject: [PATCH 200/481] Tests: Wait for editor readiness in media modal tests. Wait for the post title in the editor canvas before inserting the Image block in `openModalFromImageBlock()`. This prevents initial editor setup from resetting the inserted block before the tests can open the media modal. Developed in: https://github.com/WordPress/wordpress-develop/pull/15372 Props adrianmoldovanwp. Fixes #66442. git-svn-id: https://develop.svn.wordpress.org/trunk@65206 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/specs/media-modal-client-side-upload.test.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/e2e/specs/media-modal-client-side-upload.test.js b/tests/e2e/specs/media-modal-client-side-upload.test.js index 46a84bcbd804f..b3cdce63325d2 100644 --- a/tests/e2e/specs/media-modal-client-side-upload.test.js +++ b/tests/e2e/specs/media-modal-client-side-upload.test.js @@ -94,6 +94,10 @@ async function failMediaCreate( page ) { * @return {Promise} The modal. */ async function openModalFromImageBlock( page, editor ) { + // Blocks inserted before the editor sets up the post are reset away. + await expect( + editor.canvas.getByRole( 'textbox', { name: 'Add title' } ) + ).toBeVisible(); await editor.insertBlock( { name: 'core/image' } ); await editor.canvas.getByRole( 'button', { name: 'Media Library' } ).click(); From 427987045702bfe7c12093c27bebf28937d9c342 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 19:44:08 +0000 Subject: [PATCH 201/481] Build/Test Tools: Recover E2E fixtures after interrupted runs. Remove stale plugin and theme fixtures before each management test, preserving the existing absence and activation assertions. Remove leftover `.maintenance` and `fatal-error.php` fixtures before global setup connects to WordPress. Reuse the fixture cleanup after each test so subsequent runs do not require a manual environment reset. Developed in: https://github.com/WordPress/wordpress-develop/pull/15369 Props adrianmoldovanwp. Fixes #66443. git-svn-id: https://develop.svn.wordpress.org/trunk@65207 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/config/global-setup.js | 9 ++++++ tests/e2e/specs/plugins.test.js | 44 +++++++++++++++--------------- tests/e2e/specs/themes.test.js | 47 ++++++++++++++++++-------------- 3 files changed, 57 insertions(+), 43 deletions(-) diff --git a/tests/e2e/config/global-setup.js b/tests/e2e/config/global-setup.js index 0c8063cf1a5a5..219f409e80126 100644 --- a/tests/e2e/config/global-setup.js +++ b/tests/e2e/config/global-setup.js @@ -1,6 +1,8 @@ /** * External dependencies */ +import { rmSync } from 'node:fs'; +import { join } from 'node:path'; import { request } from '@playwright/test'; /** @@ -18,6 +20,13 @@ async function globalSetup( config ) { const storageStatePath = typeof storageState === 'string' ? storageState : undefined; + // An interrupted run can leave these behind, and each one breaks the whole site. + const documentRoot = join( process.cwd(), process.env.LOCAL_DIR ?? 'src' ); + rmSync( join( documentRoot, '.maintenance' ), { force: true } ); + rmSync( join( documentRoot, 'wp-content/mu-plugins/fatal-error.php' ), { + force: true, + } ); + const requestContext = await request.newContext( { baseURL, } ); diff --git a/tests/e2e/specs/plugins.test.js b/tests/e2e/specs/plugins.test.js index 29424db7b95ee..19030255f130b 100644 --- a/tests/e2e/specs/plugins.test.js +++ b/tests/e2e/specs/plugins.test.js @@ -21,38 +21,38 @@ async function uploadPlugin( admin, page, version ) { .click(); } -test.describe( 'Plugin management', () => { - let ownsPlugin; +async function deletePlugin( requestUtils ) { + const plugins = await requestUtils.rest( { path: '/wp/v2/plugins' } ); + const installed = plugins.find( ( item ) => item.plugin === plugin ); + if ( ! installed ) { + return; + } + if ( installed.status !== 'inactive' ) { + await requestUtils.rest( { + method: 'PUT', + path: `/wp/v2/plugins/${ plugin }`, + data: { status: 'inactive' }, + } ); + } + await requestUtils.rest( { + method: 'DELETE', + path: `/wp/v2/plugins/${ plugin }`, + } ); +} +test.describe( 'Plugin management', () => { test.beforeEach( async ( { requestUtils } ) => { // The fixture slug requires an environment not shared with another test run. - ownsPlugin = false; + // An interrupted run can leave the fixture plugin installed. + await deletePlugin( requestUtils ); const plugins = await requestUtils.rest( { path: '/wp/v2/plugins' } ); expect( plugins.map( ( item ) => item.plugin ) ).not.toContain( plugin ); - ownsPlugin = true; } ); test.afterEach( async ( { requestUtils } ) => { - if ( ! ownsPlugin ) { - return; - } - const plugins = await requestUtils.rest( { path: '/wp/v2/plugins' } ); - const installed = plugins.find( ( item ) => item.plugin === plugin ); - if ( installed ) { - if ( installed.status !== 'inactive' ) { - await requestUtils.rest( { - method: 'PUT', - path: `/wp/v2/plugins/${ plugin }`, - data: { status: 'inactive' }, - } ); - } - await requestUtils.rest( { - method: 'DELETE', - path: `/wp/v2/plugins/${ plugin }`, - } ); - } + await deletePlugin( requestUtils ); } ); test( 'uploads, activates and deactivates a plugin', async ( { diff --git a/tests/e2e/specs/themes.test.js b/tests/e2e/specs/themes.test.js index 686f0faab3862..8596e4f012992 100644 --- a/tests/e2e/specs/themes.test.js +++ b/tests/e2e/specs/themes.test.js @@ -6,13 +6,35 @@ import { test, expect } from '@wordpress/e2e-test-utils-playwright'; const themeSlug = 'e2e-test-theme'; const themeName = 'E2E Test Theme'; +async function deleteTheme( requestUtils ) { + const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); + if ( ! themes.some( ( theme ) => theme.stylesheet === themeSlug ) ) { + return; + } + const themesResponse = await requestUtils.request.get( + 'wp-admin/themes.php' + ); + const html = await themesResponse.text(); + await themesResponse.dispose(); + const deleteQuery = html.match( + `action=delete&stylesheet=${ themeSlug }&_wpnonce=[a-z0-9]+` + ); + expect( deleteQuery ).not.toBeNull(); + const response = await requestUtils.request.get( + `wp-admin/themes.php?${ deleteQuery[ 0 ].replace( /&/g, '&' ) }` + ); + expect( response.ok() ).toBe( true ); + await response.dispose(); +} + test.describe( 'Theme management', () => { let previousTheme; - let ownsTheme; test.beforeEach( async ( { admin, page, requestUtils } ) => { + previousTheme = undefined; // The fixture slug requires an environment not shared with another test run. - ownsTheme = false; + // An interrupted run can leave the fixture theme installed. + await deleteTheme( requestUtils ); const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); expect( themes.map( ( theme ) => theme.stylesheet ) ).not.toContain( themeSlug @@ -20,7 +42,6 @@ test.describe( 'Theme management', () => { previousTheme = themes.find( ( theme ) => theme.status === 'active' ).stylesheet; - ownsTheme = true; await admin.visitAdminPage( 'theme-install.php' ); await page .getByRole( 'button', { name: 'Upload Theme', exact: true } ) @@ -37,27 +58,11 @@ test.describe( 'Theme management', () => { } ); test.afterEach( async ( { requestUtils } ) => { - if ( ! ownsTheme ) { + if ( ! previousTheme ) { return; } await requestUtils.activateTheme( previousTheme ); - const themes = await requestUtils.rest( { path: '/wp/v2/themes' } ); - if ( themes.some( ( theme ) => theme.stylesheet === themeSlug ) ) { - const themesResponse = await requestUtils.request.get( - 'wp-admin/themes.php' - ); - const html = await themesResponse.text(); - await themesResponse.dispose(); - const deleteQuery = html.match( - `action=delete&stylesheet=${ themeSlug }&_wpnonce=[a-z0-9]+` - ); - expect( deleteQuery ).not.toBeNull(); - const response = await requestUtils.request.get( - `wp-admin/themes.php?${ deleteQuery[ 0 ].replace( /&/g, '&' ) }` - ); - expect( response.ok() ).toBe( true ); - await response.dispose(); - } + await deleteTheme( requestUtils ); const remainingThemes = await requestUtils.rest( { path: '/wp/v2/themes', } ); From ab9aba68e27ed6192a7d96d6f57f31034859e52d Mon Sep 17 00:00:00 2001 From: Joe Dolson Date: Mon, 2 Nov 2026 19:53:13 +0000 Subject: [PATCH 202/481] Accessibility: Improve focus state and contrast in admin bar. Change the admin bar focus state to use a focus ring, similar to the majority of other focus states throughout the admin. Previous focus state was only a color change, and set a color contrast of 2.97:1 on the default theme, below WCAG requirements. Also fix miscellaneous alignment errors in the admin bar that were made more obvious by shifting to a focus outline. Props joedolson, khokansardar, afercia, jns141191, iamraju, Joen, muryam, sukhendu2002, sabernhardt, ugyensupport, mciampini, fushar, rollybueno, shamimmoeen, wildworks, nicoblandel. Fixes #65445. git-svn-id: https://develop.svn.wordpress.org/trunk@65208 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/css/admin-menu.css | 14 +++------- src/wp-admin/css/colors/_admin.scss | 36 +++++++++++++++++-------- src/wp-includes/css/admin-bar.css | 42 +++++++++++++++-------------- 3 files changed, 51 insertions(+), 41 deletions(-) diff --git a/src/wp-admin/css/admin-menu.css b/src/wp-admin/css/admin-menu.css index c51dbfb5b6b24..db332e8d9a5c2 100644 --- a/src/wp-admin/css/admin-menu.css +++ b/src/wp-admin/css/admin-menu.css @@ -811,12 +811,10 @@ li#wp-admin-bar-menu-toggle { display: block; padding: 0; overflow: hidden; - outline: none; text-decoration: none; - border: 1px solid transparent; background: none; - height: 44px; - margin-left: -1px; + height: 46px; + box-sizing: border-box; } .wp-responsive-open #wpadminbar #wp-admin-bar-menu-toggle a { @@ -827,17 +825,13 @@ li#wp-admin-bar-menu-toggle { display: block; } - #wpadminbar #wp-admin-bar-menu-toggle a:hover { - border: 1px solid transparent; - } - #wpadminbar #wp-admin-bar-menu-toggle .ab-icon { display: flex; align-items: center; float: left; margin: 0; - height: 44px; - width: 50px; + height: 46px; + width: 52px; padding: 0; border: none; box-sizing: border-box; diff --git a/src/wp-admin/css/colors/_admin.scss b/src/wp-admin/css/colors/_admin.scss index 0666e6f5008d9..e8d79401ce7e7 100644 --- a/src/wp-admin/css/colors/_admin.scss +++ b/src/wp-admin/css/colors/_admin.scss @@ -399,6 +399,11 @@ ul#adminmenu > li.current > a.current::after { color: variables.$menu-text; } +#wpadminbar a:focus, +#wpadminbar .ab-item[tabindex="0"]:focus { + outline-color: variables.$menu-submenu-focus-text; +} + #wpadminbar .ab-icon, #wpadminbar .ab-item::before, #wpadminbar .ab-item::after { @@ -411,12 +416,13 @@ ul#adminmenu > li.current > a.current::after { #wpadminbar.nojs .ab-top-menu > li.menupop:hover > .ab-item, #wpadminbar .ab-top-menu > li.menupop.hover > .ab-item { color: variables.$menu-submenu-focus-text; - background: variables.$menu-submenu-background; } -#wpadminbar:not(.mobile) > #wp-toolbar li:hover span.ab-label, -#wpadminbar:not(.mobile) > #wp-toolbar li.hover span.ab-label, -#wpadminbar:not(.mobile) > #wp-toolbar a:focus span.ab-label { +#wpadminbar > #wp-toolbar li:hover span.ab-label, +#wpadminbar > #wp-toolbar li.hover span.ab-label, +/* The adminbar menu may output either links or focusable div elements. */ +/* As such, we target the focus state without specifying the element type. */ +#wpadminbar > #wp-toolbar :focus span.ab-label { color: variables.$menu-submenu-focus-text; } @@ -465,10 +471,14 @@ ul#adminmenu > li.current > a.current::after { #wpadminbar li .ab-item:focus .ab-icon, #wpadminbar li.hover .ab-icon, #wpadminbar li.hover .ab-item::before, -#wpadminbar li #adminbarsearch.adminbar-focused .ab-icon { +#wpadminbar li #adminbarsearch.adminbar-focused .ab-icon, +#wpadminbar.mobile .quicklinks .ab-item:focus::before, +#wpadminbar.mobile .quicklinks .ab-item:hover::before, +#wpadminbar.mobile .quicklinks a:hover .ab-icon { color: variables.$menu-submenu-focus-text; } +// Note that the icon of the site-name item is not wrapped within a span with class ab-icon like other items. #wpadminbar .quicklinks li a:hover .blavatar, #wpadminbar .quicklinks li a:focus .blavatar, #wpadminbar .quicklinks .ab-sub-wrapper .menupop.hover > a .blavatar, @@ -507,7 +517,7 @@ ul#adminmenu > li.current > a.current::after { #wpadminbar:not(.mobile) .ab-top-menu > #wp-admin-bar-recovery-mode:hover > .ab-item, #wpadminbar:not(.mobile) .ab-top-menu > #wp-admin-bar-recovery-mode > .ab-item:focus { color: variables.$adminbar-recovery-exit-text; - background-color: variables.$adminbar-recovery-exit-background-alt; + outline-color: currentColor; } /* Admin Bar: my account */ @@ -521,15 +531,19 @@ ul#adminmenu > li.current > a.current::after { color: variables.$menu-text; } -#wpadminbar #wp-admin-bar-user-info a:hover .display-name, -#wpadminbar #wp-admin-bar-user-info a:focus .display-name { - color: variables.$menu-submenu-focus-text; -} - #wpadminbar #wp-admin-bar-user-info .username { color: variables.$menu-submenu-text; } +#wpadminbar #wp-admin-bar-user-info a:hover .howdy, +#wpadminbar #wp-admin-bar-user-info a:focus .howdy, +#wpadminbar #wp-admin-bar-user-info a:hover .display-name, +#wpadminbar #wp-admin-bar-user-info a:focus .display-name, +#wpadminbar #wp-admin-bar-user-info a:hover .username, +#wpadminbar #wp-admin-bar-user-info a:focus .username { + color: variables.$menu-submenu-focus-text; +} + /* Pointers */ .wp-pointer .wp-pointer-content h3 { diff --git a/src/wp-includes/css/admin-bar.css b/src/wp-includes/css/admin-bar.css index eab5e89c3a996..7a2d686786b78 100644 --- a/src/wp-includes/css/admin-bar.css +++ b/src/wp-includes/css/admin-bar.css @@ -97,10 +97,16 @@ html:lang(he-il) .rtl #wpadminbar * { box-shadow: none; } -#wpadminbar a:focus { - outline-offset: -1px; - /* Only visible in Windows High Contrast mode */ - outline: 2px solid transparent; +#wpadminbar a, +#wpadminbar .ab-item[tabindex="0"] { + border-radius: 5px; +} + +#wpadminbar a:focus, +#wpadminbar .ab-item[tabindex="0"]:focus { + outline-offset: -4px; + /* Always visible, also in Windows High Contrast mode */ + outline: var(--wp-admin-border-width-focus, 1.5px) solid #72aee6; } #wpadminbar { @@ -235,13 +241,14 @@ html:lang(he-il) .rtl #wpadminbar * { #wpadminbar.nojq .quicklinks .ab-top-menu > li > .ab-item:focus, #wpadminbar:not(.mobile) .ab-top-menu > li:hover > .ab-item, #wpadminbar .ab-top-menu > li.hover > .ab-item { - background: #2c3338; color: #72aee6; } -#wpadminbar:not(.mobile) > #wp-toolbar li:hover span.ab-label, +#wpadminbar > #wp-toolbar li:hover span.ab-label, #wpadminbar > #wp-toolbar li.hover span.ab-label, -#wpadminbar:not(.mobile) > #wp-toolbar a:focus span.ab-label { +/* The adminbar menu may output either links or focusable div elements. */ +/* As such, we target the focus state without specifying the element type. */ +#wpadminbar > #wp-toolbar :focus span.ab-label { color: #72aee6; } @@ -335,7 +342,8 @@ html:lang(he-il) .rtl #wpadminbar * { #wpadminbar li .ab-item:focus .ab-icon, #wpadminbar li.hover .ab-icon, #wpadminbar li.hover .ab-item::before, -#wpadminbar li #adminbarsearch.adminbar-focused .ab-icon { +#wpadminbar li #adminbarsearch.adminbar-focused .ab-icon, +#wpadminbar.mobile .quicklinks .ab-item:focus::before { color: #72aee6; } @@ -429,11 +437,6 @@ html:lang(he-il) .rtl #wpadminbar * { float: right; } -#wpadminbar ul li:last-child, -#wpadminbar ul li:last-child .ab-item { - box-shadow: none; -} - /** * Recovery Mode */ @@ -447,7 +450,7 @@ html:lang(he-il) .rtl #wpadminbar * { #wpadminbar:not(.mobile) .ab-top-menu > #wp-admin-bar-recovery-mode:hover > .ab-item, #wpadminbar:not(.mobile) .ab-top-menu > #wp-admin-bar-recovery-mode > .ab-item:focus { color: #fff; - background-color: #d63638; + outline-color: currentColor; } /** @@ -485,8 +488,8 @@ html:lang(he-il) .rtl #wpadminbar * { } #wpadminbar #wp-admin-bar-user-info { - margin-top: 6px; - margin-bottom: 15px; + margin-top: 2px; + margin-bottom: 10px; height: auto; background: none; } @@ -494,7 +497,7 @@ html:lang(he-il) .rtl #wpadminbar * { #wp-admin-bar-user-info .avatar { position: absolute; left: -72px; - top: 4px; + top: 0; width: 64px; height: 64px; border-radius: 50%; @@ -503,12 +506,13 @@ html:lang(he-il) .rtl #wpadminbar * { #wpadminbar #wp-admin-bar-user-info a { background: none; height: auto; + padding: 4px 10px; } #wpadminbar #wp-admin-bar-user-info span { background: none; padding: 0; - height: 18px; + line-height: 1.38461538; } #wpadminbar #wp-admin-bar-user-info .display-name, @@ -525,7 +529,6 @@ html:lang(he-il) .rtl #wpadminbar * { } #wpadminbar #wp-admin-bar-user-info .username { - color: #a7aaad; font-size: 11px; } @@ -900,7 +903,6 @@ html:lang(he-il) .rtl #wpadminbar * { overflow: hidden; width: 52px; padding: 0; - color: #a7aaad; /* @todo not needed? this text is hidden */ position: relative; } From f684568b5f2a001ac0c3e06eb73cad2a10fdcb8a Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Mon, 2 Nov 2026 21:13:49 +0000 Subject: [PATCH 203/481] Customize: Correct section heading height to match the back button. Sets `line-height: 2` on the small label above Customizer section titles. This restores the heading height to 74px, matching the back button. Developed in https://github.com/WordPress/wordpress-develop/pull/15379. Follow-up to r63966. Props sainathpoojary, sabernhardt. Fixes #66444. git-svn-id: https://develop.svn.wordpress.org/trunk@65209 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/css/customize-controls.css | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wp-admin/css/customize-controls.css b/src/wp-admin/css/customize-controls.css index 7cdc6e97ae4d3..b53baf94744de 100644 --- a/src/wp-admin/css/customize-controls.css +++ b/src/wp-admin/css/customize-controls.css @@ -471,6 +471,7 @@ body.trashing #publish-settings { } #customize-controls .customize-section-title span.customize-action { + line-height: 2; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; From 6ae5eb07b72e652ee686912999095e844b58e50f Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Mon, 2 Nov 2026 21:18:32 +0000 Subject: [PATCH 204/481] Tests: Cover eleven admin AJAX handlers. Dispatch registered AJAX actions and verify their responses, permission checks, and resulting database state. Consolidate the earlier handler test proposals and mock dashboard feeds to avoid network requests. Add `WP_Ajax_UnitTestCase::get_ajax_response()` to clear the response buffer before dispatch and fail when a handler does not terminate with `wp_die()`. Developed in: https://github.com/WordPress/wordpress-develop/pull/15381 Props mindctrl, pbearne. See #65252. git-svn-id: https://develop.svn.wordpress.org/trunk@65210 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/phpunit/includes/testcase-ajax.php | 25 ++ .../ajax-actions/addHierarchicalTerm.php | 238 ++++++++++++++++++ .../includes/ajax-actions/addLinkCategory.php | 191 ++++++++++++++ .../includes/ajax-actions/closedPostboxes.php | 121 +++++++++ .../ajax-actions/dashboardWidgets.php | 168 +++++++++++++ .../includes/ajax-actions/deleteMeta.php | 179 +++++++++++++ .../includes/ajax-actions/deletePage.php | 173 +++++++++++++ .../includes/ajax-actions/deletePost.php | 142 +++++++++++ .../admin/includes/ajax-actions/findPosts.php | 190 ++++++++++++++ .../includes/ajax-actions/getPermalink.php | 147 +++++++++++ .../includes/ajax-actions/getTagcloud.php | 109 ++++++++ .../includes/ajax-actions/untrashPost.php | 143 +++++++++++ 12 files changed, 1826 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/addHierarchicalTerm.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/addLinkCategory.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/closedPostboxes.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/dashboardWidgets.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/deleteMeta.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/deletePage.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/deletePost.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/findPosts.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/getPermalink.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/getTagcloud.php create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/untrashPost.php diff --git a/tests/phpunit/includes/testcase-ajax.php b/tests/phpunit/includes/testcase-ajax.php index 228c6ff2daec1..ce0d13c5d5a8e 100644 --- a/tests/phpunit/includes/testcase-ajax.php +++ b/tests/phpunit/includes/testcase-ajax.php @@ -285,4 +285,29 @@ protected function _handleAjax( $action ) { $this->_last_response = $buffer; } } + + /** + * Dispatches an Ajax action and returns its response. + * + * Fails the test if the handler returns without calling wp_die(). + * + * @since 7.2.0 + * + * @param string $action The action to handle. + * @return string The output if any was sent, otherwise the wp_die() message. + */ + protected function get_ajax_response( $action ) { + // dieHandler() appends to the previous response, which would leak into this one. + $this->_last_response = ''; + + try { + $this->_handleAjax( $action ); + } catch ( WPAjaxDieStopException $e ) { + return $e->getMessage(); + } catch ( WPAjaxDieContinueException $e ) { + return $this->_last_response; + } + + $this->fail( "The '{$action}' Ajax handler did not terminate." ); + } } diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/addHierarchicalTerm.php b/tests/phpunit/tests/admin/includes/ajax-actions/addHierarchicalTerm.php new file mode 100644 index 0000000000000..26461894672ba --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/addHierarchicalTerm.php @@ -0,0 +1,238 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + } + + /** + * Populates $_POST for an add request. + * + * @param string $taxonomy Taxonomy name. + * @param string $names Comma-separated term names. + * @param array $extra Optional. Additional request fields. Default empty array. + * @param string|null $nonce Optional. Nonce to send. Default is a valid nonce. + */ + private function set_request( string $taxonomy, string $names, array $extra = array(), ?string $nonce = null ): void { + $_POST = array_merge( + array( + "new{$taxonomy}" => $names, + "_ajax_nonce-add-{$taxonomy}" => $nonce ?? wp_create_nonce( "add-{$taxonomy}" ), + ), + $extra + ); + } + + /** + * Dispatches the request and parses the XML response. + * + * @param string $taxonomy Taxonomy name. + * @return SimpleXMLElement The first response element. + */ + private function get_xml_response( string $taxonomy ): SimpleXMLElement { + $xml = simplexml_load_string( $this->get_ajax_response( "add-{$taxonomy}" ), 'SimpleXMLElement', LIBXML_NOCDATA ); + $this->assertInstanceOf( SimpleXMLElement::class, $xml, 'The response should be valid XML.' ); + + return $xml->response; + } + + /** + * @ticket 65252 + */ + public function test_add_category_returns_checklist_and_parent_dropdown(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'category', 'New Category' ); + + $response = $this->get_xml_response( 'category' ); + + $term = get_term_by( 'name', 'New Category', 'category' ); + $this->assertInstanceOf( WP_Term::class, $term ); + $this->assertSame( 0, $term->parent ); + $this->assertSame( (string) $term->term_id, (string) $response->category['id'] ); + $this->assertStringContainsString( "value=\"{$term->term_id}\" type=\"checkbox\" name=\"post_category[]\"", (string) $response->category->response_data ); + $this->assertStringContainsString( "name='newcategory_parent'", (string) $response->category->supplemental->newcat_parent ); + } + + /** + * When a parent is given, the response replaces the checklist of the top-level ancestor. + * + * @ticket 65252 + */ + public function test_add_child_category_returns_top_level_ancestor_checklist(): void { + wp_set_current_user( self::$admin_id ); + + $grandparent_id = self::factory()->category->create(); + $parent_id = self::factory()->category->create( array( 'parent' => $grandparent_id ) ); + $this->set_request( 'category', 'Child Category', array( 'newcategory_parent' => $parent_id ) ); + + $response = $this->get_xml_response( 'category' ); + + $term = get_term_by( 'name', 'Child Category', 'category' ); + $this->assertInstanceOf( WP_Term::class, $term ); + $this->assertSame( $parent_id, $term->parent ); + $this->assertSame( (string) $grandparent_id, (string) $response->category['id'] ); + + $data = (string) $response->category->response_data; + $this->assertStringContainsString( "value=\"{$grandparent_id}\"", $data ); + $this->assertStringContainsString( "value=\"{$parent_id}\"", $data ); + $this->assertStringContainsString( "value=\"{$term->term_id}\"", $data ); + } + + /** + * @ticket 65252 + */ + public function test_add_category_clamps_negative_parent_to_zero(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'category', 'Negative Parent', array( 'newcategory_parent' => -5 ) ); + + $this->get_xml_response( 'category' ); + + $term = get_term_by( 'name', 'Negative Parent', 'category' ); + $this->assertInstanceOf( WP_Term::class, $term ); + $this->assertSame( 0, $term->parent ); + } + + /** + * @ticket 65252 + */ + public function test_add_category_creates_multiple_terms_and_skips_blank_names(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'category', 'Cat A, , Cat B' ); + + $response = $this->get_xml_response( 'category' ); + + $cat_a = get_term_by( 'name', 'Cat A', 'category' ); + $cat_b = get_term_by( 'name', 'Cat B', 'category' ); + $this->assertInstanceOf( WP_Term::class, $cat_a ); + $this->assertInstanceOf( WP_Term::class, $cat_b ); + $this->assertSame( (string) $cat_b->term_id, (string) $response->category['id'], 'Only the last term should be returned.' ); + } + + /** + * @ticket 65252 + */ + public function test_add_category_skips_existing_term(): void { + wp_set_current_user( self::$admin_id ); + + self::factory()->category->create( array( 'name' => 'Existing' ) ); + $this->set_request( 'category', 'Existing' ); + + $response = $this->get_xml_response( 'category' ); + + $this->assertCount( 0, $response->category ); + $this->assertCount( + 1, + get_terms( + array( + 'taxonomy' => 'category', + 'name' => 'Existing', + 'hide_empty' => false, + ) + ) + ); + } + + /** + * Taxonomies other than category read the checked terms from tax_input. + * + * @ticket 65252 + */ + public function test_add_term_to_custom_taxonomy_uses_tax_input(): void { + register_taxonomy( + 'wptests_tax', + 'post', + array( + 'hierarchical' => true, + 'show_ui' => true, + ) + ); + wp_set_current_user( self::$admin_id ); + + $parent_id = self::factory()->term->create( array( 'taxonomy' => 'wptests_tax' ) ); + $sibling_id = self::factory()->term->create( + array( + 'taxonomy' => 'wptests_tax', + 'parent' => $parent_id, + ) + ); + $this->set_request( + 'wptests_tax', + 'Custom Child', + array( + 'newwptests_tax_parent' => $parent_id, + 'tax_input' => array( 'wptests_tax' => array( $sibling_id ) ), + ) + ); + + $response = $this->get_xml_response( 'wptests_tax' ); + + $term = get_term_by( 'name', 'Custom Child', 'wptests_tax' ); + $this->assertInstanceOf( WP_Term::class, $term ); + $this->assertSame( (string) $parent_id, (string) $response->wptests_tax['id'] ); + $this->assertMatchesRegularExpression( + "/value=\"{$sibling_id}\" type=\"checkbox\" name=\"tax_input\[wptests_tax\]\[\]\" id=\"[^\"]+\" checked='checked'/", + (string) $response->wptests_tax->response_data + ); + } + + /** + * @ticket 65252 + */ + public function test_add_category_rejects_invalid_nonce(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'category', 'Invalid Nonce Category', array(), 'invalid-nonce' ); + + $this->assertSame( '-1', $this->get_ajax_response( 'add-category' ) ); + $this->assertFalse( get_term_by( 'name', 'Invalid Nonce Category', 'category' ) ); + } + + /** + * @ticket 65252 + */ + public function test_add_category_rejects_user_without_capability(): void { + wp_set_current_user( self::$subscriber_id ); + $this->set_request( 'category', 'No Permission Category' ); + + $this->assertSame( '-1', $this->get_ajax_response( 'add-category' ) ); + $this->assertFalse( get_term_by( 'name', 'No Permission Category', 'category' ) ); + } +} diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/addLinkCategory.php b/tests/phpunit/tests/admin/includes/ajax-actions/addLinkCategory.php new file mode 100644 index 0000000000000..61c644445fb07 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/addLinkCategory.php @@ -0,0 +1,191 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + } + + /** + * Setup before each test method. + */ + public function set_up(): void { + parent::set_up(); + + // The manage_links capability is only granted while the Link Manager is enabled. + update_option( 'link_manager_enabled', 1 ); + } + + /** + * Populates $_POST for an add request. + * + * @param string $newcat Comma-separated category names. + * @param string|null $nonce Optional. Nonce to send. Default is a valid nonce. + */ + private function set_request( string $newcat, ?string $nonce = null ): void { + $_POST = array( + 'newcat' => $newcat, + '_ajax_nonce' => $nonce ?? wp_create_nonce( 'add-link-category' ), + ); + } + + /** + * Dispatches the request and returns the link-category elements from the XML response. + * + * @return SimpleXMLElement[] + */ + private function get_link_category_responses(): array { + $xml = simplexml_load_string( $this->get_ajax_response( 'add-link-category' ), 'SimpleXMLElement', LIBXML_NOCDATA ); + $this->assertInstanceOf( SimpleXMLElement::class, $xml, 'The response should be valid XML.' ); + + $responses = array(); + foreach ( $xml->response as $response ) { + $responses[] = $response->{'link-category'}; + } + + return $responses; + } + + /** + * @ticket 65252 + */ + public function test_add_link_category_creates_category(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'New Link Category' ); + + $responses = $this->get_link_category_responses(); + + $term = get_term_by( 'name', 'New Link Category', 'link_category' ); + $this->assertInstanceOf( WP_Term::class, $term ); + $this->assertCount( 1, $responses ); + $this->assertSame( (string) $term->term_id, (string) $responses[0]['id'] ); + $this->assertStringContainsString( "id='in-link-category-{$term->term_id}'", (string) $responses[0]->response_data ); + $this->assertStringContainsString( 'New Link Category', (string) $responses[0]->response_data ); + } + + /** + * @ticket 65252 + */ + public function test_add_link_category_creates_multiple_categories_and_skips_blank_names(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'Cat 1, , Cat 2' ); + + $responses = $this->get_link_category_responses(); + + $this->assertCount( 2, $responses ); + $this->assertInstanceOf( WP_Term::class, get_term_by( 'name', 'Cat 1', 'link_category' ) ); + $this->assertInstanceOf( WP_Term::class, get_term_by( 'name', 'Cat 2', 'link_category' ) ); + } + + /** + * @ticket 65252 + */ + public function test_add_link_category_skips_existing_category(): void { + wp_set_current_user( self::$admin_id ); + + self::factory()->term->create( + array( + 'taxonomy' => 'link_category', + 'name' => 'Existing', + ) + ); + $this->set_request( 'Existing' ); + + $this->assertSame( array(), $this->get_link_category_responses() ); + $this->assertCount( + 1, + get_terms( + array( + 'taxonomy' => 'link_category', + 'name' => 'Existing', + 'hide_empty' => false, + ) + ) + ); + } + + /** + * @ticket 65252 + */ + public function test_add_link_category_escapes_name_in_response(): void { + wp_set_current_user( self::$admin_id ); + $this->set_request( 'Escaped' ); + + $responses = $this->get_link_category_responses(); + + $this->assertCount( 1, $responses ); + $data = (string) $responses[0]->response_data; + $this->assertStringContainsString( '<script>alert(1)</script>Escaped', $data ); + $this->assertStringNotContainsString( 'H:i'; + + $actual_format = null; + add_filter( + 'date_i18n', + static function ( $date, $format ) use ( &$actual_format ) { + $actual_format = $format; + return 'formatted time'; + }, + 10, + 2 + ); + + try { + $this->_handleAjax( 'time_format' ); + } catch ( WPAjaxDieContinueException $e ) { + $this->_last_response = (string) $e->getMessage(); + } catch ( WPAjaxDieStopException $e ) { + $this->_last_response = (string) $e->getMessage(); + } + + $this->assertSame( 'alert(1)H:i', $actual_format ); + $this->assertSame( 'formatted time', $this->_last_response ); + } + + /** + * Tests as an unprivileged user. + * + * @ticket 65228 + */ + public function test_unprivileged_user(): void { + // wp_ajax_time_format() does not have an explicit permission check, + // but it is only registered for logged-in users. + $this->_setRole( 'subscriber' ); + + $_POST['action'] = 'time_format'; + $_POST['_ajax_nonce'] = wp_create_nonce( 'time_format' ); + $_POST['date'] = 'H:i'; + + try { + $this->_handleAjax( 'time_format' ); + } catch ( WPAjaxDieContinueException $e ) { + $this->_last_response = (string) $e->getMessage(); + } catch ( WPAjaxDieStopException $e ) { + $this->_last_response = (string) $e->getMessage(); + } + + $this->assertSame( date_i18n( 'H:i' ), $this->_last_response ); + } + + /** + * Data provider for test_time_format. + * + * @return array + */ + public function data_time_format(): array { + return array( + 'standard_time' => array( + 'payload' => array( + 'date' => 'H:i', + ), + ), + 'custom_time' => array( + 'payload' => array( + 'date' => 'g:i a', + ), + ), + 'empty_time' => array( + 'payload' => array( + 'date' => '', + ), + ), + ); + } +} From 392e2a39cb1a56f3195eff4192d9f1e7bae11794 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Thu, 5 Nov 2026 23:59:27 +0000 Subject: [PATCH 285/481] Tests: Add a test for `wp_ajax_logged_in()`. Check that the handler responds with `1` for a logged-in user. Developed in: https://github.com/WordPress/wordpress-develop/pull/11836 Props pbearne. Fixes #65242. git-svn-id: https://develop.svn.wordpress.org/trunk@65291 602fd350-edb4-49c9-b593-d223f7449a82 --- .../includes/ajax-actions/wpAjaxLoggedIn.php | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxLoggedIn.php diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxLoggedIn.php b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxLoggedIn.php new file mode 100644 index 0000000000000..5728a071bab23 --- /dev/null +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxLoggedIn.php @@ -0,0 +1,49 @@ +_setRole( 'subscriber' ); + + // Set up the request. + $_REQUEST['action'] = 'logged-in'; + + // Make the request. + try { + $this->_handleAjax( 'logged-in' ); + } catch ( WPAjaxDieContinueException $e ) { + // Expected exception. + unset( $e ); + } catch ( WPAjaxDieStopException $e ) { + $this->_last_response = $e->getMessage(); + } + + // The response should be 1. + $this->assertSame( '1', $this->_last_response, 'The response should be 1 for logged-in users' ); + } +} From 91b5099c743fbeed3583f894f5575105b0811ea0 Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Fri, 6 Nov 2026 01:23:05 +0000 Subject: [PATCH 286/481] Build/Test Tools: Use the PCOV extension included in local Docker images. PCOV is now preinstalled in the `wordpressdevelop` local Docker images for PHP 7.4 and higher. Instead of installing PCOV during each GitHub Actions run that generates a code coverage report, it is now turned on with a new `LOCAL_PHP_PCOV` environment variable. PCOV is not interoperable with Xdebug. When both are enabled, Xdebug is used and PCOV is turned off. Generating an HTML coverage report still turns on Xdebug automatically, unless PCOV is enabled and Xdebug is not. Follow-up to r62409. Developed in https://github.com/WordPress/wordpress-develop/pull/11949. Props lancewillett, johnbillion. See #65845, #64893. git-svn-id: https://develop.svn.wordpress.org/trunk@65292 602fd350-edb4-49c9-b593-d223f7449a82 --- .env.example | 10 +++++++ .../workflows/reusable-phpunit-tests-v3.yml | 26 +------------------ README.md | 4 ++- docker-compose.yml | 2 ++ tools/local-env/php-config.ini | 5 ++++ tools/local-env/scripts/docker.js | 6 ++++- 6 files changed, 26 insertions(+), 27 deletions(-) diff --git a/.env.example b/.env.example index 1ca8f9658dbef..a90402036839c 100644 --- a/.env.example +++ b/.env.example @@ -45,6 +45,16 @@ LOCAL_PHP_XDEBUG_MODE=develop,debug # Whether or not to enable Memcached. LOCAL_PHP_MEMCACHED=false +## +# Whether or not to enable PCOV. +# +# PCOV is not interoperable with Xdebug. To use PCOV, `LOCAL_PHP_XDEBUG` must be +# set to `false`. When both are enabled, Xdebug is used and PCOV is disabled. +# +# PCOV is only available for PHP 7.4 and higher. +## +LOCAL_PHP_PCOV=false + ## # The database software to use. # diff --git a/.github/workflows/reusable-phpunit-tests-v3.yml b/.github/workflows/reusable-phpunit-tests-v3.yml index 1e1c85ad0a453..01dd82e983940 100644 --- a/.github/workflows/reusable-phpunit-tests-v3.yml +++ b/.github/workflows/reusable-phpunit-tests-v3.yml @@ -114,6 +114,7 @@ env: LOCAL_PHP: ${{ inputs.php }}-fpm LOCAL_PHP_XDEBUG: false LOCAL_PHP_XDEBUG_MODE: 'develop,debug' + LOCAL_PHP_PCOV: ${{ inputs.coverage-report }} LOCAL_DB_TYPE: ${{ inputs.db-type }} LOCAL_DB_VERSION: ${{ inputs.db-version }} LOCAL_PHP_MEMCACHED: ${{ inputs.memcached }} @@ -292,31 +293,6 @@ jobs: - name: Install WordPress run: npm run env:install - # Installs PCOV as the code coverage driver for the PHPUnit run below. - # - # The INI directives tune PCOV for WordPress's codebase: - # - `pcov.enabled` keeps the Zend hooks active (this is the default, but - # stated explicitly for clarity). - # - `pcov.directory` restricts instrumentation to `src/`, so PCOV does not - # record hits for `vendor/`, `tests/`, or WordPress test fixtures that - # PHPUnit would discard at report time anyway. - # - `pcov.initial.files` pre-sizes the internal file tracking array for - # the thousands of files under `src/`, avoiding reallocation churn - # during test warmup. The default of 64 is far too low here. - - name: Install PCOV coverage driver - if: ${{ inputs.coverage-report }} - run: | - docker compose exec -T -u 0 php sh -c ' - pecl install --force pcov-1.0.12 && - docker-php-ext-enable pcov && - { - echo "pcov.enabled=1" - echo "pcov.directory=/var/www/src" - echo "pcov.initial.files=10000" - } >> /usr/local/etc/php/conf.d/docker-php-ext-pcov.ini && - php -m | grep -i pcov - ' - - name: Run external HTTP tests if: ${{ ! inputs.multisite && ! inputs.phpunit-test-groups && ! inputs.coverage-report }} continue-on-error: ${{ inputs.allow-errors }} diff --git a/README.md b/README.md index 637e24359f034..0f41da84643bd 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,9 @@ npm run test:coverage The command will generate three coverage reports in HTML, PHP, and text formats, saving them in the `coverage` folder. -**Note:** xDebug is required to generate a code coverage report, which can slow down PHPUnit significantly. Passing selection-based options such as `--group` or `--filter` can decrease the overall time required but will result in an incomplete report. +**Note:** A code coverage driver is required to generate a code coverage report. By default, xDebug is used, which can slow down PHPUnit significantly. PCOV is a faster alternative that is available for PHP 7.4 and higher. To use it, set `LOCAL_PHP_PCOV` to `true` and `LOCAL_PHP_XDEBUG` to `false` in your `.env` file. + +Passing selection-based options such as `--group` or `--filter` can decrease the overall time required but will result in an incomplete report. #### To restart the development environment diff --git a/docker-compose.yml b/docker-compose.yml index 61a123f7427c7..62bce43174293 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -42,6 +42,7 @@ services: environment: LOCAL_PHP_XDEBUG: ${LOCAL_PHP_XDEBUG-false} XDEBUG_MODE: ${LOCAL_PHP_XDEBUG_MODE-develop,debug} + LOCAL_PHP_PCOV: ${LOCAL_PHP_PCOV-false} LOCAL_PHP_MEMCACHED: ${LOCAL_PHP_MEMCACHED-false} PHP_FPM_UID: ${PHP_FPM_UID-1000} PHP_FPM_GID: ${PHP_FPM_GID-1000} @@ -118,6 +119,7 @@ services: environment: LOCAL_PHP_XDEBUG: ${LOCAL_PHP_XDEBUG-false} + LOCAL_PHP_PCOV: ${LOCAL_PHP_PCOV-false} LOCAL_PHP_MEMCACHED: ${LOCAL_PHP_MEMCACHED-false} PHP_FPM_UID: ${PHP_FPM_UID-1000} PHP_FPM_GID: ${PHP_FPM_GID-1000} diff --git a/tools/local-env/php-config.ini b/tools/local-env/php-config.ini index 6f98802e5c68a..c01d94af40aa2 100644 --- a/tools/local-env/php-config.ini +++ b/tools/local-env/php-config.ini @@ -5,3 +5,8 @@ post_max_size = 1G xdebug.start_with_request=trigger xdebug.discover_client_host=true xdebug.client_host=host.docker.internal + +; Pre-sizes PCOV's internal file tables (default: 64) to more than the number +; of PHP files loaded during a test run, including test and vendor files. +; This avoids repeatedly resizing the tables as files are loaded. +pcov.initial.files=10000 diff --git a/tools/local-env/scripts/docker.js b/tools/local-env/scripts/docker.js index a6b0f4e0af38e..0ef6d469d19d6 100644 --- a/tools/local-env/scripts/docker.js +++ b/tools/local-env/scripts/docker.js @@ -8,7 +8,11 @@ local_env_utils.ensure_env_file(); dotenvExpand.expand( dotenv.config() ); -if ( process.argv.includes( '--coverage-html' ) ) { +// Use Xdebug to generate HTML code coverage reports, unless PCOV is enabled and Xdebug is not. +if ( + process.argv.includes( '--coverage-html' ) && + ( process.env.LOCAL_PHP_PCOV !== 'true' || process.env.LOCAL_PHP_XDEBUG === 'true' ) +) { process.env.LOCAL_PHP_XDEBUG = 'true'; process.env.LOCAL_PHP_XDEBUG_MODE = 'coverage'; } From 830f997d54c5471d60c66e0b5a28a724a994a9cf Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Fri, 6 Nov 2026 01:24:44 +0000 Subject: [PATCH 287/481] Administration: Remove unnoticeable notice from RSS dashboard Widget. Remove notice that the RSS portion of the "WordPress Events and News" dashboard widget requires JavaScript. The container in which the notice is displayed is hidden if JavaScript is unavailable so the notice is never visible to user. The widget level notice "The WordPress Events and News feeds require JavaScript" is unchanged as that is displayed to users when JavaScript is turned off in the browser. Props rishabhwp, joedolson, afercia. Fixes #66296. git-svn-id: https://develop.svn.wordpress.org/trunk@65293 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-admin/includes/dashboard.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/wp-admin/includes/dashboard.php b/src/wp-admin/includes/dashboard.php index 3e0d28d7f85f1..37d98dfb1c9a4 100644 --- a/src/wp-admin/includes/dashboard.php +++ b/src/wp-admin/includes/dashboard.php @@ -1417,13 +1417,6 @@ function wp_dashboard_rss_output( $widget_id ) { function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array(), ...$args ) { $doing_ajax = wp_doing_ajax(); $loading = '

    ' . __( 'Loading…' ) . '

    '; - $loading .= wp_get_admin_notice( - __( 'This widget requires JavaScript.' ), - array( - 'type' => 'error', - 'additional_classes' => array( 'inline', 'hide-if-js' ), - ) - ); if ( empty( $check_urls ) ) { $widgets = get_option( 'dashboard_widget_options' ); From 39e403e0fbc400ec94f2ef20144338d8ef5c367c Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Fri, 6 Nov 2026 01:47:51 +0000 Subject: [PATCH 288/481] Media: Report failed image writes to streams. When saving an image to a stream, `WP_Image_Editor::make_image()` currently ignores the return values of `fwrite()` and `fclose()`. A save that failed to write the image still reported success. `WP_Image_Editor_GD` uses this path for all stream destinations. The buffered image is now written with `file_put_contents()`, and `make_image()` returns `false` when that fails. This happens when the stream cannot be opened or the image is only partially written. As of PHP 8.6, it also happens when flushing or closing the stream fails. For stream wrappers that only send data on flush or close, a failed upload was previously reported as a successful save. Streams are now written the same way as in `WP_Image_Editor_Imagick::write_image()`, so both editors report the same failures. Developed in https://github.com/WordPress/wordpress-develop/pull/15477. Props adamsilverstein. Fixes #66486. git-svn-id: https://develop.svn.wordpress.org/trunk@65294 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-image-editor.php | 19 +++-- tests/phpunit/tests/image/editorGd.php | 99 +++++++++++++++++++++++ 2 files changed, 110 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor.php b/src/wp-includes/class-wp-image-editor.php index 90a9f12cf16b3..df07c4229b623 100644 --- a/src/wp-includes/class-wp-image-editor.php +++ b/src/wp-includes/class-wp-image-editor.php @@ -559,6 +559,7 @@ public function maybe_exif_rotate() { * Either calls editor's save function or handles file as a stream. * * @since 3.5.0 + * @since 7.2.0 Returns false when the image cannot be fully written to a stream. * * @param string $filename * @param callable $callback @@ -579,15 +580,17 @@ protected function make_image( $filename, $callback, $arguments ) { if ( $result && $stream ) { $contents = ob_get_contents(); - $fp = fopen( $filename, 'w' ); - - if ( ! $fp ) { - ob_end_clean(); - return false; + /* + * file_put_contents() returns false if the stream cannot be opened, or if fewer + * bytes are written than the image contains. + * + * As of PHP 8.6, false is also returned when flushing or closing the stream fails. + * For stream wrappers that only send data on flush or close, such a failure means + * the image was never saved. + */ + if ( false === file_put_contents( $filename, $contents ) ) { + $result = false; } - - fwrite( $fp, $contents ); - fclose( $fp ); } if ( $stream ) { diff --git a/tests/phpunit/tests/image/editorGd.php b/tests/phpunit/tests/image/editorGd.php index e1763a7d5dd3e..1df7f5a570be0 100644 --- a/tests/phpunit/tests/image/editorGd.php +++ b/tests/phpunit/tests/image/editorGd.php @@ -8,6 +8,7 @@ * @group wp-image-editor-gd */ require_once __DIR__ . '/base.php'; +require_once DIR_TESTROOT . '/includes/class-wp-test-stream.php'; class Tests_Image_Editor_GD extends WP_Image_UnitTestCase { @@ -674,4 +675,102 @@ public function test_image_non_existent_extension() { $this->assertTrue( $loaded ); } + + /** + * Tests that images can be saved to a stream. + * + * @covers WP_Image_Editor::make_image + */ + public function test_save_to_stream() { + $saved = $this->save_to_stream( 'wptestgd', 'WP_Test_Stream' ); + + $this->assertNotWPError( $saved ); + $this->assertSame( 'wptestgd://Tests_Image_Editor_GD/write.jpg', $saved['path'] ); + $this->assertNotEmpty( WP_Test_Stream::$data['Tests_Image_Editor_GD']['/write.jpg'], 'The image should have been written to the stream.' ); + } + + /** + * Tests that saving fails when the image cannot be fully written to the stream. + * + * @covers WP_Image_Editor::make_image + */ + public function test_save_to_stream_fails_when_write_fails() { + // file_put_contents() warns about the incomplete write. $this->expectWarning() is deprecated in PHPUnit 10. + $warnings = array(); + set_error_handler( + static function ( int $errno, string $errstr ) use ( &$warnings ) { + $warnings[] = $errstr; + return true; + }, + E_WARNING + ); + + try { + $saved = $this->save_to_stream( 'wptestgdwritefail', 'WP_Test_Stream_GD_Write_Failure' ); + } finally { + restore_error_handler(); + } + + $this->assertCount( 1, $warnings, 'Expected one warning about the incomplete write.' ); + $this->assertStringContainsString( 'bytes written', $warnings[0] ); + $this->assertWPError( $saved ); + $this->assertSame( 'image_save_error', $saved->get_error_code() ); + } + + /** + * Tests that saving fails when the stream cannot be flushed. + * + * PHP 8.6 is the first version where fclose() reports flush and close failures. + * + * @requires PHP >= 8.6 + * + * @covers WP_Image_Editor::make_image + */ + public function test_save_to_stream_fails_when_flush_fails() { + $saved = $this->save_to_stream( 'wptestgdflushfail', 'WP_Test_Stream_GD_Flush_Failure' ); + + $this->assertWPError( $saved ); + $this->assertSame( 'image_save_error', $saved->get_error_code() ); + } + + /** + * Loads a JPEG image with the GD editor and saves it to a stream. + * + * @param string $protocol The stream protocol to register. + * @param string $wrapper_class The stream wrapper class to register for the protocol. + * @return array|WP_Error The result of WP_Image_Editor_GD::save(). + */ + private function save_to_stream( $protocol, $wrapper_class ) { + stream_wrapper_register( $protocol, $wrapper_class ); + WP_Test_Stream::$data = array(); + + $gd_image_editor = new WP_Image_Editor_GD( DIR_TESTDATA . '/images/waffles.jpg' ); + $loaded = $gd_image_editor->load(); + + $saved = $gd_image_editor->save( $protocol . '://Tests_Image_Editor_GD/write.jpg', 'image/jpeg' ); + + stream_wrapper_unregister( $protocol ); + + $this->assertTrue( $loaded ); + + return $saved; + } +} + +/** + * A stream wrapper that fails to write any data. + */ +class WP_Test_Stream_GD_Write_Failure extends WP_Test_Stream { + public function stream_write( $data ) { + return 0; + } +} + +/** + * A stream wrapper that fails to flush, like a remote storage wrapper whose upload fails. + */ +class WP_Test_Stream_GD_Flush_Failure extends WP_Test_Stream { + public function stream_flush() { + return false; + } } From 54312c753fd44a38101fe0c2a8badce811857557 Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Fri, 6 Nov 2026 02:16:03 +0000 Subject: [PATCH 289/481] General: Replace `is_a()` conditions with `instanceOf` for PHP 8.6 compat. PHP 8.6 deprecates passing class names as strings to `is_a()`, for example `is_a( $post, 'WP_Post' )`. This replaces the pattern with their equivalent `instanceof` conditions within the adopted IXR and Text packages. Introduces tests to cover the code paths to demonstrate the tests fail in PHP 8.6. Props dhrupo, westonruter. Fixes #66418. git-svn-id: https://develop.svn.wordpress.org/trunk@65303 602fd350-edb4-49c9-b593-d223f7449a82 --- .../IXR/class-IXR-introspectionserver.php | 2 +- src/wp-includes/IXR/class-IXR-server.php | 4 +- src/wp-includes/IXR/class-IXR-value.php | 4 +- src/wp-includes/Text/Diff.php | 12 +- src/wp-includes/Text/Diff/Renderer.php | 2 +- tests/phpunit/tests/diff/textDiff.php | 75 ++++++++++++ tests/phpunit/tests/xmlrpc/basic.php | 107 ++++++++++++++++++ 7 files changed, 194 insertions(+), 12 deletions(-) create mode 100644 tests/phpunit/tests/diff/textDiff.php diff --git a/src/wp-includes/IXR/class-IXR-introspectionserver.php b/src/wp-includes/IXR/class-IXR-introspectionserver.php index afb05b0e0d2b4..0be5d319d1c12 100644 --- a/src/wp-includes/IXR/class-IXR-introspectionserver.php +++ b/src/wp-includes/IXR/class-IXR-introspectionserver.php @@ -114,7 +114,7 @@ function call($methodname, $args) break; case 'date': case 'dateTime.iso8601': - if (!is_a($arg, 'IXR_Date')) { + if (!($arg instanceof IXR_Date)) { $ok = false; } break; diff --git a/src/wp-includes/IXR/class-IXR-server.php b/src/wp-includes/IXR/class-IXR-server.php index e11f40fbe7c7f..1019718512a8d 100644 --- a/src/wp-includes/IXR/class-IXR-server.php +++ b/src/wp-includes/IXR/class-IXR-server.php @@ -59,7 +59,7 @@ function serve($data = false) $result = $this->call($this->message->methodName, $this->message->params); // Is the result an error? - if (is_a($result, 'IXR_Error')) { + if ($result instanceof IXR_Error) { $this->error($result); } @@ -234,7 +234,7 @@ function multiCall($methodcalls) } else { $result = $this->call($method, $params); } - if (is_a($result, 'IXR_Error')) { + if ($result instanceof IXR_Error) { $return[] = array( 'faultCode' => $result->code, 'faultString' => $result->message diff --git a/src/wp-includes/IXR/class-IXR-value.php b/src/wp-includes/IXR/class-IXR-value.php index 850f318f2c6b2..fcbb64012fb55 100644 --- a/src/wp-includes/IXR/class-IXR-value.php +++ b/src/wp-includes/IXR/class-IXR-value.php @@ -52,10 +52,10 @@ function calculateType() } // Deal with IXR object types base64 and date - if (is_object($this->data) && is_a($this->data, 'IXR_Date')) { + if ($this->data instanceof IXR_Date) { return 'date'; } - if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) { + if ($this->data instanceof IXR_Base64) { return 'base64'; } diff --git a/src/wp-includes/Text/Diff.php b/src/wp-includes/Text/Diff.php index a7a79e50802af..47b90cdb56178 100644 --- a/src/wp-includes/Text/Diff.php +++ b/src/wp-includes/Text/Diff.php @@ -81,8 +81,8 @@ function countAddedLines() { $count = 0; foreach ($this->_edits as $edit) { - if (is_a($edit, 'Text_Diff_Op_add') || - is_a($edit, 'Text_Diff_Op_change')) { + if ($edit instanceof Text_Diff_Op_add || + $edit instanceof Text_Diff_Op_change) { $count += $edit->nfinal(); } } @@ -100,8 +100,8 @@ function countDeletedLines() { $count = 0; foreach ($this->_edits as $edit) { - if (is_a($edit, 'Text_Diff_Op_delete') || - is_a($edit, 'Text_Diff_Op_change')) { + if ($edit instanceof Text_Diff_Op_delete || + $edit instanceof Text_Diff_Op_change) { $count += $edit->norig(); } } @@ -144,7 +144,7 @@ function reverse() function isEmpty() { foreach ($this->_edits as $edit) { - if (!is_a($edit, 'Text_Diff_Op_copy')) { + if (!($edit instanceof Text_Diff_Op_copy)) { return false; } } @@ -162,7 +162,7 @@ function lcs() { $lcs = 0; foreach ($this->_edits as $edit) { - if (is_a($edit, 'Text_Diff_Op_copy')) { + if ($edit instanceof Text_Diff_Op_copy) { $lcs += count($edit->orig); } } diff --git a/src/wp-includes/Text/Diff/Renderer.php b/src/wp-includes/Text/Diff/Renderer.php index 2417670aef062..ccaaa62fbfc95 100644 --- a/src/wp-includes/Text/Diff/Renderer.php +++ b/src/wp-includes/Text/Diff/Renderer.php @@ -90,7 +90,7 @@ function render($diff) /* If these are unchanged (copied) lines, and we want to keep * leading or trailing context lines, extract them from the copy * block. */ - if (is_a($edit, 'Text_Diff_Op_copy')) { + if ($edit instanceof Text_Diff_Op_copy) { /* Do we have any diff blocks yet? */ if (is_array($block)) { /* How many lines to keep as context from the copy diff --git a/tests/phpunit/tests/diff/textDiff.php b/tests/phpunit/tests/diff/textDiff.php new file mode 100644 index 0000000000000..b5be97609b0c5 --- /dev/null +++ b/tests/phpunit/tests/diff/textDiff.php @@ -0,0 +1,75 @@ +assertSame( $added, $diff->countAddedLines(), 'Added lines do not match.' ); + $this->assertSame( $deleted, $diff->countDeletedLines(), 'Deleted lines do not match.' ); + $this->assertSame( $is_empty, $diff->isEmpty(), 'isEmpty() does not match.' ); + $this->assertSame( $unchanged_lines, $diff->lcs(), 'Unchanged lines do not match.' ); + } + + /** + * Data provider for {@see self::test_edit_counts()}. + * + * @return array + */ + public static function data_edit_counts(): array { + return array( + 'both empty' => array( array(), array(), 0, 0, true, 0 ), + 'identical' => array( array( 'a', 'b' ), array( 'a', 'b' ), 0, 0, true, 2 ), + 'add only' => array( array( 'a' ), array( 'a', 'b' ), 1, 0, false, 1 ), + 'delete only' => array( array( 'a', 'b' ), array( 'a' ), 0, 1, false, 1 ), + 'changed only' => array( array( 'a', 'b', 'c' ), array( 'x', 'b', 'z' ), 2, 2, false, 1 ), + 'change, copy and add' => array( array( 'a', 'b' ), array( 'x', 'b', 'c' ), 2, 1, false, 1 ), + ); + } + + /** + * @ticket 66418 + * + * @covers Text_Diff_Renderer::render + */ + public function test_render_keeps_context_lines_from_copied_blocks() { + $diff = new Text_Diff( 'native', array( array( 'a', 'b', 'c', 'd', 'e' ), array( 'a', 'b', 'X', 'd', 'e' ) ) ); + $renderer = new Text_Diff_Renderer( + array( + 'leading_context_lines' => 1, + 'trailing_context_lines' => 1, + ) + ); + + $this->assertSame( "2,4c2,4\n b\n< c\n---\n> X\n d\n", $renderer->render( $diff ) ); + } +} diff --git a/tests/phpunit/tests/xmlrpc/basic.php b/tests/phpunit/tests/xmlrpc/basic.php index c70e2d4bb17fa..d8745fe6a6a75 100644 --- a/tests/phpunit/tests/xmlrpc/basic.php +++ b/tests/phpunit/tests/xmlrpc/basic.php @@ -323,6 +323,113 @@ public function test_multicall_with_missing_method_name(): void { $this->assertSame( array( 'Hello!' ), $result[1] ); } + /** + * Tests that a multicall entry returning a non-object result is not treated as an error. + * + * @ticket 66418 + * + * @covers IXR_Server::multiCall + * + * @dataProvider data_multicall_with_non_object_result + * + * @param mixed $value The value the method returns. + */ + public function test_multicall_with_non_object_result( $value ): void { + $this->myxmlrpcserver->callbacks = array( + 'test.echo' => array( $this, 'echo_args' ), + ); + + $result = $this->myxmlrpcserver->multiCall( + array( + array( + 'methodName' => 'test.echo', + 'params' => array( $value ), + ), + ) + ); + + $this->assertSame( array( array( $value ) ), $result ); + } + + /** + * Data provider. + * + * @return array + */ + public static function data_multicall_with_non_object_result(): array { + return array( + 'string' => array( 'IXR_Error' ), + 'integer' => array( 42 ), + 'boolean' => array( true ), + 'non-struct array' => array( array( 'IXR_Error' ) ), + ); + } + + /** + * Tests that the introspection server rejects a non-object argument for a date parameter. + * + * @ticket 66418 + * + * @covers IXR_IntrospectionServer::call + * + * @dataProvider data_introspection_server_rejects_non_date_argument + * + * @param mixed $arg The argument passed for the date parameter. + */ + public function test_introspection_server_rejects_non_date_argument( $arg ): void { + $server = new IXR_IntrospectionServer(); + $server->addCallback( 'test.echo', array( $this, 'echo_args' ), array( 'string', 'dateTime.iso8601' ), 'Echoes a date.' ); + + $result = $server->call( 'test.echo', array( $arg ) ); + + $this->assertIXRError( $result, 'A non-date argument should return an IXR_Error.' ); + $this->assertSame( -32602, $result->code, 'The error code should indicate invalid method parameters.' ); + $this->assertSame( 'server error. invalid method parameters', $result->message, 'The error message should indicate an invalid parameter type rather than a wrong parameter count.' ); + } + + /** + * Data provider. + * + * @return array + */ + public static function data_introspection_server_rejects_non_date_argument(): array { + return array( + 'date string' => array( '20261030T12:00:00' ), + 'class name' => array( 'IXR_Date' ), + 'integer' => array( 1793361600 ), + ); + } + + /** + * Tests that the introspection server accepts an IXR_Date argument for a date parameter. + * + * @ticket 66418 + * + * @covers IXR_IntrospectionServer::call + */ + public function test_introspection_server_accepts_date_argument(): void { + $server = new IXR_IntrospectionServer(); + $server->addCallback( 'test.echo', array( $this, 'echo_args' ), array( 'string', 'dateTime.iso8601' ), 'Echoes a date.' ); + + $date = new IXR_Date( '20261030T12:00:00' ); + $result = $server->call( 'test.echo', array( $date ) ); + + $this->assertSame( $date, $result ); + } + + /** + * Tests that IXR_Value encodes IXR_Date and IXR_Base64 objects as their XML-RPC types, and strings as strings. + * + * @ticket 66418 + * + * @covers IXR_Value::calculateType + */ + public function test_ixr_value_calculate_type(): void { + $this->assertSame( 'date', ( new IXR_Value( new IXR_Date( '20261030T12:00:00' ) ) )->calculateType(), 'An IXR_Date object should be typed as a date.' ); + $this->assertSame( 'base64', ( new IXR_Value( new IXR_Base64( 'data' ) ) )->calculateType(), 'An IXR_Base64 object should be typed as base64.' ); + $this->assertSame( 'string', ( new IXR_Value( 'IXR_Date' ) )->calculateType(), 'A string matching a class name should be typed as a string.' ); + } + /** * @ticket 36586 */ From 4110c7f0a310045fa3b379ef1da69d6e3a06ebc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=B3=C5=82kowski?= Date: Fri, 6 Nov 2026 08:36:45 +0000 Subject: [PATCH 290/481] Abilities API: Document input preparation for direct permission checks `WP_Ability::check_permissions()` does not prepare the input. Callers outside of `WP_Ability::execute()` must run `normalize_input()`, `validate_input()`, and `coerce_input()` first, or the permission callback may get different input than during `execute()`. Developed in https://github.com/WordPress/wordpress-develop/pull/15514. Props euvoor, gziolo, zaguiini, jorbin. See #66482. git-svn-id: https://develop.svn.wordpress.org/trunk@65306 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/abilities-api.php | 33 +++++++++++-------- .../abilities-api/class-wp-ability.php | 32 +++++++++++++----- 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index 764261d3313a4..f50531e5b5efa 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -199,9 +199,10 @@ * #### Execute Callback * * The execute callback performs the ability's core functionality. It receives - * the normalized, validated input when an input schema is defined, and no arguments - * otherwise. It returns either a result or `WP_Error` on failure. Exceptions thrown - * by execute or permission callbacks are caught and converted to a `WP_Error`. + * the normalized, validated, and coerced input when an input schema is defined, + * and no arguments otherwise. It returns either a result or `WP_Error` on failure. + * Exceptions thrown by execute or permission callbacks are caught and converted + * to a `WP_Error`. * * function my_plugin_analyze_text( string $input ): string|WP_Error { * $score = My_Plugin::perform_sentiment_analysis( $input ); @@ -224,12 +225,12 @@ * For an ability that everyone may execute, use `__return_true` as the callback * with no required capabilities. * - * The permission callback determines whether the ability can be executed. - * It receives the same input as the execute callback and must return a - * boolean or `WP_Error`. Common use cases include checking user capabilities, - * validating API keys, or verifying system state. In the example above, every - * execution requires `edit_posts`, and the callback only adds the check that - * depends on the input: + * The permission callback determines whether the ability can be executed and + * must return a boolean or `WP_Error`. When called through `WP_Ability::execute()`, + * it receives the same normalized, validated, and coerced input as the execute + * callback. Common use cases include checking user capabilities, validating API + * keys, or verifying system state. In the example above, every execution requires + * `edit_posts`, and the callback only adds the check that depends on the input: * * function my_plugin_can_analyze_text( string $input ): bool|WP_Error { * // Only administrators can analyze long texts. @@ -241,9 +242,13 @@ * * ### Execution Lifecycle * - * Call `WP_Ability::execute()` to normalize and validate input, check permissions, - * invoke the execute callback, and validate output. It returns the result or a - * `WP_Error` on failure. Custom ability classes can override this behavior. + * Call `WP_Ability::execute()` to normalize, validate, and coerce input, check + * permissions, invoke the execute callback, and validate output. It returns the + * result or a `WP_Error` on failure. Custom ability classes can override this + * behavior. + * + * Integrations that call `WP_Ability::check_permissions()` directly must prepare + * the input first. See `WP_Ability::check_permissions()` for the required steps. * * Hooks run in this order, and processing stops at the first failure: * @@ -251,7 +256,9 @@ * 2. `wp_pre_execute_ability` filter, which can short-circuit the rest of execution. * 3. `wp_ability_normalize_input`, `wp_ability_validate_input`, and * `wp_ability_permission_result` filters. The input validation filter runs only - * when a non-empty input schema is defined. + * when a non-empty input schema is defined. Input coercion has no filter. It runs + * between validation and the permission check, only when a non-empty input + * schema is defined. * 4. `wp_before_execute_ability` action. * 5. `wp_ability_execute_result` and `wp_ability_validate_output` filters. * 6. `wp_after_execute_ability` action. diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index a9f53586d4cc5..d27d4c2cb5f0c 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -566,9 +566,9 @@ public function normalize_input( $input = null ) { * Coerces validated input to the types declared in the input schema. * * Also applies schema format sanitization, such as stripping tags for - * `text-field` and sanitizing URLs for `uri`, using rest_sanitize_value_from_schema(). + * `text-field` and sanitizing URLs for `uri`, using `rest_sanitize_value_from_schema()`. * - * Call validate_input() before this method. Coercing unvalidated input can + * Call `validate_input()` before this method. Coercing unvalidated input can * remove unknown properties or cast invalid values, hiding validation errors. * This method does not apply defaults or run input validation filters. * @@ -577,10 +577,10 @@ public function normalize_input( $input = null ) { * * @since 7.2.0 * - * @see validate_input() + * @see WP_Ability::validate_input() * * @param mixed $input Validated ability input. - * @return mixed|WP_Error Coerced input, or WP_Error when it cannot be safely coerced. + * @return mixed|WP_Error Coerced input, or `WP_Error` when it cannot be safely coerced. */ public function coerce_input( $input ) { $schema = $this->get_input_schema(); @@ -751,8 +751,20 @@ protected function invoke_callback( callable $callback, $input = null ) { /** * Checks whether the ability has the necessary permissions. * - * Please note that input is not automatically validated against the input schema. - * Use `validate_input()` method to validate input before calling this method if needed. + * This method does not prepare the input. Use `execute()` to run the full ability + * lifecycle, which prepares the input before calling this method. + * + * When calling this method directly, prepare the input in the same order as + * `execute()`, and stop if any step returns a `WP_Error`: + * + * 1. `normalize_input()` applies the schema default and returns the input. + * 2. `validate_input()` checks the input against the schema and returns `true`. + * 3. `coerce_input()` converts values to the schema types and returns the input + * to pass to this method. + * + * Skipping these steps means the permission callback may receive different input + * than it does during `execute()`, such as a missing schema default or a string + * instead of an integer. * * The checks run in this order: * @@ -768,9 +780,13 @@ protected function invoke_callback( callable $callback, $input = null ) { * @since 7.1.0 Added the `wp_ability_permission_result` filter. * @since 7.2.0 Added the `required_capabilities` check. * - * @see validate_input() + * @see WP_Ability::normalize_input() + * @see WP_Ability::validate_input() + * @see WP_Ability::coerce_input() + * @see WP_Ability::execute() * - * @param mixed $input Optional. The valid input data for permission checking. Default `null`. + * @param mixed $input Optional. The normalized, validated, and coerced input data for permission checking. + * Default `null`. * @return bool|WP_Error Whether the ability has the necessary permission. */ public function check_permissions( $input = null ) { From 6af92384177f3a357e9a83495773f97233b44718 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=B3=C5=82kowski?= Date: Fri, 6 Nov 2026 12:57:48 +0000 Subject: [PATCH 291/481] Tests: Extend coverage for core abilities Cover `core/get-site-info` permissions, the categories and annotations of the core information abilities, and the roles returned by `core/get-user-info`. Developed in https://github.com/WordPress/wordpress-develop/pull/15528. Props hmbashar, gziolo. Fixes #66493. git-svn-id: https://develop.svn.wordpress.org/trunk@65307 602fd350-edb4-49c9-b593-d223f7449a82 --- .../abilities-api/wpRegisterCoreAbilities.php | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php index b5b44c5be02cb..9f4f0ee841bbc 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php @@ -532,6 +532,154 @@ public static function data_core_ability_field_lists(): array { return $datasets; } + /** + * Tests that the `core/get-site-info` ability is denied to users who cannot manage options. + * + * @ticket 66493 + * + * @dataProvider data_users_who_cannot_manage_options + * + * @param string $role Role of the current user, or an empty string for a logged-out visitor. + */ + public function test_core_get_site_info_denies_users_who_cannot_manage_options( string $role ): void { + if ( '' !== $role ) { + wp_set_current_user( self::factory()->user->create( array( 'role' => $role ) ) ); + } else { + wp_set_current_user( 0 ); + } + + $result = wp_get_ability( 'core/get-site-info' )->execute(); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_invalid_permissions', $result->get_error_code() ); + } + + /** + * Data provider for the users who cannot manage options. + * + * @return array[] + */ + public static function data_users_who_cannot_manage_options(): array { + return array( + 'subscriber' => array( 'subscriber' ), + 'logged-out user' => array( '' ), + ); + } + + /** + * Tests that managing options is enough to use the `core/get-site-info` ability. + * + * @ticket 66493 + */ + public function test_core_get_site_info_allows_delegated_manage_options(): void { + $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) ); + $user = wp_set_current_user( $user_id ); + $user->add_cap( 'manage_options' ); + + $ability = wp_get_ability( 'core/get-site-info' ); + + $this->assertTrue( $ability->check_permissions() ); + $this->assertIsArray( $ability->execute() ); + } + + /** + * Tests the category of each core information ability. + * + * @ticket 66493 + * + * @dataProvider data_core_information_abilities + * + * @param string $ability_name Ability name. + * @param string $category Expected category slug. + */ + public function test_core_information_abilities_use_expected_category( string $ability_name, string $category ): void { + $ability = wp_get_ability( $ability_name ); + + $this->assertSame( $category, $ability->get_category() ); + } + + /** + * Tests that the core information abilities are annotated as read-only and idempotent. + * + * @ticket 66493 + * + * @dataProvider data_core_information_abilities + * + * @param string $ability_name Ability name. + */ + public function test_core_information_abilities_are_annotated_as_read_only( string $ability_name ): void { + $annotations = wp_get_ability( $ability_name )->get_meta_item( 'annotations' ); + + $this->assertTrue( $annotations['readonly'], 'The ability should be read-only.' ); + $this->assertFalse( $annotations['destructive'], 'The ability should not be destructive.' ); + $this->assertTrue( $annotations['idempotent'], 'The ability should be idempotent.' ); + } + + /** + * Data provider for the core information abilities. + * + * @return array[] + */ + public static function data_core_information_abilities(): array { + return array( + 'core/get-site-info' => array( 'core/get-site-info', 'site' ), + 'core/get-user-info' => array( 'core/get-user-info', 'user' ), + 'core/get-environment-info' => array( 'core/get-environment-info', 'site' ), + ); + } + + /** + * Tests that the roles of a user with several roles are returned in order. + * + * @ticket 66493 + */ + public function test_core_get_user_info_returns_all_roles_of_user(): void { + $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) ); + $user = wp_set_current_user( $user_id ); + $user->add_role( 'editor' ); + + $result = wp_get_ability( 'core/get-user-info' )->execute( array( 'fields' => array( 'roles' ) ) ); + + $this->assertSame( array( 'roles' => array( 'subscriber', 'editor' ) ), $result ); + } + + /** + * Tests that the roles are returned as a list when the roles of the user are not numbered in sequence. + * + * @ticket 66493 + */ + public function test_core_get_user_info_returns_roles_as_list(): void { + $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) ); + $user = wp_set_current_user( $user_id ); + + // The roles of a user can come with gaps in their numbering, for example when they are filtered. + $user->roles = array( + 2 => 'subscriber', + 5 => 'editor', + ); + + $result = wp_get_ability( 'core/get-user-info' )->execute( array( 'fields' => array( 'roles' ) ) ); + + $this->assertSame( array( 'roles' => array( 'subscriber', 'editor' ) ), $result ); + $this->assertSame( '{"roles":["subscriber","editor"]}', wp_json_encode( $result ), 'The roles should be encoded as a JSON array.' ); + } + + /** + * Tests that a user without roles gets an empty list of roles. + * + * @ticket 66493 + */ + public function test_core_get_user_info_returns_empty_roles_for_user_without_roles(): void { + $user_id = self::factory()->user->create( array( 'role' => '' ) ); + $user = wp_set_current_user( $user_id ); + + $this->assertSame( array(), $user->roles, 'The user should not have any roles.' ); + + $result = wp_get_ability( 'core/get-user-info' )->execute( array( 'fields' => array( 'roles' ) ) ); + + $this->assertSame( array( 'roles' => array() ), $result ); + } + /** * Tests that all core ability schemas only use valid JSON Schema keywords. * From 3fe7aba7dbd76e091d840bcf0d2b99d8943405c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=B3=C5=82kowski?= Date: Fri, 6 Nov 2026 13:09:43 +0000 Subject: [PATCH 292/481] Abilities API: Require a registered category for abilities Partially reverts [63343]. Abilities that omit a category are no longer assigned to the built-in `uncategorized` category, which is removed. Registration fails with a `_doing_it_wrong()` notice instead. Updates the docs to explain why categories are required and how to reuse existing ones. Developed in https://github.com/WordPress/wordpress-develop/pull/15462. Props gziolo, jason_the_adams, jorgefilipecosta. Fixes #65569. git-svn-id: https://develop.svn.wordpress.org/trunk@65308 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/abilities-api.php | 26 ++++++------- .../class-wp-abilities-registry.php | 16 ++------ src/wp-includes/abilities.php | 10 +---- .../abilities-api/wpAbilitiesRegistry.php | 4 +- .../tests/abilities-api/wpRegisterAbility.php | 39 +++++-------------- .../abilities-api/wpRegisterCoreAbilities.php | 10 ++--- 6 files changed, 31 insertions(+), 74 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index f50531e5b5efa..6647aa7c2b6c2 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -52,10 +52,9 @@ * } * add_action( 'wp_abilities_api_init', 'my_plugin_register_abilities' ); * - * Use a category to group related abilities and improve discoverability. The - * `data-export` category must be registered first with `wp_register_ability_category()` + * Every ability requires a category to group related abilities and improve discoverability. + * The `data-export` category must be registered first with `wp_register_ability_category()` * on `wp_abilities_api_categories_init`, or the ability registration fails. - * Abilities that omit `category` fall back to the built-in `uncategorized` category. * * Once registered, abilities can be checked, retrieved, and managed: * @@ -148,9 +147,11 @@ * * ### Categories * - * Abilities can be organized into categories. If no category is provided, the ability is - * assigned to the built-in `uncategorized` category. Custom categories must be registered - * before the abilities that reference them: + * Every ability must specify a registered category. Categories group related abilities + * so clients can discover and retrieve relevant subsets. Plugins can reuse an existing + * category when appropriate, including categories registered by core. Custom categories must be + * registered on `wp_abilities_api_categories_init` before abilities that reference them + * are registered on `wp_abilities_api_init`: * * function my_plugin_register_categories(): void { * wp_register_ability_category( @@ -286,7 +287,6 @@ * * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. - * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. * @since 7.2.0 Added the `required_capabilities` argument. * * @see WP_Abilities_Registry::register() @@ -304,9 +304,9 @@ * @type string $label Required. The human-readable label for the ability. * @type string $description Required. A detailed description of what the ability does * and when it should be used. - * @type string $category Optional. The ability category slug this ability belongs to. - * Defaults to `uncategorized`. Custom categories must be registered - * via `wp_register_ability_category()` before registering the ability. + * @type string $category Required. The registered ability category slug this ability belongs to. + * Custom categories must be registered via + * `wp_register_ability_category()` before registering the ability. * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. * Receives optional mixed input data and must return either a result * value (any type) or a `WP_Error` object on failure. @@ -707,10 +707,8 @@ function _wp_get_abilities_match_meta( array $meta, array $conditions ): bool { * Registers a new ability category. * * Ability categories provide a way to organize and group related abilities for better - * discoverability and management. Custom categories must be registered before abilities - * that reference them. Abilities that omit a category are assigned to the built-in - * `uncategorized` category, which is intended as an escape hatch for simple or transitional - * registrations. + * discoverability and management. Every ability requires a registered category. + * Custom categories must be registered before abilities that reference them. * * Ability categories must be registered on the `wp_abilities_api_categories_init` action hook. * diff --git a/src/wp-includes/abilities-api/class-wp-abilities-registry.php b/src/wp-includes/abilities-api/class-wp-abilities-registry.php index fe41f8e0f64a7..dc0b30835d9d1 100644 --- a/src/wp-includes/abilities-api/class-wp-abilities-registry.php +++ b/src/wp-includes/abilities-api/class-wp-abilities-registry.php @@ -41,7 +41,6 @@ final class WP_Abilities_Registry { * * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. - * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. * @since 7.2.0 Added the `required_capabilities` argument. * * @see wp_register_ability() @@ -54,8 +53,7 @@ final class WP_Abilities_Registry { * * @type string $label The human-readable label for the ability. * @type string $description A detailed description of what the ability does. - * @type string $category Optional. The ability category slug this ability belongs to. - * Defaults to `uncategorized`. + * @type string $category The registered ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. * @type callable $permission_callback A callback function to check permissions before execution. @@ -119,7 +117,6 @@ public function register( string $name, array $args ): ?WP_Ability { * * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. - * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. * @since 7.2.0 Added the `required_capabilities` argument. * * @param array $args { @@ -127,8 +124,7 @@ public function register( string $name, array $args ): ?WP_Ability { * * @type string $label The human-readable label for the ability. * @type string $description A detailed description of what the ability does. - * @type string $category Optional. The ability category slug this ability belongs to. - * Defaults to `uncategorized`. + * @type string $category The registered ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. * @type callable $permission_callback A callback function to check permissions before execution. @@ -156,14 +152,10 @@ public function register( string $name, array $args ): ?WP_Ability { */ $args = apply_filters( 'wp_register_ability_args', $args, $name ); - if ( ! array_key_exists( 'category', $args ) ) { - $args['category'] = 'uncategorized'; - } - - if ( ! is_string( $args['category'] ) ) { + if ( ! isset( $args['category'] ) || ! is_string( $args['category'] ) ) { _doing_it_wrong( __METHOD__, - __( 'Ability category must be a string.' ), + __( 'The ability properties must contain a `category` string.' ), '6.9.0' ); return null; diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index c4489f7e36c92..835c19e04f949 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -17,7 +17,7 @@ * Registers the core ability categories. * * @since 6.9.0 - * @since 7.2.0 Added the `content` and `uncategorized` categories. + * @since 7.2.0 Added the `content` category. */ function wp_register_core_ability_categories(): void { wp_register_ability_category( @@ -43,14 +43,6 @@ function wp_register_core_ability_categories(): void { 'description' => __( 'Abilities that retrieve or manage posts and other content.' ), ) ); - - wp_register_ability_category( - 'uncategorized', - array( - 'label' => __( 'Uncategorized' ), - 'description' => __( 'Abilities that have not been assigned to a specific category.' ), - ) - ); } /** diff --git a/tests/phpunit/tests/abilities-api/wpAbilitiesRegistry.php b/tests/phpunit/tests/abilities-api/wpAbilitiesRegistry.php index b29bbe38a27f7..7d98cb2780454 100644 --- a/tests/phpunit/tests/abilities-api/wpAbilitiesRegistry.php +++ b/tests/phpunit/tests/abilities-api/wpAbilitiesRegistry.php @@ -245,7 +245,7 @@ public function test_register_ability_rejects_invalid_category_type( $category ) $this->assertNull( $result ); $this->assertStringContainsString( - 'Ability category must be a string.', + 'The ability properties must contain a `category` string.', $this->caught_doing_it_wrong['WP_Abilities_Registry::register'] ); } @@ -265,7 +265,7 @@ public static function data_invalid_category_types(): array { } /** - * Tests that an empty category is rejected rather than replaced by the default. + * Tests that an empty category is rejected. * * @ticket 65569 * diff --git a/tests/phpunit/tests/abilities-api/wpRegisterAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterAbility.php index 4c54eeeb2163f..9a248b76ae478 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterAbility.php @@ -100,9 +100,6 @@ public function tear_down(): void { // Clean up registered test ability category. wp_unregister_ability_category( 'math' ); - if ( wp_has_ability_category( 'uncategorized' ) ) { - wp_unregister_ability_category( 'uncategorized' ); - } parent::tear_down(); } @@ -226,39 +223,21 @@ public function test_register_valid_ability(): void { } /** + * Tests that registering an ability requires a category. + * * @ticket 65569 + * @expectedIncorrectUsage WP_Abilities_Registry::register */ - public function test_register_ability_without_category_uses_uncategorized_category(): void { - global $wp_current_filter; - + public function test_register_ability_without_category_fails(): void { $this->simulate_doing_wp_abilities_init_action(); - $wp_current_filter[] = 'wp_abilities_api_categories_init'; - wp_register_ability_category( - 'uncategorized', - array( - 'label' => 'Uncategorized', - 'description' => 'Abilities that have not been assigned to a specific category.', - ) - ); - array_pop( $wp_current_filter ); + $args = self::$test_ability_args; + unset( $args['category'] ); - $ability = wp_register_ability( - 'test/without-category', - array( - 'label' => 'Test ability without category', - 'description' => 'Test ability description.', - 'input_schema' => array(), - 'output_schema' => array(), - 'permission_callback' => '__return_true', - 'execute_callback' => static function (): array { - return array( 'success' => true ); - }, - ) - ); + $ability = wp_register_ability( self::$test_ability_name, $args ); - $this->assertInstanceOf( WP_Ability::class, $ability ); - $this->assertSame( 'uncategorized', $ability->get_category() ); + $this->assertNull( $ability ); + $this->assertFalse( wp_has_ability( self::$test_ability_name ) ); } /** diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php index 9f4f0ee841bbc..0f23eb7831177 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreAbilities.php @@ -57,16 +57,12 @@ public static function tear_down_after_class(): void { } /** - * Tests that the uncategorized fallback category is registered by core. + * Tests that core does not register an uncategorized fallback category. * * @ticket 65569 */ - public function test_uncategorized_category_is_registered(): void { - $category = wp_get_ability_category( 'uncategorized' ); - - $this->assertInstanceOf( WP_Ability_Category::class, $category ); - $this->assertSame( 'Uncategorized', $category->get_label() ); - $this->assertSame( 'Abilities that have not been assigned to a specific category.', $category->get_description() ); + public function test_uncategorized_category_is_not_registered(): void { + $this->assertFalse( wp_has_ability_category( 'uncategorized' ) ); } /** From ed8c8077fc2e1ee23012b1d12f1dd23d06ecbd6e Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Fri, 6 Nov 2026 14:10:40 +0000 Subject: [PATCH 293/481] Build/Test Tools: Remove script to run Gutenberg E2E tests in Core. In r48382 a script was added to run the Gutenberg end-to-end tests in `wordpress-develop`. Besides a few small changes related to normal Gutenberg syncs, these files have not been touched since being introduced and the script no longer works: - The specified `wp/trunk` branch checked out from `gutenberg` no longer exists (it was renamed to `wp/latest`). - The `test-e2e` npm script no longer exists (it was renamed to `test:e2e` in https://github.com/WordPress/gutenberg/pull/42368). - `packages/e2e-tests/specs` - The `FORCE_REDUCED_MOTION` build flag it passed was removed in r56699. - It crashes on startup because the `chalk` dependency is now ESM-only. - It was never formally added to any Github Actions workflows. Removing this script also allows the `chalk` and `uuid` dependencies to be removed. "And another one gone, and another one gone." See #65845, #50469, #59407. git-svn-id: https://develop.svn.wordpress.org/trunk@65309 602fd350-edb4-49c9-b593-d223f7449a82 --- package-lock.json | 29 --------- package.json | 2 - tests/gutenberg/.wp-env.sample.json | 13 ---- tests/gutenberg/run.js | 97 ----------------------------- 4 files changed, 141 deletions(-) diff --git a/package-lock.json b/package-lock.json index 104144e86e833..fd5807b735a8d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -57,7 +57,6 @@ "@wordpress/prettier-config": "4.51.0", "@wordpress/scripts": "33.0.0", "autoprefixer": "10.5.3", - "chalk": "5.6.2", "cssnano": "7.1.9", "dotenv": "17.4.2", "dotenv-expand": "13.0.0", @@ -92,7 +91,6 @@ "source-map-loader": "5.0.0", "typescript": "6.0.3", "update-browserslist-db": "1.3.1", - "uuid": "14.0.1", "wait-on": "9.0.10", "webpack": "5.108.4" }, @@ -10399,19 +10397,6 @@ "node": ">= 10" } }, - "node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, "node_modules/change-case": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/change-case/-/change-case-4.1.2.tgz", @@ -28630,20 +28615,6 @@ "node": ">= 0.4.0" } }, - "node_modules/uuid": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.1.tgz", - "integrity": "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==", - "dev": true, - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "license": "MIT", - "bin": { - "uuid": "dist-node/bin/uuid" - } - }, "node_modules/v8-to-istanbul": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", diff --git a/package.json b/package.json index e209ae46d2058..b260b675af0ba 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,6 @@ "@wordpress/prettier-config": "4.51.0", "@wordpress/scripts": "33.0.0", "autoprefixer": "10.5.3", - "chalk": "5.6.2", "cssnano": "7.1.9", "dotenv": "17.4.2", "dotenv-expand": "13.0.0", @@ -90,7 +89,6 @@ "source-map-loader": "5.0.0", "typescript": "6.0.3", "update-browserslist-db": "1.3.1", - "uuid": "14.0.1", "wait-on": "9.0.10", "webpack": "5.108.4" }, diff --git a/tests/gutenberg/.wp-env.sample.json b/tests/gutenberg/.wp-env.sample.json index f5caea7afc139..e69de29bb2d1d 100644 --- a/tests/gutenberg/.wp-env.sample.json +++ b/tests/gutenberg/.wp-env.sample.json @@ -1,13 +0,0 @@ -{ - "core": "{WP_PATH}", - "mappings": { - "wp-content/mu-plugins": "{MU_PlUGINS_PATH}", - "wp-content/plugins/test-plugins": "{TEST_PlUGINS_PATH}" - }, - "config": { - "SCRIPT_DEBUG": false, - "WP_PHP_BINARY": "php", - "WP_TESTS_EMAIL": "admin@example.org", - "WP_TESTS_TITLE": "Test Blog" - } -} diff --git a/tests/gutenberg/run.js b/tests/gutenberg/run.js index c463bfde0bc8e..e69de29bb2d1d 100755 --- a/tests/gutenberg/run.js +++ b/tests/gutenberg/run.js @@ -1,97 +0,0 @@ -#!/usr/bin/env node -const path = require( 'path' ); -const { v4: uuid } = require( 'uuid' ); -const os = require( 'os' ); -const fs = require( 'fs' ); -const chalk = require( 'chalk' ); -const childProcess = require( 'child_process' ); - -// Config -const GUTENBERG_VERSION = 'wp/trunk'; - -// Utils -/** - * Utility to run a child script - * - * @param {string} script Script to run. - * @param {string=} cwd Working directory. - */ -function runShellScript( script, cwd ) { - childProcess.execSync( script, { - cwd, - env: { - NO_CHECKS: 'true', - PATH: process.env.PATH, - HOME: process.env.HOME, - }, - stdio: [ 'inherit', 'ignore', 'inherit' ], - } ); -} - -/** - * Small utility used to read an uncached version of a JSON file - * - * @param {string} fileName - */ -function readJSONFile( fileName ) { - const data = fs.readFileSync( fileName, 'utf8' ); - return JSON.parse( data ); -} - -/** - * Generates a random temporary path in the OS's tmp dir. - * - * @return {string} Temporary Path. - */ -function getRandomTemporaryPath() { - return path.join( os.tmpdir(), uuid() ); -} - -// Useful constants -const title = chalk.bold; -const success = chalk.bold.green; -const rootFolder = path.resolve( __dirname, '../../' ); -const testLauncherPath = getRandomTemporaryPath(); -const testEnvironmentPath = getRandomTemporaryPath(); -const sampleEnvConfig = path.resolve( __dirname, '.wp-env.sample.json' ); - -// Welcome -console.log( title( '>> 🏁 Welcome, this command is going to prepare a running WordPress environment and run the Gutenberg e2e tests against it.' ) ); -console.log( title( '>> It uses the current WordPress folder from which it\'s being run and a separate Gutenberg clone performed by the command.' ) ); -console.log( title( '>> Configuration: ' ) ); -console.log( 'Gutenberg Version: ' + success( GUTENBERG_VERSION ) ); -console.log( 'Test Launcher Path (Gutenberg): ' + success( testLauncherPath ) ); -console.log( 'Test Environment Path (wp-env): ' + success( testEnvironmentPath ) ); - -// Steps -// 1- Preparing the WordPress environment -console.log( '>> Preparing the WordPress clone' ); -runShellScript( 'npm install && FORCE_REDUCED_MOTION=true npm run build', rootFolder ); - -// 2- Preparing the Gutenberg clone -// The tests and the launcher comes from the Gutenberg repository e2e tests -console.log( title( '>> Preparing the e2e tests launcher' ) ); -runShellScript( 'git clone https://github.com/WordPress/gutenberg.git ' + testLauncherPath + ' --depth=1 --no-single-branch' ); -runShellScript( 'git checkout ' + GUTENBERG_VERSION, testLauncherPath ); -runShellScript( 'npm install && npm run build', testLauncherPath ); - -// 3- Running the WordPress environment using wp-env -// The environment should include the WordPress install and the e2e tests plugins.s -console.log( title( '>> Preparing the environment' ) ); -runShellScript( 'mkdir -p ' + testEnvironmentPath ); -const envConfig = readJSONFile( sampleEnvConfig ); -envConfig.core = path.resolve( rootFolder, 'build' ); -envConfig.mappings[ 'wp-content/mu-plugins' ] = path.resolve( testLauncherPath, 'packages/e2e-tests/mu-plugins' ); -envConfig.mappings[ 'wp-content/plugins/test-plugins' ] = path.resolve( testLauncherPath, 'packages/e2e-tests/plugins' ); -fs.writeFileSync( - path.resolve( testEnvironmentPath, '.wp-env.json' ), - JSON.stringify( envConfig, null, '\t' ) + '\n' -); - -// 4- Starting the environment -console.log( title( '>> Starting the environment' ) ); -runShellScript( path.resolve( testLauncherPath, 'node_modules/.bin/wp-env' ) + ' start ', testEnvironmentPath ); - -// 5- Running the tests -console.log( title( '>> Running the e2e tests' ) ); -runShellScript( 'npm run test-e2e packages/e2e-tests/specs/editor', testLauncherPath ); From 8045dc48928661def887896d55b72c4942008d74 Mon Sep 17 00:00:00 2001 From: Jonathan Desrosiers Date: Fri, 6 Nov 2026 16:09:55 +0000 Subject: [PATCH 294/481] Build/Test Tools: Raise the maximum PHP version for PHPStan. The `tests/phpstan/base.neon` file currently defines `80500` for `phpVersion.max`. Since WordPress 7.2 aims to be compatible with PHP 8.6 due out later this month, this is now set to `80600`. This also updates the `phpstan/phpstan` dependency's pinned version from `2.3.4` to `2.3.5`. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65310 602fd350-edb4-49c9-b593-d223f7449a82 --- composer.json | 2 +- tests/phpstan/base.neon | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 70928671aa6e3..e20f4c7806b6e 100644 --- a/composer.json +++ b/composer.json @@ -52,7 +52,7 @@ "squizlabs/php_codesniffer": "3.13.5", "wp-coding-standards/wpcs": "~3.4.1", "phpcompatibility/phpcompatibility-wp": "~2.1.3", - "phpstan/phpstan": "2.3.4", + "phpstan/phpstan": "2.3.5", "phpstan/phpstan-phpunit": "2.1.1", "phpstan/phpstan-strict-rules": "2.1.1", "yoast/phpunit-polyfills": "^1.1.0" diff --git a/tests/phpstan/base.neon b/tests/phpstan/base.neon index be98b5e1503cc..1c102ca47e7da 100644 --- a/tests/phpstan/base.neon +++ b/tests/phpstan/base.neon @@ -105,10 +105,10 @@ parameters: # Cache is stored locally, so it's available for CI. tmpDir: ../../.cache - # The Minimum PHP Version + # Supported PHP versions. phpVersion: min: 70400 - max: 80500 + max: 80600 # If it's not enforced by PHP we can't assume users are passing valid values. treatPhpDocTypesAsCertain: false From 2f5f4cdec43d6a345338e36ab36c6488d720571c Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 6 Nov 2026 16:56:53 +0000 Subject: [PATCH 295/481] Build/Test Tools: Wait for maintenance mode to end in E2E tests. The maintenance mode spec deletes the `.maintenance` file from the host. With a Docker file share on macOS, the file can still show as present for about a second. In that time, `file_exists()` passes in `wp_is_maintenance_mode()`, the `require` fails, and the first tests of the next spec fail. The spec now waits until the home page loads without that error before it ends. It fails if the site does not recover within 10 seconds. Follow-up to [58430]. Developed in: https://github.com/WordPress/wordpress-develop/pull/15727 Props adrianmoldovanwp. See #66455. git-svn-id: https://develop.svn.wordpress.org/trunk@65311 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/specs/maintenance-mode.test.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/e2e/specs/maintenance-mode.test.js b/tests/e2e/specs/maintenance-mode.test.js index df9d409a07895..6ccbfbb8063f1 100644 --- a/tests/e2e/specs/maintenance-mode.test.js +++ b/tests/e2e/specs/maintenance-mode.test.js @@ -20,8 +20,16 @@ test.describe( 'Maintenance mode', () => { writeFileSync( maintenanceLockFile, '' ); // Year 2286. } ); - test.afterAll( async () => { + test.afterAll( async ( { request } ) => { unlinkSync( maintenanceLockFile ); + + // A Docker file share can report a deleted file as present for about a + // second, and require() then fails in wp_is_maintenance_mode(). + await expect( async () => { + const response = await request.get( '/' ); + await expect( response ).toBeOK(); + expect( await response.text() ).not.toContain( '.maintenance' ); + }, 'should leave maintenance mode after the lock file is deleted' ).toPass( { timeout: 10_000 } ); } ); test( 'should display maintenance mode page', async ( { page } ) => { From 0c0ab54942cc00e32b404059fe6bf3b539e03382 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 6 Nov 2026 16:57:57 +0000 Subject: [PATCH 296/481] Build/Test Tools: Replace E2E site state hooks with fixtures. Four E2E specs each had their own hooks to put settings, options and must-use plugins back after a test. Three shared fixtures in `tests/e2e/fixtures/site.js` now restore that state in teardown, also when a test fails. If a restore fails, the test fails. `siteSettings` changes settings through REST, `siteOptions` changes options through WP-CLI, and `muPlugin` writes a must-use plugin and deletes it after the test. The settings and options fixtures restore only the keys a test changes. The E2E README has a new Fixtures section. Follow-up to [56949], [58068], [58430], [64409], [64584], [65274]. Developed in: https://github.com/WordPress/wordpress-develop/pull/15709 Props adrianmoldovanwp. See #66455. git-svn-id: https://develop.svn.wordpress.org/trunk@65312 602fd350-edb4-49c9-b593-d223f7449a82 --- tests/e2e/README.md | 2 +- tests/e2e/fixtures/index.js | 8 + tests/e2e/fixtures/site.js | 148 ++++++++++++++++++ tests/e2e/specs/fatal-error-handler.test.js | 32 +--- .../general-settings-invalid-timezone.test.js | 44 +----- tests/e2e/specs/login-localize-script.test.js | 37 +---- tests/e2e/specs/privacy.test.js | 39 ++--- 7 files changed, 188 insertions(+), 122 deletions(-) create mode 100644 tests/e2e/fixtures/site.js diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 214f3a964dd47..ff5584dd547c5 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -1 +1 @@ -# E2E Tests End-To-End (E2E) tests for WordPress. ## Running the tests The e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`. If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md). Then you can launch the tests by running: ``` npm run test:e2e ``` which will run the test suite using a headless browser. If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this: ``` WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e ``` **DO NOT run these tests in an actual production environment, as they will delete all your content.** For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode: ``` npm run test:e2e -- --ui ``` [UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode. All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test. You can also run a single test file separately: ``` npm run test:e2e tests/e2e/specs/hello.test.js ``` ## Projects The suite has three Playwright projects, defined in `playwright.config.js`: * `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project. * `parallel`: specs that can share the site with other tests. Spec files run at the same time on several workers, one for every two CPU cores. Tests inside one file still run in order. Run it with `npm run test:e2e -- --project=parallel`. * `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`. CI runs `parallel` and `serial` in separate jobs. New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` only if it makes the site unusable for other tests, or if it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`. Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails: ``` npm run test:e2e -- --project=parallel --shuffle ``` Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`. ## Logged-out pages Most specs run logged in as the admin user. There are two ways to run a test logged out: * To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`. * To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`. ## Documentation * Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing * Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright * Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json) \ No newline at end of file +# E2E Tests End-To-End (E2E) tests for WordPress. ## Running the tests The e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`. If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md). Then you can launch the tests by running: ``` npm run test:e2e ``` which will run the test suite using a headless browser. If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this: ``` WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e ``` **DO NOT run these tests in an actual production environment, as they will delete all your content.** For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode: ``` npm run test:e2e -- --ui ``` [UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode. All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test. You can also run a single test file separately: ``` npm run test:e2e tests/e2e/specs/hello.test.js ``` ## Projects The suite has three Playwright projects, defined in `playwright.config.js`: * `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project. * `parallel`: specs that can share the site with other tests. Spec files run at the same time on several workers, one for every two CPU cores. Tests inside one file still run in order. Run it with `npm run test:e2e -- --project=parallel`. * `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`. CI runs `parallel` and `serial` in separate jobs. New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` only if it makes the site unusable for other tests, or if it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`. Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails: ``` npm run test:e2e -- --project=parallel --shuffle ``` Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`. ## Logged-out pages Most specs run logged in as the admin user. There are two ways to run a test logged out: * To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`. * To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`. ## Fixtures To change a setting, an option, or a must-use plugin, import `test` and `expect` from `../fixtures`, and use one of the fixtures in `fixtures/site.js`. Each fixture restores the state when the test ends, also if the test fails. If a restore fails, the test fails. * `siteSettings`: reads and changes the settings of `/wp/v2/settings` through REST, with `get()` and `set( patch )`. It restores only the keys passed to `set`. See `specs/privacy.test.js`. * `siteOptions`: reads and changes options through WP-CLI, with `get( names )` and `set( values )`. It reads and restores the stored `gmt_offset`, not the value calculated for a named timezone. It restores only the keys passed to `set`. See `specs/general-settings-invalid-timezone.test.js`. * `muPlugin`: writes a must-use plugin with `write( fileName, php )`, and deletes the file when the test ends. Call `write` before the test visits a page. See `specs/fatal-error-handler.test.js`. If the test changes a setting or an option through a form, first call `set` with the current value. The fixture then knows that it must restore the key. ## Documentation * Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing * Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright * Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json) \ No newline at end of file diff --git a/tests/e2e/fixtures/index.js b/tests/e2e/fixtures/index.js index 0a541aa4c7234..97ec0aac82634 100644 --- a/tests/e2e/fixtures/index.js +++ b/tests/e2e/fixtures/index.js @@ -3,6 +3,11 @@ */ import { test as base, expect } from '@wordpress/e2e-test-utils-playwright'; +/** + * Internal dependencies + */ +import { muPlugin, siteOptions, siteSettings } from './site'; + export const test = base.extend( { loggedOutPage: async ( { browser }, use ) => { const context = await browser.newContext( { @@ -11,6 +16,9 @@ export const test = base.extend( { await use( await context.newPage() ); await context.close(); }, + muPlugin, + siteOptions, + siteSettings, } ); export { expect }; diff --git a/tests/e2e/fixtures/site.js b/tests/e2e/fixtures/site.js new file mode 100644 index 0000000000000..3ced323f74899 --- /dev/null +++ b/tests/e2e/fixtures/site.js @@ -0,0 +1,148 @@ +/** + * External dependencies + */ +import { mkdir, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +/** + * WordPress dependencies + */ +import { expect } from '@wordpress/e2e-test-utils-playwright'; + +/** + * Internal dependencies + */ +import { wpCli } from '../utils/wp-cli'; + +/** + * Writes options, then reads options, through WP-CLI. + * + * @param {string} baseURL The URL of the site. + * @param {string[]} names The names of the options to read. + * @param {Object} values The option values to write. A value of `false` deletes the option. + * @return {Object} The stored values of the options in `names`. + */ +function syncOptions( baseURL, names, values = {} ) { + const input = Buffer.from( JSON.stringify( { names, values } ) ).toString( + 'base64' + ); + + return JSON.parse( + wpCli( [ + `--url=${ baseURL }`, + 'eval', + ` + // Read and restore the stored offset, not the value calculated for a named timezone. + remove_filter( 'pre_option_gmt_offset', 'wp_timezone_override_offset' ); + $input = json_decode( base64_decode( '${ input }' ), true ); + foreach ( $input['values'] as $option => $value ) { + // get_option() returns false for an option that does not exist. + false === $value ? delete_option( $option ) : update_option( $option, $value ); + } + $stored = array(); + foreach ( $input['names'] as $option ) { + $stored[ $option ] = get_option( $option ); + } + echo wp_json_encode( (object) $stored ); + `, + ] ) + ); +} + +/** + * Waits for all restores to finish, so that one failure does not stop the others. + * + * @param {Promise[]} restores The restores in progress. + * @throws {AggregateError} If a restore failed. + */ +async function settleRestores( restores ) { + const errors = ( await Promise.allSettled( restores ) ) + .filter( ( { status } ) => status === 'rejected' ) + .map( ( { reason } ) => reason ); + + if ( errors.length > 0 ) { + throw new AggregateError( + errors, + errors.map( ( { message } ) => message ).join( '\n' ) + ); + } +} + +/** + * Reads and changes site settings through REST. Teardown restores the keys passed to `set`. + */ +export const siteSettings = async ( { requestUtils }, use ) => { + const originals = {}; + const get = () => requestUtils.rest( { path: '/wp/v2/settings' } ); + const post = ( data ) => + requestUtils.rest( { method: 'POST', path: '/wp/v2/settings', data } ); + + await use( { + get, + set: async ( patch ) => { + const current = await get(); + for ( const key of Object.keys( patch ) ) { + if ( ! Object.hasOwn( originals, key ) ) { + originals[ key ] = current[ key ]; + } + } + await post( patch ); + }, + } ); + + await settleRestores( + Object.entries( originals ).map( async ( [ key, value ] ) => { + const original = { [ key ]: value }; + expect( await post( original ) ).toMatchObject( original ); + } ) + ); +}; + +/** + * Reads and changes site options through WP-CLI. Teardown restores the keys passed to `set`. + */ +export const siteOptions = async ( { baseURL }, use ) => { + let originals = {}; + + await use( { + get: async ( names ) => syncOptions( baseURL, names ), + set: async ( values ) => { + originals = { + ...syncOptions( baseURL, Object.keys( values ) ), + ...originals, + }; + syncOptions( baseURL, [], values ); + }, + } ); + + const names = Object.keys( originals ); + if ( names.length > 0 ) { + expect( syncOptions( baseURL, names, originals ) ).toEqual( originals ); + } +}; + +/** + * Writes must-use plugins. Teardown deletes each file that `write` wrote. + */ +export const muPlugin = async ( {}, use ) => { + const directory = join( + process.cwd(), + process.env.LOCAL_DIR ?? 'src', + 'wp-content/mu-plugins' + ); + const files = new Set(); + + await use( { + write: async ( fileName, php ) => { + const file = join( directory, fileName ); + files.add( file ); + await mkdir( directory, { recursive: true } ); + await writeFile( file, php ); + return file; + }, + } ); + + await settleRestores( + [ ...files ].map( ( file ) => rm( file, { force: true } ) ) + ); +}; diff --git a/tests/e2e/specs/fatal-error-handler.test.js b/tests/e2e/specs/fatal-error-handler.test.js index 1b5522358ebb9..3d1e320f57f4f 100644 --- a/tests/e2e/specs/fatal-error-handler.test.js +++ b/tests/e2e/specs/fatal-error-handler.test.js @@ -1,36 +1,12 @@ /** - * External dependencies + * Internal dependencies */ -import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs'; -import { join } from 'node:path'; - -/** - * WordPress dependencies - */ -import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +import { test, expect } from '../fixtures'; test.describe( 'Fatal error handler', () => { - const muPlugins = join( - process.cwd(), - process.env.LOCAL_DIR ?? 'src', - 'wp-content/mu-plugins' - ); - const muPluginFile = join( muPlugins, 'fatal-error.php' ); - - test.beforeAll( async () => { - const muPluginCode = ` { - unlinkSync( muPluginFile ); - } ); + test( 'should display fatal error notice', async ( { admin, page, muPlugin } ) => { + await muPlugin.write( 'fatal-error.php', ` { await admin.visitAdminPage( '/' ); await expect( diff --git a/tests/e2e/specs/general-settings-invalid-timezone.test.js b/tests/e2e/specs/general-settings-invalid-timezone.test.js index d19d026db8659..35cb231b96db2 100644 --- a/tests/e2e/specs/general-settings-invalid-timezone.test.js +++ b/tests/e2e/specs/general-settings-invalid-timezone.test.js @@ -1,49 +1,19 @@ -import { test, expect } from '@wordpress/e2e-test-utils-playwright'; -import { wpCli } from '../utils/wp-cli'; - -function timezoneOptions( baseURL, values ) { - const restore = values === undefined ? '' : ` - $values = json_decode( base64_decode( '${ Buffer.from( JSON.stringify( values ) ).toString( 'base64' ) }' ), true ); - foreach ( $values as $option => $value ) { - update_option( $option, $value ); - } - `; - - return JSON.parse( wpCli( [ - `--url=${ baseURL }`, 'eval', - ` - // Read and restore the stored offset, not the value calculated for a named timezone. - remove_filter( 'pre_option_gmt_offset', 'wp_timezone_override_offset' ); - ${ restore } - echo wp_json_encode( array( - 'timezone_string' => get_option( 'timezone_string' ), - 'gmt_offset' => get_option( 'gmt_offset' ), - ) ); - `, - ] ) ); -} +import { test, expect } from '../fixtures'; test.describe( 'Settings -> General', () => { const invalidTimezones = [ '', '0', 'Barry/Gary' ]; - let originalOptions; - test.beforeEach( async ( { admin, baseURL } ) => { - originalOptions = undefined; - originalOptions = timezoneOptions( baseURL ); + test.beforeEach( async ( { admin } ) => { await admin.visitAdminPage( '/options-general.php' ); } ); - test.afterEach( async ( { baseURL } ) => { - if ( originalOptions === undefined ) { - return; - } + for ( const invalidTimezone of invalidTimezones ) { + test( `Does not allow saving an invalid timezone string with "${invalidTimezone}"`, async ( { admin, page, siteOptions } ) => { + const originalOptions = await siteOptions.get( [ 'timezone_string', 'gmt_offset' ] ); - // The settings form can normalize stored UTC offsets, so restore the options directly. - expect( timezoneOptions( baseURL, originalOptions ) ).toEqual( originalOptions ); - } ); + // The settings form can normalize stored UTC offsets, so register the options for the fixture to restore directly. + await siteOptions.set( originalOptions ); - for ( const invalidTimezone of invalidTimezones ) { - test( `Does not allow saving an invalid timezone string with "${invalidTimezone}"`, async ( { admin, page } ) => { const validTimezone = originalOptions.timezone_string === 'Europe/Lisbon' ? 'Africa/Libreville' : 'Europe/Lisbon'; // Set the timezone to a different valid value. diff --git a/tests/e2e/specs/login-localize-script.test.js b/tests/e2e/specs/login-localize-script.test.js index 652a18954820a..54eed0cac0427 100644 --- a/tests/e2e/specs/login-localize-script.test.js +++ b/tests/e2e/specs/login-localize-script.test.js @@ -1,24 +1,13 @@ /** - * External dependencies + * Internal dependencies */ -import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs'; -import { join } from 'node:path'; - -/** - * WordPress dependencies - */ -import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +import { test, expect } from '../fixtures'; test.describe( 'Localize Script on wp-login.php', () => { - const muPlugins = join( - process.cwd(), - process.env.LOCAL_DIR ?? 'src', - 'wp-content/mu-plugins' - ); - const muPluginFile = join( muPlugins, 'login-test.php' ); - - test.beforeAll( async () => { - const muPluginCode = ` { + await muPlugin.write( + 'login-test.php', + ` { ] ); } - );`; - - if ( ! existsSync( muPlugins ) ) { - mkdirSync( muPlugins, { recursive: true } ); - } - writeFileSync( muPluginFile, muPluginCode ); - } ); - - test.afterAll( async () => { - unlinkSync( muPluginFile ); - } ); + );` + ); - test( 'should localize script', async ( { page } ) => { await page.goto( '/wp-login.php' ); await expect( page.getByRole( 'button', { name: 'Log In', exact: true } ) diff --git a/tests/e2e/specs/privacy.test.js b/tests/e2e/specs/privacy.test.js index 44094fa572e34..edc3193ba0b36 100644 --- a/tests/e2e/specs/privacy.test.js +++ b/tests/e2e/specs/privacy.test.js @@ -1,46 +1,26 @@ /** - * WordPress dependencies + * Internal dependencies */ -import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +import { test, expect } from '../fixtures'; function normalizeText( text ) { return text.replace( /\s+/g, ' ' ).trim(); } test.describe( 'Privacy page creation', () => { - let originalSettings; let createdPageId; - test.beforeEach( async ( { requestUtils } ) => { - originalSettings = undefined; + test.beforeEach( () => { createdPageId = undefined; - originalSettings = await requestUtils.rest( { - path: '/wp/v2/settings', - } ); } ); test.afterEach( async ( { requestUtils } ) => { - if ( ! originalSettings ) { - return; - } - - try { + if ( createdPageId ) { await requestUtils.rest( { - method: 'POST', - path: '/wp/v2/settings', - data: { - page_for_privacy_policy: - originalSettings.page_for_privacy_policy, - }, + method: 'DELETE', + path: `/wp/v2/pages/${ createdPageId }`, + params: { force: true }, } ); - } finally { - if ( createdPageId ) { - await requestUtils.rest( { - method: 'DELETE', - path: `/wp/v2/pages/${ createdPageId }`, - params: { force: true }, - } ); - } } } ); @@ -48,7 +28,12 @@ test.describe( 'Privacy page creation', () => { admin, page, requestUtils, + siteSettings, } ) => { + // The form changes this setting, so register it for the fixture to restore. + const { page_for_privacy_policy } = await siteSettings.get(); + await siteSettings.set( { page_for_privacy_policy } ); + await admin.visitAdminPage( 'options-privacy.php' ); await Promise.all( [ page From 17c142193f0a25109d7eb74bf8ac04a128eee8b7 Mon Sep 17 00:00:00 2001 From: Lance Willett Date: Fri, 6 Nov 2026 17:12:06 +0000 Subject: [PATCH 297/481] Tests: Make template, theme and other data providers public and static. Update the template, theme, view configuration, Ajax time format and PHPUnit group filter test providers for newer PHPUnit versions. Two providers used `$this`: the late-printed styles provider now uses static closures with `self::assert*()`, and the default themes list is now a static property. Developed in: https://github.com/WordPress/wordpress-develop/pull/15730, https://github.com/WordPress/wordpress-develop/pull/15731, https://github.com/WordPress/wordpress-develop/pull/15732, https://github.com/WordPress/wordpress-develop/pull/15733, https://github.com/WordPress/wordpress-develop/pull/15734, https://github.com/WordPress/wordpress-develop/pull/15442, https://github.com/WordPress/wordpress-develop/pull/15438 Props fozlerabbi48, devmuhib. See #66211. git-svn-id: https://develop.svn.wordpress.org/trunk@65313 602fd350-edb4-49c9-b593-d223f7449a82 --- .../ajax-actions/wpAjaxTimeFormat.php | 2 +- tests/phpunit/tests/phpunit/groupFilters.php | 2 +- tests/phpunit/tests/template.php | 22 ++++++++--------- tests/phpunit/tests/theme.php | 24 +++++++++---------- tests/phpunit/tests/view-config.php | 4 ++-- 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxTimeFormat.php b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxTimeFormat.php index 6c2f315458b5e..856eecdbb710c 100644 --- a/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxTimeFormat.php +++ b/tests/phpunit/tests/admin/includes/ajax-actions/wpAjaxTimeFormat.php @@ -140,7 +140,7 @@ public function test_unprivileged_user(): void { * }, * }> */ - public function data_time_format(): array { + public static function data_time_format(): array { return array( 'standard_time' => array( 'payload' => array( diff --git a/tests/phpunit/tests/phpunit/groupFilters.php b/tests/phpunit/tests/phpunit/groupFilters.php index eea4333e7ce00..2ae59209af806 100644 --- a/tests/phpunit/tests/phpunit/groupFilters.php +++ b/tests/phpunit/tests/phpunit/groupFilters.php @@ -40,7 +40,7 @@ public function test_requested_group_is_not_reported_as_default_excluded( $argum * * @return array>> */ - public function data_group_argument_syntax() { + public static function data_group_argument_syntax() { return array( 'spaced' => array( array( 'phpunit', '--group', 'ajax' ) ), 'equals' => array( array( 'phpunit', '--group=ajax' ) ), diff --git a/tests/phpunit/tests/template.php b/tests/phpunit/tests/template.php index 35003da308fbf..78042b2d96c01 100644 --- a/tests/phpunit/tests/template.php +++ b/tests/phpunit/tests/template.php @@ -1039,7 +1039,7 @@ public function test_wp_start_template_enhancement_output_buffer_for_json(): voi * expected_displayed_errors: string[], * }> */ - public function data_provider_to_test_wp_finalize_template_enhancement_output_buffer_with_errors_while_processing(): array { + public static function data_provider_to_test_wp_finalize_template_enhancement_output_buffer_with_errors_while_processing(): array { $log_and_display_all = array( 'error_reporting' => E_ALL, 'display_errors' => true, @@ -1429,7 +1429,7 @@ public function test_wp_load_classic_theme_block_styles_on_demand_in_block_theme * * @return array */ - public function data_wp_load_classic_theme_block_styles_on_demand(): array { + public static function data_wp_load_classic_theme_block_styles_on_demand(): array { return array( 'block_theme' => array( 'theme' => 'block-theme', @@ -1514,7 +1514,7 @@ public function test_wp_load_classic_theme_block_styles_on_demand( string $theme * assert?: Closure( string, string ): void, * }> */ - public function data_wp_hoist_late_printed_styles(): array { + public static function data_wp_hoist_late_printed_styles(): array { $blocks_content = '
    This is only a test!
    '; $early_common_styles = array( @@ -1718,7 +1718,7 @@ static function () { ), 'BODY' => array(), ), - 'assert' => function ( string $buffer, string $filtered_buffer ) { + 'assert' => static function ( string $buffer, string $filtered_buffer ) { $block_separator_core_style_span = null; $block_separator_custom_style_span = null; $processor = new class( $filtered_buffer ) extends WP_HTML_Tag_Processor { @@ -1743,9 +1743,9 @@ public function get_span(): WP_HTML_Span { } } - $this->assertInstanceOf( WP_HTML_Span::class, $block_separator_core_style_span, 'Expected the block separator core style to be present.' ); - $this->assertInstanceOf( WP_HTML_Span::class, $block_separator_custom_style_span, 'Expected the block separator custom style to be present.' ); - $this->assertGreaterThan( $block_separator_core_style_span->start, $block_separator_custom_style_span->start, 'Expected the block separator custom style to appear after the block separator stylesheet.' ); + self::assertInstanceOf( WP_HTML_Span::class, $block_separator_core_style_span, 'Expected the block separator core style to be present.' ); + self::assertInstanceOf( WP_HTML_Span::class, $block_separator_custom_style_span, 'Expected the block separator custom style to be present.' ); + self::assertGreaterThan( $block_separator_core_style_span->start, $block_separator_custom_style_span->start, 'Expected the block separator custom style to appear after the block separator stylesheet.' ); }, ), @@ -1779,14 +1779,14 @@ static function () { ), 'BODY' => array(), ), - 'assert' => function ( string $buffer, string $filtered_buffer ) { + 'assert' => static function ( string $buffer, string $filtered_buffer ) { $block_separator_inline_style_start_tag = '