Browse Source

update tests

windhamdavid 3 years ago
parent
commit
6e23193e8d
100 changed files with 19103 additions and 1 deletions
  1. 1 1
      .gitignore
  2. 136 0
      tests/e2e/config/bootstrap.js
  3. 10 0
      tests/e2e/jest.config.js
  4. 17 0
      tests/e2e/run-tests.js
  5. 11 0
      tests/e2e/specs/hello.test.js
  6. 13 0
      tests/gutenberg/.wp-env.sample.json
  7. 98 0
      tests/gutenberg/run.js
  8. 1318 0
      tests/phpunit/includes/abstract-testcase.php
  9. 42 0
      tests/phpunit/includes/class-basic-object.php
  10. 17 0
      tests/phpunit/includes/class-basic-subclass.php
  11. 21 0
      tests/phpunit/includes/class-jsonserializable-object.php
  12. 27 0
      tests/phpunit/includes/class-wp-fake-block-type.php
  13. 60 0
      tests/phpunit/includes/class-wp-rest-test-configurable-controller.php
  14. 91 0
      tests/phpunit/includes/class-wp-rest-test-search-handler.php
  15. 38 0
      tests/phpunit/includes/class-wp-sitemaps-empty-test-provider.php
  16. 59 0
      tests/phpunit/includes/class-wp-sitemaps-large-test-provider.php
  17. 52 0
      tests/phpunit/includes/class-wp-sitemaps-test-provider.php
  18. 248 0
      tests/phpunit/includes/class-wp-test-stream.php
  19. 29 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-callback-after-create.php
  20. 76 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php
  21. 91 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-blog.php
  22. 37 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-bookmark.php
  23. 74 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-comment.php
  24. 44 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-network.php
  25. 60 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-post.php
  26. 108 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-term.php
  27. 206 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-thing.php
  28. 58 0
      tests/phpunit/includes/factory/class-wp-unittest-factory-for-user.php
  29. 95 0
      tests/phpunit/includes/factory/class-wp-unittest-factory.php
  30. 45 0
      tests/phpunit/includes/factory/class-wp-unittest-generator-sequence.php
  31. 7 0
      tests/phpunit/includes/listener-loader.php
  32. 76 0
      tests/phpunit/includes/normalize-xml.xsl
  33. 2187 0
      tests/phpunit/includes/object-cache.php
  34. 41 0
      tests/phpunit/includes/phpunit6/compat.php
  35. 43 0
      tests/phpunit/includes/phpunit7/MockObject/Builder/NamespaceMatch.php
  36. 66 0
      tests/phpunit/includes/phpunit7/MockObject/Builder/ParametersMatch.php
  37. 2 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/deprecation.tpl.dist
  38. 46 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_class.tpl.dist
  39. 8 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_class_method.tpl.dist
  40. 4 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_clone.tpl.dist
  41. 22 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_method.tpl.dist
  42. 20 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_method_void.tpl.dist
  43. 5 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_static_method.tpl.dist
  44. 26 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/proxied_method.tpl.dist
  45. 26 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/proxied_method_void.tpl.dist
  46. 4 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/trait_class.tpl.dist
  47. 5 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/unmocked_clone.tpl.dist
  48. 7 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/wsdl_class.tpl.dist
  49. 4 0
      tests/phpunit/includes/phpunit7/MockObject/Generator/wsdl_method.tpl.dist
  50. 192 0
      tests/phpunit/includes/phpunit7/MockObject/InvocationMocker.php
  51. 33 0
      tests/phpunit/includes/phpunit7/MockObject/LICENSE
  52. 363 0
      tests/phpunit/includes/phpunit7/MockObject/MockMethod.php
  53. 307 0
      tests/phpunit/includes/phpunit7/speed-trap-listener.php
  54. 40 0
      tests/phpunit/includes/phpunit7/testcase.php
  55. 20 0
      tests/phpunit/includes/plural-form-function.php
  56. 306 0
      tests/phpunit/includes/speed-trap-listener.php
  57. 88 0
      tests/phpunit/includes/spy-rest-server.php
  58. 772 0
      tests/phpunit/includes/testcase-block-supports.php
  59. 357 0
      tests/phpunit/includes/testcase-canonical.php
  60. 19 0
      tests/phpunit/includes/testcase-rest-api.php
  61. 52 0
      tests/phpunit/includes/testcase-rest-controller.php
  62. 317 0
      tests/phpunit/includes/testcase-rest-post-type-controller.php
  63. 92 0
      tests/phpunit/includes/testcase-xml.php
  64. 83 0
      tests/phpunit/tests/admin/includesComment.php
  65. 580 0
      tests/phpunit/tests/admin/includesCommunityEvents.php
  66. 462 0
      tests/phpunit/tests/admin/includesListTable.php
  67. 293 0
      tests/phpunit/tests/admin/includesSchema.php
  68. 58 0
      tests/phpunit/tests/admin/includesUser.php
  69. 182 0
      tests/phpunit/tests/admin/wpPrivacyRequestsTable.php
  70. 71 0
      tests/phpunit/tests/ajax/AddMeta.php
  71. 118 0
      tests/phpunit/tests/ajax/Attachments.php
  72. 717 0
      tests/phpunit/tests/ajax/CustomizeManager.php
  73. 784 0
      tests/phpunit/tests/ajax/CustomizeMenus.php
  74. 158 0
      tests/phpunit/tests/ajax/DeletePlugin.php
  75. 173 0
      tests/phpunit/tests/ajax/ManageThemes.php
  76. 839 0
      tests/phpunit/tests/ajax/PrivacyErasePersonalData.php
  77. 842 0
      tests/phpunit/tests/ajax/PrivacyExportPersonalData.php
  78. 86 0
      tests/phpunit/tests/ajax/QuickEdit.php
  79. 169 0
      tests/phpunit/tests/ajax/UpdatePlugin.php
  80. 283 0
      tests/phpunit/tests/avatar.php
  81. 215 0
      tests/phpunit/tests/blocks/block-context.php
  82. 112 0
      tests/phpunit/tests/blocks/block-list.php
  83. 119 0
      tests/phpunit/tests/blocks/block-parser.php
  84. 191 0
      tests/phpunit/tests/blocks/block-type-registry.php
  85. 422 0
      tests/phpunit/tests/blocks/block-type.php
  86. 416 0
      tests/phpunit/tests/blocks/block.php
  87. 499 0
      tests/phpunit/tests/blocks/register.php
  88. 134 0
      tests/phpunit/tests/blocks/render-reusable.php
  89. 503 0
      tests/phpunit/tests/blocks/render.php
  90. 60 0
      tests/phpunit/tests/blocks/serialization.php
  91. 151 0
      tests/phpunit/tests/bookmark/getBookmarks.php
  92. 111 0
      tests/phpunit/tests/canonical/category.php
  93. 54 0
      tests/phpunit/tests/canonical/https.php
  94. 30 0
      tests/phpunit/tests/canonical/paged.php
  95. 973 0
      tests/phpunit/tests/canonical/postStatus.php
  96. 16 0
      tests/phpunit/tests/canonical/robots.php
  97. 114 0
      tests/phpunit/tests/canonical/sitemaps.php
  98. 245 0
      tests/phpunit/tests/category.php
  99. 86 0
      tests/phpunit/tests/category/categoryDescription.php
  100. 15 0
      tests/phpunit/tests/category/getCategories.php

+ 1 - 1
.gitignore

@@ -33,9 +33,9 @@ wp-tests-config.php
 bin/
 src
 build
-tests/*
 tools/*
 phpunit.xml
+tests/phpunit/data/*
 tests/phpunit/build
 tests/phpunit/data/plugins/wordpress-importer
 tests/phpunit/data/.trac-ticket-cache*

+ 136 - 0
tests/e2e/config/bootstrap.js

@@ -0,0 +1,136 @@
+import { get } from 'lodash';
+import {
+	clearLocalStorage,
+	enablePageDialogAccept,
+	setBrowserViewport,
+} from '@wordpress/e2e-test-utils';
+
+/**
+ * Environment variables
+ */
+const { PUPPETEER_TIMEOUT } = process.env;
+
+/**
+ * Set of console logging types observed to protect against unexpected yet
+ * handled (i.e. not catastrophic) errors or warnings. Each key corresponds
+ * to the Puppeteer ConsoleMessage type, its value the corresponding function
+ * on the console global object.
+ *
+ * @type {Object<string,string>}
+ */
+const OBSERVED_CONSOLE_MESSAGE_TYPES = {
+	warning: 'warn',
+	error: 'error',
+};
+
+/**
+ * Array of page event tuples of [ eventName, handler ].
+ *
+ * @type {Array}
+ */
+const pageEvents = [];
+
+// The Jest timeout is increased because these tests are a bit slow
+jest.setTimeout( PUPPETEER_TIMEOUT || 100000 );
+
+
+/**
+ * Adds an event listener to the page to handle additions of page event
+ * handlers, to assure that they are removed at test teardown.
+ */
+function capturePageEventsForTearDown() {
+	page.on( 'newListener', ( eventName, listener ) => {
+		pageEvents.push( [ eventName, listener ] );
+	} );
+}
+
+/**
+ * Removes all bound page event handlers.
+ */
+function removePageEvents() {
+	pageEvents.forEach( ( [ eventName, handler ] ) => {
+		page.removeListener( eventName, handler );
+	} );
+}
+
+/**
+ * Adds a page event handler to emit uncaught exception to process if one of
+ * the observed console logging types is encountered.
+ */
+function observeConsoleLogging() {
+	page.on( 'console', ( message ) => {
+		const type = message.type();
+		if ( ! OBSERVED_CONSOLE_MESSAGE_TYPES.hasOwnProperty( type ) ) {
+			return;
+		}
+
+		let text = message.text();
+
+		// An exception is made for _blanket_ deprecation warnings: Those
+		// which log regardless of whether a deprecated feature is in use.
+		if ( text.includes( 'This is a global warning' ) ) {
+			return;
+		}
+
+		// Viewing posts on the front end can result in this error, which
+		// has nothing to do with Gutenberg.
+		if ( text.includes( 'net::ERR_UNKNOWN_URL_SCHEME' ) ) {
+			return;
+		}
+
+		// A bug present in WordPress 5.2 will produce console warnings when
+		// loading the Dashicons font. These can be safely ignored, as they do
+		// not otherwise regress on application behavior. This logic should be
+		// removed once the associated ticket has been closed.
+		//
+		// See: https://core.trac.wordpress.org/ticket/47183
+		if (
+			text.startsWith( 'Failed to decode downloaded font:' ) ||
+			text.startsWith( 'OTS parsing error:' )
+		) {
+			return;
+		}
+
+		const logFunction = OBSERVED_CONSOLE_MESSAGE_TYPES[ type ];
+
+		// As of Puppeteer 1.6.1, `message.text()` wrongly returns an object of
+		// type JSHandle for error logging, instead of the expected string.
+		//
+		// See: https://github.com/GoogleChrome/puppeteer/issues/3397
+		//
+		// The recommendation there to asynchronously resolve the error value
+		// upon a console event may be prone to a race condition with the test
+		// completion, leaving a possibility of an error not being surfaced
+		// correctly. Instead, the logic here synchronously inspects the
+		// internal object shape of the JSHandle to find the error text. If it
+		// cannot be found, the default text value is used instead.
+		text = get( message.args(), [ 0, '_remoteObject', 'description' ], text );
+
+		// Disable reason: We intentionally bubble up the console message
+		// which, unless the test explicitly anticipates the logging via
+		// @wordpress/jest-console matchers, will cause the intended test
+		// failure.
+
+		// eslint-disable-next-line no-console
+		console[ logFunction ]( text );
+	} );
+}
+
+// Before every test suite run, delete all content created by the test. This ensures
+// other posts/comments/etc. aren't dirtying tests and tests don't depend on
+// each other's side-effects.
+beforeAll( async () => {
+	capturePageEventsForTearDown();
+	enablePageDialogAccept();
+	observeConsoleLogging();
+	await setBrowserViewport( 'large' );
+} );
+
+afterEach( async () => {
+	await clearLocalStorage();
+	await setBrowserViewport( 'large' );
+} );
+
+afterAll( () => {
+	removePageEvents();
+} );

+ 10 - 0
tests/e2e/jest.config.js

@@ -0,0 +1,10 @@
+const config = require( '@wordpress/scripts/config/jest-e2e.config' );
+
+const jestE2EConfig = {
+	...config,
+	setupFilesAfterEnv: [
+		'<rootDir>/config/bootstrap.js',
+	],
+};
+
+module.exports = jestE2EConfig;

+ 17 - 0
tests/e2e/run-tests.js

@@ -0,0 +1,17 @@
+const dotenv = require( 'dotenv' );
+const dotenv_expand = require( 'dotenv-expand' );
+const { sync: spawn } = require( 'cross-spawn' );
+const { execSync } = require( 'child_process' );
+
+// WP_BASE_URL interpolates LOCAL_PORT, so needs to be parsed by dotenv_expand().
+dotenv_expand( dotenv.config() );
+
+const result = spawn( 'node', [ require.resolve( 'puppeteer/install' ) ], {
+	stdio: 'inherit',
+} );
+if ( result.status > 0 ) {
+	process.exit( result.status );
+}
+
+// Run the tests, passing additional arguments through to the test script.
+execSync( 'wp-scripts test-e2e --config tests/e2e/jest.config.js ' + process.argv.slice( 2 ).join( ' ' ), { stdio: 'inherit' } );

+ 11 - 0
tests/e2e/specs/hello.test.js

@@ -0,0 +1,11 @@
+import { visitAdminPage } from '@wordpress/e2e-test-utils';
+
+describe( 'Hello World', () => {
+	it( 'Should load properly', async () => {
+		await visitAdminPage( '/' );
+		const nodes = await page.$x(
+			'//h2[contains(text(), "Welcome to WordPress!")]'
+		);
+		expect( nodes.length ).not.toEqual( 0 );
+	} );
+} );

+ 13 - 0
tests/gutenberg/.wp-env.sample.json

@@ -0,0 +1,13 @@
+{
+	"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"
+	}
+}

+ 98 - 0
tests/gutenberg/run.js

@@ -0,0 +1,98 @@
+#!/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
+// This should be updated every time we update the WordPress packages.
+const GUTENBERG_VERSION = '@wordpress/block-editor@5.0.1';
+
+// 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 );

+ 1318 - 0
tests/phpunit/includes/abstract-testcase.php

@@ -0,0 +1,1318 @@
+<?php
+
+require_once __DIR__ . '/factory.php';
+require_once __DIR__ . '/trac.php';
+
+/**
+ * Defines a basic fixture to run multiple tests.
+ *
+ * Resets the state of the WordPress installation before and after every test.
+ *
+ * Includes utility functions and assertions useful for testing WordPress.
+ *
+ * All WordPress unit tests should inherit from this class.
+ */
+abstract class WP_UnitTestCase_Base extends PHPUnit\Framework\TestCase {
+
+	protected static $forced_tickets   = array();
+	protected $expected_deprecated     = array();
+	protected $caught_deprecated       = array();
+	protected $expected_doing_it_wrong = array();
+	protected $caught_doing_it_wrong   = array();
+
+	protected static $hooks_saved = array();
+	protected static $ignore_files;
+
+	public function __isset( $name ) {
+		return 'factory' === $name;
+	}
+
+	public function __get( $name ) {
+		if ( 'factory' === $name ) {
+			return self::factory();
+		}
+	}
+
+	/**
+	 * Fetches the factory object for generating WordPress fixtures.
+	 *
+	 * @return WP_UnitTest_Factory The fixture factory.
+	 */
+	protected static function factory() {
+		static $factory = null;
+		if ( ! $factory ) {
+			$factory = new WP_UnitTest_Factory();
+		}
+		return $factory;
+	}
+
+	/**
+	 * Retrieves the name of the class the static method is called in.
+	 *
+	 * @deprecated 5.3.0 Use the PHP native get_called_class() function instead.
+	 *
+	 * @return string The class name.
+	 */
+	public static function get_called_class() {
+		return get_called_class();
+	}
+
+	/**
+	 * Runs the routine before setting up all tests.
+	 */
+	public static function setUpBeforeClass() {
+		global $wpdb;
+
+		$wpdb->suppress_errors = false;
+		$wpdb->show_errors     = true;
+		$wpdb->db_connect();
+		ini_set( 'display_errors', 1 );
+
+		parent::setUpBeforeClass();
+
+		$class = get_called_class();
+
+		if ( method_exists( $class, 'wpSetUpBeforeClass' ) ) {
+			call_user_func( array( $class, 'wpSetUpBeforeClass' ), self::factory() );
+		}
+
+		self::commit_transaction();
+	}
+
+	/**
+	 * Runs the routine after all tests have been run.
+	 */
+	public static function tearDownAfterClass() {
+		parent::tearDownAfterClass();
+
+		_delete_all_data();
+		self::flush_cache();
+
+		$class = get_called_class();
+
+		if ( method_exists( $class, 'wpTearDownAfterClass' ) ) {
+			call_user_func( array( $class, 'wpTearDownAfterClass' ) );
+		}
+
+		self::commit_transaction();
+	}
+
+	/**
+	 * Runs the routine before each test is executed.
+	 */
+	public function setUp() {
+		set_time_limit( 0 );
+
+		if ( ! self::$ignore_files ) {
+			self::$ignore_files = $this->scan_user_uploads();
+		}
+
+		if ( ! self::$hooks_saved ) {
+			$this->_backup_hooks();
+		}
+
+		global $wp_rewrite;
+
+		$this->clean_up_global_scope();
+
+		/*
+		 * When running core tests, ensure that post types and taxonomies
+		 * are reset for each test. We skip this step for non-core tests,
+		 * given the large number of plugins that register post types and
+		 * taxonomies at 'init'.
+		 */
+		if ( defined( 'WP_RUN_CORE_TESTS' ) && WP_RUN_CORE_TESTS ) {
+			$this->reset_post_types();
+			$this->reset_taxonomies();
+			$this->reset_post_statuses();
+			$this->reset__SERVER();
+
+			if ( $wp_rewrite->permalink_structure ) {
+				$this->set_permalink_structure( '' );
+			}
+		}
+
+		$this->start_transaction();
+		$this->expectDeprecated();
+		add_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
+	}
+
+	/**
+	 * After a test method runs, reset any state in WordPress the test method might have changed.
+	 */
+	public function tearDown() {
+		global $wpdb, $wp_query, $wp;
+		$wpdb->query( 'ROLLBACK' );
+		if ( is_multisite() ) {
+			while ( ms_is_switched() ) {
+				restore_current_blog();
+			}
+		}
+		$wp_query = new WP_Query();
+		$wp       = new WP();
+
+		// Reset globals related to the post loop and `setup_postdata()`.
+		$post_globals = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' );
+		foreach ( $post_globals as $global ) {
+			$GLOBALS[ $global ] = null;
+		}
+
+		// Reset $wp_sitemap global so that sitemap-related dynamic $wp->public_query_vars are added when the next test runs.
+		$GLOBALS['wp_sitemaps'] = null;
+
+		$this->unregister_all_meta_keys();
+		remove_theme_support( 'html5' );
+		remove_filter( 'query', array( $this, '_create_temporary_tables' ) );
+		remove_filter( 'query', array( $this, '_drop_temporary_tables' ) );
+		remove_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
+		$this->_restore_hooks();
+		wp_set_current_user( 0 );
+	}
+
+	/**
+	 * Cleans the global scope (e.g `$_GET` and `$_POST`).
+	 */
+	public function clean_up_global_scope() {
+		$_GET  = array();
+		$_POST = array();
+		self::flush_cache();
+	}
+
+	/**
+	 * Allow tests to be skipped on some automated runs.
+	 *
+	 * For test runs on Travis/GitHub Actions for something other than trunk/master,
+	 * we want to skip tests that only need to run for master.
+	 */
+	public function skipOnAutomatedBranches() {
+		// https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
+		$travis_branch       = getenv( 'TRAVIS_BRANCH' );
+		$travis_pull_request = getenv( 'TRAVIS_PULL_REQUEST' );
+
+		// https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables
+		$github_event_name = getenv( 'GITHUB_EVENT_NAME' );
+		$github_ref        = getenv( 'GITHUB_REF' );
+
+		if ( $github_event_name && 'false' !== $github_event_name ) {
+			// We're on GitHub Actions.
+			$skipped = array( 'pull_request', 'pull_request_target' );
+
+			if ( in_array( $github_event_name, $skipped, true ) || 'refs/heads/master' !== $github_ref ) {
+				$this->markTestSkipped( 'For automated test runs, this test is only run on trunk/master' );
+			}
+		} elseif ( $travis_branch && 'false' !== $travis_branch ) {
+			// We're on Travis CI.
+			if ( 'master' !== $travis_branch || 'false' !== $travis_pull_request ) {
+				$this->markTestSkipped( 'For automated test runs, this test is only run on trunk/master' );
+			}
+		}
+	}
+
+	/**
+	 * Allow tests to be skipped when Multisite is not in use.
+	 *
+	 * Use in conjunction with the ms-required group.
+	 */
+	public function skipWithoutMultisite() {
+		if ( ! is_multisite() ) {
+			$this->markTestSkipped( 'Test only runs on Multisite' );
+		}
+	}
+
+	/**
+	 * Allow tests to be skipped when Multisite is in use.
+	 *
+	 * Use in conjunction with the ms-excluded group.
+	 */
+	public function skipWithMultisite() {
+		if ( is_multisite() ) {
+			$this->markTestSkipped( 'Test does not run on Multisite' );
+		}
+	}
+
+	/**
+	 * Allow tests to be skipped if the HTTP request times out.
+	 *
+	 * @param array|WP_Error $response HTTP response.
+	 */
+	public function skipTestOnTimeout( $response ) {
+		if ( ! is_wp_error( $response ) ) {
+			return;
+		}
+		if ( 'connect() timed out!' === $response->get_error_message() ) {
+			$this->markTestSkipped( 'HTTP timeout' );
+		}
+
+		if ( false !== strpos( $response->get_error_message(), 'timed out after' ) ) {
+			$this->markTestSkipped( 'HTTP timeout' );
+		}
+
+		if ( 0 === strpos( $response->get_error_message(), 'stream_socket_client(): unable to connect to tcp://s.w.org:80' ) ) {
+			$this->markTestSkipped( 'HTTP timeout' );
+		}
+
+	}
+
+	/**
+	 * Unregister existing post types and register defaults.
+	 *
+	 * Run before each test in order to clean up the global scope, in case
+	 * a test forgets to unregister a post type on its own, or fails before
+	 * it has a chance to do so.
+	 */
+	protected function reset_post_types() {
+		foreach ( get_post_types( array(), 'objects' ) as $pt ) {
+			if ( empty( $pt->tests_no_auto_unregister ) ) {
+				_unregister_post_type( $pt->name );
+			}
+		}
+		create_initial_post_types();
+	}
+
+	/**
+	 * Unregister existing taxonomies and register defaults.
+	 *
+	 * Run before each test in order to clean up the global scope, in case
+	 * a test forgets to unregister a taxonomy on its own, or fails before
+	 * it has a chance to do so.
+	 */
+	protected function reset_taxonomies() {
+		foreach ( get_taxonomies() as $tax ) {
+			_unregister_taxonomy( $tax );
+		}
+		create_initial_taxonomies();
+	}
+
+	/**
+	 * Unregister non-built-in post statuses.
+	 */
+	protected function reset_post_statuses() {
+		foreach ( get_post_stati( array( '_builtin' => false ) ) as $post_status ) {
+			_unregister_post_status( $post_status );
+		}
+	}
+
+	/**
+	 * Reset `$_SERVER` variables
+	 */
+	protected function reset__SERVER() {
+		tests_reset__SERVER();
+	}
+
+	/**
+	 * Saves the action and filter-related globals so they can be restored later.
+	 *
+	 * Stores $wp_actions, $wp_current_filter, and $wp_filter on a class variable
+	 * so they can be restored on tearDown() using _restore_hooks().
+	 *
+	 * @global array $wp_actions
+	 * @global array $wp_current_filter
+	 * @global array $wp_filter
+	 */
+	protected function _backup_hooks() {
+		$globals = array( 'wp_actions', 'wp_current_filter' );
+		foreach ( $globals as $key ) {
+			self::$hooks_saved[ $key ] = $GLOBALS[ $key ];
+		}
+		self::$hooks_saved['wp_filter'] = array();
+		foreach ( $GLOBALS['wp_filter'] as $hook_name => $hook_object ) {
+			self::$hooks_saved['wp_filter'][ $hook_name ] = clone $hook_object;
+		}
+	}
+
+	/**
+	 * Restores the hook-related globals to their state at setUp()
+	 * so that future tests aren't affected by hooks set during this last test.
+	 *
+	 * @global array $wp_actions
+	 * @global array $wp_current_filter
+	 * @global array $wp_filter
+	 */
+	protected function _restore_hooks() {
+		$globals = array( 'wp_actions', 'wp_current_filter' );
+		foreach ( $globals as $key ) {
+			if ( isset( self::$hooks_saved[ $key ] ) ) {
+				$GLOBALS[ $key ] = self::$hooks_saved[ $key ];
+			}
+		}
+		if ( isset( self::$hooks_saved['wp_filter'] ) ) {
+			$GLOBALS['wp_filter'] = array();
+			foreach ( self::$hooks_saved['wp_filter'] as $hook_name => $hook_object ) {
+				$GLOBALS['wp_filter'][ $hook_name ] = clone $hook_object;
+			}
+		}
+	}
+
+	/**
+	 * Flushes the WordPress object cache.
+	 */
+	public static function flush_cache() {
+		global $wp_object_cache;
+		$wp_object_cache->group_ops      = array();
+		$wp_object_cache->stats          = array();
+		$wp_object_cache->memcache_debug = array();
+		$wp_object_cache->cache          = array();
+		if ( method_exists( $wp_object_cache, '__remoteset' ) ) {
+			$wp_object_cache->__remoteset();
+		}
+		wp_cache_flush();
+		wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'useremail', 'userslugs', 'site-transient', 'site-options', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache', 'networks', 'sites', 'site-details', 'blog_meta' ) );
+		wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
+	}
+
+	/**
+	 * Clean up any registered meta keys.
+	 *
+	 * @since 5.1.0
+	 *
+	 * @global array $wp_meta_keys
+	 */
+	public function unregister_all_meta_keys() {
+		global $wp_meta_keys;
+		if ( ! is_array( $wp_meta_keys ) ) {
+			return;
+		}
+		foreach ( $wp_meta_keys as $object_type => $type_keys ) {
+			foreach ( $type_keys as $object_subtype => $subtype_keys ) {
+				foreach ( $subtype_keys as $key => $value ) {
+					unregister_meta_key( $object_type, $key, $object_subtype );
+				}
+			}
+		}
+	}
+
+	/**
+	 * Starts a database transaction.
+	 */
+	public function start_transaction() {
+		global $wpdb;
+		$wpdb->query( 'SET autocommit = 0;' );
+		$wpdb->query( 'START TRANSACTION;' );
+		add_filter( 'query', array( $this, '_create_temporary_tables' ) );
+		add_filter( 'query', array( $this, '_drop_temporary_tables' ) );
+	}
+
+	/**
+	 * Commit the queries in a transaction.
+	 *
+	 * @since 4.1.0
+	 */
+	public static function commit_transaction() {
+		global $wpdb;
+		$wpdb->query( 'COMMIT;' );
+	}
+
+	/**
+	 * Replaces the `CREATE TABLE` statement with a `CREATE TEMPORARY TABLE` statement.
+	 *
+	 * @param string $query The query to replace the statement for.
+	 * @return string The altered query.
+	 */
+	public function _create_temporary_tables( $query ) {
+		if ( 0 === strpos( trim( $query ), 'CREATE TABLE' ) ) {
+			return substr_replace( trim( $query ), 'CREATE TEMPORARY TABLE', 0, 12 );
+		}
+		return $query;
+	}
+
+	/**
+	 * Replaces the `DROP TABLE` statement with a `DROP TEMPORARY TABLE` statement.
+	 *
+	 * @param string $query The query to replace the statement for.
+	 * @return string The altered query.
+	 */
+	public function _drop_temporary_tables( $query ) {
+		if ( 0 === strpos( trim( $query ), 'DROP TABLE' ) ) {
+			return substr_replace( trim( $query ), 'DROP TEMPORARY TABLE', 0, 10 );
+		}
+		return $query;
+	}
+
+	/**
+	 * Retrieves the `wp_die()` handler.
+	 *
+	 * @param callable $handler The current die handler.
+	 * @return callable The test die handler.
+	 */
+	public function get_wp_die_handler( $handler ) {
+		return array( $this, 'wp_die_handler' );
+	}
+
+	/**
+	 * Throws an exception when called.
+	 *
+	 * @throws WPDieException Exception containing the message.
+	 *
+	 * @param string $message The `wp_die()` message.
+	 */
+	public function wp_die_handler( $message ) {
+		if ( is_wp_error( $message ) ) {
+			$message = $message->get_error_message();
+		}
+
+		if ( ! is_scalar( $message ) ) {
+			$message = '0';
+		}
+
+		throw new WPDieException( $message );
+	}
+
+	/**
+	 * Sets up the expectations for testing a deprecated call.
+	 */
+	public function expectDeprecated() {
+		$annotations = $this->getAnnotations();
+		foreach ( array( 'class', 'method' ) as $depth ) {
+			if ( ! empty( $annotations[ $depth ]['expectedDeprecated'] ) ) {
+				$this->expected_deprecated = array_merge( $this->expected_deprecated, $annotations[ $depth ]['expectedDeprecated'] );
+			}
+			if ( ! empty( $annotations[ $depth ]['expectedIncorrectUsage'] ) ) {
+				$this->expected_doing_it_wrong = array_merge( $this->expected_doing_it_wrong, $annotations[ $depth ]['expectedIncorrectUsage'] );
+			}
+		}
+		add_action( 'deprecated_function_run', array( $this, 'deprecated_function_run' ) );
+		add_action( 'deprecated_argument_run', array( $this, 'deprecated_function_run' ) );
+		add_action( 'deprecated_hook_run', array( $this, 'deprecated_function_run' ) );
+		add_action( 'doing_it_wrong_run', array( $this, 'doing_it_wrong_run' ) );
+		add_action( 'deprecated_function_trigger_error', '__return_false' );
+		add_action( 'deprecated_argument_trigger_error', '__return_false' );
+		add_action( 'deprecated_hook_trigger_error', '__return_false' );
+		add_action( 'doing_it_wrong_trigger_error', '__return_false' );
+	}
+
+	/**
+	 * Handles a deprecated expectation.
+	 *
+	 * The DocBlock should contain `@expectedDeprecated` to trigger this.
+	 */
+	public function expectedDeprecated() {
+		$errors = array();
+
+		$not_caught_deprecated = array_diff( $this->expected_deprecated, $this->caught_deprecated );
+		foreach ( $not_caught_deprecated as $not_caught ) {
+			$errors[] = "Failed to assert that $not_caught triggered a deprecated notice";
+		}
+
+		$unexpected_deprecated = array_diff( $this->caught_deprecated, $this->expected_deprecated );
+		foreach ( $unexpected_deprecated as $unexpected ) {
+			$errors[] = "Unexpected deprecated notice for $unexpected";
+		}
+
+		$not_caught_doing_it_wrong = array_diff( $this->expected_doing_it_wrong, $this->caught_doing_it_wrong );
+		foreach ( $not_caught_doing_it_wrong as $not_caught ) {
+			$errors[] = "Failed to assert that $not_caught triggered an incorrect usage notice";
+		}
+
+		$unexpected_doing_it_wrong = array_diff( $this->caught_doing_it_wrong, $this->expected_doing_it_wrong );
+		foreach ( $unexpected_doing_it_wrong as $unexpected ) {
+			$errors[] = "Unexpected incorrect usage notice for $unexpected";
+		}
+
+		// Perform an assertion, but only if there are expected or unexpected deprecated calls or wrongdoings.
+		if ( ! empty( $this->expected_deprecated ) ||
+			! empty( $this->expected_doing_it_wrong ) ||
+			! empty( $this->caught_deprecated ) ||
+			! empty( $this->caught_doing_it_wrong ) ) {
+			$this->assertEmpty( $errors, implode( "\n", $errors ) );
+		}
+	}
+
+	/**
+	 * Detect post-test failure conditions.
+	 *
+	 * We use this method to detect expectedDeprecated and expectedIncorrectUsage annotations.
+	 *
+	 * @since 4.2.0
+	 */
+	protected function assertPostConditions() {
+		$this->expectedDeprecated();
+	}
+
+	/**
+	 * Declare an expected `_deprecated_function()` or `_deprecated_argument()` call from within a test.
+	 *
+	 * @since 4.2.0
+	 *
+	 * @param string $deprecated Name of the function, method, class, or argument that is deprecated. Must match
+	 *                           the first parameter of the `_deprecated_function()` or `_deprecated_argument()` call.
+	 */
+	public function setExpectedDeprecated( $deprecated ) {
+		$this->expected_deprecated[] = $deprecated;
+	}
+
+	/**
+	 * Declare an expected `_doing_it_wrong()` call from within a test.
+	 *
+	 * @since 4.2.0
+	 *
+	 * @param string $doing_it_wrong Name of the function, method, or class that appears in the first argument
+	 *                               of the source `_doing_it_wrong()` call.
+	 */
+	public function setExpectedIncorrectUsage( $doing_it_wrong ) {
+		$this->expected_doing_it_wrong[] = $doing_it_wrong;
+	}
+
+	/**
+	 * PHPUnit 6+ compatibility shim.
+	 *
+	 * @param mixed      $exception
+	 * @param string     $message
+	 * @param int|string $code
+	 */
+	public function setExpectedException( $exception, $message = '', $code = null ) {
+		if ( method_exists( 'PHPUnit_Framework_TestCase', 'setExpectedException' ) ) {
+			parent::setExpectedException( $exception, $message, $code );
+		} else {
+			$this->expectException( $exception );
+			if ( '' !== $message ) {
+				$this->expectExceptionMessage( $message );
+			}
+			if ( null !== $code ) {
+				$this->expectExceptionCode( $code );
+			}
+		}
+	}
+
+	/**
+	 * Adds a deprecated function to the list of caught deprecated calls.
+	 *
+	 * @param string $function The deprecated function.
+	 */
+	public function deprecated_function_run( $function ) {
+		if ( ! in_array( $function, $this->caught_deprecated, true ) ) {
+			$this->caught_deprecated[] = $function;
+		}
+	}
+
+	/**
+	 * Adds a function called in a wrong way to the list of `_doing_it_wrong()` calls.
+	 *
+	 * @param string $function The function to add.
+	 */
+	public function doing_it_wrong_run( $function ) {
+		if ( ! in_array( $function, $this->caught_doing_it_wrong, true ) ) {
+			$this->caught_doing_it_wrong[] = $function;
+		}
+	}
+
+	/**
+	 * Asserts that the given value is an instance of WP_Error.
+	 *
+	 * @param mixed  $actual  The value to check.
+	 * @param string $message Optional. Message to display when the assertion fails.
+	 */
+	public function assertWPError( $actual, $message = '' ) {
+		$this->assertInstanceOf( 'WP_Error', $actual, $message );
+	}
+
+	/**
+	 * Asserts that the given value is not an instance of WP_Error.
+	 *
+	 * @param mixed  $actual  The value to check.
+	 * @param string $message Optional. Message to display when the assertion fails.
+	 */
+	public function assertNotWPError( $actual, $message = '' ) {
+		if ( '' === $message && is_wp_error( $actual ) ) {
+			$message = $actual->get_error_message();
+		}
+		$this->assertNotInstanceOf( 'WP_Error', $actual, $message );
+	}
+
+	/**
+	 * Asserts that the given value is an instance of IXR_Error.
+	 *
+	 * @param mixed  $actual  The value to check.
+	 * @param string $message Optional. Message to display when the assertion fails.
+	 */
+	public function assertIXRError( $actual, $message = '' ) {
+		$this->assertInstanceOf( 'IXR_Error', $actual, $message );
+	}
+
+	/**
+	 * Asserts that the given value is not an instance of IXR_Error.
+	 *
+	 * @param mixed  $actual  The value to check.
+	 * @param string $message Optional. Message to display when the assertion fails.
+	 */
+	public function assertNotIXRError( $actual, $message = '' ) {
+		if ( $actual instanceof IXR_Error && '' === $message ) {
+			$message = $actual->message;
+		}
+		$this->assertNotInstanceOf( 'IXR_Error', $actual, $message );
+	}
+
+	/**
+	 * Asserts that the given fields are present in the given object.
+	 *
+	 * @param object $object The object to check.
+	 * @param array  $fields The fields to check.
+	 */
+	public function assertEqualFields( $object, $fields ) {
+		foreach ( $fields as $field_name => $field_value ) {
+			if ( $object->$field_name !== $field_value ) {
+				$this->fail();
+			}
+		}
+	}
+
+	/**
+	 * Asserts that two values are equal, with whitespace differences discarded.
+	 *
+	 * @param string $expected The expected value.
+	 * @param string $actual   The actual value.
+	 */
+	public function assertDiscardWhitespace( $expected, $actual ) {
+		$this->assertEquals( preg_replace( '/\s*/', '', $expected ), preg_replace( '/\s*/', '', $actual ) );
+	}
+
+	/**
+	 * Asserts that two values have the same type and value, with EOL differences discarded.
+	 *
+	 * @since 5.6.0
+	 *
+	 * @param string $expected The expected value.
+	 * @param string $actual   The actual value.
+	 */
+	public function assertSameIgnoreEOL( $expected, $actual ) {
+		$this->assertSame( str_replace( "\r\n", "\n", $expected ), str_replace( "\r\n", "\n", $actual ) );
+	}
+
+	/**
+	 * Asserts that two values are equal, with EOL differences discarded.
+	 *
+	 * @since 5.4.0
+	 * @since 5.6.0 Turned into an alias for `::assertSameIgnoreEOL()`.
+	 *
+	 * @param string $expected The expected value.
+	 * @param string $actual   The actual value.
+	 */
+	public function assertEqualsIgnoreEOL( $expected, $actual ) {
+		$this->assertSameIgnoreEOL( $expected, $actual );
+	}
+
+	/**
+	 * Asserts that the contents of two un-keyed, single arrays are the same, without accounting for the order of elements.
+	 *
+	 * @since 5.6.0
+	 *
+	 * @param array $expected Expected array.
+	 * @param array $actual   Array to check.
+	 */
+	public function assertSameSets( $expected, $actual ) {
+		sort( $expected );
+		sort( $actual );
+		$this->assertSame( $expected, $actual );
+	}
+
+	/**
+	 * Asserts that the contents of two un-keyed, single arrays are equal, without accounting for the order of elements.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @param array $expected Expected array.
+	 * @param array $actual   Array to check.
+	 */
+	public function assertEqualSets( $expected, $actual ) {
+		sort( $expected );
+		sort( $actual );
+		$this->assertEquals( $expected, $actual );
+	}
+
+	/**
+	 * Asserts that the contents of two keyed, single arrays are the same, without accounting for the order of elements.
+	 *
+	 * @since 5.6.0
+	 *
+	 * @param array $expected Expected array.
+	 * @param array $actual   Array to check.
+	 */
+	public function assertSameSetsWithIndex( $expected, $actual ) {
+		ksort( $expected );
+		ksort( $actual );
+		$this->assertSame( $expected, $actual );
+	}
+
+	/**
+	 * Asserts that the contents of two keyed, single arrays are equal, without accounting for the order of elements.
+	 *
+	 * @since 4.1.0
+	 *
+	 * @param array $expected Expected array.
+	 * @param array $actual   Array to check.
+	 */
+	public function assertEqualSetsWithIndex( $expected, $actual ) {
+		ksort( $expected );
+		ksort( $actual );
+		$this->assertEquals( $expected, $actual );
+	}
+
+	/**
+	 * Asserts that the given variable is a multidimensional array, and that all arrays are non-empty.
+	 *
+	 * @since 4.8.0
+	 *
+	 * @param array $array Array to check.
+	 */
+	public function assertNonEmptyMultidimensionalArray( $array ) {
+		$this->assertTrue( is_array( $array ) );
+		$this->assertNotEmpty( $array );
+
+		foreach ( $array as $sub_array ) {
+			$this->assertTrue( is_array( $sub_array ) );
+			$this->assertNotEmpty( $sub_array );
+		}
+	}
+
+	/**
+	 * Sets the global state to as if a given URL has been requested.
+	 *
+	 * This sets:
+	 * - The super globals.
+	 * - The globals.
+	 * - The query variables.
+	 * - The main query.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @param string $url The URL for the request.
+	 */
+	public function go_to( $url ) {
+		/*
+		 * Note: the WP and WP_Query classes like to silently fetch parameters
+		 * from all over the place (globals, GET, etc), which makes it tricky
+		 * to run them more than once without very carefully clearing everything.
+		 */
+		$_GET  = array();
+		$_POST = array();
+		foreach ( array( 'query_string', 'id', 'postdata', 'authordata', 'day', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages', 'pagenow', 'current_screen' ) as $v ) {
+			if ( isset( $GLOBALS[ $v ] ) ) {
+				unset( $GLOBALS[ $v ] );
+			}
+		}
+		$parts = parse_url( $url );
+		if ( isset( $parts['scheme'] ) ) {
+			$req = isset( $parts['path'] ) ? $parts['path'] : '';
+			if ( isset( $parts['query'] ) ) {
+				$req .= '?' . $parts['query'];
+				// Parse the URL query vars into $_GET.
+				parse_str( $parts['query'], $_GET );
+			}
+		} else {
+			$req = $url;
+		}
+		if ( ! isset( $parts['query'] ) ) {
+			$parts['query'] = '';
+		}
+
+		$_SERVER['REQUEST_URI'] = $req;
+		unset( $_SERVER['PATH_INFO'] );
+
+		self::flush_cache();
+		unset( $GLOBALS['wp_query'], $GLOBALS['wp_the_query'] );
+		$GLOBALS['wp_the_query'] = new WP_Query();
+		$GLOBALS['wp_query']     = $GLOBALS['wp_the_query'];
+
+		$public_query_vars  = $GLOBALS['wp']->public_query_vars;
+		$private_query_vars = $GLOBALS['wp']->private_query_vars;
+
+		$GLOBALS['wp']                     = new WP();
+		$GLOBALS['wp']->public_query_vars  = $public_query_vars;
+		$GLOBALS['wp']->private_query_vars = $private_query_vars;
+
+		_cleanup_query_vars();
+
+		$GLOBALS['wp']->main( $parts['query'] );
+	}
+
+	/**
+	 * Allows tests to be skipped on single or multisite installs by using @group annotations.
+	 *
+	 * This is a custom extension of the PHPUnit requirements handling.
+	 *
+	 * Contains legacy code for skipping tests that are associated with an open Trac ticket.
+	 * Core tests no longer support this behaviour.
+	 *
+	 * @since 3.5.0
+	 */
+	protected function checkRequirements() {
+		parent::checkRequirements();
+
+		$annotations = $this->getAnnotations();
+
+		$groups = array();
+		if ( ! empty( $annotations['class']['group'] ) ) {
+			$groups = array_merge( $groups, $annotations['class']['group'] );
+		}
+		if ( ! empty( $annotations['method']['group'] ) ) {
+			$groups = array_merge( $groups, $annotations['method']['group'] );
+		}
+
+		if ( ! empty( $groups ) ) {
+			if ( in_array( 'ms-required', $groups, true ) ) {
+				$this->skipWithoutMultisite();
+			}
+
+			if ( in_array( 'ms-excluded', $groups, true ) ) {
+				$this->skipWithMultisite();
+			}
+		}
+
+		// Core tests no longer check against open Trac tickets,
+		// but others using WP_UnitTestCase may do so.
+		if ( defined( 'WP_RUN_CORE_TESTS' ) && WP_RUN_CORE_TESTS ) {
+			return;
+		}
+
+		if ( WP_TESTS_FORCE_KNOWN_BUGS ) {
+			return;
+		}
+		$tickets = PHPUnit_Util_Test::getTickets( get_class( $this ), $this->getName( false ) );
+		foreach ( $tickets as $ticket ) {
+			if ( is_numeric( $ticket ) ) {
+				$this->knownWPBug( $ticket );
+			} elseif ( 0 === strpos( $ticket, 'Plugin' ) ) {
+				$ticket = substr( $ticket, 6 );
+				if ( $ticket && is_numeric( $ticket ) ) {
+					$this->knownPluginBug( $ticket );
+				}
+			}
+		}
+	}
+
+	/**
+	 * Skips the current test if there is an open Trac ticket associated with it.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @param int $ticket_id Ticket number.
+	 */
+	public function knownWPBug( $ticket_id ) {
+		if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( $ticket_id, self::$forced_tickets, true ) ) {
+			return;
+		}
+		if ( ! TracTickets::isTracTicketClosed( 'https://core.trac.wordpress.org', $ticket_id ) ) {
+			$this->markTestSkipped( sprintf( 'WordPress Ticket #%d is not fixed', $ticket_id ) );
+		}
+	}
+
+	/**
+	 * Skips the current test if there is an open Unit Test Trac ticket associated with it.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @deprecated No longer used since the Unit Test Trac was merged into the Core Trac.
+	 *
+	 * @param int $ticket_id Ticket number.
+	 */
+	public function knownUTBug( $ticket_id ) {
+		return;
+	}
+
+	/**
+	 * Skips the current test if there is an open Plugin Trac ticket associated with it.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @param int $ticket_id Ticket number.
+	 */
+	public function knownPluginBug( $ticket_id ) {
+		if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( 'Plugin' . $ticket_id, self::$forced_tickets, true ) ) {
+			return;
+		}
+		if ( ! TracTickets::isTracTicketClosed( 'https://plugins.trac.wordpress.org', $ticket_id ) ) {
+			$this->markTestSkipped( sprintf( 'WordPress Plugin Ticket #%d is not fixed', $ticket_id ) );
+		}
+	}
+
+	/**
+	 * Adds a Trac ticket number to the `$forced_tickets` property.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @param int $ticket Ticket number.
+	 */
+	public static function forceTicket( $ticket ) {
+		self::$forced_tickets[] = $ticket;
+	}
+
+	/**
+	 * Custom preparations for the PHPUnit process isolation template.
+	 *
+	 * When restoring global state between tests, PHPUnit defines all the constants that were already defined, and then
+	 * includes included files. This does not work with WordPress, as the included files define the constants.
+	 *
+	 * This method defines the constants after including files.
+	 *
+	 * @param Text_Template $template The template to prepare.
+	 */
+	public function prepareTemplate( Text_Template $template ) {
+		$template->setVar( array( 'constants' => '' ) );
+		$template->setVar( array( 'wp_constants' => PHPUnit_Util_GlobalState::getConstantsAsString() ) );
+		parent::prepareTemplate( $template );
+	}
+
+	/**
+	 * Creates a unique temporary file name.
+	 *
+	 * The directory in which the file is created depends on the environment configuration.
+	 *
+	 * @since 3.5.0
+	 *
+	 * @return string|bool Path on success, else false.
+	 */
+	public function temp_filename() {
+		$tmp_dir = '';
+		$dirs    = array( 'TMP', 'TMPDIR', 'TEMP' );
+
+		foreach ( $dirs as $dir ) {
+			if ( isset( $_ENV[ $dir ] ) && ! empty( $_ENV[ $dir ] ) ) {
+				$tmp_dir = $dir;
+				break;
+			}
+		}
+
+		if ( empty( $tmp_dir ) ) {
+			$tmp_dir = get_temp_dir();
+		}
+
+		$tmp_dir = realpath( $tmp_dir );
+
+		return tempnam( $tmp_dir, 'wpunit' );
+	}
+
+	/**
+	 * Checks each of the WP_Query is_* functions/properties against expected boolean value.
+	 *
+	 * Any properties that are listed by name as parameters will be expected to be true; all others are
+	 * expected to be false. For example, assertQueryTrue( 'is_single', 'is_feed' ) means is_single()
+	 * and is_feed() must be true and everything else must be false to pass.
+	 *
+	 * @since 2.5.0
+	 * @since 3.8.0 Moved from `Tests_Query_Conditionals` to `WP_UnitTestCase`.
+	 * @since 5.3.0 Formalized the existing `...$prop` parameter by adding it
+	 *              to the function signature.
+	 *
+	 * @param string ...$prop Any number of WP_Query properties that are expected to be true for the current request.
+	 */
+	public function assertQueryTrue( ...$prop ) {
+		global $wp_query;
+
+		$all = array(
+			'is_404',
+			'is_admin',
+			'is_archive',
+			'is_attachment',
+			'is_author',
+			'is_category',
+			'is_comment_feed',
+			'is_date',
+			'is_day',
+			'is_embed',
+			'is_feed',
+			'is_front_page',
+			'is_home',
+			'is_privacy_policy',
+			'is_month',
+			'is_page',
+			'is_paged',
+			'is_post_type_archive',
+			'is_posts_page',
+			'is_preview',
+			'is_robots',
+			'is_favicon',
+			'is_search',
+			'is_single',
+			'is_singular',
+			'is_tag',
+			'is_tax',
+			'is_time',
+			'is_trackback',
+			'is_year',
+		);
+
+		foreach ( $prop as $true_thing ) {
+			$this->assertContains( $true_thing, $all, "Unknown conditional: {$true_thing}." );
+		}
+
+		$passed  = true;
+		$message = '';
+
+		foreach ( $all as $query_thing ) {
+			$result = is_callable( $query_thing ) ? call_user_func( $query_thing ) : $wp_query->$query_thing;
+
+			if ( in_array( $query_thing, $prop, true ) ) {
+				if ( ! $result ) {
+					$message .= $query_thing . ' is false but is expected to be true. ' . PHP_EOL;
+					$passed   = false;
+				}
+			} elseif ( $result ) {
+				$message .= $query_thing . ' is true but is expected to be false. ' . PHP_EOL;
+				$passed   = false;
+			}
+		}
+
+		if ( ! $passed ) {
+			$this->fail( $message );
+		}
+	}
+
+	/**
+	 * Selectively deletes a file.
+	 *
+	 * Does not delete a file if its path is set in the `$ignore_files` property.
+	 *
+	 * @param string $file File path.
+	 */
+	public function unlink( $file ) {
+		$exists = is_file( $file );
+		if ( $exists && ! in_array( $file, self::$ignore_files, true ) ) {
+			//error_log( $file );
+			unlink( $file );
+		} elseif ( ! $exists ) {
+			$this->fail( "Trying to delete a file that doesn't exist: $file" );
+		}
+	}
+
+	/**
+	 * Selectively deletes files from a directory.
+	 *
+	 * Does not delete files if their paths are set in the `$ignore_files` property.
+	 *
+	 * @param string $path Directory path.
+	 */
+	public function rmdir( $path ) {
+		$files = $this->files_in_dir( $path );
+		foreach ( $files as $file ) {
+			if ( ! in_array( $file, self::$ignore_files, true ) ) {
+				$this->unlink( $file );
+			}
+		}
+	}
+
+	/**
+	 * Deletes files added to the `uploads` directory during tests.
+	 *
+	 * This method works in tandem with the `setUp()` and `rmdir()` methods:
+	 * - `setUp()` scans the `uploads` directory before every test, and stores its contents inside of the
+	 *   `$ignore_files` property.
+	 * - `rmdir()` and its helper methods only delete files that are not listed in the `$ignore_files` property. If
+	 *   called during `tearDown()` in tests, this will only delete files added during the previously run test.
+	 */
+	public function remove_added_uploads() {
+		$uploads = wp_upload_dir();
+		$this->rmdir( $uploads['basedir'] );
+	}
+
+	/**
+	 * Returns a list of all files contained inside a directory.
+	 *
+	 * @since 4.0.0
+	 *
+	 * @param string $dir Path to the directory to scan.
+	 * @return array List of file paths.
+	 */
+	public function files_in_dir( $dir ) {
+		$files = array();
+
+		$iterator = new RecursiveDirectoryIterator( $dir );
+		$objects  = new RecursiveIteratorIterator( $iterator );
+		foreach ( $objects as $name => $object ) {
+			if ( is_file( $name ) ) {
+				$files[] = $name;
+			}
+		}
+
+		return $files;
+	}
+
+	/**
+	 * Returns a list of all files contained inside the `uploads` directory.
+	 *
+	 * @since 4.0.0
+	 *
+	 * @return array List of file paths.
+	 */
+	public function scan_user_uploads() {
+		static $files = array();
+		if ( ! empty( $files ) ) {
+			return $files;
+		}
+
+		$uploads = wp_upload_dir();
+		$files   = $this->files_in_dir( $uploads['basedir'] );
+		return $files;
+	}
+
+	/**
+	 * Deletes all directories contained inside a directory.
+	 *
+	 * @since 4.1.0
+	 *
+	 * @param string $path Path to the directory to scan.
+	 */
+	public function delete_folders( $path ) {
+		$this->matched_dirs = array();
+		if ( ! is_dir( $path ) ) {
+			return;
+		}
+
+		$this->scandir( $path );
+		foreach ( array_reverse( $this->matched_dirs ) as $dir ) {
+			rmdir( $dir );
+		}
+		rmdir( $path );
+	}
+
+	/**
+	 * Retrieves all directories contained inside a directory and stores them in the `$matched_dirs` property. Hidden
+	 * directories are ignored.
+	 *
+	 * This is a helper for the `delete_folders()` method.
+	 *
+	 * @since 4.1.0
+	 *
+	 * @param string $dir Path to the directory to scan.
+	 */
+	public function scandir( $dir ) {
+		foreach ( scandir( $dir ) as $path ) {
+			if ( 0 !== strpos( $path, '.' ) && is_dir( $dir . '/' . $path ) ) {
+				$this->matched_dirs[] = $dir . '/' . $path;
+				$this->scandir( $dir . '/' . $path );
+			}
+		}
+	}
+
+	/**
+	 * Converts a microtime string into a float.
+	 *
+	 * @since 4.1.0
+	 *
+	 * @param string $microtime Time string generated by `microtime()`.
+	 * @return float `microtime()` output as a float.
+	 */
+	protected function _microtime_to_float( $microtime ) {
+		$time_array = explode( ' ', $microtime );
+		return array_sum( $time_array );
+	}
+
+	/**
+	 * Deletes a user from the database in a Multisite-agnostic way.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @param int $user_id User ID.
+	 * @return bool True if the user was deleted.
+	 */
+	public static function delete_user( $user_id ) {
+		if ( is_multisite() ) {
+			return wpmu_delete_user( $user_id );
+		}
+
+		return wp_delete_user( $user_id );
+	}
+
+	/**
+	 * Resets permalinks and flushes rewrites.
+	 *
+	 * @since 4.4.0
+	 *
+	 * @global WP_Rewrite $wp_rewrite
+	 *
+	 * @param string $structure Optional. Permalink structure to set. Default empty.
+	 */
+	public function set_permalink_structure( $structure = '' ) {
+		global $wp_rewrite;
+
+		$wp_rewrite->init();
+		$wp_rewrite->set_permalink_structure( $structure );
+		$wp_rewrite->flush_rules();
+	}
+
+	/**
+	 * Creates an attachment post from an uploaded file.
+	 *
+	 * @since 4.4.0
+	 *
+	 * @param array $upload         Array of information about the uploaded file, provided by wp_upload_bits().
+	 * @param int   $parent_post_id Optional. Parent post ID.
+	 * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
+	 */
+	public function _make_attachment( $upload, $parent_post_id = 0 ) {
+		$type = '';
+		if ( ! empty( $upload['type'] ) ) {
+			$type = $upload['type'];
+		} else {
+			$mime = wp_check_filetype( $upload['file'] );
+			if ( $mime ) {
+				$type = $mime['type'];
+			}
+		}
+
+		$attachment = array(
+			'post_title'     => wp_basename( $upload['file'] ),
+			'post_content'   => '',
+			'post_type'      => 'attachment',
+			'post_parent'    => $parent_post_id,
+			'post_mime_type' => $type,
+			'guid'           => $upload['url'],
+		);
+
+		$id = wp_insert_attachment( $attachment, $upload['file'], $parent_post_id );
+		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
+		return $id;
+	}
+
+	/**
+	 * Updates the modified and modified GMT date of a post in the database.
+	 *
+	 * @since 4.8.0
+	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 *
+	 * @param int    $post_id Post ID.
+	 * @param string $date    Post date, in the format YYYY-MM-DD HH:MM:SS.
+	 * @return int|false 1 on success, or false on error.
+	 */
+	protected function update_post_modified( $post_id, $date ) {
+		global $wpdb;
+		return $wpdb->update(
+			$wpdb->posts,
+			array(
+				'post_modified'     => $date,
+				'post_modified_gmt' => $date,
+			),
+			array(
+				'ID' => $post_id,
+			),
+			array(
+				'%s',
+				'%s',
+			),
+			array(
+				'%d',
+			)
+		);
+	}
+
+	/**
+	 * Touches the given file and its directory if it doesn't already exist.
+	 *
+	 * This can be used to ensure a file that is implictly relied on in a test exists
+	 * without it having to be built.
+	 *
+	 * @param string $file The file name.
+	 */
+	public static function touch( $file ) {
+		if ( file_exists( $file ) ) {
+			return;
+		}
+
+		$dir = dirname( $file );
+
+		if ( ! file_exists( $dir ) ) {
+			mkdir( $dir, 0777, true );
+		}
+
+		touch( $file );
+	}
+}

+ 42 - 0
tests/phpunit/includes/class-basic-object.php

@@ -0,0 +1,42 @@
+<?php
+/**
+ * Unit Tests: Basic_Object cloass
+ *
+ * @package WordPress
+ * @subpackage UnitTests
+ * @since 4.7.0
+ */
+
+/**
+ * Class used to test accessing methods and properties
+ *
+ * @since 4.0.0
+ */
+class Basic_Object {
+	private $foo = 'bar';
+
+	public function __get( $name ) {
+		return $this->$name;
+	}
+
+	public function __set( $name, $value ) {
+		return $this->$name = $value;
+	}
+
+	public function __isset( $name ) {
+		return isset( $this->$name );
+	}
+
+	public function __unset( $name ) {
+		unset( $this->$name );
+	}
+
+	public function __call( $name, $arguments ) {
+		return call_user_func_array( array( $this, $name ), $arguments );
+	}
+
+	// phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
+	private function callMe() {
+		return 'maybe';
+	}
+}

+ 17 - 0
tests/phpunit/includes/class-basic-subclass.php

@@ -0,0 +1,17 @@
+<?php
+/**
+ * Unit Tests: Basic_Subclass class
+ *
+ * @package WordPress
+ * @subpackage UnitTests
+ * @since 4.7.0
+ */
+
+trigger_error( __FILE__ . ' is deprecated since version 5.0.0 with no alternative available.' );
+
+/**
+ * Class used to test accessing methods and properties.
+ *
+ * @since 4.0.0
+ */
+class Basic_Subclass extends Basic_Object {}

+ 21 - 0
tests/phpunit/includes/class-jsonserializable-object.php

@@ -0,0 +1,21 @@
+<?php
+/**
+ * Unit Tests: JsonSerializable_Object
+ *
+ * @package WordPress
+ * @subpackage UnitTests
+ * @since 5.3.0
+ */
+
+class JsonSerializable_Object implements JsonSerializable {
+
+	private $data;
+
+	public function __construct( $data ) {
+		$this->data = $data;
+	}
+
+	public function jsonSerialize() {
+		return $this->data;
+	}
+}

+ 27 - 0
tests/phpunit/includes/class-wp-fake-block-type.php

@@ -0,0 +1,27 @@
+<?php
+/**
+ * WP_Fake_Block_Type for testing
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Test class extending WP_Block_Type
+ *
+ * @since 5.0.0
+ */
+class WP_Fake_Block_Type extends WP_Block_Type {
+
+	/**
+	 * Render the fake block.
+	 *
+	 * @param array  $attributes Optional. Block attributes. Default empty array.
+	 * @param string $content    Optional. Block content. Default empty string.
+	 * @return string Rendered block HTML.
+	 */
+	public function render( $attributes = array(), $content = '' ) {
+		return '<div>' . $content . '</div>';
+	}
+}

+ 60 - 0
tests/phpunit/includes/class-wp-rest-test-configurable-controller.php

@@ -0,0 +1,60 @@
+<?php
+/**
+ * Unit tests covering WP_REST_Controller functionality using a flexible schema.
+ *
+ * @package WordPress
+ * @subpackage REST API
+ * @since 5.4.0
+ */
+
+/**
+ * WP_REST_Test_Configurable_Controller class.
+ *
+ * @group restapi
+ *
+ * @since 5.4.0
+ */
+class WP_REST_Test_Configurable_Controller extends WP_REST_Controller {
+
+	/**
+	 * Test schema.
+	 *
+	 * @since 5.4.0
+	 *
+	 * @var array $test_schema
+	 */
+	protected $test_schema;
+
+	/**
+	 * Class constructor.
+	 *
+	 * @since 5.4.0
+	 *
+	 * @param array $test_schema Schema for use in testing.
+	 */
+	public function __construct( $test_schema ) {
+		$this->test_schema = $test_schema;
+	}
+
+	/**
+	 * Provides the test schema.
+	 *
+	 * @since 5.4.0
+	 *
+	 * @return array Test schema.
+	 */
+	public function get_test_schema() {
+		return $this->test_schema;
+	}
+
+	/**
+	 * Get the item's schema, conforming to JSON Schema.
+	 *
+	 * @since 5.4.0
+	 *
+	 * @return array
+	 */
+	public function get_item_schema() {
+		return $this->add_additional_fields_schema( $this->get_test_schema() );
+	}
+}

+ 91 - 0
tests/phpunit/includes/class-wp-rest-test-search-handler.php

@@ -0,0 +1,91 @@
+<?php
+/**
+ * REST API: WP_REST_Test_Search_Handler class
+ *
+ * @package WordPress
+ * @subpackage REST_API
+ */
+
+/**
+ * Test class extending WP_REST_Search_Handler
+ */
+class WP_REST_Test_Search_Handler extends WP_REST_Search_Handler {
+
+	protected $items = array();
+
+	public function __construct( $amount = 10 ) {
+		$this->type = 'test';
+
+		$this->subtypes = array( 'test_first_type', 'test_second_type' );
+
+		$this->items = array();
+		for ( $i = 1; $i <= $amount; $i++ ) {
+			$subtype = $i > $amount / 2 ? 'test_second_type' : 'test_first_type';
+
+			$this->items[ $i ] = (object) array(
+				'test_id'    => $i,
+				'test_title' => sprintf( 'Title %d', $i ),
+				'test_url'   => sprintf( home_url( '/tests/%d' ), $i ),
+				'test_type'  => $subtype,
+			);
+		}
+	}
+
+	public function search_items( WP_REST_Request $request ) {
+		$subtypes = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ];
+		if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $subtypes, true ) ) {
+			$subtypes = $this->subtypes;
+		}
+
+		$results = array();
+		foreach ( $subtypes as $subtype ) {
+			$results = array_merge( $results, wp_list_filter( array_values( $this->items ), array( 'test_type' => $subtype ) ) );
+		}
+
+		$results = wp_list_sort( $results, 'test_id', 'DESC' );
+
+		$number = (int) $request['per_page'];
+		$offset = (int) $request['per_page'] * ( (int) $request['page'] - 1 );
+
+		$total = count( $results );
+
+		$results = array_slice( $results, $offset, $number );
+
+		return array(
+			self::RESULT_IDS   => wp_list_pluck( $results, 'test_id' ),
+			self::RESULT_TOTAL => $total,
+		);
+	}
+
+	public function prepare_item( $id, array $fields ) {
+		$test = $this->items[ $id ];
+
+		$data = array();
+
+		if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) {
+			$data[ WP_REST_Search_Controller::PROP_ID ] = (int) $test->test_id;
+		}
+
+		if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) {
+			$data[ WP_REST_Search_Controller::PROP_TITLE ] = $test->test_title;
+		}
+
+		if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) {
+			$data[ WP_REST_Search_Controller::PROP_URL ] = $test->test_url;
+		}
+
+		if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) {
+			$data[ WP_REST_Search_Controller::PROP_TYPE ] = $this->type;
+		}
+
+		if ( in_array( WP_REST_Search_Controller::PROP_SUBTYPE, $fields, true ) ) {
+			$data[ WP_REST_Search_Controller::PROP_SUBTYPE ] = $test->test_type;
+		}
+
+		return $data;
+	}
+
+	public function prepare_item_links( $id ) {
+		return array();
+	}
+}

+ 38 - 0
tests/phpunit/includes/class-wp-sitemaps-empty-test-provider.php

@@ -0,0 +1,38 @@
+<?php
+
+/**
+ * Class WP_Sitemaps_Empty_Test_Provider.
+ *
+ * Provides test data for additional registered providers.
+ */
+class WP_Sitemaps_Empty_Test_Provider extends WP_Sitemaps_Provider {
+	/**
+	 * WP_Sitemaps_Empty_Test_Provider constructor.
+	 *
+	 * @param string $object_type Optional. Object type name to use. Default 'test'.
+	 */
+	public function __construct( $object_type = 'test' ) {
+		$this->object_type = $object_type;
+	}
+
+	/**
+	 * Gets a URL list for a sitemap.
+	 *
+	 * @param int    $page_num       Page of results.
+	 * @param string $object_subtype Optional. Object subtype name. Default empty.
+	 * @return array List of URLs for a sitemap.
+	 */
+	public function get_url_list( $page_num, $object_subtype = '' ) {
+		return array();
+	}
+
+	/**
+	 * Query for determining the number of pages.
+	 *
+	 * @param string $object_subtype Optional. Object subtype. Default empty.
+	 * @return int Total number of pages.
+	 */
+	public function get_max_num_pages( $object_subtype = '' ) {
+		return 0;
+	}
+}

+ 59 - 0
tests/phpunit/includes/class-wp-sitemaps-large-test-provider.php

@@ -0,0 +1,59 @@
+<?php
+
+/**
+ * Class WP_Sitemaps_Large_Test_Provider.
+ *
+ * Provides test data for additional registered providers.
+ */
+class WP_Sitemaps_Large_Test_Provider extends WP_Sitemaps_Provider {
+	/**
+	 * Number of entries in the sitemap the provider produces.
+	 *
+	 * @var integer
+	 */
+	public $num_entries = 1;
+
+	/**
+	 * WP_Sitemaps_Large_Test_Provider constructor.
+	 *
+	 * @param int $num_entries Optional. Number of entries in in the sitemap.
+	 */
+	public function __construct( $num_entries = 50001 ) {
+		$this->name        = 'tests';
+		$this->object_type = 'test';
+
+		$this->num_entries = $num_entries;
+	}
+
+	/**
+	 * Gets a URL list for a sitemap.
+	 *
+	 * @param int    $page_num       Page of results.
+	 * @param string $object_subtype Optional. Object subtype name. Default empty.
+	 * @return array List of URLs for a sitemap.
+	 */
+	public function get_url_list( $page_num, $object_subtype = '' ) {
+		return array_fill( 0, $this->num_entries, array( 'loc' => home_url( '/' ) ) );
+	}
+
+	/**
+	 * Lists sitemap pages exposed by this provider.
+	 *
+	 * The returned data is used to populate the sitemap entries of the index.
+	 *
+	 * @return array[] Array of sitemap entries.
+	 */
+	public function get_sitemap_entries() {
+		return array_fill( 0, $this->num_entries, array( 'loc' => home_url( '/' ) ) );
+	}
+
+	/**
+	 * Query for determining the number of pages.
+	 *
+	 * @param string $object_subtype Optional. Object subtype. Default empty.
+	 * @return int Total number of pages.
+	 */
+	public function get_max_num_pages( $object_subtype = '' ) {
+		return $this->num_entries;
+	}
+}

+ 52 - 0
tests/phpunit/includes/class-wp-sitemaps-test-provider.php

@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * Class WP_Sitemaps_Test_Provider.
+ *
+ * Provides test data for additional registered providers.
+ */
+class WP_Sitemaps_Test_Provider extends WP_Sitemaps_Provider {
+	/**
+	 * WP_Sitemaps_Posts constructor.
+	 *
+	 * @param string $object_type Optional. Object type name to use. Default 'test'.
+	 */
+	public function __construct( $object_type = 'test' ) {
+		$this->object_type = $object_type;
+	}
+
+	/**
+	 * Return the public post types, which excludes nav_items and similar types.
+	 * Attachments are also excluded. This includes custom post types with public = true
+	 *
+	 * @return array Map of object subtype objects (WP_Post_Type) keyed by their name.
+	 */
+	public function get_object_subtypes() {
+		return array(
+			'type-1' => (object) array( 'name' => 'type-1' ),
+			'type-2' => (object) array( 'name' => 'type-2' ),
+			'type-3' => (object) array( 'name' => 'type-3' ),
+		);
+	}
+
+	/**
+	 * Gets a URL list for a sitemap.
+	 *
+	 * @param int    $page_num       Page of results.
+	 * @param string $object_subtype Optional. Object subtype name. Default empty.
+	 * @return array List of URLs for a sitemap.
+	 */
+	public function get_url_list( $page_num, $object_subtype = '' ) {
+		return array();
+	}
+
+	/**
+	 * Query for determining the number of pages.
+	 *
+	 * @param string $object_subtype Optional. Object subtype. Default empty.
+	 * @return int Total number of pages.
+	 */
+	public function get_max_num_pages( $object_subtype = '' ) {
+		return 4;
+	}
+}

+ 248 - 0
tests/phpunit/includes/class-wp-test-stream.php

@@ -0,0 +1,248 @@
+<?php
+
+/**
+ * Class WP_Test_Stream.
+ *
+ * An in-memory streamWrapper implementation for testing streams.  Writes to a
+ * stream URL like "protocol://bucket/foo" will be stored in the static
+ * variable WP_Test_Stream::$data['bucket']['/foo'].
+ *
+ * Creating a directory at "protocol://bucket/foo" will store the string
+ * 'DIRECTORY' to the static variable WP_Test_Stream::$data['bucket']['/foo/']
+ * (note the trailing slash).
+ *
+ * This class can be used to test that code works with basic read/write streams,
+ * as such, operations such as seeking are not supported.
+ *
+ * This class does not register itself as a stream handler: test fixtures
+ * should make the appropriate call to stream_wrapper_register().
+ */
+class WP_Test_Stream {
+	const FILE_MODE      = 0100666;
+	const DIRECTORY_MODE = 040777;
+
+	/**
+	 * In-memory storage for files and directories simulated by this wrapper.
+	 */
+	static $data = array();
+
+	var $position;
+	var $file;
+	var $bucket;
+	var $data_ref;
+
+	/**
+	 * Initializes internal state for reading the given URL.
+	 *
+	 * @param string $url A URL of the form "protocol://bucket/path".
+	 */
+	private function open( $url ) {
+		$components = array_merge(
+			array(
+				'host' => '',
+				'path' => '',
+			),
+			parse_url( $url )
+		);
+
+		$this->bucket = $components['host'];
+		$this->file   = $components['path'] ? $components['path'] : '/';
+
+		if ( empty( $this->bucket ) ) {
+			trigger_error( 'Cannot use an empty bucket name', E_USER_ERROR );
+		}
+
+		if ( ! isset( WP_Test_Stream::$data[ $this->bucket ] ) ) {
+			WP_Test_Stream::$data[ $this->bucket ] = array();
+		}
+
+		$this->data_ref =& WP_Test_Stream::$data[ $this->bucket ][ $this->file ];
+
+		$this->position = 0;
+	}
+
+	/**
+	 * Opens a URL.
+	 *
+	 * @see streamWrapper::stream_open
+	 */
+	function stream_open( $path, $mode, $options, &$opened_path ) {
+		$this->open( $path );
+		return true;
+	}
+
+	/**
+	 * Reads from a stream.
+	 *
+	 * @see streamWrapper::stream_read
+	 */
+	function stream_read( $count ) {
+		if ( ! isset( $this->data_ref ) ) {
+			return '';
+		}
+
+		$ret = substr( $this->data_ref, $this->position, $count );
+
+		$this->position += strlen( $ret );
+		return $ret;
+	}
+
+	/**
+	 * Writes to a stream.
+	 *
+	 * @see streamWrapper::stream_write
+	 */
+	function stream_write( $data ) {
+		if ( ! isset( $this->data_ref ) ) {
+			$this->data_ref = '';
+		}
+
+		$left  = substr( $this->data_ref, 0, $this->position );
+		$right = substr( $this->data_ref, $this->position + strlen( $data ) );
+
+		WP_Test_Stream::$data[ $this->bucket ][ $this->file ] = $left . $data . $right;
+
+		$this->position += strlen( $data );
+		return strlen( $data );
+	}
+
+	/**
+	 * Retrieves the current position of a stream.
+	 *
+	 * @see streamWrapper::stream_tell
+	 */
+	function stream_tell() {
+		return $this->position;
+	}
+
+	/**
+	 * Tests for end-of-file.
+	 *
+	 * @see streamWrapper::stream_eof
+	 */
+	function stream_eof() {
+		if ( ! isset( $this->data_ref ) ) {
+			return true;
+		}
+
+		return $this->position >= strlen( $this->data_ref );
+	}
+
+	/**
+	 * Change stream metadata.
+	 *
+	 * @see streamWrapper::stream_metadata
+	 */
+	function stream_metadata( $path, $option, $var ) {
+		$this->open( $path );
+		if ( STREAM_META_TOUCH === $option ) {
+			if ( ! isset( $this->data_ref ) ) {
+				$this->data_ref = '';
+			}
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * Creates a directory.
+	 *
+	 * @see streamWrapper::mkdir
+	 */
+	function mkdir( $path, $mode, $options ) {
+		$this->open( $path );
+		$plainfile = rtrim( $this->file, '/' );
+
+		if ( isset( WP_Test_Stream::$data[ $this->bucket ][ $file ] ) ) {
+			return false;
+		}
+		$dir_ref = & $this->get_directory_ref();
+		$dir_ref = 'DIRECTORY';
+		return true;
+	}
+
+	/**
+	 * Creates a file metadata object, with defaults.
+	 *
+	 * @param array $stats Partial file metadata.
+	 * @return array Complete file metadata.
+	 */
+	private function make_stat( $stats ) {
+		$defaults = array(
+			'dev'     => 0,
+			'ino'     => 0,
+			'mode'    => 0,
+			'nlink'   => 0,
+			'uid'     => 0,
+			'gid'     => 0,
+			'rdev'    => 0,
+			'size'    => 0,
+			'atime'   => 0,
+			'mtime'   => 0,
+			'ctime'   => 0,
+			'blksize' => 0,
+			'blocks'  => 0,
+		);
+
+		return array_merge( $defaults, $stats );
+	}
+
+	/**
+	 * Retrieves information about a file.
+	 *
+	 * @see streamWrapper::stream_stat
+	 */
+	public function stream_stat() {
+		$dir_ref = & $this->get_directory_ref();
+		if ( substr( $this->file, -1 ) === '/' || isset( $dir_ref ) ) {
+			return $this->make_stat(
+				array(
+					'mode' => WP_Test_Stream::DIRECTORY_MODE,
+				)
+			);
+		}
+
+		if ( ! isset( $this->data_ref ) ) {
+			return false;
+		}
+
+		return $this->make_stat(
+			array(
+				'size' => strlen( $this->data_ref ),
+				'mode' => WP_Test_Stream::FILE_MODE,
+			)
+		);
+	}
+
+	/**
+	 * Retrieves information about a file.
+	 *
+	 * @see streamWrapper::url_stat
+	 */
+	public function url_stat( $path, $flags ) {
+		$this->open( $path );
+		return $this->stream_stat();
+	}
+
+	/**
+	 * Deletes a file.
+	 *
+	 * @see streamWrapper::unlink
+	 */
+	public function unlink( $path ) {
+		if ( ! isset( $this->data_ref ) ) {
+			return false;
+		}
+		unset( WP_Test_Stream::$data[ $this->bucket ][ $this->file ] );
+		return true;
+	}
+
+	/**
+	 * Interprets this stream's path as a directory, and returns the entry.
+	 *
+	 * @return A reference to the data entry for the directory.
+	 */
+	private function &get_directory_ref() {
+		return WP_Test_Stream::$data[ $this->bucket ][ rtrim( $this->file, '/' ) . '/' ];
+	}
+}

+ 29 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-callback-after-create.php

@@ -0,0 +1,29 @@
+<?php
+
+class WP_UnitTest_Factory_Callback_After_Create {
+
+	/**
+	 * @var callable
+	 */
+	public $callback;
+
+	/**
+	 * WP_UnitTest_Factory_Callback_After_Create constructor.
+	 *
+	 * @param callable $callback A callback function.
+	 */
+	public function __construct( $callback ) {
+		$this->callback = $callback;
+	}
+
+	/**
+	 * Calls the set callback on a given object.
+	 *
+	 * @param mixed $object The object to apply the callback on.
+	 *
+	 * @return mixed The possibly altered object.
+	 */
+	public function call( $object ) {
+		return call_user_func( $this->callback, $object );
+	}
+}

+ 76 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php

@@ -0,0 +1,76 @@
+<?php
+
+class WP_UnitTest_Factory_For_Attachment extends WP_UnitTest_Factory_For_Post {
+
+	/**
+	 * Create an attachment fixture.
+	 *
+	 * @param array $args {
+	 *     Array of arguments. Accepts all arguments that can be passed to
+	 *     wp_insert_attachment(), in addition to the following:
+	 *     @type int    $post_parent ID of the post to which the attachment belongs.
+	 *     @type string $file        Path of the attached file.
+	 * }
+	 * @param int   $legacy_parent Deprecated.
+	 * @param array $legacy_args   Deprecated.
+	 *
+	 * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
+	 */
+	public function create_object( $args, $legacy_parent = 0, $legacy_args = array() ) {
+		// Backward compatibility for legacy argument format.
+		if ( is_string( $args ) ) {
+			$file                = $args;
+			$args                = $legacy_args;
+			$args['post_parent'] = $legacy_parent;
+			$args['file']        = $file;
+		}
+
+		$r = array_merge(
+			array(
+				'file'        => '',
+				'post_parent' => 0,
+			),
+			$args
+		);
+
+		return wp_insert_attachment( $r, $r['file'], $r['post_parent'] );
+	}
+
+	/**
+	 * Saves an attachment.
+	 *
+	 * @param string $file   The file name to create attachment object for.
+	 * @param int    $parent ID of the post to attach the file to.
+	 *
+	 * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
+	 */
+	public function create_upload_object( $file, $parent = 0 ) {
+		$contents = file_get_contents( $file );
+		$upload   = wp_upload_bits( wp_basename( $file ), null, $contents );
+
+		$type = '';
+		if ( ! empty( $upload['type'] ) ) {
+			$type = $upload['type'];
+		} else {
+			$mime = wp_check_filetype( $upload['file'] );
+			if ( $mime ) {
+				$type = $mime['type'];
+			}
+		}
+
+		$attachment = array(
+			'post_title'     => wp_basename( $upload['file'] ),
+			'post_content'   => '',
+			'post_type'      => 'attachment',
+			'post_parent'    => $parent,
+			'post_mime_type' => $type,
+			'guid'           => $upload['url'],
+		);
+
+		// Save the data.
+		$id = wp_insert_attachment( $attachment, $upload['file'], $parent );
+		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
+
+		return $id;
+	}
+}

+ 91 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-blog.php

@@ -0,0 +1,91 @@
+<?php
+
+/**
+ * Unit test factory for sites on a multisite network.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_Site create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Blog extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		global $current_site, $base;
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'domain'     => $current_site->domain,
+			'path'       => new WP_UnitTest_Generator_Sequence( $base . 'testpath%s' ),
+			'title'      => new WP_UnitTest_Generator_Sequence( 'Site %s' ),
+			'network_id' => $current_site->id,
+		);
+	}
+
+	/**
+	 * Creates a site object.
+	 *
+	 * @param array $args Arguments for the site object.
+	 *
+	 * @return int|WP_Error The site ID on success, WP_Error object on failure.
+	 */
+	public function create_object( $args ) {
+		global $wpdb;
+
+		// Map some arguments for backward compatibility with `wpmu_create_blog()` previously used here.
+		if ( isset( $args['site_id'] ) ) {
+			$args['network_id'] = $args['site_id'];
+			unset( $args['site_id'] );
+		}
+
+		if ( isset( $args['meta'] ) ) {
+			// The `$allowed_data_fields` matches the one used in `wpmu_create_blog()`.
+			$allowed_data_fields = array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' );
+
+			foreach ( $args['meta'] as $key => $value ) {
+				// Promote allowed keys to top-level arguments, add others to the options array.
+				if ( in_array( $key, $allowed_data_fields, true ) ) {
+					$args[ $key ] = $value;
+				} else {
+					$args['options'][ $key ] = $value;
+				}
+			}
+
+			unset( $args['meta'] );
+		}
+
+		// Temporary tables will trigger DB errors when we attempt to reference them as new temporary tables.
+		$suppress = $wpdb->suppress_errors();
+
+		$blog = wp_insert_site( $args );
+
+		$wpdb->suppress_errors( $suppress );
+
+		// Tell WP we're done installing.
+		wp_installing( false );
+
+		return $blog;
+	}
+
+	/**
+	 * Updates a site object. Not implemented.
+	 *
+	 * @param int   $blog_id ID of the site to update.
+	 * @param array $fields  The fields to update.
+	 *
+	 * @return void
+	 */
+	public function update_object( $blog_id, $fields ) {}
+
+	/**
+	 * Retrieves a site by a given ID.
+	 *
+	 * @param int $blog_id ID of the site to retrieve.
+	 *
+	 * @return WP_Site|null The site object on success, null on failure.
+	 */
+	public function get_object_by_id( $blog_id ) {
+		return get_site( $blog_id );
+	}
+}

+ 37 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-bookmark.php

@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * Factory for creating fixtures for the deprecated Links/Bookmarks API.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @since 4.6.0
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method object create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Bookmark extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'link_name' => new WP_UnitTest_Generator_Sequence( 'Bookmark name %s' ),
+			'link_url'  => new WP_UnitTest_Generator_Sequence( 'Bookmark URL %s' ),
+		);
+	}
+
+	public function create_object( $args ) {
+		return wp_insert_link( $args );
+	}
+
+	public function update_object( $link_id, $fields ) {
+		$fields['link_id'] = $link_id;
+		return wp_update_link( $fields );
+	}
+
+	public function get_object_by_id( $link_id ) {
+		return get_bookmark( $link_id );
+	}
+}

+ 74 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-comment.php

@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * Unit test factory for comments.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_Comment create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Comment extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'comment_author'     => new WP_UnitTest_Generator_Sequence( 'Commenter %s' ),
+			'comment_author_url' => new WP_UnitTest_Generator_Sequence( 'http://example.com/%s/' ),
+			'comment_approved'   => 1,
+			'comment_content'    => 'This is a comment',
+		);
+	}
+
+	/**
+	 * Inserts a comment.
+	 *
+	 * @param array $args The comment details.
+	 *
+	 * @return int|false The comment's ID on success, false on failure.
+	 */
+	public function create_object( $args ) {
+		return wp_insert_comment( $this->addslashes_deep( $args ) );
+	}
+
+	/**
+	 * Updates a comment.
+	 *
+	 * @param int   $comment_id The comment ID.
+	 * @param array $fields     The comment details.
+	 *
+	 * @return int The value 1 if the comment was updated, 0 if not updated.
+	 */
+	public function update_object( $comment_id, $fields ) {
+		$fields['comment_ID'] = $comment_id;
+		return wp_update_comment( $this->addslashes_deep( $fields ) );
+	}
+
+	/**
+	 * Creates multiple comments on a given post.
+	 *
+	 * @param int   $post_id                ID of the post to create comments for.
+	 * @param int   $count                  Total amount of comments to create.
+	 * @param array $args                   The comment details.
+	 * @param null  $generation_definitions Default values.
+	 *
+	 * @return int[] Array with the comment IDs.
+	 */
+	public function create_post_comments( $post_id, $count = 1, $args = array(), $generation_definitions = null ) {
+		$args['comment_post_ID'] = $post_id;
+		return $this->create_many( $count, $args, $generation_definitions );
+	}
+
+	/**
+	 * Retrieves a comment by a given ID.
+	 *
+	 * @param int $comment_id ID of the comment to retrieve.
+	 *
+	 * @return WP_Comment|null WP_Comment object on success, null on failure.
+	 */
+	public function get_object_by_id( $comment_id ) {
+		return get_comment( $comment_id );
+	}
+}

+ 44 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-network.php

@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * Unit test factory for networks.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_Network create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Network extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'domain'            => WP_TESTS_DOMAIN,
+			'title'             => new WP_UnitTest_Generator_Sequence( 'Network %s' ),
+			'path'              => new WP_UnitTest_Generator_Sequence( '/testpath%s/' ),
+			'network_id'        => new WP_UnitTest_Generator_Sequence( '%s', 2 ),
+			'subdomain_install' => false,
+		);
+	}
+
+	public function create_object( $args ) {
+		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
+
+		if ( ! isset( $args['user'] ) ) {
+			$email = WP_TESTS_EMAIL;
+		} else {
+			$email = get_userdata( $args['user'] )->user_email;
+		}
+
+		populate_network( $args['network_id'], $args['domain'], $email, $args['title'], $args['path'], $args['subdomain_install'] );
+		return (int) $args['network_id'];
+	}
+
+	public function update_object( $network_id, $fields ) {}
+
+	public function get_object_by_id( $network_id ) {
+		return get_network( $network_id );
+	}
+}

+ 60 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-post.php

@@ -0,0 +1,60 @@
+<?php
+
+/**
+ * Unit test factory for posts.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_Post create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Post extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'post_status'  => 'publish',
+			'post_title'   => new WP_UnitTest_Generator_Sequence( 'Post title %s' ),
+			'post_content' => new WP_UnitTest_Generator_Sequence( 'Post content %s' ),
+			'post_excerpt' => new WP_UnitTest_Generator_Sequence( 'Post excerpt %s' ),
+			'post_type'    => 'post',
+		);
+	}
+
+	/**
+	 * Creates a post object.
+	 *
+	 * @param array $args Array with elements for the post.
+	 *
+	 * @return int The post ID on success. The value 0 on failure.
+	 */
+	public function create_object( $args ) {
+		return wp_insert_post( $args );
+	}
+
+	/**
+	 * Updates an existing post object.
+	 *
+	 * @param int   $post_id ID of the post to update.
+	 * @param array $fields  Post data.
+	 *
+	 * @return int The post ID on success. The value 0 on failure.
+	 */
+	public function update_object( $post_id, $fields ) {
+		$fields['ID'] = $post_id;
+		return wp_update_post( $fields );
+	}
+
+	/**
+	 * Retrieves a post by a given ID.
+	 *
+	 * @param int $post_id ID of the post to retrieve.
+	 *
+	 * @return WP_Post|null WP_Post object on success, null on failure.
+	 */
+	public function get_object_by_id( $post_id ) {
+		return get_post( $post_id );
+	}
+}

+ 108 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-term.php

@@ -0,0 +1,108 @@
+<?php
+
+/**
+ * Unit test factory for terms.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_Term create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_Term extends WP_UnitTest_Factory_For_Thing {
+
+	private $taxonomy;
+	const DEFAULT_TAXONOMY = 'post_tag';
+
+	public function __construct( $factory = null, $taxonomy = null ) {
+		parent::__construct( $factory );
+		$this->taxonomy                       = $taxonomy ? $taxonomy : self::DEFAULT_TAXONOMY;
+		$this->default_generation_definitions = array(
+			'name'        => new WP_UnitTest_Generator_Sequence( 'Term %s' ),
+			'taxonomy'    => $this->taxonomy,
+			'description' => new WP_UnitTest_Generator_Sequence( 'Term description %s' ),
+		);
+	}
+
+	/**
+	 * Creates a term object.
+	 *
+	 * @param array $args Array or string of arguments for inserting a term.
+	 *
+	 * @return array|WP_Error
+	 */
+	public function create_object( $args ) {
+		$args         = array_merge( array( 'taxonomy' => $this->taxonomy ), $args );
+		$term_id_pair = wp_insert_term( $args['name'], $args['taxonomy'], $args );
+		if ( is_wp_error( $term_id_pair ) ) {
+			return $term_id_pair;
+		}
+		return $term_id_pair['term_id'];
+	}
+
+	/**
+	 * Updates the term.
+	 *
+	 * @param int|object   $term   The term to update.
+	 * @param array|string $fields The context in which to relate the term to the object.
+	 *
+	 * @return int The term ID.
+	 */
+	public function update_object( $term, $fields ) {
+		$fields = array_merge( array( 'taxonomy' => $this->taxonomy ), $fields );
+		if ( is_object( $term ) ) {
+			$taxonomy = $term->taxonomy;
+		}
+		$term_id_pair = wp_update_term( $term, $taxonomy, $fields );
+		return $term_id_pair['term_id'];
+	}
+
+	/**
+	 * Attach terms to the given post.
+	 *
+	 * @param int          $post_id  The post ID.
+	 * @param string|array $terms    An array of terms to set for the post, or a string of terms
+	 *                               separated by commas. Hierarchical taxonomies must always pass IDs rather
+	 *                               than names so that children with the same names but different parents
+	 *                               aren't confused.
+	 * @param string       $taxonomy Taxonomy name.
+	 * @param bool         $append   Optional. If true, don't delete existing terms, just add on. If false,
+	 *                               replace the terms with the new terms. Default true.
+	 *
+	 * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
+	 */
+	public function add_post_terms( $post_id, $terms, $taxonomy, $append = true ) {
+		return wp_set_post_terms( $post_id, $terms, $taxonomy, $append );
+	}
+
+	/**
+	 * Create a term and returns it as an object.
+	 *
+	 * @param array $args                   Array or string of arguments for inserting a term.
+	 * @param null  $generation_definitions The default values.
+	 *
+	 * @return WP_Term|WP_Error|null WP_Term on success. WP_error if taxonomy does not exist. Null for miscellaneous failure.
+	 */
+	public function create_and_get( $args = array(), $generation_definitions = null ) {
+		$term_id = $this->create( $args, $generation_definitions );
+
+		if ( is_wp_error( $term_id ) ) {
+			return $term_id;
+		}
+
+		$taxonomy = isset( $args['taxonomy'] ) ? $args['taxonomy'] : $this->taxonomy;
+		return get_term( $term_id, $taxonomy );
+	}
+
+	/**
+	 * Retrieves the term by a given ID.
+	 *
+	 * @param int $term_id ID of the term to retrieve.
+	 *
+	 * @return WP_Term|WP_Error|null WP_Term on success. WP_error if taxonomy does not exist. Null for miscellaneous failure.
+	 */
+	public function get_object_by_id( $term_id ) {
+		return get_term( $term_id, $this->taxonomy );
+	}
+}

+ 206 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-thing.php

@@ -0,0 +1,206 @@
+<?php
+
+/**
+ * An abstract class that serves as a basis for all WordPress object-type factory classes.
+ */
+abstract class WP_UnitTest_Factory_For_Thing {
+
+	public $default_generation_definitions;
+	public $factory;
+
+	/**
+	 * Creates a new factory, which will create objects of a specific Thing
+	 *
+	 * @param object $factory Global factory that can be used to create other objects on the system
+	 * @param array $default_generation_definitions Defines what default values should the properties of the object have. The default values
+	 * can be generators -- an object with next() method. There are some default generators: {@link WP_UnitTest_Generator_Sequence},
+	 * {@link WP_UnitTest_Generator_Locale_Name}, {@link WP_UnitTest_Factory_Callback_After_Create}.
+	 */
+	public function __construct( $factory, $default_generation_definitions = array() ) {
+		$this->factory                        = $factory;
+		$this->default_generation_definitions = $default_generation_definitions;
+	}
+
+	/**
+	 * Creates an object.
+	 *
+	 * @param array $args The arguments.
+	 *
+	 * @return mixed The result. Can be anything.
+	 */
+	abstract public function create_object( $args );
+
+	/**
+	 * Updates an existing object.
+	 *
+	 * @param int   $object The object ID.
+	 * @param array $fields The values to update.
+	 *
+	 * @return mixed The result. Can be anything.
+	 */
+	abstract public function update_object( $object, $fields );
+
+	/**
+	 * Creates an object.
+	 *
+	 * @param array $args                   Optional. The arguments for the object to create. Default is empty array.
+	 * @param null  $generation_definitions Optional. The default values for the object. Default is null.
+	 *
+	 * @return mixed The result. Can be anything.
+	 */
+	public function create( $args = array(), $generation_definitions = null ) {
+		if ( is_null( $generation_definitions ) ) {
+			$generation_definitions = $this->default_generation_definitions;
+		}
+
+		$generated_args = $this->generate_args( $args, $generation_definitions, $callbacks );
+		$created        = $this->create_object( $generated_args );
+		if ( ! $created || is_wp_error( $created ) ) {
+			return $created;
+		}
+
+		if ( $callbacks ) {
+			$updated_fields = $this->apply_callbacks( $callbacks, $created );
+			$save_result    = $this->update_object( $created, $updated_fields );
+			if ( ! $save_result || is_wp_error( $save_result ) ) {
+				return $save_result;
+			}
+		}
+		return $created;
+	}
+
+	/**
+	 * Creates an object and returns its object.
+	 *
+	 * @param array $args                   Optional. The arguments for the object to create. Default is empty array.
+	 * @param null  $generation_definitions Optional. The default values for the object. Default is null.
+	 *
+	 * @return mixed The created object. Can be anything.
+	 */
+	public function create_and_get( $args = array(), $generation_definitions = null ) {
+		$object_id = $this->create( $args, $generation_definitions );
+
+		if ( is_wp_error( $object_id ) ) {
+			return $object_id;
+		}
+
+		return $this->get_object_by_id( $object_id );
+	}
+
+	/**
+	 * Retrieves an object by ID.
+	 *
+	 * @param int $object_id The object ID.
+	 *
+	 * @return mixed The object. Can be anything.
+	 */
+	abstract public function get_object_by_id( $object_id );
+
+	/**
+	 * Creates multiple objects.
+	 *
+	 * @param int   $count                  Amount of objects to create.
+	 * @param array $args                   Optional. The arguments for the object to create. Default is empty array.
+	 * @param null  $generation_definitions Optional. The default values for the object. Default is null.
+	 *
+	 * @return array
+	 */
+	public function create_many( $count, $args = array(), $generation_definitions = null ) {
+		$results = array();
+		for ( $i = 0; $i < $count; $i++ ) {
+			$results[] = $this->create( $args, $generation_definitions );
+		}
+		return $results;
+	}
+
+	/**
+	 * Combines the given arguments with the generation_definitions (defaults) and applies
+	 * possibly set callbacks on it.
+	 *
+	 * @param array       $args                   Optional. The arguments to combine with defaults. Default is empty array.
+	 * @param array|null  $generation_definitions Optional. The defaults. Default is null.
+	 * @param array|null  $callbacks              Optional. Array with callbacks to apply on the fields. Default is null.
+	 *
+	 * @return array|WP_Error Combined array on success. WP_Error when default value is incorrent.
+	 */
+	public function generate_args( $args = array(), $generation_definitions = null, &$callbacks = null ) {
+		$callbacks = array();
+		if ( is_null( $generation_definitions ) ) {
+			$generation_definitions = $this->default_generation_definitions;
+		}
+
+		// Use the same incrementor for all fields belonging to this object.
+		$gen = new WP_UnitTest_Generator_Sequence();
+		// Add leading zeros to make sure MySQL sorting works as expected.
+		$incr = zeroise( $gen->get_incr(), 7 );
+
+		foreach ( array_keys( $generation_definitions ) as $field_name ) {
+			if ( ! isset( $args[ $field_name ] ) ) {
+				$generator = $generation_definitions[ $field_name ];
+				if ( is_scalar( $generator ) ) {
+					$args[ $field_name ] = $generator;
+				} elseif ( is_object( $generator ) && method_exists( $generator, 'call' ) ) {
+					$callbacks[ $field_name ] = $generator;
+				} elseif ( is_object( $generator ) ) {
+					$args[ $field_name ] = sprintf( $generator->get_template_string(), $incr );
+				} else {
+					return new WP_Error( 'invalid_argument', 'Factory default value should be either a scalar or an generator object.' );
+				}
+			}
+		}
+
+		return $args;
+	}
+
+
+	/**
+	 * Applies the callbacks on the created object.
+	 *
+	 * @param WP_UnitTest_Factory_Callback_After_Create[] $callbacks Array with callback functions.
+	 * @param mixed                                       $created   The object to apply callbacks for.
+	 *
+	 * @return array The altered fields.
+	 */
+	public function apply_callbacks( $callbacks, $created ) {
+		$updated_fields = array();
+
+		foreach ( $callbacks as $field_name => $generator ) {
+			$updated_fields[ $field_name ] = $generator->call( $created );
+		}
+		return $updated_fields;
+	}
+
+	/**
+	 * Instantiates a callback objects for the given function name.
+	 *
+	 * @param string $function The callback function.
+	 *
+	 * @return WP_UnitTest_Factory_Callback_After_Create
+	 */
+	public function callback( $function ) {
+		return new WP_UnitTest_Factory_Callback_After_Create( $function );
+	}
+
+	/**
+	 * Adds slashes to the given value.
+	 *
+	 * @param array|object|string|mixed $value The value to add slashes to.
+	 *
+	 * @return array|string The value with the possibly applied slashes.
+	 */
+	public function addslashes_deep( $value ) {
+		if ( is_array( $value ) ) {
+			$value = array_map( array( $this, 'addslashes_deep' ), $value );
+		} elseif ( is_object( $value ) ) {
+			$vars = get_object_vars( $value );
+			foreach ( $vars as $key => $data ) {
+				$value->{$key} = $this->addslashes_deep( $data );
+			}
+		} elseif ( is_string( $value ) ) {
+			$value = addslashes( $value );
+		}
+
+		return $value;
+	}
+
+}

+ 58 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory-for-user.php

@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * Unit test factory for users.
+ *
+ * Note: The below @method notations are defined solely for the benefit of IDEs,
+ * as a way to indicate expected return values from the given factory methods.
+ *
+ * @method int create( $args = array(), $generation_definitions = null )
+ * @method WP_User create_and_get( $args = array(), $generation_definitions = null )
+ * @method int[] create_many( $count, $args = array(), $generation_definitions = null )
+ */
+class WP_UnitTest_Factory_For_User extends WP_UnitTest_Factory_For_Thing {
+
+	public function __construct( $factory = null ) {
+		parent::__construct( $factory );
+		$this->default_generation_definitions = array(
+			'user_login' => new WP_UnitTest_Generator_Sequence( 'User %s' ),
+			'user_pass'  => 'password',
+			'user_email' => new WP_UnitTest_Generator_Sequence( 'user_%s@example.org' ),
+		);
+	}
+
+	/**
+	 * Inserts an user.
+	 *
+	 * @param array $args The user data to insert.
+	 *
+	 * @return int|WP_Error The user ID on success, WP_Error object on failure.
+	 */
+	public function create_object( $args ) {
+		return wp_insert_user( $args );
+	}
+
+	/**
+	 * Updates the user data.
+	 *
+	 * @param int   $user_id ID of the user to update.
+	 * @param array $fields  The user data to update.
+	 *
+	 * @return int|WP_Error The user ID on success, WP_Error object on failure.
+	 */
+	public function update_object( $user_id, $fields ) {
+		$fields['ID'] = $user_id;
+		return wp_update_user( $fields );
+	}
+
+	/**
+	 * Retrieves the user for a given ID.
+	 *
+	 * @param int $user_id ID of the user ID to retrieve.
+	 *
+	 * @return WP_User The user object.
+	 */
+	public function get_object_by_id( $user_id ) {
+		return new WP_User( $user_id );
+	}
+}

+ 95 - 0
tests/phpunit/includes/factory/class-wp-unittest-factory.php

@@ -0,0 +1,95 @@
+<?php
+
+/**
+ * A factory for making WordPress data with a cross-object type API.
+ *
+ * Tests should use this factory to generate test fixtures.
+ */
+class WP_UnitTest_Factory {
+
+	/**
+	 * Generates post fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Post
+	 */
+	public $post;
+
+	/**
+	 * Generates attachment fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Attachment
+	 */
+	public $attachment;
+
+	/**
+	 * Generates comment fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Comment
+	 */
+	public $comment;
+
+	/**
+	 * Generates user fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_User
+	 */
+	public $user;
+
+	/**
+	 * Generates taxonomy term fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Term
+	 */
+	public $term;
+
+	/**
+	 * Generates category fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Term
+	 */
+	public $category;
+
+	/**
+	 * Generates tag fixtures for use in tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Term
+	 */
+	public $tag;
+
+	/**
+	 * Generates bookmark (link) fixtures for use in tests.
+	 *
+	 * @since 4.6.0
+	 * @var WP_UnitTest_Factory_For_Bookmark
+	 */
+	public $bookmark;
+
+	/**
+	 * Generates blog (site) fixtures for use in Multisite tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Blog
+	 */
+	public $blog;
+
+	/**
+	 * Generates network fixtures for use in Multisite tests.
+	 *
+	 * @var WP_UnitTest_Factory_For_Network
+	 */
+	public $network;
+
+	public function __construct() {
+		$this->post       = new WP_UnitTest_Factory_For_Post( $this );
+		$this->attachment = new WP_UnitTest_Factory_For_Attachment( $this );
+		$this->comment    = new WP_UnitTest_Factory_For_Comment( $this );
+		$this->user       = new WP_UnitTest_Factory_For_User( $this );
+		$this->term       = new WP_UnitTest_Factory_For_Term( $this );
+		$this->category   = new WP_UnitTest_Factory_For_Term( $this, 'category' );
+		$this->tag        = new WP_UnitTest_Factory_For_Term( $this, 'post_tag' );
+		$this->bookmark   = new WP_UnitTest_Factory_For_Bookmark( $this );
+		if ( is_multisite() ) {
+			$this->blog    = new WP_UnitTest_Factory_For_Blog( $this );
+			$this->network = new WP_UnitTest_Factory_For_Network( $this );
+		}
+	}
+}

+ 45 - 0
tests/phpunit/includes/factory/class-wp-unittest-generator-sequence.php

@@ -0,0 +1,45 @@
+<?php
+
+class WP_UnitTest_Generator_Sequence {
+	public static $incr = -1;
+	public $next;
+	public $template_string;
+
+	public function __construct( $template_string = '%s', $start = null ) {
+		if ( $start ) {
+			$this->next = $start;
+		} else {
+			self::$incr++;
+			$this->next = self::$incr;
+		}
+		$this->template_string = $template_string;
+	}
+
+	public function next() {
+		$generated = sprintf( $this->template_string, $this->next );
+		$this->next++;
+		return $generated;
+	}
+
+	/**
+	 * Get the incrementor.
+	 *
+	 * @since 4.6.0
+	 *
+	 * @return int
+	 */
+	public function get_incr() {
+		return self::$incr;
+	}
+
+	/**
+	 * Get the template string.
+	 *
+	 * @since 4.6.0
+	 *
+	 * @return string
+	 */
+	public function get_template_string() {
+		return $this->template_string;
+	}
+}

+ 7 - 0
tests/phpunit/includes/listener-loader.php

@@ -0,0 +1,7 @@
+<?php
+
+if ( version_compare( tests_get_phpunit_version(), '7.0', '>=' ) ) {
+	require __DIR__ . '/phpunit7/speed-trap-listener.php';
+} else {
+	require __DIR__ . '/speed-trap-listener.php';
+}

+ 76 - 0
tests/phpunit/includes/normalize-xml.xsl

@@ -0,0 +1,76 @@
+<?xml version='1.0' encoding='UTF-8' ?>
+<!--
+	Normalize an XML document to make it easier to compare whether 2 documents will
+	be seen as "equal" to an XML processor.
+
+	The normalization is similiar, in spirit, to {@link https://www.w3.org/TR/xml-c14n11/ Canonical XML},
+	but without some aspects of C14N that make the kinds of assertions we need difficult.
+
+	For example, the following XML documents will be interpreted the same by an XML processor,
+	even though a string comparison of them would show differences:
+
+	<root xmlns='urn:example'>
+		<ns0:child xmlns:ns0='urn:another-example'>this is a test</ns0:child>
+	</root>
+
+	<ns0:root xmlns:ns0='urn:example'>
+		<child xmlns='urn:another-example'>this is a test</child>
+	</ns0:root>
+  -->
+<xsl:transform
+		xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
+		version='1.0'
+	>
+
+	<!--
+		Output UTF-8 XML, no indendation and all CDATA sections replaced with their character content. 
+	  -->
+	<xsl:output
+		method='xml'
+		indent='no'
+		cdata-section-elements=''
+		encoding='UTF-8' />
+
+	<!--
+		Strip insignificant white space.
+	  -->
+	<xsl:strip-space elements='*' />
+
+	<!--
+		Noramlize elements by not relying on the prefix used in the input document
+		and ordering attributes first by namespace-uri and then by local-name.
+	  -->
+	<xsl:template match='*' priority='10'>
+		<xsl:element name='{local-name()}' namespace='{namespace-uri()}'>
+			<xsl:apply-templates select='@*'>
+				<xsl:sort select='namespace-uri()' />
+				<xsl:sort select='local-name()' />
+			</xsl:apply-templates>
+
+			<xsl:apply-templates select='node()' />
+		</xsl:element>
+	</xsl:template>
+
+	<!--
+		Noramlize attributes by not relying on the prefix used in the input document.
+	  -->
+	<xsl:template match='@*'>
+		<xsl:attribute name='{local-name()}' namespace='{namespace-uri()}'>
+			<xsl:value-of select='.' />
+		</xsl:attribute>
+	</xsl:template>
+
+	<!--
+		Strip comments. 
+	  -->
+	<xsl:template match='comment()' priority='10' />
+
+	<!--
+		Pass all other nodes through unchanged.  
+	  -->
+	<xsl:template match='node()'>
+		<xsl:copy>
+			<xsl:apply-templates select='node()' />
+		</xsl:copy>
+	</xsl:template>
+</xsl:transform>

+ 2187 - 0
tests/phpunit/includes/object-cache.php

@@ -0,0 +1,2187 @@
+<?php
+/**
+ * Adds a value to cache.
+ *
+ * If the specified key already exists, the value is not stored and the function
+ * returns false.
+ *
+ * @link https://www.php.net/manual/en/memcached.add.php
+ *
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_add( $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->add( $key, $value, $group, $expiration );
+}
+
+/**
+ * Adds a value to cache on a specific server.
+ *
+ * Using a server_key value, the object can be stored on a specified server as opposed
+ * to a random server in the stack. Note that this method will add the key/value to the
+ * _cache object as part of the runtime cache. It will add it to an array for the
+ * specified server_key.
+ *
+ * @link https://www.php.net/manual/en/memcached.addbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_add_by_key( $server_key, $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->addByKey( $server_key, $key, $value, $group, $expiration );
+}
+
+/**
+ * Adds a single server to the list of Memcached servers.
+ *
+ * @link https://www.php.net/manual/en/memcached.addserver.php
+ *
+ * @param string $host   The hostname of the memcache server.
+ * @param int    $port   The port on which memcache is running.
+ * @param int    $weight The weight of the server relative to the total weight
+ *                       of all the servers in the pool.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_add_server( $host, $port, $weight = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->addServer( $host, $port, $weight );
+}
+
+/**
+ * Adds an array of servers to the pool.
+ *
+ * Each individual server in the array must include a domain and port, with an optional
+ * weight value: $servers = array( array( '127.0.0.1', 11211, 0 ) );
+ *
+ * @link https://www.php.net/manual/en/memcached.addservers.php
+ *
+ * @param array $servers Array of server to register.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_add_servers( $servers ) {
+	global $wp_object_cache;
+	return $wp_object_cache->addServers( $servers );
+}
+
+/**
+ * Appends data to an existing item.
+ *
+ * This method should throw an error if it is used with compressed data.
+ * This is an expected behavior. Memcached casts the value to be appended to the initial value
+ * to the type of the initial value. Be careful as this leads to unexpected behavior at times.
+ * Due to how memcached treats types, the behavior has been mimicked in the internal cache to produce
+ * similar results and improve consistency. It is recommended that appends only occur with data of
+ * the same type.
+ *
+ * @link https://www.php.net/manual/en/memcached.append.php
+ *
+ * @param string $key   The key under which to store the value.
+ * @param mixed  $value Must be string as appending mixed values is not well-defined.
+ * @param string $group The group value appended to the $key.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_append( $key, $value, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->append( $key, $value, $group );
+}
+
+/**
+ * Appends data to an existing item by server key.
+ *
+ * This method should throw an error if it is used with compressed data.
+ * This is an expected behavior. Memcached casts the value to be appended to the initial value
+ * to the type of the initial value. Be careful as this leads to unexpected behavior at times.
+ * Due to how memcached treats types, the behavior has been mimicked in the internal cache to produce
+ * similar results and improve consistency. It is recommended that appends only occur with data of
+ * the same type.
+ *
+ * @link https://www.php.net/manual/en/memcached.appendbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      Must be string as appending mixed values is not well-defined.
+ * @param string $group      The group value appended to the $key.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_append_by_key( $server_key, $key, $value, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->appendByKey( $server_key, $key, $value, $group );
+}
+
+/**
+ * Performs a "check and set" to store data.
+ *
+ * The set will be successful only if the no other request has updated the value
+ * since it was fetched by this request.
+ *
+ * @link https://www.php.net/manual/en/memcached.cas.php
+ *
+ * @param float  $cas_token  Unique value associated with the existing item. Generated by memcached.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_cas( $cas_token, $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->cas( $cas_token, $key, $value, $group, $expiration );
+}
+
+/**
+ * Performs a "check and set" to store data with a server key.
+ *
+ * The set will be successful only if the no other request has updated the value
+ * since it was fetched by this request.
+ *
+ * @link https://www.php.net/manual/en/memcached.casbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param float  $cas_token  Unique value associated with the existing item. Generated by memcached.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_cas_by_key( $cas_token, $server_key, $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->casByKey( $cas_token, $server_key, $key, $value, $group, $expiration );
+}
+
+/**
+ * Closes the cache.
+ *
+ * This function has ceased to do anything since WordPress 2.5.
+ * The functionality was removed along with the rest of the persistent cache.
+ * This does not mean that plugins can't implement this function when they need
+ * to make sure that the cache is cleaned up after WordPress no longer needs it.
+ *
+ * @since 2.0.0
+ *
+ * @return bool Always returns true.
+ */
+function wp_cache_close() {
+	return true;
+}
+
+/**
+ * Decrements a numeric item's value.
+ *
+ * @link https://www.php.net/manual/en/memcached.decrement.php
+ *
+ * @param string $key    The key under which to store the value.
+ * @param int    $offset The amount by which to decrement the item's value.
+ * @param string $group  The group value appended to the $key.
+ * @return int|bool Item's new value on success, false on failure.
+ */
+function wp_cache_decrement( $key, $offset = 1, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->decrement( $key, $offset, $group );
+}
+
+/**
+ * Decrements a numeric item's value.
+ *
+ * This is the same as wp_cache_decrement(), but kept for backward compatibility.
+ * The original WordPress caching backends use wp_cache_decr().
+ *
+ * @link https://www.php.net/manual/en/memcached.decrement.php
+ *
+ * @param string $key    The key under which to store the value.
+ * @param int    $offset The amount by which to decrement the item's value.
+ * @param string $group  The group value appended to the $key.
+ * @return int|bool Item's new value on success, false on failure.
+ */
+function wp_cache_decr( $key, $offset = 1, $group = '' ) {
+	return wp_cache_decrement( $key, $offset, $group );
+}
+
+/**
+ * Removes the item from the cache.
+ *
+ * Removes an item from memcached with identified by $key after $time seconds.
+ * The $time parameter allows an object to be queued for deletion without
+ * immediately deleting. Between the time that it is queued and the time it's deleted,
+ * add, replace, and get will fail, but set will succeed.
+ *
+ * @link https://www.php.net/manual/en/memcached.delete.php
+ *
+ * @param string $key   The key under which to store the value.
+ * @param string $group The group value appended to the $key.
+ * @param int    $time  The amount of time the server will wait to delete the item in seconds.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_delete( $key, $group = '', $time = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->delete( $key, $group, $time );
+}
+
+/**
+ * Removes the item from the cache by server key.
+ *
+ * Removes an item from memcached with identified by $key after $time seconds.
+ * The $time parameter allows an object to be queued for deletion without
+ * immediately deleting. Between the time that it is queued and the time it's deleted,
+ * add, replace, and get will fail, but set will succeed.
+ *
+ * @link https://www.php.net/manual/en/memcached.deletebykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $time       The amount of time the server will wait to delete the item in seconds.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_delete_by_key( $server_key, $key, $group = '', $time = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->deleteByKey( $server_key, $key, $group, $time );
+}
+
+/**
+ * Fetches the next result.
+ *
+ * @link https://www.php.net/manual/en/memcached.fetch.php
+ *
+ * @return array|false The next result on success, false on failure.
+ */
+function wp_cache_fetch() {
+	global $wp_object_cache;
+	return $wp_object_cache->fetch();
+}
+
+/**
+ * Fetches all remaining results from the last request.
+ *
+ * @link https://www.php.net/manual/en/memcached.fetchall.php
+ *
+ * @return array|false The results on success, false on failure.
+ */
+function wp_cache_fetch_all() {
+	global $wp_object_cache;
+	return $wp_object_cache->fetchAll();
+}
+
+/**
+ * Invalidates all items in the cache.
+ *
+ * @link https://www.php.net/manual/en/memcached.flush.php
+ *
+ * @param int $delay Number of seconds to wait before invalidating the items.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_flush( $delay = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->flush( $delay );
+}
+
+/**
+ * Retrieves object from cache.
+ *
+ * Gets an object from cache based on $key and $group. In order to fully support
+ * the $cache_cb and $cas_token parameters, the runtime cache is ignored by this function
+ * if either of those values are set. In that case, the request is made directly
+ * to the memcached server for proper handling of the callback and/or token.
+ *
+ * Note that the $deprecated and $found args are only here for compatibility
+ * with the native wp_cache_get() function.
+ *
+ * @link https://www.php.net/manual/en/memcached.get.php
+ *
+ * @param string      $key       The key under which to store the value.
+ * @param string      $group     The group value appended to the $key.
+ * @param bool        $force     Whether or not to force a cache invalidation.
+ * @param null|bool   $found     Variable passed by reference to determine if the value was found or not.
+ * @param null|string $cache_cb  Read-through caching callback.
+ * @param null|float  $cas_token The variable to store the CAS token in.
+ * @return bool|mixed Cached object value.
+ */
+function wp_cache_get( $key, $group = '', $force = false, &$found = null, $cache_cb = null, &$cas_token = null ) {
+	global $wp_object_cache;
+
+	if ( func_num_args() > 4 ) {
+		return $wp_object_cache->get( $key, $group, $force, $found, '', false, $cache_cb, $cas_token );
+	} else {
+		return $wp_object_cache->get( $key, $group, $force, $found );
+	}
+}
+
+/**
+ * Retrieves object from cache from specified server.
+ *
+ * Gets an object from cache based on $key, $group, and $server_key. In order to fully support
+ * the $cache_cb and $cas_token parameters, the runtime cache is ignored by this function
+ * if either of those values are set. In that case, the request is made directly
+ * to the memcached server for proper handling of the callback and/or token.
+ *
+ * @link https://www.php.net/manual/en/memcached.getbykey.php
+ *
+ * @param string      $server_key The key identifying the server to store the value on.
+ * @param string      $key        The key under which to store the value.
+ * @param string      $group      The group value appended to the $key.
+ * @param bool        $force      Whether or not to force a cache invalidation.
+ * @param null|bool   $found      Variable passed by reference to determine if the value was found or not.
+ * @param null|string $cache_cb   Read-through caching callback.
+ * @param null|float  $cas_token  The variable to store the CAS token in.
+ * @return bool|mixed Cached object value.
+ */
+function wp_cache_get_by_key( $server_key, $key, $group = '', $force = false, &$found = null, $cache_cb = null, &$cas_token = null ) {
+	global $wp_object_cache;
+
+	if ( func_num_args() > 5 ) {
+		return $wp_object_cache->getByKey( $server_key, $key, $group, $force, $found, $cache_cb, $cas_token );
+	} else {
+		return $wp_object_cache->getByKey( $server_key, $key, $group, $force, $found );
+	}
+}
+
+/**
+ * Requests multiple keys without blocking.
+ *
+ * @link https://www.php.net/manual/en/memcached.getdelayed.php
+ *
+ * @param string|array $keys     Array or string of key(s) to request.
+ * @param string|array $groups   Array or string of group(s) for the key(s).
+ *                               See buildKeys for more on how these are handled.
+ * @param bool         $with_cas Whether to request CAS token values also.
+ * @param null         $value_cb The result callback or null.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_get_delayed( $keys, $groups = '', $with_cas = false, $value_cb = null ) {
+	global $wp_object_cache;
+	return $wp_object_cache->getDelayed( $keys, $groups, $with_cas, $value_cb );
+}
+
+/**
+ * Requests multiple keys without blocking from a specified server.
+ *
+ * @link https://www.php.net/manual/en/memcached.getdelayed.php
+ *
+ * @param string       $server_key The key identifying the server to store the value on.
+ * @param string|array $keys       Array or string of key(s) to request.
+ * @param string|array $groups     Array or string of group(s) for the key(s).
+ *                                 See buildKeys for more on how these are handled.
+ * @param bool         $with_cas   Whether to request CAS token values also.
+ * @param null         $value_cb   The result callback or null.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_get_delayed_by_key( $server_key, $keys, $groups = '', $with_cas = false, $value_cb = null ) {
+	global $wp_object_cache;
+	return $wp_object_cache->getDelayedByKey( $server_key, $keys, $groups, $with_cas, $value_cb );
+}
+
+/**
+ * Gets multiple values from memcached in one request.
+ *
+ * See the buildKeys method definition to understand the $keys/$groups parameters.
+ *
+ * @link https://www.php.net/manual/en/memcached.getmulti.php
+ *
+ * @param array        $keys       Array of keys to retrieve.
+ * @param string|array $groups     If string, used for all keys.
+ *                                 If arrays, corresponds with the $keys array.
+ * @param null|array   $cas_tokens The variable to store the CAS tokens for the found items.
+ * @param int          $flags      The flags for the get operation.
+ * @return bool|array The array of found items on success, false on failure.
+ */
+function wp_cache_get_multi( $keys, $groups = '', &$cas_tokens = null, $flags = null ) {
+	global $wp_object_cache;
+
+	if ( func_num_args() > 2 ) {
+		return $wp_object_cache->getMulti( $keys, $groups, '', $cas_tokens, $flags );
+	} else {
+		return $wp_object_cache->getMulti( $keys, $groups );
+	}
+}
+
+/**
+ * Gets multiple values from memcached in one request by specified server key.
+ *
+ * See the buildKeys method definition to understand the $keys/$groups parameters.
+ *
+ * @link https://www.php.net/manual/en/memcached.getmultibykey.php
+ *
+ * @param string       $server_key The key identifying the server to store the value on.
+ * @param array        $keys       Array of keys to retrieve.
+ * @param string|array $groups     If string, used for all keys.
+ *                                 If arrays, corresponds with the $keys array.
+ * @param null|array   $cas_tokens The variable to store the CAS tokens for the found items.
+ * @param int          $flags      The flags for the get operation.
+ * @return bool|array The array of found items on success, false on failure.
+ */
+function wp_cache_get_multi_by_key( $server_key, $keys, $groups = '', &$cas_tokens = null, $flags = null ) {
+	global $wp_object_cache;
+
+	if ( func_num_args() > 3 ) {
+		return $wp_object_cache->getMultiByKey( $server_key, $keys, $groups, $cas_tokens, $flags );
+	} else {
+		return $wp_object_cache->getMultiByKey( $server_key, $keys, $groups );
+	}
+}
+
+/**
+ * Retrieves a Memcached option value.
+ *
+ * @link https://www.php.net/manual/en/memcached.getoption.php
+ *
+ * @param int $option One of the Memcached::OPT_* constants.
+ * @return mixed The value of the requested option on success, false on failure.
+ */
+function wp_cache_get_option( $option ) {
+	global $wp_object_cache;
+	return $wp_object_cache->getOption( $option );
+}
+
+/**
+ * Returns the result code of the last option.
+ *
+ * @link https://www.php.net/manual/en/memcached.getresultcode.php
+ *
+ * @return int Result code of the last Memcached operation.
+ */
+function wp_cache_get_result_code() {
+	global $wp_object_cache;
+	return $wp_object_cache->getResultCode();
+}
+
+/**
+ * Return the message describing the result of the last operation.
+ *
+ * @link https://www.php.net/manual/en/memcached.getresultmessage.php
+ *
+ * @return string Message describing the result of the last Memcached operation.
+ */
+function wp_cache_get_result_message() {
+	global $wp_object_cache;
+	return $wp_object_cache->getResultMessage();
+}
+
+/**
+ * Gets server information by key.
+ *
+ * @link https://www.php.net/manual/en/memcached.getserverbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @return array Array with host, post, and weight on success, fales on failure.
+ */
+function wp_cache_get_server_by_key( $server_key ) {
+	global $wp_object_cache;
+	return $wp_object_cache->getServerByKey( $server_key );
+}
+
+/**
+ * Gets the list of servers in the pool.
+ *
+ * @link https://www.php.net/manual/en/memcached.getserverlist.php
+ *
+ * @return array The list of all servers in the server pool.
+ */
+function wp_cache_get_server_list() {
+	global $wp_object_cache;
+	return $wp_object_cache->getServerList();
+}
+
+/**
+ * Gets server pool statistics.
+ *
+ * @link https://www.php.net/manual/en/memcached.getstats.php
+ *
+ * @return array Array of server statistics, one entry per server.
+ */
+function wp_cache_get_stats() {
+	global $wp_object_cache;
+	return $wp_object_cache->getStats();
+}
+
+/**
+ * Gets server pool memcached version information.
+ *
+ * @link https://www.php.net/manual/en/memcached.getversion.php
+ *
+ * @return array Array of server versions, one entry per server.
+ */
+function wp_cache_get_version() {
+	global $wp_object_cache;
+	return $wp_object_cache->getVersion();
+}
+
+/**
+ * Increments a numeric item's value.
+ *
+ * @link https://www.php.net/manual/en/memcached.increment.php
+ *
+ * @param string $key    The key under which to store the value.
+ * @param int    $offset The amount by which to increment the item's value.
+ * @param string $group  The group value appended to the $key.
+ * @return int|bool Item's new value on success, false on failure.
+ */
+function wp_cache_increment( $key, $offset = 1, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->increment( $key, $offset, $group );
+}
+
+/**
+ * Increments a numeric item's value.
+ *
+ * This is the same as wp_cache_increment(), but kept for backward compatibility.
+ * The original WordPress caching backends use wp_cache_incr().
+ *
+ * @link https://www.php.net/manual/en/memcached.increment.php
+ *
+ * @param string $key    The key under which to store the value.
+ * @param int    $offset The amount by which to increment the item's value.
+ * @param string $group  The group value appended to the $key.
+ * @return int|bool Item's new value on success, false on failure.
+ */
+function wp_cache_incr( $key, $offset = 1, $group = '' ) {
+	return wp_cache_increment( $key, $offset, $group );
+}
+
+/**
+ * Prepends data to an existing item.
+ *
+ * This method should throw an error if it is used with compressed data. This is an expected behavior.
+ * Memcached casts the value to be prepended to the initial value to the type of the initial value.
+ * Be careful as this leads to unexpected behavior at times. For instance, prepending (float) 45.23
+ * to (int) 23 will result in 45, because the value is first combined (45.2323) then cast to "integer"
+ * (the original value), which will be (int) 45. Due to how memcached treats types, the behavior has been
+ * mimicked in the internal cache to produce similar results and improve consistency. It is recommended
+ * that prepends only occur with data of the same type.
+ *
+ * @link https://www.php.net/manual/en/memcached.prepend.php
+ *
+ * @param string $key   The key under which to store the value.
+ * @param string $value Must be string as prepending mixed values is not well-defined.
+ * @param string $group The group value prepended to the $key.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_prepend( $key, $value, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->prepend( $key, $value, $group );
+}
+
+/**
+ * Appends data to an existing item by server key.
+ *
+ * This method should throw an error if it is used with compressed data. This is an expected behavior.
+ * Memcached casts the value to be prepended to the initial value to the type of the initial value.
+ * Be careful as this leads to unexpected behavior at times. For instance, prepending (float) 45.23
+ * to (int) 23 will result in 45, because the value is first combined (45.2323) then cast to "integer"
+ * (the original value), which will be (int) 45. Due to how memcached treats types, the behavior has been
+ * mimicked in the internal cache to produce similar results and improve consistency. It is recommended
+ * that prepends only occur with data of the same type.
+ *
+ * @link https://www.php.net/manual/en/memcached.prependbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param string $value      Must be string as prepending mixed values is not well-defined.
+ * @param string $group      The group value prepended to the $key.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_prepend_by_key( $server_key, $key, $value, $group = '' ) {
+	global $wp_object_cache;
+	return $wp_object_cache->prependByKey( $server_key, $key, $value, $group );
+}
+
+/**
+ * Replaces a value in cache.
+ *
+ * This method is similar to "add"; however, is does not successfully set a value
+ * if the object's key is not already set in cache.
+ *
+ * @link https://www.php.net/manual/en/memcached.replace.php
+ *
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_replace( $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->replace( $key, $value, $group, $expiration );
+}
+
+/**
+ * Replaces a value in cache on a specific server.
+ *
+ * This method is similar to "addByKey"; however, is does not successfully set a value
+ * if the object's key is not already set in cache.
+ *
+ * @link https://www.php.net/manual/en/memcached.addbykey.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_replace_by_key( $server_key, $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->replaceByKey( $server_key, $key, $value, $group, $expiration );
+}
+
+/**
+ * Sets a value in cache.
+ *
+ * The value is set whether or not this key already exists in memcached.
+ *
+ * @link https://www.php.net/manual/en/memcached.set.php
+ *
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_set( $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->set( $key, $value, $group, $expiration );
+}
+
+/**
+ * Sets a value in cache.
+ *
+ * The value is set whether or not this key already exists in memcached.
+ *
+ * @link https://www.php.net/manual/en/memcached.set.php
+ *
+ * @param string $server_key The key identifying the server to store the value on.
+ * @param string $key        The key under which to store the value.
+ * @param mixed  $value      The value to store.
+ * @param string $group      The group value appended to the $key.
+ * @param int    $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_set_by_key( $server_key, $key, $value, $group = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->setByKey( $server_key, $key, $value, $group, $expiration );
+}
+
+/**
+ * Sets multiple values to cache at once.
+ *
+ * By sending an array of $items to this function, all values are saved at once to
+ * memcached, reducing the need for multiple requests to memcached. The $items array
+ * keys and values are what are stored to memcached. The keys in the $items array
+ * are merged with the $groups array/string value via buildKeys to determine the
+ * final key for the object.
+ *
+ * @param array        $items      An array of key/value pairs to store on the server.
+ * @param string|array $groups     Group(s) to merge with key(s) in $items.
+ * @param int          $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_set_multi( $items, $groups = '', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->setMulti( $items, $groups, $expiration );
+}
+
+/**
+ * Sets multiple values to cache at once on specified server.
+ *
+ * By sending an array of $items to this function, all values are saved at once to
+ * memcached, reducing the need for multiple requests to memcached. The $items array
+ * keys and values are what are stored to memcached. The keys in the $items array
+ * are merged with the $groups array/string value via buildKeys to determine the
+ * final key for the object.
+ *
+ * @param string       $server_key The key identifying the server to store the value on.
+ * @param array        $items      An array of key/value pairs to store on the server.
+ * @param string|array $groups     Group(s) to merge with key(s) in $items.
+ * @param int          $expiration The expiration time, defaults to 0.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_set_multi_by_key( $server_key, $items, $groups = 'default', $expiration = 0 ) {
+	global $wp_object_cache;
+	return $wp_object_cache->setMultiByKey( $server_key, $items, $groups, $expiration );
+}
+
+/**
+ * Sets a Memcached option.
+ *
+ * @link https://www.php.net/manual/en/memcached.setoption.php
+ *
+ * @param int   $option Option name.
+ * @param mixed $value  Option value.
+ * @return bool True on success, false on failure.
+ */
+function wp_cache_set_option( $option, $value ) {
+	global $wp_object_cache;
+	return $wp_object_cache->setOption( $option, $value );
+}
+
+/**
+ * Switches blog prefix, which changes the cache that is accessed.
+ *
+ * @param int $blog_id Blog to switch to.
+ * @return void
+ */
+function wp_cache_switch_to_blog( $blog_id ) {
+	global $wp_object_cache;
+	return $wp_object_cache->switch_to_blog( $blog_id );
+}
+
+
+/**
+ * Sets up Object Cache Global and assigns it.
+ *
+ * @global WP_Object_Cache $wp_object_cache WordPress Object Cache
+ * @return void
+ */
+function wp_cache_init() {
+	global $wp_object_cache;
+	$wp_object_cache = new WP_Object_Cache();
+}
+
+/**
+ * Adds a group or set of groups to the list of non-persistent groups.
+ *
+ * @param string|array $groups A group or an array of groups to add.
+ * @return void
+ */
+function wp_cache_add_global_groups( $groups ) {
+	global $wp_object_cache;
+	$wp_object_cache->add_global_groups( $groups );
+}
+
+/**
+ * Adds a group or set of groups to the list of non-Memcached groups.
+ *
+ * @param string|array $groups A group or an array of groups to add.
+ * @return void
+ */
+function wp_cache_add_non_persistent_groups( $groups ) {
+	global $wp_object_cache;
+	$wp_object_cache->add_non_persistent_groups( $groups );
+}
+
+// phpcs:disable WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
+class WP_Object_Cache {
+
+	/**
+	 * Holds the Memcached object.
+	 *
+	 * @var Memcached
+	 */
+	public $m;
+
+	/**
+	 * Hold the Memcached server details.
+	 *
+	 * @var array
+	 */
+	public $servers;
+
+	/**
+	 * Holds the non-Memcached objects.
+	 *
+	 * @var array
+	 */
+	public $cache = array();
+
+	/**
+	 * List of global groups.
+	 *
+	 * @var array
+	 */
+	public $global_groups = array( 'users', 'userlogins', 'usermeta', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss' );
+
+	/**
+	 * List of groups not saved to Memcached.
+	 *
+	 * @var array
+	 */
+	public $no_mc_groups = array( 'comment', 'counts' );
+
+	/**
+	 * Prefix used for global groups.
+	 *
+	 * @var string
+	 */
+	public $global_prefix = '';
+
+	/**
+	 * Prefix used for non-global groups.
+	 *
+	 * @var string
+	 */
+	public $blog_prefix = '';
+
+	/**
+	 * Instantiates the Memcached class.
+	 *
+	 * Instantiates the Memcached class and returns adds the servers specified
+	 * in the $memcached_servers global array.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.construct.php
+	 *
+	 * @param null $persistent_id To create an instance that persists between requests,
+	 *                            use persistent_id to specify a unique ID for the instance.
+	 */
+	public function __construct( $persistent_id = null ) {
+		global $memcached_servers, $blog_id, $table_prefix;
+
+		if ( is_null( $persistent_id ) || ! is_string( $persistent_id ) ) {
+			$this->m = new Memcached();
+		} else {
+			$this->m = new Memcached( $persistent_id );
+		}
+
+		if ( isset( $memcached_servers ) ) {
+			$this->servers = $memcached_servers;
+		} else {
+			$this->servers = array( array( 'memcached', 11211 ) );
+		}
+
+		$this->addServers( $this->servers );
+
+		/**
+		 * This approach is borrowed from Sivel and Boren. Use the salt for easy cache invalidation
+		 * and for multi single WP installations on the same server.
+		 */
+		if ( ! defined( 'WP_CACHE_KEY_SALT' ) ) {
+			define( 'WP_CACHE_KEY_SALT', '' );
+		}
+
+		// Assign global and blog prefixes for use with keys.
+		if ( function_exists( 'is_multisite' ) ) {
+			$this->global_prefix = ( is_multisite() || defined( 'CUSTOM_USER_TABLE' ) && defined( 'CUSTOM_USER_META_TABLE' ) ) ? '' : $table_prefix;
+			$this->blog_prefix   = ( is_multisite() ? $blog_id : $table_prefix ) . ':';
+		}
+
+		// Setup cacheable values for handling expiration times.
+		$this->thirty_days = 60 * 60 * 24 * 30;
+		$this->now         = time();
+	}
+
+	/**
+	 * Adds a value to cache.
+	 *
+	 * If the specified key already exists, the value is not stored and the function
+	 * returns false.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.add.php
+	 *
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function add( $key, $value, $group = 'default', $expiration = 0, $server_key = '', $by_key = false ) {
+		/*
+		 * Ensuring that wp_suspend_cache_addition is defined before calling, because sometimes an advanced-cache.php
+		 * file will load object-cache.php before wp-includes/functions.php is loaded. In those cases, if wp_cache_add
+		 * is called in advanced-cache.php before any more of WordPress is loaded, we get a fatal error because
+		 * wp_suspend_cache_addition will not be defined until wp-includes/functions.php is loaded.
+		 */
+		if ( function_exists( 'wp_suspend_cache_addition' ) && wp_suspend_cache_addition() ) {
+			return false;
+		}
+
+		$derived_key = $this->buildKey( $key, $group );
+		$expiration  = $this->sanitize_expiration( $expiration );
+
+		// If group is a non-Memcached group, save to runtime cache, not Memcached.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+
+			// Add does not set the value if the key exists; mimic that here.
+			if ( isset( $this->cache[ $derived_key ] ) ) {
+				return false;
+			}
+
+			$this->add_to_internal_cache( $derived_key, $value );
+
+			return true;
+		}
+
+		// Save to Memcached.
+		if ( $by_key ) {
+			$result = $this->m->addByKey( $server_key, $derived_key, $value, $expiration );
+		} else {
+			$result = $this->m->add( $derived_key, $value, $expiration );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Adds a value to cache on a specific server.
+	 *
+	 * Using a server_key value, the object can be stored on a specified server as opposed
+	 * to a random server in the stack. Note that this method will add the key/value to the
+	 * _cache object as part of the runtime cache. It will add it to an array for the
+	 * specified server_key.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.addbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function addByKey( $server_key, $key, $value, $group = 'default', $expiration = 0 ) {
+		return $this->add( $key, $value, $group, $expiration, $server_key, true );
+	}
+
+	/**
+	 * Adds a single server to the list of Memcached servers.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.addserver.php
+	 *
+	 * @param string $host   The hostname of the memcache server.
+	 * @param int    $port   The port on which memcache is running.
+	 * @param int    $weight The weight of the server relative to the total weight
+	 *                       of all the servers in the pool.
+	 * @return bool True on success, false on failure.
+	 */
+	public function addServer( $host, $port, $weight = 0 ) {
+		$host   = is_string( $host ) ? $host : '127.0.0.1';
+		$port   = is_numeric( $port ) && $port > 0 ? $port : 11211;
+		$weight = is_numeric( $weight ) && $weight > 0 ? $weight : 1;
+
+		return $this->m->addServer( $host, $port, $weight );
+	}
+
+	/**
+	 * Adds an array of servers to the pool.
+	 *
+	 * Each individual server in the array must include a domain and port, with an optional
+	 * weight value: $servers = array( array( '127.0.0.1', 11211, 0 ) );
+	 *
+	 * @link https://www.php.net/manual/en/memcached.addservers.php
+	 *
+	 * @param array $servers Array of server to register.
+	 * @return bool True on success, false on failure.
+	 */
+	public function addServers( $servers ) {
+		if ( ! is_object( $this->m ) ) {
+			return false;
+		}
+
+		return $this->m->addServers( $servers );
+	}
+
+	/**
+	 * Appends data to an existing item.
+	 *
+	 * This method should throw an error if it is used with compressed data.
+	 * This is an expected behavior. Memcached casts the value to be appended to the initial value
+	 * to the type of the initial value. Be careful as this leads to unexpected behavior at times.
+	 * Due to how memcached treats types, the behavior has been mimicked in the internal cache to produce
+	 * similar results and improve consistency. It is recommended that appends only occur with data of
+	 * the same type.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.append.php
+	 *
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      Must be string as appending mixed values is not well-defined.
+	 * @param string $group      The group value appended to the $key.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function append( $key, $value, $group = 'default', $server_key = '', $by_key = false ) {
+		if ( ! is_string( $value ) && ! is_int( $value ) && ! is_float( $value ) ) {
+			return false;
+		}
+
+		$derived_key = $this->buildKey( $key, $group );
+
+		// If group is a non-Memcached group, append to runtime cache value, not Memcached.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+			if ( ! isset( $this->cache[ $derived_key ] ) ) {
+				return false;
+			}
+
+			$combined = $this->combine_values( $this->cache[ $derived_key ], $value, 'app' );
+			$this->add_to_internal_cache( $derived_key, $combined );
+			return true;
+		}
+
+		// Append to Memcached value.
+		if ( $by_key ) {
+			$result = $this->m->appendByKey( $server_key, $derived_key, $value );
+		} else {
+			$result = $this->m->append( $derived_key, $value );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$combined = $this->combine_values( $this->cache[ $derived_key ], $value, 'app' );
+			$this->add_to_internal_cache( $derived_key, $combined );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Appends data to an existing item by server key.
+	 *
+	 * This method should throw an error if it is used with compressed data.
+	 * This is an expected behavior. Memcached casts the value to be appended to the initial value
+	 * to the type of the initial value. Be careful as this leads to unexpected behavior at times.
+	 * Due to how memcached treats types, the behavior has been mimicked in the internal cache to produce
+	 * similar results and improve consistency. It is recommended that appends only occur with data of
+	 * the same type.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.appendbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      Must be string as appending mixed values is not well-defined.
+	 * @param string $group      The group value appended to the $key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function appendByKey( $server_key, $key, $value, $group = 'default' ) {
+		return $this->append( $key, $value, $group, $server_key, true );
+	}
+
+	/**
+	 * Performs a "check and set" to store data.
+	 *
+	 * The set will be successful only if the no other request has updated the value
+	 * since it was fetched by this request.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.cas.php
+	 *
+	 * @param float  $cas_token  Unique value associated with the existing item. Generated by memcached.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function cas( $cas_token, $key, $value, $group = 'default', $expiration = 0, $server_key = '', $by_key = false ) {
+		$derived_key = $this->buildKey( $key, $group );
+		$expiration  = $this->sanitize_expiration( $expiration );
+
+		/**
+		 * If group is a non-Memcached group, save to runtime cache, not Memcached. Note
+		 * that since check and set cannot be emulated in the run time cache, this value
+		 * operation is treated as a normal "add" for no_mc_groups.
+		 */
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+			return true;
+		}
+
+		// Save to Memcached.
+		if ( $by_key ) {
+			$result = $this->m->casByKey( $cas_token, $server_key, $derived_key, $value, $expiration );
+		} else {
+			$result = $this->m->cas( $cas_token, $derived_key, $value, $expiration );
+		}
+
+		// Store in runtime cache if cas was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Performs a "check and set" to store data with a server key.
+	 *
+	 * The set will be successful only if the no other request has updated the value
+	 * since it was fetched by this request.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.casbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param float  $cas_token  Unique value associated with the existing item. Generated by memcached.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function casByKey( $cas_token, $server_key, $key, $value, $group = 'default', $expiration = 0 ) {
+		return $this->cas( $cas_token, $key, $value, $group, $expiration, $server_key, true );
+	}
+
+	/**
+	 * Decrements a numeric item's value.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.decrement.php
+	 *
+	 * @param string $key    The key under which to store the value.
+	 * @param int    $offset The amount by which to decrement the item's value.
+	 * @param string $group  The group value appended to the $key.
+	 * @return int|bool Item's new value on success, false on failure.
+	 */
+	public function decrement( $key, $offset = 1, $group = 'default' ) {
+		$derived_key = $this->buildKey( $key, $group );
+
+		// Decrement values in no_mc_groups.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+
+			// Only decrement if the key already exists and value is 0 or greater (mimics memcached behavior).
+			if ( isset( $this->cache[ $derived_key ] ) && $this->cache[ $derived_key ] >= 0 ) {
+
+				// If numeric, subtract; otherwise, consider it 0 and do nothing.
+				if ( is_numeric( $this->cache[ $derived_key ] ) ) {
+					$this->cache[ $derived_key ] -= (int) $offset;
+				} else {
+					$this->cache[ $derived_key ] = 0;
+				}
+
+				// Returned value cannot be less than 0.
+				if ( $this->cache[ $derived_key ] < 0 ) {
+					$this->cache[ $derived_key ] = 0;
+				}
+
+				return $this->cache[ $derived_key ];
+			} else {
+				return false;
+			}
+		}
+
+		$result = $this->m->decrement( $derived_key, $offset );
+
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $result );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Decrements a numeric item's value.
+	 *
+	 * Alias for $this->decrement(). Other caching backends use this abbreviated form
+	 * of the function. It *may* cause breakage somewhere, so it is nice to have.
+	 * This function will also allow the core unit tests to pass.
+	 *
+	 * @param string $key    The key under which to store the value.
+	 * @param int    $offset The amount by which to decrement the item's value.
+	 * @param string $group  The group value appended to the $key.
+	 * @return int|bool Item's new value on success, false on failure.
+	 */
+	public function decr( $key, $offset = 1, $group = 'default' ) {
+		return $this->decrement( $key, $offset, $group );
+	}
+
+	/**
+	 * Removes the item from the cache.
+	 *
+	 * Removes an item from memcached with identified by $key after $time seconds.
+	 * The $time parameter allows an object to be queued for deletion without
+	 * immediately deleting. Between the time that it is queued and the time it's deleted,
+	 * add, replace, and get will fail, but set will succeed.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.delete.php
+	 *
+	 * @param string $key        The key under which to store the value.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $time       The amount of time the server will wait to delete the item in seconds.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function delete( $key, $group = 'default', $time = 0, $server_key = '', $by_key = false ) {
+		$derived_key = $this->buildKey( $key, $group );
+
+		// Remove from no_mc_groups array.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+			if ( isset( $this->cache[ $derived_key ] ) ) {
+				unset( $this->cache[ $derived_key ] );
+			}
+
+			return true;
+		}
+
+		if ( $by_key ) {
+			$result = $this->m->deleteByKey( $server_key, $derived_key, $time );
+		} else {
+			$result = $this->m->delete( $derived_key, $time );
+		}
+
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			unset( $this->cache[ $derived_key ] );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Removes the item from the cache by server key.
+	 *
+	 * Removes an item from memcached with identified by $key after $time seconds.
+	 * The $time parameter allows an object to be queued for deletion without
+	 * immediately deleting. Between the time that it is queued and the time it's deleted,
+	 * add, replace, and get will fail, but set will succeed.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.deletebykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $time       The amount of time the server will wait to delete the item in seconds.
+	 * @return bool True on success, false on failure.
+	 */
+	public function deleteByKey( $server_key, $key, $group = 'default', $time = 0 ) {
+		return $this->delete( $key, $group, $time, $server_key, true );
+	}
+
+	/**
+	 * Fetches the next result.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.fetch.php
+	 *
+	 * @return array|false The next result on success, false on failure.
+	 */
+	public function fetch() {
+		return $this->m->fetch();
+	}
+
+	/**
+	 * Fetches all remaining results from the last request.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.fetchall.php
+	 *
+	 * @return array|false The results on success, false on failure.
+	 */
+	public function fetchAll() {
+		return $this->m->fetchAll();
+	}
+
+	/**
+	 * Invalidates all items in the cache.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.flush.php
+	 *
+	 * @param int $delay Number of seconds to wait before invalidating the items.
+	 * @return bool True on success, false on failure.
+	 */
+	public function flush( $delay = 0 ) {
+		$result = $this->m->flush( $delay );
+
+		// Only reset the runtime cache if memcached was properly flushed.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->cache = array();
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Retrieves object from cache.
+	 *
+	 * Gets an object from cache based on $key and $group. In order to fully support
+	 * the $cache_cb and $cas_token parameters, the runtime cache is ignored by this function
+	 * if either of those values are set. In that case, the request is made directly
+	 * to the memcached server for proper handling of the callback and/or token.
+	 * Note that the $cas_token variable cannot be directly passed to the function.
+	 * The variable needs to be first defined with a non-null value.
+	 *
+	 * If using the $cache_cb argument, the new value will always have an expiration
+	 * of time of 0 (forever). This is a limitation of the Memcached PECL extension.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.get.php
+	 *
+	 * @param string        $key        The key under which to store the value.
+	 * @param string        $group      The group value appended to the $key.
+	 * @param bool          $force      Whether or not to force a cache invalidation.
+	 * @param null|bool     $found      Variable passed by reference to determine if the value was found or not.
+	 * @param string        $server_key The key identifying the server to store the value on.
+	 * @param bool          $by_key     True to store in internal cache by key; false to not store by key.
+	 * @param null|callable $cache_cb   Read-through caching callback.
+	 * @param null|float    $cas_token  The variable to store the CAS token in.
+	 * @return bool|mixed Cached object value.
+	 */
+	public function get( $key, $group = 'default', $force = false, &$found = null, $server_key = '', $by_key = false, $cache_cb = null, &$cas_token = null ) {
+		$derived_key = $this->buildKey( $key, $group );
+
+		// Assume object is not found.
+		$found = false;
+
+		// If either $cache_db, or $cas_token is set, must hit Memcached and bypass runtime cache.
+		if ( func_num_args() > 6 && ! in_array( $group, $this->no_mc_groups, true ) ) {
+			if ( $by_key ) {
+				$value = $this->m->getByKey( $server_key, $derived_key, $cache_cb, $cas_token );
+			} else {
+				$value = $this->m->get( $derived_key, $cache_cb, $cas_token );
+			}
+		} else {
+			if ( isset( $this->cache[ $derived_key ] ) ) {
+				$found = true;
+				return is_object( $this->cache[ $derived_key ] ) ? clone $this->cache[ $derived_key ] : $this->cache[ $derived_key ];
+			} elseif ( in_array( $group, $this->no_mc_groups, true ) ) {
+				return false;
+			} else {
+				if ( $by_key ) {
+					$value = $this->m->getByKey( $server_key, $derived_key );
+				} else {
+					$value = $this->m->get( $derived_key );
+				}
+			}
+		}
+
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+			$found = true;
+		}
+
+		return is_object( $value ) ? clone $value : $value;
+	}
+
+	/**
+	 * Retrieves object from cache from specified server.
+	 *
+	 * Gets an object from cache based on $key and $group, and $server_key. In order to fully support
+	 * the $cache_cb and $cas_token parameters, the runtime cache is ignored by this function
+	 * if either of those values are set. In that case, the request is made directly
+	 * to the memcached server for proper handling of the callback and/or token.
+	 * Note that the $cas_token variable cannot be directly passed to the function.
+	 * The variable needs to be first defined with a non-null value.
+	 *
+	 * If using the $cache_cb argument, the new value will always have an expiration
+	 * of time of 0 (forever). This is a limitation of the Memcached PECL extension.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getbykey.php
+	 *
+	 * @param string      $server_key The key identifying the server to store the value on.
+	 * @param string      $key        The key under which to store the value.
+	 * @param string      $group      The group value appended to the $key.
+	 * @param bool        $force      Whether or not to force a cache invalidation.
+	 * @param null|bool   $found      Variable passed by reference to determine if the value was found or not.
+	 * @param null|string $cache_cb   Read-through caching callback.
+	 * @param null|float  $cas_token  The variable to store the CAS token in.
+	 * @return bool|mixed Cached object value.
+	 */
+	public function getByKey( $server_key, $key, $group = 'default', $force = false, &$found = null, $cache_cb = null, &$cas_token = null ) {
+		/**
+		 * Need to be careful how "get" is called. If you send $cache_cb, and $cas_token, it will hit memcached.
+		 * Only send those args if they were sent to this function.
+		 */
+		if ( func_num_args() > 5 ) {
+			return $this->get( $key, $group, $force, $found, $server_key, true, $cache_cb, $cas_token );
+		} else {
+			return $this->get( $key, $group, $force, $found, $server_key, true );
+		}
+	}
+
+	/**
+	 * Requests multiple keys without blocking.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getdelayed.php
+	 *
+	 * @param string|array $keys     Array or string of key(s) to request.
+	 * @param string|array $groups   Array or string of group(s) for the key(s).
+	 *                               See buildKeys for more on how these are handled.
+	 * @param bool         $with_cas Whether to request CAS token values also.
+	 * @param null         $value_cb The result callback or null.
+	 * @return bool True on success, false on failure.
+	 */
+	public function getDelayed( $keys, $groups = 'default', $with_cas = false, $value_cb = null ) {
+		$derived_keys = $this->buildKeys( $keys, $groups );
+		return $this->m->getDelayed( $derived_keys, $with_cas, $value_cb );
+	}
+
+	/**
+	 * Requests multiple keys without blocking from a specified server.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getdelayed.php
+	 *
+	 * @param string       $server_key The key identifying the server to store the value on.
+	 * @param string|array $keys       Array or string of key(s) to request.
+	 * @param string|array $groups     Array or string of group(s) for the key(s).
+	 *                                 See buildKeys for more on how these are handled.
+	 * @param bool         $with_cas   Whether to request CAS token values also.
+	 * @param null         $value_cb   The result callback or null.
+	 * @return bool True on success, false on failure.
+	 */
+	public function getDelayedByKey( $server_key, $keys, $groups = 'default', $with_cas = false, $value_cb = null ) {
+		$derived_keys = $this->buildKeys( $keys, $groups );
+		return $this->m->getDelayedByKey( $server_key, $derived_keys, $with_cas, $value_cb );
+	}
+
+	/**
+	 * Gets multiple values from memcached in one request.
+	 *
+	 * See the buildKeys method definition to understand the $keys/$groups parameters.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getmulti.php
+	 *
+	 * @param array        $keys       Array of keys to retrieve.
+	 * @param string|array $groups     If string, used for all keys.
+	 *                                 If arrays, corresponds with the $keys array.
+	 * @param string       $server_key The key identifying the server to store the value on.
+	 * @param null|array   $cas_tokens The variable to store the CAS tokens for the found items.
+	 * @param int          $flags      The flags for the get operation.
+	 * @return bool|array The array of found items on success, false on failure.
+	 */
+	public function getMulti( $keys, $groups = 'default', $server_key = '', &$cas_tokens = null, $flags = null ) {
+		$derived_keys = $this->buildKeys( $keys, $groups );
+
+		/**
+		 * If either $cas_tokens, or $flags is set, must hit Memcached and bypass runtime cache.
+		 * Note that this will purposely ignore no_mc_groups values as they cannot handle CAS tokens
+		 * or the special flags; however, if the groups of groups contains a no_mc_group, this is bypassed.
+		 */
+		if ( func_num_args() > 3 && ! $this->contains_no_mc_group( $groups ) ) {
+			if ( ! empty( $server_key ) ) {
+				$values = $this->m->getMultiByKey( $server_key, $derived_keys, $cas_tokens, $flags );
+			} else {
+				$values = $this->m->getMulti( $derived_keys, $cas_tokens, $flags );
+			}
+		} else {
+			$values      = array();
+			$need_to_get = array();
+
+			// Pull out values from runtime cache, or mark for retrieval.
+			foreach ( $derived_keys as $key ) {
+				if ( isset( $this->cache[ $key ] ) ) {
+					$values[ $key ] = $this->cache[ $key ];
+				} else {
+					$need_to_get[ $key ] = $key;
+				}
+			}
+
+			// Get those keys not found in the runtime cache.
+			if ( ! empty( $need_to_get ) ) {
+				if ( ! empty( $server_key ) ) {
+					$result = $this->m->getMultiByKey( $server_key, array_keys( $need_to_get ) );
+				} else {
+					$result = $this->m->getMulti( array_keys( $need_to_get ) );
+				}
+			}
+
+			// Merge with values found in runtime cache.
+			if ( isset( $result ) && Memcached::RES_SUCCESS === $this->getResultCode() ) {
+				$values = array_merge( $values, $result );
+			}
+
+			// If order should be preserved, reorder now.
+			if ( ! empty( $need_to_get ) && Memcached::GET_PRESERVE_ORDER === $flags ) {
+				$ordered_values = array();
+
+				foreach ( $derived_keys as $key ) {
+					if ( isset( $values[ $key ] ) ) {
+						$ordered_values[ $key ] = $values[ $key ];
+					}
+				}
+
+				$values = $ordered_values;
+				unset( $ordered_values );
+			}
+		}
+
+		// Add the values to the runtime cache.
+		$this->cache = array_merge( $this->cache, $values );
+
+		return $values;
+	}
+
+	/**
+	 * Gets multiple values from memcached in one request by specified server key.
+	 *
+	 * See the buildKeys method definition to understand the $keys/$groups parameters.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getmultibykey.php
+	 *
+	 * @param string       $server_key The key identifying the server to store the value on.
+	 * @param array        $keys       Array of keys to retrieve.
+	 * @param string|array $groups     If string, used for all keys.
+	 *                                 If arrays, corresponds with the $keys array.
+	 * @param null|array   $cas_tokens The variable to store the CAS tokens for the found items.
+	 * @param int          $flags      The flags for the get operation.
+	 * @return bool|array The array of found items on success, false on failure.
+	 */
+	public function getMultiByKey( $server_key, $keys, $groups = 'default', &$cas_tokens = null, $flags = null ) {
+		/**
+		 * Need to be careful how "getMulti" is called. If you send $cache_cb, and $cas_token, it will hit memcached.
+		 * Only send those args if they were sent to this function.
+		 */
+		if ( func_num_args() > 3 ) {
+			return $this->getMulti( $keys, $groups, $server_key, $cas_tokens, $flags );
+		} else {
+			return $this->getMulti( $keys, $groups, $server_key );
+		}
+	}
+
+	/**
+	 * Retrieves a Memcached option value.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getoption.php
+	 *
+	 * @param int $option One of the Memcached::OPT_* constants.
+	 * @return mixed The value of the requested option on success, false on failure.
+	 */
+	public function getOption( $option ) {
+		return $this->m->getOption( $option );
+	}
+
+	/**
+	 * Returns the result code of the last option.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getresultcode.php
+	 *
+	 * @return int Result code of the last Memcached operation.
+	 */
+	public function getResultCode() {
+		return $this->m->getResultCode();
+	}
+
+	/**
+	 * Return the message describing the result of the last operation.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getresultmessage.php
+	 *
+	 * @return string Message describing the result of the last Memcached operation.
+	 */
+	public function getResultMessage() {
+		return $this->m->getResultMessage();
+	}
+
+	/**
+	 * Gets server information by key.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getserverbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @return array Array with host, post, and weight on success, false on failure.
+	 */
+	public function getServerByKey( $server_key ) {
+		return $this->m->getServerByKey( $server_key );
+	}
+
+	/**
+	 * Gets the list of servers in the pool.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getserverlist.php
+	 *
+	 * @return array The list of all servers in the server pool.
+	 */
+	public function getServerList() {
+		return $this->m->getServerList();
+	}
+
+	/**
+	 * Gets server pool statistics.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getstats.php
+	 *
+	 * @return array Array of server statistics, one entry per server.
+	 */
+	public function getStats() {
+		return $this->m->getStats();
+	}
+
+	/**
+	 * Gets server pool memcached version information.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.getversion.php
+	 *
+	 * @return array Array of server versions, one entry per server.
+	 */
+	public function getVersion() {
+		return $this->m->getVersion();
+	}
+
+	/**
+	 * Increments a numeric item's value.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.increment.php
+	 *
+	 * @param string $key    The key under which to store the value.
+	 * @param int    $offset The amount by which to increment the item's value.
+	 * @param string $group  The group value appended to the $key.
+	 * @return int|bool Item's new value on success, false on failure.
+	 */
+	public function increment( $key, $offset = 1, $group = 'default' ) {
+		$derived_key = $this->buildKey( $key, $group );
+
+		// Increment values in no_mc_groups.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+
+			// Only increment if the key already exists and the number is currently 0 or greater (mimics memcached behavior).
+			if ( isset( $this->cache[ $derived_key ] ) && $this->cache[ $derived_key ] >= 0 ) {
+
+				// If numeric, add; otherwise, consider it 0 and do nothing.
+				if ( is_numeric( $this->cache[ $derived_key ] ) ) {
+					$this->cache[ $derived_key ] += (int) $offset;
+				} else {
+					$this->cache[ $derived_key ] = 0;
+				}
+
+				// Returned value cannot be less than 0.
+				if ( $this->cache[ $derived_key ] < 0 ) {
+					$this->cache[ $derived_key ] = 0;
+				}
+
+				return $this->cache[ $derived_key ];
+			} else {
+				return false;
+			}
+		}
+
+		$result = $this->m->increment( $derived_key, $offset );
+
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $result );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Alias for $this->incr().
+	 *
+	 * Certain plugins expect an "incr" method on the $wp_object_cache object (e.g., Batcache).
+	 * Since the original version of this library matched names to the memcached methods,
+	 * the "incr" method was missing. Adding this method restores compatibility with plugins
+	 * expecting an "incr" method.
+	 *
+	 * @param string $key    The key under which to store the value.
+	 * @param int    $offset The amount by which to increment the item's value.
+	 * @param string $group  The group value appended to the $key.
+	 * @return int|bool Item's new value on success, false on failure.
+	 */
+	public function incr( $key, $offset = 1, $group = 'default' ) {
+		return $this->increment( $key, $offset, $group );
+	}
+
+	/**
+	 * Prepends data to an existing item.
+	 *
+	 * This method should throw an error if it is used with compressed data. This is an expected behavior.
+	 * Memcached casts the value to be prepended to the initial value to the type of the initial value.
+	 * Be careful as this leads to unexpected behavior at times. For instance, prepending (float) 45.23
+	 * to (int) 23 will result in 45, because the value is first combined (45.2323) then cast to "integer"
+	 * (the original value), which will be (int) 45. Due to how memcached treats types, the behavior has been
+	 * mimicked in the internal cache to produce similar results and improve consistency. It is recommended
+	 * that prepends only occur with data of the same type.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.prepend.php
+	 *
+	 * @param string $key        The key under which to store the value.
+	 * @param string $value      Must be string as prepending mixed values is not well-defined.
+	 * @param string $group      The group value prepended to the $key.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function prepend( $key, $value, $group = 'default', $server_key = '', $by_key = false ) {
+		if ( ! is_string( $value ) && ! is_int( $value ) && ! is_float( $value ) ) {
+			return false;
+		}
+
+		$derived_key = $this->buildKey( $key, $group );
+
+		// If group is a non-Memcached group, prepend to runtime cache value, not Memcached.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+			if ( ! isset( $this->cache[ $derived_key ] ) ) {
+				return false;
+			}
+
+			$combined = $this->combine_values( $this->cache[ $derived_key ], $value, 'pre' );
+			$this->add_to_internal_cache( $derived_key, $combined );
+			return true;
+		}
+
+		// Append to Memcached value.
+		if ( $by_key ) {
+			$result = $this->m->prependByKey( $server_key, $derived_key, $value );
+		} else {
+			$result = $this->m->prepend( $derived_key, $value );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$combined = $this->combine_values( $this->cache[ $derived_key ], $value, 'pre' );
+			$this->add_to_internal_cache( $derived_key, $combined );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Appends data to an existing item by server key.
+	 *
+	 * This method should throw an error if it is used with compressed data. This is an expected behavior.
+	 * Memcached casts the value to be prepended to the initial value to the type of the initial value.
+	 * Be careful as this leads to unexpected behavior at times. For instance, prepending (float) 45.23
+	 * to (int) 23 will result in 45, because the value is first combined (45.2323) then cast to "integer"
+	 * (the original value), which will be (int) 45. Due to how memcached treats types, the behavior has been
+	 * mimicked in the internal cache to produce similar results and improve consistency. It is recommended
+	 * that prepends only occur with data of the same type.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.prependbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param string $value      Must be string as prepending mixed values is not well-defined.
+	 * @param string $group      The group value prepended to the $key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function prependByKey( $server_key, $key, $value, $group = 'default' ) {
+		return $this->prepend( $key, $value, $group, $server_key, true );
+	}
+
+	/**
+	 * Replaces a value in cache.
+	 *
+	 * This method is similar to "add"; however, is does not successfully set a value
+	 * if the object's key is not already set in cache.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.replace.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function replace( $key, $value, $group = 'default', $expiration = 0, $server_key = '', $by_key = false ) {
+		$derived_key = $this->buildKey( $key, $group );
+		$expiration  = $this->sanitize_expiration( $expiration );
+
+		// If group is a non-Memcached group, save to runtime cache, not Memcached.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+
+			// Replace won't save unless the key already exists; mimic this behavior here.
+			if ( ! isset( $this->cache[ $derived_key ] ) ) {
+				return false;
+			}
+
+			$this->cache[ $derived_key ] = $value;
+			return true;
+		}
+
+		// Save to Memcached.
+		if ( $by_key ) {
+			$result = $this->m->replaceByKey( $server_key, $derived_key, $value, $expiration );
+		} else {
+			$result = $this->m->replace( $derived_key, $value, $expiration );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Replaces a value in cache on a specific server.
+	 *
+	 * This method is similar to "addByKey"; however, is does not successfully set a value
+	 * if the object's key is not already set in cache.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.addbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function replaceByKey( $server_key, $key, $value, $group = 'default', $expiration = 0 ) {
+		return $this->replace( $key, $value, $group, $expiration, $server_key, true );
+	}
+
+	/**
+	 * Sets a value in cache.
+	 *
+	 * The value is set whether or not this key already exists in memcached.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.set.php
+	 *
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param bool   $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function set( $key, $value, $group = 'default', $expiration = 0, $server_key = '', $by_key = false ) {
+		$derived_key = $this->buildKey( $key, $group );
+		$expiration  = $this->sanitize_expiration( $expiration );
+
+		// If group is a non-Memcached group, save to runtime cache, not Memcached.
+		if ( in_array( $group, $this->no_mc_groups, true ) ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+			return true;
+		}
+
+		// Save to Memcached.
+		if ( $by_key ) {
+			$result = $this->m->setByKey( $server_key, $derived_key, $value, $expiration );
+		} else {
+			$result = $this->m->set( $derived_key, $value, $expiration );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->add_to_internal_cache( $derived_key, $value );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Sets a value in cache on a specific server.
+	 *
+	 * The value is set whether or not this key already exists in memcached.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.setbykey.php
+	 *
+	 * @param string $server_key The key identifying the server to store the value on.
+	 * @param string $key        The key under which to store the value.
+	 * @param mixed  $value      The value to store.
+	 * @param string $group      The group value appended to the $key.
+	 * @param int    $expiration The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function setByKey( $server_key, $key, $value, $group = 'default', $expiration = 0 ) {
+		return $this->set( $key, $value, $group, $expiration, $server_key, true );
+	}
+
+	/**
+	 * Sets multiple values to cache at once.
+	 *
+	 * By sending an array of $items to this function, all values are saved at once to
+	 * memcached, reducing the need for multiple requests to memcached. The $items array
+	 * keys and values are what are stored to memcached. The keys in the $items array
+	 * are merged with the $groups array/string value via buildKeys to determine the
+	 * final key for the object.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.setmulti.php
+	 *
+	 * @param array        $items      An array of key/value pairs to store on the server.
+	 * @param string|array $groups     Group(s) to merge with key(s) in $items.
+	 * @param int          $expiration The expiration time, defaults to 0.
+	 * @param string       $server_key The key identifying the server to store the value on.
+	 * @param bool         $by_key     True to store in internal cache by key; false to not store by key.
+	 * @return bool True on success, false on failure.
+	 */
+	public function setMulti( $items, $groups = 'default', $expiration = 0, $server_key = '', $by_key = false ) {
+		// Build final keys and replace $items keys with the new keys.
+		$derived_keys  = $this->buildKeys( array_keys( $items ), $groups );
+		$expiration    = $this->sanitize_expiration( $expiration );
+		$derived_items = array_combine( $derived_keys, $items );
+
+		// Do not add to memcached if in no_mc_groups.
+		foreach ( $derived_items as $derived_key => $value ) {
+
+			// Get the individual item's group.
+			$key_pieces = explode( ':', $derived_key );
+
+			// If group is a non-Memcached group, save to runtime cache, not Memcached.
+			if ( in_array( $key_pieces[1], $this->no_mc_groups, true ) ) {
+				$this->add_to_internal_cache( $derived_key, $value );
+				unset( $derived_items[ $derived_key ] );
+			}
+		}
+
+		// Save to memcached.
+		if ( $by_key ) {
+			$result = $this->m->setMultiByKey( $server_key, $derived_items, $expiration );
+		} else {
+			$result = $this->m->setMulti( $derived_items, $expiration );
+		}
+
+		// Store in runtime cache if add was successful.
+		if ( Memcached::RES_SUCCESS === $this->getResultCode() ) {
+			$this->cache = array_merge( $this->cache, $derived_items );
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Sets multiple values to cache at once on specified server.
+	 *
+	 * By sending an array of $items to this function, all values are saved at once to
+	 * memcached, reducing the need for multiple requests to memcached. The $items array
+	 * keys and values are what are stored to memcached. The keys in the $items array
+	 * are merged with the $groups array/string value via buildKeys to determine the
+	 * final key for the object.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.setmultibykey.php
+	 *
+	 * @param string       $server_key  The key identifying the server to store the value on.
+	 * @param array        $items       An array of key/value pairs to store on the server.
+	 * @param string|array $groups      Group(s) to merge with key(s) in $items.
+	 * @param int          $expiration  The expiration time, defaults to 0.
+	 * @return bool True on success, false on failure.
+	 */
+	public function setMultiByKey( $server_key, $items, $groups = 'default', $expiration = 0 ) {
+		return $this->setMulti( $items, $groups, $expiration, $server_key, true );
+	}
+
+	/**
+	 * Sets a Memcached option.
+	 *
+	 * @link https://www.php.net/manual/en/memcached.setoption.php
+	 *
+	 * @param int   $option Option name.
+	 * @param mixed $value  Option value.
+	 * @return bool True on success, false on failure.
+	 */
+	public function setOption( $option, $value ) {
+		return $this->m->setOption( $option, $value );
+	}
+
+	/**
+	 * Builds a key for the cached object using the blog_id, key, and group values.
+	 *
+	 * This function is inspired by the original WP Memcached Object cache.
+	 *
+	 * @author Ryan Boren
+	 * @link http://wordpress.org/extend/plugins/memcached/
+	 *
+	 * @param string $key   The key under which to store the value.
+	 * @param string $group The group value appended to the $key.
+	 * @return string
+	 */
+	public function buildKey( $key, $group = 'default' ) {
+		if ( empty( $group ) ) {
+			$group = 'default';
+		}
+
+		if ( false !== array_search( $group, $this->global_groups, true ) ) {
+			$prefix = $this->global_prefix;
+		} else {
+			$prefix = $this->blog_prefix;
+		}
+
+		return preg_replace( '/\s+/', '', WP_CACHE_KEY_SALT . "$prefix$group:$key" );
+	}
+
+	/**
+	 * Creates an array of keys from passed key(s) and group(s).
+	 *
+	 * This function takes a string or array of key(s) and group(s) and combines them into a single dimensional
+	 * array that merges the keys and groups. If the same number of keys and groups exist, the final keys will
+	 * append $groups[n] to $keys[n]. If there are more keys than groups and the $groups parameter is an array,
+	 * $keys[n] will be combined with $groups[n] until $groups runs out of values. 'default' will be used for remaining
+	 * values. If $keys is an array and $groups is a string, all final values will append $groups to $keys[n].
+	 * If both values are strings, they will be combined into a single string. Note that if more $groups are received
+	 * than $keys, the method will return an empty array. This method is primarily a helper method for methods
+	 * that call memcached with an array of keys.
+	 *
+	 * @param string|array $keys   Key(s) to merge with group(s).
+	 * @param string|array $groups Group(s) to merge with key(s).
+	 * @return array Array that combines keys and groups into a single set of memcached keys.
+	 */
+	public function buildKeys( $keys, $groups = 'default' ) {
+		$derived_keys = array();
+
+		// If strings sent, convert to arrays for proper handling.
+		if ( ! is_array( $groups ) ) {
+			$groups = (array) $groups;
+		}
+
+		if ( ! is_array( $keys ) ) {
+			$keys = (array) $keys;
+		}
+
+		// If we have equal numbers of keys and groups, merge $keys[n] and $group[n].
+		if ( count( $keys ) === count( $groups ) ) {
+			for ( $i = 0; $i < count( $keys ); $i++ ) {
+				$derived_keys[] = $this->buildKey( $keys[ $i ], $groups[ $i ] );
+			}
+
+			// If more keys are received than groups, merge $keys[n] and $group[n]
+			// until no more groups are left; remaining groups are 'default'.
+		} elseif ( count( $keys ) > count( $groups ) ) {
+			for ( $i = 0; $i < count( $keys ); $i++ ) {
+				if ( isset( $groups[ $i ] ) ) {
+					$derived_keys[] = $this->buildKey( $keys[ $i ], $groups[ $i ] );
+				} elseif ( count( $groups ) === 1 ) {
+					$derived_keys[] = $this->buildKey( $keys[ $i ], $groups[0] );
+				} else {
+					$derived_keys[] = $this->buildKey( $keys[ $i ], 'default' );
+				}
+			}
+		}
+
+		return $derived_keys;
+	}
+
+	/**
+	 * Ensures that a proper expiration time is set.
+	 *
+	 * Memcached treats any value over 30 days as a timestamp. If a developer sets the expiration
+	 * for greater than 30 days or less than the current timestamp, the timestamp is in the past
+	 * and the value isn't cached. This function detects values in that range and corrects them.
+	 *
+	 * @param string|int $expiration The dirty expiration time.
+	 * @return string|int The sanitized expiration time.
+	 */
+	public function sanitize_expiration( $expiration ) {
+		if ( $expiration > $this->thirty_days && $expiration <= $this->now ) {
+			$expiration = $expiration + $this->now;
+		}
+
+		return $expiration;
+	}
+
+	/**
+	 * Concatenates two values and casts to type of the first value.
+	 *
+	 * This is used in append and prepend operations to match how these functions are handled
+	 * by memcached. In both cases, whichever value is the original value in the combined value
+	 * will dictate the type of the combined value.
+	 *
+	 * @param mixed  $original  Original value that dictates the combined type.
+	 * @param mixed  $pended    Value to combine with original value.
+	 * @param string $direction Either 'pre' or 'app'.
+	 * @return mixed Combined value casted to the type of the first value.
+	 */
+	public function combine_values( $original, $pended, $direction ) {
+		$type = gettype( $original );
+
+		// Combine the values based on direction of the "pend".
+		if ( 'pre' === $direction ) {
+			$combined = $pended . $original;
+		} else {
+			$combined = $original . $pended;
+		}
+
+		// Cast type of combined value.
+		settype( $combined, $type );
+
+		return $combined;
+	}
+
+	/**
+	 * Simple wrapper for saving object to the internal cache.
+	 *
+	 * @param string $derived_key Key to save value under.
+	 * @param mixed  $value       Object value.
+	 */
+	public function add_to_internal_cache( $derived_key, $value ) {
+		if ( is_object( $value ) ) {
+			$value = clone $value;
+		}
+
+		$this->cache[ $derived_key ] = $value;
+	}
+
+	/**
+	 * Determines if a no_mc_group exists in a group of groups.
+	 *
+	 * @param mixed $groups The groups to search.
+	 * @return bool True if a no_mc_group is present; false if a no_mc_group is not present.
+	 */
+	public function contains_no_mc_group( $groups ) {
+		if ( is_scalar( $groups ) ) {
+			return in_array( $groups, $this->no_mc_groups, true );
+		}
+
+		if ( ! is_array( $groups ) ) {
+			return false;
+		}
+
+		foreach ( $groups as $group ) {
+			if ( in_array( $group, $this->no_mc_groups, true ) ) {
+				return true;
+			}
+		}
+
+		return false;
+	}
+
+	/**
+	 * Adds global groups.
+	 *
+	 * This function comes straight from the original WP Memcached Object cache.
+	 *
+	 * @author Ryan Boren
+	 * @link http://wordpress.org/extend/plugins/memcached/
+	 *
+	 * @param array $groups Array of groups.
+	 * @return void
+	 */
+	public function add_global_groups( $groups ) {
+		if ( ! is_array( $groups ) ) {
+			$groups = (array) $groups;
+		}
+
+		$this->global_groups = array_merge( $this->global_groups, $groups );
+		$this->global_groups = array_unique( $this->global_groups );
+	}
+
+	/**
+	 * Adds non-persistent groups.
+	 *
+	 * This function comes straight from the original WP Memcached Object cache.
+	 *
+	 * @author Ryan Boren
+	 * @link http://wordpress.org/extend/plugins/memcached/
+	 *
+	 * @param array $groups Array of groups.
+	 * @return void
+	 */
+	public function add_non_persistent_groups( $groups ) {
+		if ( ! is_array( $groups ) ) {
+			$groups = (array) $groups;
+		}
+
+		$this->no_mc_groups = array_merge( $this->no_mc_groups, $groups );
+		$this->no_mc_groups = array_unique( $this->no_mc_groups );
+	}
+
+	/**
+	 * Gets a value specifically from the internal, run-time cache, not memcached.
+	 *
+	 * @param int|string $key   Key value.
+	 * @param int|string $group Group that the value belongs to.
+	 * @return bool|mixed Value on success, false on failure.
+	 */
+	public function get_from_runtime_cache( $key, $group ) {
+		$derived_key = $this->buildKey( $key, $group );
+
+		if ( isset( $this->cache[ $derived_key ] ) ) {
+			return $this->cache[ $derived_key ];
+		}
+
+		return false;
+	}
+
+	/**
+	 * Switches blog prefix, which changes the cache that is accessed.
+	 *
+	 * @param int $blog_id Blog to switch to.
+	 * @return void
+	 */
+	public function switch_to_blog( $blog_id ) {
+		global $table_prefix;
+		$blog_id           = (int) $blog_id;
+		$this->blog_prefix = ( is_multisite() ? $blog_id : $table_prefix ) . ':';
+	}
+}
+// phpcs:enable

+ 41 - 0
tests/phpunit/includes/phpunit6/compat.php

@@ -0,0 +1,41 @@
+<?php
+
+if ( class_exists( 'PHPUnit\Runner\Version' ) && version_compare( PHPUnit\Runner\Version::id(), '6.0', '>=' ) ) {
+
+	class_alias( 'PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase' );
+	class_alias( 'PHPUnit\Framework\Exception', 'PHPUnit_Framework_Exception' );
+	class_alias( 'PHPUnit\Framework\ExpectationFailedException', 'PHPUnit_Framework_ExpectationFailedException' );
+	class_alias( 'PHPUnit\Framework\Error\Deprecated', 'PHPUnit_Framework_Error_Deprecated' );
+	class_alias( 'PHPUnit\Framework\Error\Notice', 'PHPUnit_Framework_Error_Notice' );
+	class_alias( 'PHPUnit\Framework\Error\Warning', 'PHPUnit_Framework_Error_Warning' );
+	class_alias( 'PHPUnit\Framework\Test', 'PHPUnit_Framework_Test' );
+	class_alias( 'PHPUnit\Framework\Warning', 'PHPUnit_Framework_Warning' );
+	class_alias( 'PHPUnit\Framework\AssertionFailedError', 'PHPUnit_Framework_AssertionFailedError' );
+	class_alias( 'PHPUnit\Framework\Constraint\IsEqual', 'PHPUnit_Framework_Constraint_IsEqual' );
+	class_alias( 'PHPUnit\Framework\TestSuite', 'PHPUnit_Framework_TestSuite' );
+	class_alias( 'PHPUnit\Framework\TestListener', 'PHPUnit_Framework_TestListener' );
+	class_alias( 'PHPUnit\Util\GlobalState', 'PHPUnit_Util_GlobalState' );
+	class_alias( 'PHPUnit\Util\Getopt', 'PHPUnit_Util_Getopt' );
+
+	class PHPUnit_Util_Test {
+
+		// phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
+		public static function getTickets( $class_name, $method_name ) {
+			$annotations = PHPUnit\Util\Test::parseTestMethodAnnotations( $class_name, $method_name );
+
+			$tickets = array();
+
+			if ( isset( $annotations['class']['ticket'] ) ) {
+				$tickets = $annotations['class']['ticket'];
+			}
+
+			if ( isset( $annotations['method']['ticket'] ) ) {
+				$tickets = array_merge( $tickets, $annotations['method']['ticket'] );
+			}
+
+			return array_unique( $tickets );
+		}
+
+	}
+
+}

+ 43 - 0
tests/phpunit/includes/phpunit7/MockObject/Builder/NamespaceMatch.php

@@ -0,0 +1,43 @@
+<?php
+/*
+ * This file is part of PHPUnit.
+ *
+ * This file is modified to replace the Match interface with ParametersMatch,
+ * to avoid parse errors due to `match` being a reserved keyword in PHP 8.
+ * 
+ * When the test suite is updated for compatibility with PHPUnit 9.x,
+ * this override can be removed.
+ * 
+ * (c) Sebastian Bergmann <sebastian@phpunit.de>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+namespace PHPUnit\Framework\MockObject\Builder;
+
+/**
+ * Interface for builders which can register builders with a given identification.
+ *
+ * This interface relates to Identity.
+ */
+interface NamespaceMatch
+{
+    /**
+     * Looks up the match builder with identification $id and returns it.
+     *
+     * @param string $id The identification of the match builder
+     *
+     * @return Match
+     */
+    public function lookupId($id);
+
+    /**
+     * Registers the match builder $builder with the identification $id. The
+     * builder can later be looked up using lookupId() to figure out if it
+     * has been invoked.
+     *
+     * @param string $id      The identification of the match builder
+     * @param Match  $builder The builder which is being registered
+     */
+    public function registerId($id, ParametersMatch $builder);
+}

+ 66 - 0
tests/phpunit/includes/phpunit7/MockObject/Builder/ParametersMatch.php

@@ -0,0 +1,66 @@
+<?php
+/*
+ * This file is part of PHPUnit.
+ *
+ * This file is modified to replace the Match interface with ParametersMatch,
+ * to avoid parse errors due to `match` being a reserved keyword in PHP 8.
+ * 
+ * When the test suite is updated for compatibility with PHPUnit 9.x,
+ * this override can be removed.
+ * 
+ * (c) Sebastian Bergmann <sebastian@phpunit.de>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+namespace PHPUnit\Framework\MockObject\Builder;
+
+use PHPUnit\Framework\MockObject\Matcher\AnyParameters;
+
+/**
+ * Builder interface for parameter matchers.
+ */
+interface ParametersMatch extends Stub
+{
+    /**
+     * Defines the expectation which must occur before the current is valid.
+     *
+     * @param string $id the identification of the expectation that should
+     *                   occur before this one
+     *
+     * @return Stub
+     */
+    public function after($id);
+
+    /**
+     * Sets the parameters to match for, each parameter to this function will
+     * be part of match. To perform specific matches or constraints create a
+     * new PHPUnit\Framework\Constraint\Constraint and use it for the parameter.
+     * If the parameter value is not a constraint it will use the
+     * PHPUnit\Framework\Constraint\IsEqual for the value.
+     *
+     * Some examples:
+     * <code>
+     * // match first parameter with value 2
+     * $b->with(2);
+     * // match first parameter with value 'smock' and second identical to 42
+     * $b->with('smock', new PHPUnit\Framework\Constraint\IsEqual(42));
+     * </code>
+     *
+     * @return ParametersMatch
+     */
+    public function with(...$arguments);
+
+    /**
+     * Sets a matcher which allows any kind of parameters.
+     *
+     * Some examples:
+     * <code>
+     * // match any number of parameters
+     * $b->withAnyParameters();
+     * </code>
+     *
+     * @return AnyParameters
+     */
+    public function withAnyParameters();
+}

+ 2 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/deprecation.tpl.dist

@@ -0,0 +1,2 @@
+
+        @trigger_error({deprecation}, E_USER_DEPRECATED);

+ 46 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_class.tpl.dist

@@ -0,0 +1,46 @@
+{prologue}{class_declaration}
+{
+    private $__phpunit_invocationMocker;
+    private $__phpunit_originalObject;
+    private $__phpunit_configurable = {configurable};
+    private $__phpunit_returnValueGeneration = true;
+
+{clone}{mocked_methods}
+    public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher)
+    {
+        return $this->__phpunit_getInvocationMocker()->expects($matcher);
+    }
+{method}
+    public function __phpunit_setOriginalObject($originalObject)
+    {
+        $this->__phpunit_originalObject = $originalObject;
+    }
+
+    public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration)
+    {
+        $this->__phpunit_returnValueGeneration = $returnValueGeneration;
+    }
+
+    public function __phpunit_getInvocationMocker()
+    {
+        if ($this->__phpunit_invocationMocker === null) {
+            $this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration);
+        }
+
+        return $this->__phpunit_invocationMocker;
+    }
+
+    public function __phpunit_hasMatchers()
+    {
+        return $this->__phpunit_getInvocationMocker()->hasMatchers();
+    }
+
+    public function __phpunit_verify(bool $unsetInvocationMocker = true)
+    {
+        $this->__phpunit_getInvocationMocker()->verify();
+
+        if ($unsetInvocationMocker) {
+            $this->__phpunit_invocationMocker = null;
+        }
+    }
+}{epilogue}

+ 8 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_class_method.tpl.dist

@@ -0,0 +1,8 @@
+
+    public function method()
+    {
+        $any     = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
+        $expects = $this->expects($any);
+
+        return call_user_func_array([$expects, 'method'], func_get_args());
+    }

+ 4 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_clone.tpl.dist

@@ -0,0 +1,4 @@
+    public function __clone()
+    {
+        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
+    }

+ 22 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_method.tpl.dist

@@ -0,0 +1,22 @@
+
+    {modifier} function {reference}{method_name}({arguments_decl}){return_delim}{return_type}
+    {{deprecation}
+        $__phpunit_arguments = [{arguments_call}];
+        $__phpunit_count     = func_num_args();
+
+        if ($__phpunit_count > {arguments_count}) {
+            $__phpunit_arguments_tmp = func_get_args();
+
+            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
+                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
+            }
+        }
+
+        $__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke(
+            new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
+                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_type}', $this, {clone_arguments}
+            )
+        );
+
+        return $__phpunit_result;
+    }

+ 20 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_method_void.tpl.dist

@@ -0,0 +1,20 @@
+
+    {modifier} function {reference}{method_name}({arguments_decl}){return_delim}{return_type}
+    {{deprecation}
+        $__phpunit_arguments = [{arguments_call}];
+        $__phpunit_count     = func_num_args();
+
+        if ($__phpunit_count > {arguments_count}) {
+            $__phpunit_arguments_tmp = func_get_args();
+
+            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
+                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
+            }
+        }
+
+        $this->__phpunit_getInvocationMocker()->invoke(
+            new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
+                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_type}', $this, {clone_arguments}
+            )
+        );
+    }

+ 5 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/mocked_static_method.tpl.dist

@@ -0,0 +1,5 @@
+
+    {modifier} function {reference}{method_name}({arguments_decl}){return_delim}{return_type}
+    {
+        throw new \PHPUnit\Framework\MockObject\BadMethodCallException('Static method "{method_name}" cannot be invoked on mock object');
+    }

+ 26 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/proxied_method.tpl.dist

@@ -0,0 +1,26 @@
+
+    {modifier} function {reference}{method_name}({arguments_decl}){return_delim}{return_type}
+    {
+        $__phpunit_arguments = [{arguments_call}];
+        $__phpunit_count     = func_num_args();
+
+        if ($__phpunit_count > {arguments_count}) {
+            $__phpunit_arguments_tmp = func_get_args();
+
+            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
+                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
+            }
+        }
+
+        $__phpunit_invocation = new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
+            '{class_name}', '{method_name}', $__phpunit_arguments, '{return_type}', $this, {clone_arguments}
+        );
+
+        $__phpunit_invocation->setProxiedCall();
+
+        $this->__phpunit_getInvocationMocker()->invoke($__phpunit_invocation);
+
+        unset($__phpunit_invocation);
+
+        return call_user_func_array(array($this->__phpunit_originalObject, "{method_name}"), $__phpunit_arguments);
+    }

+ 26 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/proxied_method_void.tpl.dist

@@ -0,0 +1,26 @@
+
+    {modifier} function {reference}{method_name}({arguments_decl}){return_delim}{return_type}
+    {
+        $__phpunit_arguments = [{arguments_call}];
+        $__phpunit_count     = func_num_args();
+
+        if ($__phpunit_count > {arguments_count}) {
+            $__phpunit_arguments_tmp = func_get_args();
+
+            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
+                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
+            }
+        }
+
+        $__phpunit_invocation = new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation(
+            '{class_name}', '{method_name}', $__phpunit_arguments, '{return_type}', $this, {clone_arguments}
+        );
+
+        $__phpunit_invocation->setProxiedCall();
+
+        $this->__phpunit_getInvocationMocker()->invoke($__phpunit_invocation);
+
+        unset($__phpunit_invocation);
+
+        call_user_func_array(array($this->__phpunit_originalObject, "{method_name}"), $__phpunit_arguments);
+    }

+ 4 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/trait_class.tpl.dist

@@ -0,0 +1,4 @@
+{prologue}class {class_name}
+{
+    use {trait_name};
+}

+ 5 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/unmocked_clone.tpl.dist

@@ -0,0 +1,5 @@
+    public function __clone()
+    {
+        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker();
+        parent::__clone();
+    }

+ 7 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/wsdl_class.tpl.dist

@@ -0,0 +1,7 @@
+{namespace}class {class_name} extends \SoapClient
+{
+    public function __construct($wsdl, array $options)
+    {
+        parent::__construct('{wsdl}', $options);
+    }
+{methods}}

+ 4 - 0
tests/phpunit/includes/phpunit7/MockObject/Generator/wsdl_method.tpl.dist

@@ -0,0 +1,4 @@
+
+    public function {method_name}({arguments})
+    {
+    }

+ 192 - 0
tests/phpunit/includes/phpunit7/MockObject/InvocationMocker.php

@@ -0,0 +1,192 @@
+<?php
+/*
+ * This file is part of PHPUnit.
+ *
+ * This file is modified to replace the Match interface with ParametersMatch,
+ * to avoid parse errors due to `match` being a reserved keyword in PHP 8.
+ * 
+ * When the test suite is updated for compatibility with PHPUnit 9.x,
+ * this override can be removed.
+ * 
+ * (c) Sebastian Bergmann <sebastian@phpunit.de>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+namespace PHPUnit\Framework\MockObject;
+
+use Exception;
+use PHPUnit\Framework\ExpectationFailedException;
+use PHPUnit\Framework\MockObject\Builder\InvocationMocker as BuilderInvocationMocker;
+use PHPUnit\Framework\MockObject\Builder\ParametersMatch;
+use PHPUnit\Framework\MockObject\Builder\NamespaceMatch;
+use PHPUnit\Framework\MockObject\Matcher\DeferredError;
+use PHPUnit\Framework\MockObject\Matcher\Invocation as MatcherInvocation;
+use PHPUnit\Framework\MockObject\Stub\MatcherCollection;
+
+/**
+ * Mocker for invocations which are sent from
+ * MockObject objects.
+ *
+ * Keeps track of all expectations and stubs as well as registering
+ * identifications for builders.
+ */
+class InvocationMocker implements Invokable, MatcherCollection, NamespaceMatch
+{
+    /**
+     * @var MatcherInvocation[]
+     */
+    private $matchers = [];
+
+    /**
+     * @var Match[]
+     */
+    private $builderMap = [];
+
+    /**
+     * @var string[]
+     */
+    private $configurableMethods;
+
+    /**
+     * @var bool
+     */
+    private $returnValueGeneration;
+
+    public function __construct(array $configurableMethods, bool $returnValueGeneration)
+    {
+        $this->configurableMethods   = $configurableMethods;
+        $this->returnValueGeneration = $returnValueGeneration;
+    }
+
+    public function addMatcher(MatcherInvocation $matcher): void
+    {
+        $this->matchers[] = $matcher;
+    }
+
+    public function hasMatchers()
+    {
+        foreach ($this->matchers as $matcher) {
+            if ($matcher->hasMatchers()) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * @return null|bool
+     */
+    public function lookupId($id)
+    {
+        if (isset($this->builderMap[$id])) {
+            return $this->builderMap[$id];
+        }
+    }
+
+    /**
+     * @throws RuntimeException
+     */
+    public function registerId($id, ParametersMatch $builder): void
+    {
+        if (isset($this->builderMap[$id])) {
+            throw new RuntimeException(
+                'Match builder with id <' . $id . '> is already registered.'
+            );
+        }
+
+        $this->builderMap[$id] = $builder;
+    }
+
+    /**
+     * @return BuilderInvocationMocker
+     */
+    public function expects(MatcherInvocation $matcher)
+    {
+        return new BuilderInvocationMocker(
+            $this,
+            $matcher,
+            $this->configurableMethods
+        );
+    }
+
+    /**
+     * @throws Exception
+     */
+    public function invoke(Invocation $invocation)
+    {
+        $exception      = null;
+        $hasReturnValue = false;
+        $returnValue    = null;
+
+        foreach ($this->matchers as $match) {
+            try {
+                if ($match->matches($invocation)) {
+                    $value = $match->invoked($invocation);
+
+                    if (!$hasReturnValue) {
+                        $returnValue    = $value;
+                        $hasReturnValue = true;
+                    }
+                }
+            } catch (Exception $e) {
+                $exception = $e;
+            }
+        }
+
+        if ($exception !== null) {
+            throw $exception;
+        }
+
+        if ($hasReturnValue) {
+            return $returnValue;
+        }
+
+        if ($this->returnValueGeneration === false) {
+            $exception = new ExpectationFailedException(
+                \sprintf(
+                    'Return value inference disabled and no expectation set up for %s::%s()',
+                    $invocation->getClassName(),
+                    $invocation->getMethodName()
+                )
+            );
+
+            if (\strtolower($invocation->getMethodName()) === '__tostring') {
+                $this->addMatcher(new DeferredError($exception));
+
+                return '';
+            }
+
+            throw $exception;
+        }
+
+        return $invocation->generateReturnValue();
+    }
+
+    /**
+     * @return bool
+     */
+    public function matches(Invocation $invocation)
+    {
+        foreach ($this->matchers as $matcher) {
+            if (!$matcher->matches($invocation)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @throws \PHPUnit\Framework\ExpectationFailedException
+     *
+     * @return bool
+     */
+    public function verify()
+    {
+        foreach ($this->matchers as $matcher) {
+            $matcher->verify();
+        }
+    }
+}

+ 33 - 0
tests/phpunit/includes/phpunit7/MockObject/LICENSE

@@ -0,0 +1,33 @@
+PHPUnit
+
+Copyright (c) 2001-2019, Sebastian Bergmann <sebastian@phpunit.de>.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in
+   the documentation and/or other materials provided with the
+   distribution.
+
+ * Neither the name of Sebastian Bergmann nor the names of his
+   contributors may be used to endorse or promote products derived
+   from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.

+ 363 - 0
tests/phpunit/includes/phpunit7/MockObject/MockMethod.php

@@ -0,0 +1,363 @@
+<?php declare(strict_types=1);
+/*
+ * This file is part of PHPUnit.
+ *
+ * This file is modified to replace ReflectionParameter::getClass() usage,
+ * which is deprecated in PHP 8.
+ * 
+ * When the test suite is updated for compatibility with PHPUnit 9.x,
+ * this override can be removed.
+ * 
+ * (c) Sebastian Bergmann <sebastian@phpunit.de>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+namespace PHPUnit\Framework\MockObject;
+
+use ReflectionClass;
+use ReflectionException;
+use ReflectionMethod;
+use Text_Template;
+
+final class MockMethod
+{
+    /**
+     * @var Text_Template[]
+     */
+    private static $templates = [];
+
+    /**
+     * @var string
+     */
+    private $className;
+
+    /**
+     * @var string
+     */
+    private $methodName;
+
+    /**
+     * @var bool
+     */
+    private $cloneArguments;
+
+    /**
+     * @var string string
+     */
+    private $modifier;
+
+    /**
+     * @var string
+     */
+    private $argumentsForDeclaration;
+
+    /**
+     * @var string
+     */
+    private $argumentsForCall;
+
+    /**
+     * @var string
+     */
+    private $returnType;
+
+    /**
+     * @var string
+     */
+    private $reference;
+
+    /**
+     * @var bool
+     */
+    private $callOriginalMethod;
+
+    /**
+     * @var bool
+     */
+    private $static;
+
+    /**
+     * @var ?string
+     */
+    private $deprecation;
+
+    /**
+     * @var bool
+     */
+    private $allowsReturnNull;
+
+    public static function fromReflection(ReflectionMethod $method, bool $callOriginalMethod, bool $cloneArguments): self
+    {
+        if ($method->isPrivate()) {
+            $modifier = 'private';
+        } elseif ($method->isProtected()) {
+            $modifier = 'protected';
+        } else {
+            $modifier = 'public';
+        }
+
+        if ($method->isStatic()) {
+            $modifier .= ' static';
+        }
+
+        if ($method->returnsReference()) {
+            $reference = '&';
+        } else {
+            $reference = '';
+        }
+
+        if ($method->hasReturnType()) {
+            $returnType = $method->getReturnType()->getName();
+        } else {
+            $returnType = '';
+        }
+
+        $docComment = $method->getDocComment();
+
+        if (\is_string($docComment)
+            && \preg_match('#\*[ \t]*+@deprecated[ \t]*+(.*?)\r?+\n[ \t]*+\*(?:[ \t]*+@|/$)#s', $docComment, $deprecation)
+        ) {
+            $deprecation = \trim(\preg_replace('#[ \t]*\r?\n[ \t]*+\*[ \t]*+#', ' ', $deprecation[1]));
+        } else {
+            $deprecation = null;
+        }
+
+        return new self(
+            $method->getDeclaringClass()->getName(),
+            $method->getName(),
+            $cloneArguments,
+            $modifier,
+            self::getMethodParameters($method),
+            self::getMethodParameters($method, true),
+            $returnType,
+            $reference,
+            $callOriginalMethod,
+            $method->isStatic(),
+            $deprecation,
+            $method->hasReturnType() && $method->getReturnType()->allowsNull()
+        );
+    }
+
+    public static function fromName(string $fullClassName, string $methodName, bool $cloneArguments): self
+    {
+        return new self(
+            $fullClassName,
+            $methodName,
+            $cloneArguments,
+            'public',
+            '',
+            '',
+            '',
+            '',
+            false,
+            false,
+            null,
+            false
+        );
+    }
+
+    public function __construct(string $className, string $methodName, bool $cloneArguments, string $modifier, string $argumentsForDeclaration, string $argumentsForCall, string $returnType, string $reference, bool $callOriginalMethod, bool $static, ?string $deprecation, bool $allowsReturnNull)
+    {
+        $this->className               = $className;
+        $this->methodName              = $methodName;
+        $this->cloneArguments          = $cloneArguments;
+        $this->modifier                = $modifier;
+        $this->argumentsForDeclaration = $argumentsForDeclaration;
+        $this->argumentsForCall        = $argumentsForCall;
+        $this->returnType              = $returnType;
+        $this->reference               = $reference;
+        $this->callOriginalMethod      = $callOriginalMethod;
+        $this->static                  = $static;
+        $this->deprecation             = $deprecation;
+        $this->allowsReturnNull        = $allowsReturnNull;
+    }
+
+    public function getName(): string
+    {
+        return $this->methodName;
+    }
+
+    /**
+     * @throws \ReflectionException
+     * @throws \PHPUnit\Framework\MockObject\RuntimeException
+     * @throws \InvalidArgumentException
+     */
+    public function generateCode(): string
+    {
+        if ($this->static) {
+            $templateFile = 'mocked_static_method.tpl';
+        } elseif ($this->returnType === 'void') {
+            $templateFile = \sprintf(
+                '%s_method_void.tpl',
+                $this->callOriginalMethod ? 'proxied' : 'mocked'
+            );
+        } else {
+            $templateFile = \sprintf(
+                '%s_method.tpl',
+                $this->callOriginalMethod ? 'proxied' : 'mocked'
+            );
+        }
+
+        $returnType = $this->returnType;
+        // @see https://bugs.php.net/bug.php?id=70722
+        if ($returnType === 'self') {
+            $returnType = $this->className;
+        }
+
+        // @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/406
+        if ($returnType === 'parent') {
+            $reflector = new ReflectionClass($this->className);
+
+            $parentClass = $reflector->getParentClass();
+
+            if ($parentClass === false) {
+                throw new RuntimeException(
+                    \sprintf(
+                        'Cannot mock %s::%s because "parent" return type declaration is used but %s does not have a parent class',
+                        $this->className,
+                        $this->methodName,
+                        $this->className
+                    )
+                );
+            }
+
+            $returnType = $parentClass->getName();
+        }
+
+        $deprecation = $this->deprecation;
+
+        if (null !== $this->deprecation) {
+            $deprecation         = "The $this->className::$this->methodName method is deprecated ($this->deprecation).";
+            $deprecationTemplate = $this->getTemplate('deprecation.tpl');
+
+            $deprecationTemplate->setVar([
+                'deprecation' => \var_export($deprecation, true),
+            ]);
+
+            $deprecation = $deprecationTemplate->render();
+        }
+
+        $template = $this->getTemplate($templateFile);
+
+        $template->setVar(
+            [
+                'arguments_decl'  => $this->argumentsForDeclaration,
+                'arguments_call'  => $this->argumentsForCall,
+                'return_delim'    => $returnType ? ': ' : '',
+                'return_type'     => $this->allowsReturnNull ? '?' . $returnType : $returnType,
+                'arguments_count' => !empty($this->argumentsForCall) ? \substr_count($this->argumentsForCall, ',') + 1 : 0,
+                'class_name'      => $this->className,
+                'method_name'     => $this->methodName,
+                'modifier'        => $this->modifier,
+                'reference'       => $this->reference,
+                'clone_arguments' => $this->cloneArguments ? 'true' : 'false',
+                'deprecation'     => $deprecation,
+            ]
+        );
+
+        return $template->render();
+    }
+
+    private function getTemplate(string $template): Text_Template
+    {
+        $filename = __DIR__ . \DIRECTORY_SEPARATOR . 'Generator' . \DIRECTORY_SEPARATOR . $template;
+
+        if (!isset(self::$templates[$filename])) {
+            self::$templates[$filename] = new Text_Template($filename);
+        }
+
+        return self::$templates[$filename];
+    }
+
+    /**
+     * Returns the parameters of a function or method.
+     *
+     * @throws RuntimeException
+     */
+    private static function getMethodParameters(ReflectionMethod $method, bool $forCall = false): string
+    {
+        $parameters = [];
+
+        foreach ($method->getParameters() as $i => $parameter) {
+            $name = '$' . $parameter->getName();
+
+            /* Note: PHP extensions may use empty names for reference arguments
+             * or "..." for methods taking a variable number of arguments.
+             */
+            if ($name === '$' || $name === '$...') {
+                $name = '$arg' . $i;
+            }
+
+            if ($parameter->isVariadic()) {
+                if ($forCall) {
+                    continue;
+                }
+
+                $name = '...' . $name;
+            }
+
+            $nullable        = '';
+            $default         = '';
+            $reference       = '';
+            $typeDeclaration = '';
+
+            if (!$forCall) {
+                if ($parameter->hasType() && $parameter->allowsNull()) {
+                    $nullable = '?';
+                }
+
+                if ($parameter->hasType() && $parameter->getType()->getName() !== 'self') {
+                    $typeDeclaration = $parameter->getType()->getName() . ' ';
+                } else {
+                    try {
+                        $class = $parameter->getType() && !$parameter->getType()->isBuiltin() 
+                            ? new ReflectionClass($parameter->getType()->getName())
+                            : null;
+                    } catch (ReflectionException $e) {
+                        throw new RuntimeException(
+                            \sprintf(
+                                'Cannot mock %s::%s() because a class or ' .
+                                'interface used in the signature is not loaded',
+                                $method->getDeclaringClass()->getName(),
+                                $method->getName()
+                            ),
+                            0,
+                            $e
+                        );
+                    }
+
+                    if ($class !== null) {
+                        $typeDeclaration = $class->getName() . ' ';
+                    }
+                }
+
+                if (!$parameter->isVariadic()) {
+                    if ($parameter->isDefaultValueAvailable()) {
+                        try {
+                            $value = \var_export($parameter->getDefaultValue(), true);
+                        } catch (\ReflectionException $e) {
+                            throw new RuntimeException(
+                                $e->getMessage(),
+                                (int) $e->getCode(),
+                                $e
+                            );
+                        }
+
+                        $default = ' = ' . $value;
+                    } elseif ($parameter->isOptional()) {
+                        $default = ' = null';
+                    }
+                }
+            }
+
+            if ($parameter->isPassedByReference()) {
+                $reference = '&';
+            }
+
+            $parameters[] = $nullable . $typeDeclaration . $reference . $name . $default;
+        }
+
+        return \implode(', ', $parameters);
+    }
+}

+ 307 - 0
tests/phpunit/includes/phpunit7/speed-trap-listener.php

@@ -0,0 +1,307 @@
+<?php
+
+/**
+ * A PHPUnit TestListener that exposes your slowest running tests by outputting
+ * results directly to the console.
+ */
+class SpeedTrapListener implements PHPUnit_Framework_TestListener {
+
+	/**
+	 * Internal tracking for test suites.
+	 *
+	 * Increments as more suites are run, then decremented as they finish. All
+	 * suites have been run when returns to 0.
+	 *
+	 * @var integer
+	 */
+	protected $suites = 0;
+
+	/**
+	 * Time in milliseconds at which a test will be considered "slow" and be
+	 * reported by this listener.
+	 *
+	 * @var int
+	 */
+	protected $slow_threshold;
+
+	/**
+	 * Number of tests to report on for slowness.
+	 *
+	 * @var int
+	 */
+	protected $report_length;
+
+	/**
+	 * Collection of slow tests.
+	 *
+	 * @var array
+	 */
+	protected $slow = array();
+
+	/**
+	 * Construct a new instance.
+	 *
+	 * @param array $options
+	 */
+	public function __construct( array $options = array() ) {
+		$this->loadOptions( $options );
+	}
+
+	/**
+	 * An error occurred.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addError( PHPUnit\Framework\Test $test, Throwable $t, float $time ): void {
+	}
+
+	/**
+	 * A warning occurred.
+	 *
+	 * @param PHPUnit_Framework_Test    $test
+	 * @param PHPUnit_Framework_Warning $e
+	 * @param float                     $time
+	 * @since Method available since Release 5.1.0
+	 */
+	public function addWarning( PHPUnit\Framework\Test $test, PHPUnit\Framework\Warning $e, float $time ): void {
+	}
+
+	/**
+	 * A failure occurred.
+	 *
+	 * @param PHPUnit_Framework_Test                 $test
+	 * @param PHPUnit_Framework_AssertionFailedError $e
+	 * @param float                                  $time
+	 */
+	public function addFailure( PHPUnit\Framework\Test $test, PHPUnit\Framework\AssertionFailedError $e, float $time ): void {
+	}
+
+	/**
+	 * Incomplete test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addIncompleteTest( PHPUnit\Framework\Test $test, Throwable $t, float $time ): void {
+	}
+
+	/**
+	 * Risky test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 * @since  Method available since Release 4.0.0
+	 */
+	public function addRiskyTest( PHPUnit\Framework\Test $test, Throwable $t, float $time ): void {
+	}
+
+	/**
+	 * Skipped test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addSkippedTest( PHPUnit\Framework\Test $test, Throwable $t, float $time ): void {
+	}
+
+	/**
+	 * A test started.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 */
+	public function startTest( PHPUnit\Framework\Test $test ): void {
+	}
+
+	/**
+	 * A test ended.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param float                  $time
+	 */
+	public function endTest( PHPUnit\Framework\Test $test, float $time ): void {
+		if ( ! $test instanceof PHPUnit_Framework_TestCase ) {
+			return;
+		}
+
+		$time      = $this->toMilliseconds( $time );
+		$threshold = $this->getSlowThreshold( $test );
+
+		if ( $this->isSlow( $time, $threshold ) ) {
+			$this->addSlowTest( $test, $time );
+		}
+	}
+
+	/**
+	 * A test suite started.
+	 *
+	 * @param PHPUnit_Framework_TestSuite $suite
+	 */
+	public function startTestSuite( PHPUnit\Framework\TestSuite $suite ): void {
+		$this->suites++;
+	}
+
+	/**
+	 * A test suite ended.
+	 *
+	 * @param PHPUnit_Framework_TestSuite $suite
+	 */
+	public function endTestSuite( PHPUnit\Framework\TestSuite $suite ): void {
+		$this->suites--;
+
+		if ( 0 === $this->suites && $this->hasSlowTests() ) {
+			arsort( $this->slow ); // Sort longest running tests to the top.
+
+			$this->renderHeader();
+			$this->renderBody();
+			$this->renderFooter();
+		}
+	}
+
+	/**
+	 * Whether the given test execution time is considered slow.
+	 *
+	 * @param int $time           Test execution time in milliseconds
+	 * @param int $slow_threshold Test execution time at which a test should be considered slow (milliseconds)
+	 * @return bool
+	 */
+	protected function isSlow( $time, $slow_threshold ) {
+		return $time >= $slow_threshold;
+	}
+
+	/**
+	 * Stores a test as slow.
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @param int                        $time Test execution time in milliseconds
+	 */
+	protected function addSlowTest( PHPUnit_Framework_TestCase $test, $time ) {
+		$label = $this->makeLabel( $test );
+
+		$this->slow[ $label ] = $time;
+	}
+
+	/**
+	 * Whether at least one test has been considered slow.
+	 *
+	 * @return bool
+	 */
+	protected function hasSlowTests() {
+		return ! empty( $this->slow );
+	}
+
+	/**
+	 * Convert PHPUnit's reported test time (microseconds) to milliseconds.
+	 *
+	 * @param float $time
+	 * @return int
+	 */
+	protected function toMilliseconds( $time ) {
+		return (int) round( $time * 1000 );
+	}
+
+	/**
+	 * Label for describing a test.
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @return string
+	 */
+	protected function makeLabel( PHPUnit_Framework_TestCase $test ) {
+		return sprintf( '%s:%s', get_class( $test ), $test->getName() );
+	}
+
+	/**
+	 * Calculate number of slow tests to report about.
+	 *
+	 * @return int
+	 */
+	protected function getReportLength() {
+		return min( count( $this->slow ), $this->report_length );
+	}
+
+	/**
+	 * Find how many slow tests occurred that won't be shown due to list length.
+	 *
+	 * @return int Number of hidden slow tests
+	 */
+	protected function getHiddenCount() {
+		$total   = count( $this->slow );
+		$showing = $this->getReportLength( $this->slow );
+
+		$hidden = 0;
+		if ( $total > $showing ) {
+			$hidden = $total - $showing;
+		}
+
+		return $hidden;
+	}
+
+	/**
+	 * Renders slow test report header.
+	 */
+	protected function renderHeader() {
+		echo sprintf( "\n\nYou should really fix these slow tests (>%sms)...\n", $this->slow_threshold );
+	}
+
+	/**
+	 * Renders slow test report body.
+	 */
+	protected function renderBody() {
+		$slow_tests = $this->slow;
+
+		$length = $this->getReportLength( $slow_tests );
+		for ( $i = 1; $i <= $length; ++$i ) {
+			$label = key( $slow_tests );
+			$time  = array_shift( $slow_tests );
+
+			echo sprintf( " %s. %sms to run %s\n", $i, $time, $label );
+		}
+	}
+
+	/**
+	 * Renders slow test report footer.
+	 */
+	protected function renderFooter() {
+		$hidden = $this->getHiddenCount( $this->slow );
+		if ( $hidden ) {
+			echo sprintf( '...and there %s %s more above your threshold hidden from view', 1 === $hidden ? 'is' : 'are', $hidden );
+		}
+	}
+
+	/**
+	 * Populate options into class internals.
+	 *
+	 * @param array $options
+	 */
+	protected function loadOptions( array $options ) {
+		$this->slow_threshold = isset( $options['slowThreshold'] ) ? $options['slowThreshold'] : 500;
+		$this->report_length  = isset( $options['reportLength'] ) ? $options['reportLength'] : 10;
+	}
+
+	/**
+	 * Get slow test threshold for given test. A TestCase can override the
+	 * suite-wide slow threshold by using the annotation @slowThreshold with
+	 * the threshold value in milliseconds.
+	 *
+	 * The following test will only be considered slow when its execution time
+	 * reaches 5000ms (5 seconds):
+	 *
+	 * <code>
+	 *
+	 * @slowThreshold 5000
+	 * public function testLongRunningProcess() {}
+	 * </code>
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @return int
+	 */
+	protected function getSlowThreshold( PHPUnit_Framework_TestCase $test ) {
+		$ann = $test->getAnnotations();
+
+		return isset( $ann['method']['slowThreshold'][0] ) ? $ann['method']['slowThreshold'][0] : $this->slow_threshold;
+	}
+}

+ 40 - 0
tests/phpunit/includes/phpunit7/testcase.php

@@ -0,0 +1,40 @@
+<?php
+
+require_once dirname( __DIR__ ) . '/abstract-testcase.php';
+
+/**
+ * Defines a basic fixture to run multiple tests.
+ *
+ * Resets the state of the WordPress installation before and after every test.
+ *
+ * Includes utility functions and assertions useful for testing WordPress.
+ *
+ * All WordPress unit tests should inherit from this class.
+ */
+class WP_UnitTestCase extends WP_UnitTestCase_Base {
+
+	/**
+	 * Asserts that two variables are equal (with delta).
+	 *
+	 * This method has been backported from a more recent PHPUnit version,
+	 * as tests running on PHP 5.6 use PHPUnit 5.7.x.
+	 *
+	 * @since 5.6.0
+	 *
+	 * @param mixed  $expected First value to compare.
+	 * @param mixed  $actual   Second value to compare.
+	 * @param float  $delta    Allowed numerical distance between two values to consider them equal.
+	 * @param string $message  Optional. Message to display when the assertion fails.
+	 *
+	 * @throws ExpectationFailedException
+	 * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
+	 */
+	public static function assertEqualsWithDelta( $expected, $actual, float $delta, string $message = '' ): void {
+		$constraint = new PHPUnit\Framework\Constraint\IsEqual(
+			$expected,
+			$delta
+		);
+
+		static::assertThat( $actual, $constraint, $message );
+	}
+}

+ 20 - 0
tests/phpunit/includes/plural-form-function.php

@@ -0,0 +1,20 @@
+<?php
+
+/**
+ * Legacy plural form function.
+ *
+ * @param int $nplurals
+ * @param string $expression
+ */
+function tests_make_plural_form_function( $nplurals, $expression ) {
+	$closure = function ( $n ) use ( $nplurals, $expression ) {
+		$expression = str_replace( 'n', $n, $expression );
+
+		// phpcs:ignore Squiz.PHP.Eval -- This is test code, not production.
+		$index = (int) eval( 'return ' . $expression . ';' );
+
+		return ( $index < $nplurals ) ? $index : $nplurals - 1;
+	};
+
+	return $closure;
+}

+ 306 - 0
tests/phpunit/includes/speed-trap-listener.php

@@ -0,0 +1,306 @@
+<?php
+
+/**
+ * A PHPUnit TestListener that exposes your slowest running tests by outputting
+ * results directly to the console.
+ */
+class SpeedTrapListener implements PHPUnit_Framework_TestListener {
+
+	/**
+	 * Internal tracking for test suites.
+	 *
+	 * Increments as more suites are run, then decremented as they finish. All
+	 * suites have been run when returns to 0.
+	 *
+	 * @var integer
+	 */
+	protected $suites = 0;
+
+	/**
+	 * Time in milliseconds at which a test will be considered "slow" and be
+	 * reported by this listener.
+	 *
+	 * @var int
+	 */
+	protected $slow_threshold;
+
+	/**
+	 * Number of tests to report on for slowness.
+	 *
+	 * @var int
+	 */
+	protected $report_length;
+
+	/**
+	 * Collection of slow tests.
+	 *
+	 * @var array
+	 */
+	protected $slow = array();
+
+	/**
+	 * Construct a new instance.
+	 *
+	 * @param array $options
+	 */
+	public function __construct( array $options = array() ) {
+		$this->loadOptions( $options );
+	}
+
+	/**
+	 * An error occurred.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addError( PHPUnit_Framework_Test $test, Exception $e, $time ) {
+	}
+
+	/**
+	 * A warning occurred.
+	 *
+	 * @param PHPUnit_Framework_Test    $test
+	 * @param PHPUnit_Framework_Warning $e
+	 * @param float                     $time
+	 * @since Method available since Release 5.1.0
+	 */
+	public function addWarning( PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time ) {
+	}
+
+	/**
+	 * A failure occurred.
+	 *
+	 * @param PHPUnit_Framework_Test                 $test
+	 * @param PHPUnit_Framework_AssertionFailedError $e
+	 * @param float                                  $time
+	 */
+	public function addFailure( PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time ) {
+	}
+
+	/**
+	 * Incomplete test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addIncompleteTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
+	}
+
+	/**
+	 * Risky test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 * @since  Method available since Release 4.0.0
+	 */
+	public function addRiskyTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
+	}
+
+	/**
+	 * Skipped test.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param Exception              $e
+	 * @param float                  $time
+	 */
+	public function addSkippedTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
+	}
+
+	/**
+	 * A test started.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 */
+	public function startTest( PHPUnit_Framework_Test $test ) {
+	}
+
+	/**
+	 * A test ended.
+	 *
+	 * @param PHPUnit_Framework_Test $test
+	 * @param float                  $time
+	 */
+	public function endTest( PHPUnit_Framework_Test $test, $time ) {
+		if ( ! $test instanceof PHPUnit_Framework_TestCase ) {
+			return;
+		}
+
+		$time      = $this->toMilliseconds( $time );
+		$threshold = $this->getSlowThreshold( $test );
+
+		if ( $this->isSlow( $time, $threshold ) ) {
+			$this->addSlowTest( $test, $time );
+		}
+	}
+
+	/**
+	 * A test suite started.
+	 *
+	 * @param PHPUnit_Framework_TestSuite $suite
+	 */
+	public function startTestSuite( PHPUnit_Framework_TestSuite $suite ) {
+		$this->suites++;
+	}
+
+	/**
+	 * A test suite ended.
+	 *
+	 * @param PHPUnit_Framework_TestSuite $suite
+	 */
+	public function endTestSuite( PHPUnit_Framework_TestSuite $suite ) {
+		$this->suites--;
+
+		if ( 0 === $this->suites && $this->hasSlowTests() ) {
+			arsort( $this->slow ); // Sort longest running tests to the top.
+
+			$this->renderHeader();
+			$this->renderBody();
+			$this->renderFooter();
+		}
+	}
+
+	/**
+	 * Whether the given test execution time is considered slow.
+	 *
+	 * @param int $time           Test execution time in milliseconds
+	 * @param int $slow_threshold Test execution time at which a test should be considered slow (milliseconds)
+	 * @return bool
+	 */
+	protected function isSlow( $time, $slow_threshold ) {
+		return $time >= $slow_threshold;
+	}
+
+	/**
+	 * Stores a test as slow.
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @param int                        $time Test execution time in milliseconds
+	 */
+	protected function addSlowTest( PHPUnit_Framework_TestCase $test, $time ) {
+		$label = $this->makeLabel( $test );
+
+		$this->slow[ $label ] = $time;
+	}
+
+	/**
+	 * Whether at least one test has been considered slow.
+	 *
+	 * @return bool
+	 */
+	protected function hasSlowTests() {
+		return ! empty( $this->slow );
+	}
+
+	/**
+	 * Convert PHPUnit's reported test time (microseconds) to milliseconds.
+	 *
+	 * @param float $time
+	 * @return int
+	 */
+	protected function toMilliseconds( $time ) {
+		return (int) round( $time * 1000 );
+	}
+
+	/**
+	 * Label for describing a test.
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @return string
+	 */
+	protected function makeLabel( PHPUnit_Framework_TestCase $test ) {
+		return sprintf( '%s:%s', get_class( $test ), $test->getName() );
+	}
+
+	/**
+	 * Calculate number of slow tests to report about.
+	 *
+	 * @return int
+	 */
+	protected function getReportLength() {
+		return min( count( $this->slow ), $this->report_length );
+	}
+
+	/**
+	 * Find how many slow tests occurred that won't be shown due to list length.
+	 *
+	 * @return int Number of hidden slow tests
+	 */
+	protected function getHiddenCount() {
+		$total   = count( $this->slow );
+		$showing = $this->getReportLength( $this->slow );
+
+		$hidden = 0;
+		if ( $total > $showing ) {
+			$hidden = $total - $showing;
+		}
+
+		return $hidden;
+	}
+
+	/**
+	 * Renders slow test report header.
+	 */
+	protected function renderHeader() {
+		echo sprintf( "\n\nYou should really fix these slow tests (>%sms)...\n", $this->slow_threshold );
+	}
+
+	/**
+	 * Renders slow test report body.
+	 */
+	protected function renderBody() {
+		$slow_tests = $this->slow;
+
+		$length = $this->getReportLength( $slow_tests );
+		for ( $i = 1; $i <= $length; ++$i ) {
+			$label = key( $slow_tests );
+			$time  = array_shift( $slow_tests );
+
+			echo sprintf( " %s. %sms to run %s\n", $i, $time, $label );
+		}
+	}
+
+	/**
+	 * Renders slow test report footer.
+	 */
+	protected function renderFooter() {
+		if ( $hidden = $this->getHiddenCount( $this->slow ) ) {
+			echo sprintf( '...and there %s %s more above your threshold hidden from view', 1 === $hidden ? 'is' : 'are', $hidden );
+		}
+	}
+
+	/**
+	 * Populate options into class internals.
+	 *
+	 * @param array $options
+	 */
+	protected function loadOptions( array $options ) {
+		$this->slow_threshold = isset( $options['slowThreshold'] ) ? $options['slowThreshold'] : 500;
+		$this->report_length  = isset( $options['reportLength'] ) ? $options['reportLength'] : 10;
+	}
+
+	/**
+	 * Get slow test threshold for given test. A TestCase can override the
+	 * suite-wide slow threshold by using the annotation @slowThreshold with
+	 * the threshold value in milliseconds.
+	 *
+	 * The following test will only be considered slow when its execution time
+	 * reaches 5000ms (5 seconds):
+	 *
+	 * <code>
+	 *
+	 * @slowThreshold 5000
+	 * public function testLongRunningProcess() {}
+	 * </code>
+	 *
+	 * @param PHPUnit_Framework_TestCase $test
+	 * @return int
+	 */
+	protected function getSlowThreshold( PHPUnit_Framework_TestCase $test ) {
+		$ann = $test->getAnnotations();
+
+		return isset( $ann['method']['slowThreshold'][0] ) ? $ann['method']['slowThreshold'][0] : $this->slow_threshold;
+	}
+}

+ 88 - 0
tests/phpunit/includes/spy-rest-server.php

@@ -0,0 +1,88 @@
+<?php
+
+class Spy_REST_Server extends WP_REST_Server {
+
+	public $sent_headers        = array();
+	public $sent_body           = '';
+	public $last_request        = null;
+	public $override_by_default = false;
+
+	/**
+	 * Gets the raw $endpoints data from the server.
+	 *
+	 * @return array
+	 */
+	public function get_raw_endpoint_data() {
+		return $this->endpoints;
+	}
+
+	/**
+	 * Allow calling protected methods from tests.
+	 *
+	 * @param string $method Method to call.
+	 * @param array  $args   Arguments to pass to the method.
+	 * @return mixed
+	 */
+	public function __call( $method, $args ) {
+		return call_user_func_array( array( $this, $method ), $args );
+	}
+
+	/**
+	 * Adds a header to the list of sent headers.
+	 *
+	 * @param string $header Header name.
+	 * @param string $value  Header value.
+	 */
+	public function send_header( $header, $value ) {
+		$this->sent_headers[ $header ] = $value;
+	}
+
+	/**
+	 * Removes a header from the list of sent headers.
+	 *
+	 * @param string $header Header name.
+	 */
+	public function remove_header( $header ) {
+		unset( $this->sent_headers[ $header ] );
+	}
+
+	/**
+	 * Overrides the dispatch method so we can get a handle on the request object.
+	 *
+	 * @param  WP_REST_Request $request Request to attempt dispatching.
+	 * @return WP_REST_Response Response returned by the callback.
+	 */
+	public function dispatch( $request ) {
+		$this->last_request = $request;
+		return parent::dispatch( $request );
+	}
+
+	/**
+	 * Overrides the register_route method so we can re-register routes internally if needed.
+	 *
+	 * @param string $namespace  Namespace.
+	 * @param string $route      The REST route.
+	 * @param array  $route_args Route arguments.
+	 * @param bool   $override   Optional. Whether the route should be overridden if it already exists.
+	 *                           Default false. Also set `$GLOBALS['wp_rest_server']->override_by_default = true`
+	 *                           to set overrides when you don't have access to the caller context.
+	 */
+	public function register_route( $namespace, $route, $route_args, $override = false ) {
+		parent::register_route( $namespace, $route, $route_args, $override || $this->override_by_default );
+	}
+
+	/**
+	 * Serves the request and returns the result.
+	 *
+	 * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
+	 *                     Default null.
+	 * @return null|false Null if not served and a HEAD request, false otherwise.
+	 */
+	public function serve_request( $path = null ) {
+
+		ob_start();
+		$result          = parent::serve_request( $path );
+		$this->sent_body = ob_get_clean();
+		return $result;
+	}
+}

+ 772 - 0
tests/phpunit/includes/testcase-block-supports.php

@@ -0,0 +1,772 @@
+<?php
+/**
+ * Test block supported styles.
+ *
+ * @package    WordPress
+ * @subpackage UnitTests
+ * @since      5.6.0
+ */
+class Block_Supported_Styles_Test extends WP_UnitTestCase {
+
+	/**
+	 * Registered block names.
+	 *
+	 * @var string[]
+	 */
+	private $registered_block_names = array();
+
+	/**
+	 * Tear down each test method.
+	 */
+	public function tearDown() {
+		while ( ! empty( $this->registered_block_names ) ) {
+			$block_name = array_pop( $this->registered_block_names );
+			unregister_block_type( $block_name );
+		}
+
+		parent::tearDown();
+	}
+
+	/**
+	 * Registers a block type.
+	 *
+	 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively a
+	 *                                   complete WP_Block_Type instance. In case a WP_Block_Type
+	 *                                   is provided, the $args parameter will be ignored.
+	 * @param array                $args {
+	 *     Optional. Array of block type arguments. Any arguments may be defined, however the
+	 *     ones described below are supported by default. Default empty array.
+	 *
+	 *     @type callable $render_callback Callback used to render blocks of this block type.
+	 * }
+	 */
+	protected function register_block_type( $name, $args ) {
+		register_block_type( $name, $args );
+
+		$this->registered_block_names[] = $name;
+	}
+
+	/**
+	 * Retrieves attribute such as 'class' or 'style' from the rendered block string.
+	 *
+	 * @param string $attribute Name of attribute to get.
+	 * @param string $block String of rendered block to check.
+	 */
+	private function get_attribute_from_block( $attribute, $block ) {
+		$start_index = strpos( $block, $attribute . '="' ) + strlen( $attribute ) + 2;
+		$split_arr   = substr( $block, $start_index );
+		$end_index   = strpos( $split_arr, '"' );
+		return substr( $split_arr, 0, $end_index );
+	}
+
+	/**
+	 * Retrieves block content from the rendered block string
+	 * (i.e. what's wrapped by the block wrapper `<div />`).
+	 *
+	 * @param string $block String of rendered block to check.
+	 */
+	private function get_content_from_block( $block ) {
+		$start_index = strpos( $block, '>' ) + 1; // First occurrence of '>'.
+		$split_arr   = substr( $block, $start_index );
+		$end_index   = strrpos( $split_arr, '<' ); // Last occurrence of '<'.
+		return substr( $split_arr, 0, $end_index ); // String between first '>' and last '<'.
+	}
+
+	/**
+	 * Block content to test with (i.e. what's wrapped by the block wrapper `<div />`).
+	 *
+	 * @var string
+	 */
+	const BLOCK_CONTENT = '
+		<p data-image-description="&lt;p&gt;Test!&lt;/p&gt;">Test</p>
+		<p>รครถรผ</p>
+		<p>รŸ</p>
+		<p>็ณปใฎๅฎถๅบญใซ</p>
+		<p>Example &lt;p&gt;Test!&lt;/p&gt;</p>
+	';
+
+	/**
+	 * Returns the rendered output for the current block.
+	 *
+	 * @param array $block Block to render.
+	 *
+	 * @return string Rendered output for the current block.
+	 */
+	private function render_example_block( $block ) {
+		WP_Block_Supports::init();
+		WP_Block_Supports::$block_to_render = $block;
+		$wrapper_attributes                 = get_block_wrapper_attributes(
+			array(
+				'class' => 'foo-bar-class',
+				'style' => 'test: style;',
+			)
+		);
+		return '<div ' . $wrapper_attributes . '>' . self::BLOCK_CONTENT . '</div>';
+	}
+
+	/**
+	 * Runs assertions that the rendered output has expected class/style attrs.
+	 *
+	 * @param array  $block Block to render.
+	 * @param string $expected_classes Expected output class attr string.
+	 * @param string $expected_styles Expected output styles attr string.
+	 */
+	private function assert_styles_and_classes_match( $block, $expected_classes, $expected_styles ) {
+		$styled_block = $this->render_example_block( $block );
+		$class_list   = $this->get_attribute_from_block( 'class', $styled_block );
+		$style_list   = $this->get_attribute_from_block( 'style', $styled_block );
+
+		$this->assertSame( $expected_classes, $class_list );
+		$this->assertSame( $expected_styles, $style_list );
+	}
+
+	/**
+	 * Runs assertions that the rendered output has expected content and class/style attrs.
+	 *
+	 * @param array  $block Block to render.
+	 * @param string $expected_classes Expected output class attr string.
+	 * @param string $expected_styles Expected output styles attr string.
+	 */
+	private function assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles ) {
+		$styled_block = $this->render_example_block( $block );
+
+		// Ensure blocks to not add extra whitespace.
+		$this->assertSame( $styled_block, trim( $styled_block ) );
+
+		$content    = $this->get_content_from_block( $styled_block );
+		$class_list = $this->get_attribute_from_block( 'class', $styled_block );
+		$style_list = $this->get_attribute_from_block( 'style', $styled_block );
+
+		$this->assertSame( self::BLOCK_CONTENT, $content );
+		$this->assertSameSets(
+			explode( ' ', $expected_classes ),
+			explode( ' ', $class_list )
+		);
+		$this->assertSame(
+			array_map( 'trim', explode( ';', $expected_styles ) ),
+			array_map( 'trim', explode( ';', $style_list ) )
+		);
+	}
+
+	/**
+	 * Tests color support for named color support for named colors.
+	 */
+	function test_named_color_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => true,
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'textColor'       => 'red',
+				'backgroundColor' => 'black',
+				// The following should not be applied (subcatagories of color support).
+				'gradient'        => 'some-gradient',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-text-color has-red-color has-background has-black-background-color';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests color support for custom colors.
+	 */
+	function test_custom_color_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => true,
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array(
+					'color' => array(
+						'text'       => '#000',
+						'background' => '#fff',
+						// The following should not be applied (subcatagories of color support).
+						'gradient'   => 'some-gradient',
+						'style'      => array( 'color' => array( 'link' => '#fff' ) ),
+					),
+				),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_styles  = 'test: style; color: #000; background-color: #fff;';
+		$expected_classes = 'foo-bar-class wp-block-example has-text-color has-background';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests link color support for named colors.
+	 */
+	function test_named_link_color_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => array(
+					'link' => true,
+				),
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'color' => array( 'link' => 'var:preset|color|red' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-link-color';
+		$expected_styles  = 'test: style; --wp--style--color--link: var(--wp--preset--color--red);';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests link color support for custom colors.
+	 */
+	function test_custom_link_color_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => array(
+					'link' => true,
+				),
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'color' => array( 'link' => '#fff' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-link-color';
+		$expected_styles  = 'test: style; --wp--style--color--link: #fff;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests gradient color support for named gradients.
+	 */
+	function test_named_gradient_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => array(
+					'gradients' => true,
+				),
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'gradient' => 'red',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-background has-red-gradient-background';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests gradient color support for custom gradients.
+	 */
+	function test_custom_gradient_support() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(
+				'color' => array(
+					'gradients' => true,
+				),
+			),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'color' => array( 'gradient' => 'some-gradient-style' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-background';
+		$expected_styles  = 'test: style; background: some-gradient-style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests that style attributes for colors are not applied without the support flag.
+	 */
+	function test_color_unsupported() {
+		$block_type_settings = array(
+			'attributes'      => array(),
+			'supports'        => array(),
+			'render_callback' => true,
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'textColor'       => 'red',
+				'backgroundColor' => 'black',
+				'style'           => array(
+					'color' => array(
+						'text'       => '#000',
+						'background' => '#fff',
+						'link'       => '#ggg',
+						'gradient'   => 'some-gradient',
+					),
+				),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests support for named font sizes.
+	 */
+	function test_named_font_size() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'fontSize' => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'fontSize' => 'large',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-large-font-size';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests support for custom font sizes.
+	 */
+	function test_custom_font_size() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'fontSize' => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'typography' => array( 'fontSize' => '10' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style; font-size: 10px;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests that font size attributes are not applied without support flag.
+	 */
+	function test_font_size_unsupported() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'fontSize' => 'large',
+				'style'    => array( 'typography' => array( 'fontSize' => '10' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests line height support.
+	 */
+	function test_line_height() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'lineHeight' => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'typography' => array( 'lineHeight' => '10' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style; line-height: 10;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests line height not applied without support flag.
+	 */
+	function test_line_height_unsupported() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'style' => array( 'typography' => array( 'lineHeight' => '10' ) ),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests support for block alignment.
+	 */
+	function test_block_alignment() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'align' => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'align' => 'wide',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example alignwide';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests block alignment requires support to be added.
+	 */
+	function test_block_alignment_unsupported() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'align' => 'wide',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests all support flags together to ensure they work together as expected.
+	 */
+	function test_all_supported() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'color'      => array(
+					'gradients' => true,
+					'link'      => true,
+				),
+				'fontSize'   => true,
+				'lineHeight' => true,
+				'align'      => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'align' => 'wide',
+				'style' => array(
+					'color'      => array(
+						'text'       => '#000',
+						'background' => '#fff',
+						'style'      => array( 'color' => array( 'link' => '#fff' ) ),
+					),
+					'typography' => array(
+						'lineHeight' => '20',
+						'fontSize'   => '10',
+					),
+				),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example has-text-color has-background alignwide';
+		$expected_styles  = 'test: style; color: #000; background-color: #fff; font-size: 10px; line-height: 20;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests that only styles for the supported flag are added.
+	 * Verify one support enabled does not imply multiple supports enabled.
+	 */
+	function test_one_supported() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'fontSize' => true,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'align' => 'wide',
+				'style' => array(
+					'color'      => array(
+						'text'       => '#000',
+						'background' => '#fff',
+						'gradient'   => 'some-gradient',
+						'style'      => array( 'color' => array( 'link' => '#fff' ) ),
+					),
+					'typography' => array(
+						'lineHeight' => '20',
+						'fontSize'   => '10',
+					),
+				),
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_classes = 'foo-bar-class wp-block-example';
+		$expected_styles  = 'test: style; font-size: 10px;';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests custom classname server-side block support.
+	 */
+	function test_custom_classnames_support() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'className' => 'my-custom-classname',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_styles  = 'test: style;';
+		$expected_classes = 'foo-bar-class wp-block-example my-custom-classname';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests custom classname server-side block support opt-out.
+	 */
+	function test_custom_classnames_support_opt_out() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'customClassName' => false,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(
+				'className' => 'my-custom-classname',
+			),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_styles  = 'test: style;';
+		$expected_classes = 'foo-bar-class wp-block-example';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Tests generated classname server-side block support opt-out.
+	 */
+	function test_generatted_classnames_support_opt_out() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(
+				'className' => false,
+			),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		$expected_styles  = 'test: style;';
+		$expected_classes = 'foo-bar-class';
+
+		$this->assert_content_and_styles_and_classes_match( $block, $expected_classes, $expected_styles );
+	}
+
+	/**
+	 * Ensures libxml_internal_errors is being used instead of @ warning suppression
+	 */
+	public function test_render_block_suppresses_warnings_without_at_suppression() {
+		$block_type_settings = array(
+			'attributes' => array(),
+			'supports'   => array(),
+		);
+		$this->register_block_type( 'core/example', $block_type_settings );
+
+		$block = array(
+			'blockName'    => 'core/example',
+			'attrs'        => array(),
+			'innerBlock'   => array(),
+			'innerContent' => array(),
+			'innerHTML'    => array(),
+		);
+
+		// Custom error handler's see Warnings even if they are suppressed by the @ symbol.
+		$errors = array();
+		set_error_handler(
+			function ( $errno = 0, $errstr = '' ) use ( &$errors ) {
+				$errors[] = $errstr;
+				return false;
+			}
+		);
+
+		// HTML5 elements like <time> are not supported by the DOMDocument parser used by the block supports feature.
+		// This specific example is emitted by the "Display post date" setting in the latest-posts block.
+		apply_filters( 'render_block', '<div><time datetime="2020-06-18T04:01:43+10:00" class="wp-block-latest-posts__post-date">June 18, 2020</time></div>', $block );
+
+		restore_error_handler();
+
+		$this->assertEmpty( $errors, 'Libxml errors should be dropped.' );
+	}
+}

+ 357 - 0
tests/phpunit/includes/testcase-canonical.php

@@ -0,0 +1,357 @@
+<?php
+
+class WP_Canonical_UnitTestCase extends WP_UnitTestCase {
+	public static $old_current_user;
+	public static $author_id;
+	public static $post_ids    = array();
+	public static $comment_ids = array();
+	public static $term_ids    = array();
+	public static $terms       = array();
+	public static $old_options = array();
+
+	/**
+	 * This can be defined in a subclass of this class which contains its own data() method.
+	 * Those tests will be run against the specified permastruct.
+	 */
+	public $structure = '/%year%/%monthnum%/%day%/%postname%/';
+
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::generate_shared_fixtures( $factory );
+	}
+
+	public static function wpTearDownAfterClass() {
+		self::delete_shared_fixtures();
+	}
+
+	public function setUp() {
+		parent::setUp();
+
+		update_option( 'page_comments', true );
+		update_option( 'comments_per_page', 5 );
+		update_option( 'posts_per_page', 5 );
+
+		$this->set_permalink_structure( $this->structure );
+		create_initial_taxonomies();
+	}
+
+	/**
+	 * Generate fixtures to be shared between canonical tests.
+	 *
+	 * Abstracted here because it's invoked by setUpBeforeClass() in more than one class.
+	 *
+	 * @since 4.1.0
+	 */
+	public static function generate_shared_fixtures( WP_UnitTest_Factory $factory ) {
+		self::$old_current_user = get_current_user_id();
+		self::$author_id        = $factory->user->create( array( 'user_login' => 'canonical-author' ) );
+
+		/*
+		 * Also set in self::setUp(), but we must configure here to make sure that
+		 * post authorship is properly attributed for fixtures.
+		 */
+		wp_set_current_user( self::$author_id );
+
+		// Already created by install defaults:
+		// $factory->term->create( array( 'taxonomy' => 'category', 'name' => 'uncategorized' ) );
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'import_id'  => 587,
+				'post_title' => 'post-format-test-audio',
+				'post_date'  => '2008-06-02 00:00:00',
+			)
+		);
+
+		$gallery_post_id = $factory->post->create(
+			array(
+				'post_title' => 'post-format-test-gallery',
+				'post_date'  => '2008-06-10 00:00:00',
+			)
+		);
+
+		self::$post_ids[] = $gallery_post_id;
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'import_id'   => 611,
+				'post_type'   => 'attachment',
+				'post_title'  => 'canola2',
+				'post_parent' => $gallery_post_id,
+			)
+		);
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'post_title' => 'images-test',
+				'post_date'  => '2008-09-03 00:00:00',
+			)
+		);
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'post_title'   => 'multipage-post-test',
+				'post_date'    => '2008-09-03 00:00:00',
+				'post_content' => 'Page 1 <!--nextpage--> Page 2 <!--nextpage--> Page 3',
+			)
+		);
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'post_title' => 'non-paged-post-test',
+				'post_date'  => '2008-09-03 00:00:00',
+			)
+		);
+
+		$comment_post_id = $factory->post->create(
+			array(
+				'import_id'  => 149,
+				'post_title' => 'comment-test',
+				'post_date'  => '2008-03-03 00:00:00',
+			)
+		);
+
+		self::$post_ids[]  = $comment_post_id;
+		self::$comment_ids = $factory->comment->create_post_comments( $comment_post_id, 15 );
+
+		self::$post_ids[] = $factory->post->create( array( 'post_date' => '2008-09-05 00:00:00' ) );
+
+		self::$post_ids[] = $factory->post->create( array( 'import_id' => 123 ) );
+		self::$post_ids[] = $factory->post->create( array( 'import_id' => 1 ) );
+		self::$post_ids[] = $factory->post->create( array( 'import_id' => 358 ) );
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'post_type'  => 'page',
+				'post_title' => 'sample-page',
+			)
+		);
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'post_type'  => 'page',
+				'post_title' => 'about',
+			)
+		);
+
+		$parent_page_id = $factory->post->create(
+			array(
+				'post_type'  => 'page',
+				'post_title' => 'parent-page',
+			)
+		);
+
+		self::$post_ids[] = $parent_page_id;
+
+		self::$post_ids[] = $factory->post->create(
+			array(
+				'import_id'   => 144,
+				'post_type'   => 'page',
+				'post_title'  => 'child-page-1',
+				'post_parent' => $parent_page_id,
+			)
+		);
+
+		$parent_page_id = $factory->post->create(
+			array(
+				'post_name' => 'parent',
+				'post_type' => 'page',
+			)
+		);
+
+		self::$post_ids[] = $parent_page_id;
+
+		$child_id_1 = $factory->post->create(
+			array(
+				'post_name'   => 'child1',
+				'post_type'   => 'page',
+				'post_parent' => $parent_page_id,
+			)
+		);
+
+		self::$post_ids[] = $child_id_1;
+
+		$child_id_2 = $factory->post->create(
+			array(
+				'post_name'   => 'child2',
+				'post_type'   => 'page',
+				'post_parent' => $parent_page_id,
+			)
+		);
+
+		self::$post_ids[] = $child_id_2;
+
+		$grandchild_id_1 = $factory->post->create(
+			array(
+				'post_name'   => 'grandchild',
+				'post_type'   => 'page',
+				'post_parent' => $child_id_1,
+			)
+		);
+
+		self::$post_ids[] = $grandchild_id_1;
+
+		$grandchild_id_2 = $factory->post->create(
+			array(
+				'post_name'   => 'grandchild',
+				'post_type'   => 'page',
+				'post_parent' => $child_id_2,
+			)
+		);
+
+		self::$post_ids[] = $grandchild_id_2;
+
+		$cat1 = $factory->term->create(
+			array(
+				'taxonomy' => 'category',
+				'name'     => 'parent',
+			)
+		);
+
+		self::$terms['/category/parent/'] = $cat1;
+
+		self::$term_ids[ $cat1 ] = 'category';
+
+		$cat2 = $factory->term->create(
+			array(
+				'taxonomy' => 'category',
+				'name'     => 'child-1',
+				'parent'   => self::$terms['/category/parent/'],
+			)
+		);
+
+		self::$terms['/category/parent/child-1/'] = $cat2;
+
+		self::$term_ids[ $cat2 ] = 'category';
+
+		$cat3 = $factory->term->create(
+			array(
+				'taxonomy' => 'category',
+				'name'     => 'child-2',
+				'parent'   => self::$terms['/category/parent/child-1/'],
+			)
+		);
+
+		self::$terms['/category/parent/child-1/child-2/'] = $cat3;
+
+		self::$term_ids[ $cat3 ] = 'category';
+
+		$cat4 = $factory->term->create(
+			array(
+				'taxonomy' => 'category',
+				'name'     => 'cat-a',
+			)
+		);
+
+		self::$term_ids[ $cat4 ] = 'category';
+
+		$cat5 = $factory->term->create(
+			array(
+				'taxonomy' => 'category',
+				'name'     => 'cat-b',
+			)
+		);
+
+		self::$term_ids[ $cat5 ] = 'category';
+
+		$tag1 = $factory->term->create(
+			array(
+				'name' => 'post-formats',
+			)
+		);
+
+		self::$term_ids[ $tag1 ] = 'post_tag';
+	}
+
+	/**
+	 * Clean up shared fixtures.
+	 *
+	 * @since 4.1.0
+	 */
+	public static function delete_shared_fixtures() {
+		self::$author_id   = null;
+		self::$post_ids    = array();
+		self::$comment_ids = array();
+		self::$term_ids    = array();
+		self::$terms       = array();
+	}
+
+	/**
+	 * Assert that a given URL is the same a the canonical URL generated by WP.
+	 *
+	 * @since 4.1.0
+	 *
+	 * @param string $test_url                Raw URL that will be run through redirect_canonical().
+	 * @param string $expected                Expected string.
+	 * @param int    $ticket                  Optional. Trac ticket number.
+	 * @param array  $expected_doing_it_wrong Array of class/function names expected to throw _doing_it_wrong() notices.
+	 */
+	public function assertCanonical( $test_url, $expected, $ticket = 0, $expected_doing_it_wrong = array() ) {
+		$this->expected_doing_it_wrong = array_merge( $this->expected_doing_it_wrong, (array) $expected_doing_it_wrong );
+
+		$ticket_ref = ( $ticket > 0 ) ? 'Ticket #' . $ticket : '';
+
+		if ( is_string( $expected ) ) {
+			$expected = array( 'url' => $expected );
+		} elseif ( is_array( $expected ) && ! isset( $expected['url'] ) && ! isset( $expected['qv'] ) ) {
+			$expected = array( 'qv' => $expected );
+		}
+
+		if ( ! isset( $expected['url'] ) && ! isset( $expected['qv'] ) ) {
+			$this->fail( 'No valid expected output was provided' );
+		}
+
+		$this->go_to( home_url( $test_url ) );
+
+		// Does the redirect match what's expected?
+		$can_url        = $this->get_canonical( $test_url );
+		$parsed_can_url = parse_url( $can_url );
+
+		// Just test the path and query if present.
+		if ( isset( $expected['url'] ) ) {
+			$this->assertSame( $expected['url'], $parsed_can_url['path'] . ( ! empty( $parsed_can_url['query'] ) ? '?' . $parsed_can_url['query'] : '' ), $ticket_ref );
+		}
+
+		// If the test data doesn't include expected query vars, then we're done here.
+		if ( ! isset( $expected['qv'] ) ) {
+			return;
+		}
+
+		// "make" that the request and check the query is correct.
+		$this->go_to( $can_url );
+
+		// Are all query vars accounted for, and correct?
+		global $wp;
+
+		$query_vars = array_diff( $wp->query_vars, $wp->extra_query_vars );
+		if ( ! empty( $parsed_can_url['query'] ) ) {
+			parse_str( $parsed_can_url['query'], $_qv );
+
+			// $_qv should not contain any elements which are set in $query_vars already
+			// (i.e. $_GET vars should not be present in the Rewrite).
+			$this->assertSame( array(), array_intersect( $query_vars, $_qv ), 'Query vars are duplicated from the Rewrite into $_GET; ' . $ticket_ref );
+
+			$query_vars = array_merge( $query_vars, $_qv );
+		}
+
+		$this->assertEquals( $expected['qv'], $query_vars );
+	}
+
+	/**
+	 * Get the canonical URL given a raw URL.
+	 *
+	 * @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().
+	 */
+	public function get_canonical( $test_url ) {
+		$test_url = home_url( $test_url );
+
+		$can_url = redirect_canonical( $test_url, false );
+		if ( ! $can_url ) {
+			return $test_url; // No redirect will take place for this request.
+		}
+
+		return $can_url;
+	}
+}

+ 19 - 0
tests/phpunit/includes/testcase-rest-api.php

@@ -0,0 +1,19 @@
+<?php
+
+abstract class WP_Test_REST_TestCase extends WP_UnitTestCase {
+	protected function assertErrorResponse( $code, $response, $status = null ) {
+
+		if ( is_a( $response, 'WP_REST_Response' ) ) {
+			$response = $response->as_error();
+		}
+
+		$this->assertWPError( $response );
+		$this->assertSame( $code, $response->get_error_code() );
+
+		if ( null !== $status ) {
+			$data = $response->get_error_data();
+			$this->assertArrayHasKey( 'status', $data );
+			$this->assertSame( $status, $data['status'] );
+		}
+	}
+}

+ 52 - 0
tests/phpunit/includes/testcase-rest-controller.php

@@ -0,0 +1,52 @@
+<?php
+
+abstract class WP_Test_REST_Controller_Testcase extends WP_Test_REST_TestCase {
+
+	protected $server;
+
+	public function setUp() {
+		parent::setUp();
+		add_filter( 'rest_url', array( $this, 'filter_rest_url_for_leading_slash' ), 10, 2 );
+		/** @var WP_REST_Server $wp_rest_server */
+		global $wp_rest_server;
+		$wp_rest_server = new Spy_REST_Server;
+		do_action( 'rest_api_init', $wp_rest_server );
+	}
+
+	public function tearDown() {
+		remove_filter( 'rest_url', array( $this, 'test_rest_url_for_leading_slash' ), 10, 2 );
+		/** @var WP_REST_Server $wp_rest_server */
+		global $wp_rest_server;
+		$wp_rest_server = null;
+		parent::tearDown();
+	}
+
+	abstract public function test_register_routes();
+
+	abstract public function test_context_param();
+
+	abstract public function test_get_items();
+
+	abstract public function test_get_item();
+
+	abstract public function test_create_item();
+
+	abstract public function test_update_item();
+
+	abstract public function test_delete_item();
+
+	abstract public function test_prepare_item();
+
+	abstract public function test_get_item_schema();
+
+	public function filter_rest_url_for_leading_slash( $url, $path ) {
+		if ( is_multisite() || get_option( 'permalink_structure' ) ) {
+			return $url;
+		}
+
+		// Make sure path for rest_url has a leading slash for proper resolution.
+		$this->assertTrue( 0 === strpos( $path, '/' ), 'REST API URL should have a leading slash.' );
+
+		return $url;
+	}
+}

+ 317 - 0
tests/phpunit/includes/testcase-rest-post-type-controller.php

@@ -0,0 +1,317 @@
+<?php
+
+abstract class WP_Test_REST_Post_Type_Controller_Testcase extends WP_Test_REST_Controller_Testcase {
+
+	protected function check_post_data( $post, $data, $context, $links ) {
+		$post_type_obj = get_post_type_object( $post->post_type );
+
+		// Standard fields.
+		$this->assertSame( $post->ID, $data['id'] );
+		$this->assertSame( $post->post_name, $data['slug'] );
+		$this->assertSame( get_permalink( $post->ID ), $data['link'] );
+		if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
+			$post_date_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_date ) - ( get_option( 'gmt_offset' ) * 3600 ) );
+			$this->assertSame( mysql_to_rfc3339( $post_date_gmt ), $data['date_gmt'] );
+		} else {
+			$this->assertSame( mysql_to_rfc3339( $post->post_date_gmt ), $data['date_gmt'] );
+		}
+		$this->assertSame( mysql_to_rfc3339( $post->post_date ), $data['date'] );
+
+		if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) {
+			$post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * 3600 ) );
+			$this->assertSame( mysql_to_rfc3339( $post_modified_gmt ), $data['modified_gmt'] );
+		} else {
+			$this->assertSame( mysql_to_rfc3339( $post->post_modified_gmt ), $data['modified_gmt'] );
+		}
+		$this->assertSame( mysql_to_rfc3339( $post->post_modified ), $data['modified'] );
+
+		// Author.
+		if ( post_type_supports( $post->post_type, 'author' ) ) {
+			$this->assertEquals( $post->post_author, $data['author'] );
+		} else {
+			$this->assertEmpty( $data['author'] );
+		}
+
+		// Post parent.
+		if ( $post_type_obj->hierarchical ) {
+			$this->assertArrayHasKey( 'parent', $data );
+			if ( $post->post_parent ) {
+				if ( is_int( $data['parent'] ) ) {
+					$this->assertSame( $post->post_parent, $data['parent'] );
+				} else {
+					$this->assertSame( $post->post_parent, $data['parent']['id'] );
+					$this->check_get_post_response( $data['parent'], get_post( $data['parent']['id'] ), 'view-parent' );
+				}
+			} else {
+				$this->assertEmpty( $data['parent'] );
+			}
+		} else {
+			$this->assertFalse( isset( $data['parent'] ) );
+		}
+
+		// Page attributes.
+		if ( $post_type_obj->hierarchical && post_type_supports( $post->post_type, 'page-attributes' ) ) {
+			$this->assertSame( $post->menu_order, $data['menu_order'] );
+		} else {
+			$this->assertFalse( isset( $data['menu_order'] ) );
+		}
+
+		// Comments.
+		if ( post_type_supports( $post->post_type, 'comments' ) ) {
+			$this->assertSame( $post->comment_status, $data['comment_status'] );
+			$this->assertSame( $post->ping_status, $data['ping_status'] );
+		} else {
+			$this->assertFalse( isset( $data['comment_status'] ) );
+			$this->assertFalse( isset( $data['ping_status'] ) );
+		}
+
+		if ( 'post' === $post->post_type ) {
+			$this->assertSame( is_sticky( $post->ID ), $data['sticky'] );
+		}
+
+		if ( 'post' === $post->post_type && 'edit' === $context ) {
+			$this->assertSame( $post->post_password, $data['password'] );
+		}
+
+		if ( 'page' === $post->post_type ) {
+			$this->assertSame( get_page_template_slug( $post->ID ), $data['template'] );
+		}
+
+		if ( post_type_supports( $post->post_type, 'thumbnail' ) ) {
+			$this->assertSame( (int) get_post_thumbnail_id( $post->ID ), $data['featured_media'] );
+		} else {
+			$this->assertFalse( isset( $data['featured_media'] ) );
+		}
+
+		// Check post format.
+		if ( post_type_supports( $post->post_type, 'post-formats' ) ) {
+			$post_format = get_post_format( $post->ID );
+			if ( empty( $post_format ) ) {
+				$this->assertSame( 'standard', $data['format'] );
+			} else {
+				$this->assertSame( get_post_format( $post->ID ), $data['format'] );
+			}
+		} else {
+			$this->assertFalse( isset( $data['format'] ) );
+		}
+
+		// Check filtered values.
+		if ( post_type_supports( $post->post_type, 'title' ) ) {
+			add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
+			$this->assertSame( get_the_title( $post->ID ), $data['title']['rendered'] );
+			remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
+			if ( 'edit' === $context ) {
+				$this->assertSame( $post->post_title, $data['title']['raw'] );
+			} else {
+				$this->assertFalse( isset( $data['title']['raw'] ) );
+			}
+		} else {
+			$this->assertFalse( isset( $data['title'] ) );
+		}
+
+		if ( post_type_supports( $post->post_type, 'editor' ) ) {
+			// TODO: Apply content filter for more accurate testing.
+			if ( ! $post->post_password ) {
+				$this->assertSame( wpautop( $post->post_content ), $data['content']['rendered'] );
+			}
+
+			if ( 'edit' === $context ) {
+				$this->assertSame( $post->post_content, $data['content']['raw'] );
+			} else {
+				$this->assertFalse( isset( $data['content']['raw'] ) );
+			}
+		} else {
+			$this->assertFalse( isset( $data['content'] ) );
+		}
+
+		if ( post_type_supports( $post->post_type, 'excerpt' ) ) {
+			if ( empty( $post->post_password ) ) {
+				// TODO: Apply excerpt filter for more accurate testing.
+				$this->assertSame( wpautop( $post->post_excerpt ), $data['excerpt']['rendered'] );
+			} else {
+				// TODO: Better testing for excerpts for password protected posts.
+			}
+			if ( 'edit' === $context ) {
+				$this->assertSame( $post->post_excerpt, $data['excerpt']['raw'] );
+			} else {
+				$this->assertFalse( isset( $data['excerpt']['raw'] ) );
+			}
+		} else {
+			$this->assertFalse( isset( $data['excerpt'] ) );
+		}
+
+		$this->assertSame( $post->post_status, $data['status'] );
+		$this->assertSame( $post->guid, $data['guid']['rendered'] );
+
+		if ( 'edit' === $context ) {
+			$this->assertSame( $post->guid, $data['guid']['raw'] );
+		}
+
+		$taxonomies = wp_list_filter( get_object_taxonomies( $post->post_type, 'objects' ), array( 'show_in_rest' => true ) );
+		foreach ( $taxonomies as $taxonomy ) {
+			$this->assertTrue( isset( $data[ $taxonomy->rest_base ] ) );
+			$terms = wp_get_object_terms( $post->ID, $taxonomy->name, array( 'fields' => 'ids' ) );
+			sort( $terms );
+			sort( $data[ $taxonomy->rest_base ] );
+			$this->assertSame( $terms, $data[ $taxonomy->rest_base ] );
+		}
+
+		// Test links.
+		if ( $links ) {
+
+			$links     = test_rest_expand_compact_links( $links );
+			$post_type = get_post_type_object( $data['type'] );
+			$this->assertSame( $links['self'][0]['href'], rest_url( 'wp/v2/' . $post_type->rest_base . '/' . $data['id'] ) );
+			$this->assertSame( $links['collection'][0]['href'], rest_url( 'wp/v2/' . $post_type->rest_base ) );
+			$this->assertSame( $links['about'][0]['href'], rest_url( 'wp/v2/types/' . $data['type'] ) );
+
+			if ( post_type_supports( $post->post_type, 'author' ) && $data['author'] ) {
+				$this->assertSame( $links['author'][0]['href'], rest_url( 'wp/v2/users/' . $data['author'] ) );
+			}
+
+			if ( post_type_supports( $post->post_type, 'comments' ) ) {
+				$this->assertSame( $links['replies'][0]['href'], add_query_arg( 'post', $data['id'], rest_url( 'wp/v2/comments' ) ) );
+			}
+
+			if ( post_type_supports( $post->post_type, 'revisions' ) ) {
+				$this->assertSame( $links['version-history'][0]['href'], rest_url( 'wp/v2/' . $post_type->rest_base . '/' . $data['id'] . '/revisions' ) );
+			}
+
+			if ( $post_type->hierarchical && ! empty( $data['parent'] ) ) {
+				$this->assertSame( $links['up'][0]['href'], rest_url( 'wp/v2/' . $post_type->rest_base . '/' . $data['parent'] ) );
+			}
+
+			if ( ! in_array( $data['type'], array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
+				$this->assertSame( $links['https://api.w.org/attachment'][0]['href'], add_query_arg( 'parent', $data['id'], rest_url( 'wp/v2/media' ) ) );
+			}
+
+			if ( ! empty( $data['featured_media'] ) ) {
+				$this->assertSame( $links['https://api.w.org/featuredmedia'][0]['href'], rest_url( 'wp/v2/media/' . $data['featured_media'] ) );
+			}
+
+			$num = 0;
+			foreach ( $taxonomies as $key => $taxonomy ) {
+				$this->assertSame( $taxonomy->name, $links['https://api.w.org/term'][ $num ]['attributes']['taxonomy'] );
+				$this->assertSame( add_query_arg( 'post', $data['id'], rest_url( 'wp/v2/' . $taxonomy->rest_base ) ), $links['https://api.w.org/term'][ $num ]['href'] );
+				$num++;
+			}
+		}
+
+	}
+
+	protected function check_get_posts_response( $response, $context = 'view' ) {
+		$this->assertNotWPError( $response );
+		$response = rest_ensure_response( $response );
+		$this->assertSame( 200, $response->get_status() );
+
+		$headers = $response->get_headers();
+		$this->assertArrayHasKey( 'X-WP-Total', $headers );
+		$this->assertArrayHasKey( 'X-WP-TotalPages', $headers );
+
+		$all_data = $response->get_data();
+		foreach ( $all_data as $data ) {
+			$post = get_post( $data['id'] );
+			// As the links for the post are "response_links" format in the data array,
+			// we have to pull them out and parse them.
+			$links = $data['_links'];
+			foreach ( $links as &$links_array ) {
+				foreach ( $links_array as &$link ) {
+					$attributes         = array_diff_key(
+						$link,
+						array(
+							'href' => 1,
+							'name' => 1,
+						)
+					);
+					$link               = array_diff_key( $link, $attributes );
+					$link['attributes'] = $attributes;
+				}
+			}
+
+			$this->check_post_data( $post, $data, $context, $links );
+		}
+	}
+
+	protected function check_get_post_response( $response, $context = 'view' ) {
+		$this->assertNotWPError( $response );
+		$response = rest_ensure_response( $response );
+		$this->assertSame( 200, $response->get_status() );
+
+		$data = $response->get_data();
+		$post = get_post( $data['id'] );
+		$this->check_post_data( $post, $data, $context, $response->get_links() );
+
+	}
+
+	protected function check_create_post_response( $response ) {
+		$this->assertNotWPError( $response );
+		$response = rest_ensure_response( $response );
+
+		$this->assertSame( 201, $response->get_status() );
+		$headers = $response->get_headers();
+		$this->assertArrayHasKey( 'Location', $headers );
+
+		$data = $response->get_data();
+		$post = get_post( $data['id'] );
+		$this->check_post_data( $post, $data, 'edit', $response->get_links() );
+	}
+
+	protected function check_update_post_response( $response ) {
+		$this->assertNotWPError( $response );
+		$response = rest_ensure_response( $response );
+
+		$this->assertSame( 200, $response->get_status() );
+		$headers = $response->get_headers();
+		$this->assertArrayNotHasKey( 'Location', $headers );
+
+		$data = $response->get_data();
+		$post = get_post( $data['id'] );
+		$this->check_post_data( $post, $data, 'edit', $response->get_links() );
+	}
+
+	protected function set_post_data( $args = array() ) {
+		$defaults = array(
+			'title'   => 'Post Title',
+			'content' => 'Post content',
+			'excerpt' => 'Post excerpt',
+			'name'    => 'test',
+			'status'  => 'publish',
+			'author'  => get_current_user_id(),
+			'type'    => 'post',
+		);
+
+		return wp_parse_args( $args, $defaults );
+	}
+
+	protected function set_raw_post_data( $args = array() ) {
+		return wp_parse_args(
+			$args,
+			$this->set_post_data(
+				array(
+					'title'   => array(
+						'raw' => 'Post Title',
+					),
+					'content' => array(
+						'raw' => 'Post content',
+					),
+					'excerpt' => array(
+						'raw' => 'Post excerpt',
+					),
+				)
+			)
+		);
+	}
+
+	/**
+	 * Overwrite the default protected title format.
+	 *
+	 * By default WordPress will show password protected posts with a title of
+	 * "Protected: %s", as the REST API communicates the protected status of a post
+	 * in a machine readable format, we remove the "Protected: " prefix.
+	 *
+	 * @return string
+	 */
+	public function protected_title_format() {
+		return '%s';
+	}
+}

+ 92 - 0
tests/phpunit/includes/testcase-xml.php

@@ -0,0 +1,92 @@
+<?php
+
+abstract class WP_Test_XML_TestCase extends WP_UnitTestCase {
+	/**
+	 * Load XML from a string.
+	 *
+	 * @param string $xml
+	 * @param int    $options Bitwise OR of the {@link https://www.php.net/manual/en/libxml.constants.php libxml option constants}.
+	 *                        Default is 0.
+	 * @return DOMDocument The DOMDocument object loaded from the XML.
+	 */
+	public function loadXML( $xml, $options = 0 ) {
+		// Suppress PHP warnings generated by DOMDocument::loadXML(), which would cause
+		// PHPUnit to incorrectly report an error instead of a just a failure.
+		$internal = libxml_use_internal_errors( true );
+		libxml_clear_errors();
+
+		$xml_dom = new DOMDocument();
+		$xml_dom->loadXML( $xml, $options );
+		$libxml_last_error = libxml_get_last_error();
+
+		$this->assertFalse(
+			isset( $libxml_last_error->message ),
+			isset( $libxml_last_error->message ) ? sprintf( 'Non-well-formed XML: %s.', $libxml_last_error->message ) : ''
+		);
+
+		// Restore default error handler.
+		libxml_use_internal_errors( $internal );
+		libxml_clear_errors();
+
+		return $xml_dom;
+	}
+
+	/**
+	 * Normalize an XML document to make comparing two documents easier.
+	 *
+	 * @param string $xml
+	 * @param int    $options Bitwise OR of the {@link https://www.php.net/manual/en/libxml.constants.php libxml option constants}.
+	 *                        Default is 0.
+	 * @return string The normalized form of `$xml`.
+	 */
+	public function normalizeXML( $xml, $options = 0 ) {
+		if ( ! class_exists( 'XSLTProcessor' ) ) {
+			$this->markTestSkipped( 'This test requires the XSL extension.' );
+		}
+
+		static $xslt_proc;
+
+		if ( ! $xslt_proc ) {
+			$xslt_proc = new XSLTProcessor();
+			$xslt_proc->importStyleSheet( simplexml_load_file( __DIR__ . '/normalize-xml.xsl' ) );
+		}
+
+		return $xslt_proc->transformToXML( $this->loadXML( $xml, $options ) );
+	}
+
+	/**
+	 * Reports an error identified by `$message` if the namespace normalized form of the XML document in `$actualXml`
+	 * is equal to the namespace normalized form of the XML document in `$expectedXml`.
+	 *
+	 * This is similar to {@link https://phpunit.de/manual/6.5/en/appendixes.assertions.html#appendixes.assertions.assertXmlStringEqualsXmlString assertXmlStringEqualsXmlString()}
+	 * except that differences in namespace prefixes are normalized away, such that given
+	 * `$actualXml = "<root xmlns='urn:wordpress.org'><child/></root>";` and
+	 * `$expectedXml = "<ns0:root xmlns:ns0='urn:wordpress.org'><ns0:child></ns0:root>";`
+	 * then `$this->assertXMLEquals( $expectedXml, $actualXml )` will succeed.
+	 *
+	 * @param string $expectedXml
+	 * @param string $actualXml
+	 * @param string $message   Optional. Message to display when the assertion fails.
+	 */
+	public function assertXMLEquals( $expectedXml, $actualXml, $message = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
+		$this->assertSame( $this->normalizeXML( $expectedXml ), $this->normalizeXML( $actualXml ), $message ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
+	}
+
+	/**
+	 * Reports an error identified by `$message` if the namespace normalized form of the XML document in `$actualXml`
+	 * is not equal to the namespace normalized form of the XML document in `$expectedXml`.
+	 *
+	 * This is similar to {@link https://phpunit.de/manual/6.5/en/appendixes.assertions.html#appendixes.assertions.assertXmlStringEqualsXmlString assertXmlStringNotEqualsXmlString()}
+	 * except that differences in namespace prefixes are normalized away, such that given
+	 * `$actualXml = "<root xmlns='urn:wordpress.org'><child></root>";` and
+	 * `$expectedXml = "<ns0:root xmlns:ns0='urn:wordpress.org'><ns0:child/></ns0:root>";`
+	 * then `$this->assertXMLNotEquals( $expectedXml, $actualXml )` will fail.
+	 *
+	 * @param string $expectedXml
+	 * @param string $actualXml
+	 * @param string $message   Optional. Message to display when the assertion fails.
+	 */
+	public function assertXMLNotEquals( $expectedXml, $actualXml, $message = '' ) { //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
+		$this->assertNotEquals( $this->normalizeXML( $expectedXml ), $this->normalizeXML( $actualXml ), $message ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
+	}
+}

+ 83 - 0
tests/phpunit/tests/admin/includesComment.php

@@ -0,0 +1,83 @@
+<?php
+
+/**
+ * @group admin
+ * @group comment
+ */
+class Tests_Admin_IncludesComment extends WP_UnitTestCase {
+	/**
+	 * Post ID to add comments to.
+	 *
+	 * @var int
+	 */
+	public static $post_id;
+
+	/**
+	 * Comment IDs.
+	 *
+	 * @var array
+	 */
+	public static $comment_ids = array();
+
+	/**
+	 * Create the post and comments for the tests.
+	 *
+	 * @param WP_UnitTest_Factory $factory
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$post_id = $factory->post->create();
+
+		self::$comment_ids[] = $factory->comment->create(
+			array(
+				'comment_author'   => 1,
+				'comment_date'     => '2014-05-06 12:00:00',
+				'comment_date_gmt' => '2014-05-06 07:00:00',
+				'comment_post_ID'  => self::$post_id,
+			)
+		);
+
+		self::$comment_ids[] = $factory->comment->create(
+			array(
+				'comment_author'  => 2,
+				'comment_date'    => '2004-01-02 12:00:00',
+				'comment_post_ID' => self::$post_id,
+			)
+		);
+	}
+
+	/**
+	 * Verify that both the comment date and author must match for a comment to exist.
+	 */
+	public function test_must_match_date_and_author() {
+		$this->assertNull( comment_exists( 1, '2004-01-02 12:00:00' ) );
+		$this->assertEquals( self::$post_id, comment_exists( 1, '2014-05-06 12:00:00' ) );
+	}
+
+	/**
+	 * @ticket 33871
+	 */
+	public function test_default_value_of_timezone_should_be_blog() {
+		$this->assertEquals( self::$post_id, comment_exists( 1, '2014-05-06 12:00:00' ) );
+	}
+
+	/**
+	 * @ticket 33871
+	 */
+	public function test_should_respect_timezone_blog() {
+		$this->assertEquals( self::$post_id, comment_exists( 1, '2014-05-06 12:00:00', 'blog' ) );
+	}
+
+	/**
+	 * @ticket 33871
+	 */
+	public function test_should_respect_timezone_gmt() {
+		$this->assertEquals( self::$post_id, comment_exists( 1, '2014-05-06 07:00:00', 'gmt' ) );
+	}
+
+	/**
+	 * @ticket 33871
+	 */
+	public function test_invalid_timezone_should_fall_back_on_blog() {
+		$this->assertEquals( self::$post_id, comment_exists( 1, '2014-05-06 12:00:00', 'not_a_valid_value' ) );
+	}
+}

+ 580 - 0
tests/phpunit/tests/admin/includesCommunityEvents.php

@@ -0,0 +1,580 @@
+<?php
+/**
+ * Unit tests for methods in WP_Community_Events.
+ *
+ * @package WordPress
+ * @subpackage UnitTests
+ * @since 4.8.0
+ */
+
+/**
+ * Class Test_WP_Community_Events.
+ *
+ * @group admin
+ * @group community-events
+ *
+ * @since 4.8.0
+ */
+class Test_WP_Community_Events extends WP_UnitTestCase {
+	/**
+	 * An instance of the class to test.
+	 *
+	 * @access private
+	 * @since 4.8.0
+	 *
+	 * @var WP_Community_Events
+	 */
+	private $instance;
+
+	/**
+	 * Performs setup tasks for every test.
+	 *
+	 * @since 4.8.0
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php';
+
+		$this->instance = new WP_Community_Events( 1, $this->get_user_location() );
+	}
+
+	/**
+	 * Simulates a stored user location.
+	 *
+	 * @access private
+	 * @since 4.8.0
+	 *
+	 * @return array The mock location.
+	 */
+	private function get_user_location() {
+		return array(
+			'description' => 'San Francisco',
+			'latitude'    => '37.7749300',
+			'longitude'   => '-122.4194200',
+			'country'     => 'US',
+		);
+	}
+
+	/**
+	 * Test: get_events() should return an instance of WP_Error if the response code is not 200.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_events_bad_response_code() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_bad_response_code' ) );
+
+		$this->assertWPError( $this->instance->get_events() );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_bad_response_code' ) );
+	}
+
+	/**
+	 * Test: The response body should not be cached if the response code is not 200.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_cached_events_bad_response_code() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_bad_response_code' ) );
+
+		$this->instance->get_events();
+
+		$this->assertFalse( $this->instance->get_cached_events() );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_bad_response_code' ) );
+	}
+
+	/**
+	 * Simulates an HTTP response with a non-200 response code.
+	 *
+	 * @since 4.8.0
+	 *
+	 * @return array A mock response with a 404 HTTP status code
+	 */
+	public function _http_request_bad_response_code() {
+		return array(
+			'headers'  => '',
+			'body'     => '',
+			'response' => array(
+				'code' => 404,
+			),
+			'cookies'  => '',
+			'filename' => '',
+		);
+	}
+
+	/**
+	 * Test: get_events() should return an instance of WP_Error if the response body does not have
+	 * the required properties.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_events_invalid_response() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_invalid_response' ) );
+
+		$this->assertWPError( $this->instance->get_events() );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_invalid_response' ) );
+	}
+
+	/**
+	 * Test: The response body should not be cached if it does not have the required properties.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_cached_events_invalid_response() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_invalid_response' ) );
+
+		$this->instance->get_events();
+
+		$this->assertFalse( $this->instance->get_cached_events() );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_invalid_response' ) );
+	}
+
+	/**
+	 * Simulates an HTTP response with a body that does not have the required properties.
+	 *
+	 * @since 4.8.0
+	 *
+	 * @return array A mock response that's missing required properties.
+	 */
+	public function _http_request_invalid_response() {
+		return array(
+			'headers'  => '',
+			'body'     => wp_json_encode( array() ),
+			'response' => array(
+				'code' => 200,
+			),
+			'cookies'  => '',
+			'filename' => '',
+		);
+	}
+
+	/**
+	 * Test: With a valid response, get_events() should return an associative array containing a location array and
+	 * an events array with individual events that have Unix start/end timestamps.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_events_valid_response() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_valid_response' ) );
+
+		$response = $this->instance->get_events();
+
+		$this->assertNotWPError( $response );
+		$this->assertSameSetsWithIndex( $this->get_user_location(), $response['location'] );
+		$this->assertSame( strtotime( 'next Sunday 1pm' ), $response['events'][0]['start_unix_timestamp'] );
+		$this->assertSame( strtotime( 'next Sunday 2pm' ), $response['events'][0]['end_unix_timestamp'] );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_valid_response' ) );
+	}
+
+	/**
+	 * Test: `get_cached_events()` should return the same data as get_events(), including Unix start/end
+	 * timestamps for each event.
+	 *
+	 * @since 4.8.0
+	 */
+	public function test_get_cached_events_valid_response() {
+		add_filter( 'pre_http_request', array( $this, '_http_request_valid_response' ) );
+
+		$this->instance->get_events();
+
+		$cached_events = $this->instance->get_cached_events();
+
+		$this->assertNotWPError( $cached_events );
+		$this->assertSameSetsWithIndex( $this->get_user_location(), $cached_events['location'] );
+		$this->assertSame( strtotime( 'next Sunday 1pm' ), $cached_events['events'][0]['start_unix_timestamp'] );
+		$this->assertSame( strtotime( 'next Sunday 2pm' ), $cached_events['events'][0]['end_unix_timestamp'] );
+
+		remove_filter( 'pre_http_request', array( $this, '_http_request_valid_response' ) );
+	}
+
+	/**
+	 * Simulates an HTTP response with valid location and event data.
+	 *
+	 * @since 4.8.0
+	 *
+	 * @return array A mock HTTP response with valid data.
+	 */
+	public function _http_request_valid_response() {
+		return array(
+			'headers'  => '',
+			'body'     => wp_json_encode(
+				array(
+					'location' => $this->get_user_location(),
+					'events'   => $this->get_valid_events(),
+				)
+			),
+			'response' => array(
+				'code' => 200,
+			),
+			'cookies'  => '',
+			'filename' => '',
+		);
+	}
+
+	/**
+	 * Get a sample of valid events.
+	 *
+	 * @return array[]
+	 */
+	protected function get_valid_events() {
+		return array(
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Flexbox + CSS Grid: Magic for Responsive Layouts',
+				'url'                  => 'https://www.meetup.com/Eastbay-WordPress-Meetup/events/236031233/',
+				'meetup'               => 'The East Bay WordPress Meetup Group',
+				'meetup_url'           => 'https://www.meetup.com/Eastbay-WordPress-Meetup/',
+				'start_unix_timestamp' => strtotime( 'next Sunday 1pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Sunday 2pm' ),
+
+				'location'             => array(
+					'location'  => 'Oakland, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.808453,
+					'longitude' => -122.26593,
+				),
+			),
+
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Part 3- Site Maintenance - Tools to Make It Easy',
+				'url'                  => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/events/237706839/',
+				'meetup'               => 'WordPress Bay Area Foothills Group',
+				'meetup_url'           => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/',
+				'start_unix_timestamp' => strtotime( 'next Wednesday 1:30pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Wednesday 2:30pm' ),
+
+				'location'             => array(
+					'location'  => 'Milpitas, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.432813,
+					'longitude' => -121.907095,
+				),
+			),
+
+			array(
+				'type'                 => 'wordcamp',
+				'title'                => 'WordCamp San Francisco',
+				'url'                  => 'https://sf.wordcamp.org/2020/',
+				'meetup'               => null,
+				'meetup_url'           => null,
+				'start_unix_timestamp' => strtotime( 'next Saturday' ),
+				'end_unix_timestamp'   => strtotime( 'next Saturday 8pm' ),
+
+				'location'             => array(
+					'location'  => 'San Francisco, CA',
+					'country'   => 'US',
+					'latitude'  => 37.432813,
+					'longitude' => -121.907095,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Test: `trim_events()` should immediately remove expired events.
+	 *
+	 * @covers WP_Community_Events::trim_events
+	 *
+	 * @since 5.5.2
+	 */
+	public function test_trim_expired_events() {
+		$trim_events = new ReflectionMethod( $this->instance, 'trim_events' );
+		$trim_events->setAccessible( true );
+
+		$events = $this->get_valid_events();
+
+		// This should be removed because it's already ended.
+		$events[0]['start_unix_timestamp'] = strtotime( '1 hour ago' );
+		$events[0]['end_unix_timestamp']   = strtotime( '2 seconds ago' );
+
+		// This should remain because it hasn't ended yet.
+		$events[1]['start_unix_timestamp'] = strtotime( '2 seconds ago' );
+		$events[1]['end_unix_timestamp']   = strtotime( '+1 hour' );
+
+		$actual = $trim_events->invoke( $this->instance, $events );
+
+		$this->assertCount( 2, $actual );
+		$this->assertSame( $actual[0]['title'], 'Part 3- Site Maintenance - Tools to Make It Easy' );
+		$this->assertSame( $actual[1]['title'], 'WordCamp San Francisco' );
+	}
+
+	/**
+	 * Test: get_events() should return the events with the WordCamp pinned in the prepared list.
+	 *
+	 * @covers WP_Community_Events::trim_events
+	 *
+	 * @since 4.9.7
+	 * @since 5.5.2 Tests `trim_events()` directly instead of indirectly via `get_events()`.
+	 */
+	public function test_trim_events_pin_wordcamp() {
+		$trim_events = new ReflectionMethod( $this->instance, 'trim_events' );
+		$trim_events->setAccessible( true );
+
+		$actual = $trim_events->invoke( $this->instance, $this->_events_with_unpinned_wordcamp() );
+
+		/*
+		 * San Diego was at index 3 in the mock API response, but pinning puts it at index 2,
+		 * so that it remains in the list. The other events should remain unchanged.
+		 */
+		$this->assertCount( 3, $actual );
+		$this->assertSame( $actual[0]['title'], 'Flexbox + CSS Grid: Magic for Responsive Layouts' );
+		$this->assertSame( $actual[1]['title'], 'Part 3- Site Maintenance - Tools to Make It Easy' );
+		$this->assertSame( $actual[2]['title'], 'WordCamp San Diego' );
+	}
+
+	/**
+	 * Simulates a scenario where a WordCamp needs to be pinned higher than it's default position.
+	 *
+	 * @since 4.9.7
+	 * @since 5.5.2 Accepts and returns only the events, rather than an entire HTTP response.
+	 *
+	 * @return array A list of mock events.
+	 */
+	public function _events_with_unpinned_wordcamp() {
+		return array(
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Flexbox + CSS Grid: Magic for Responsive Layouts',
+				'url'                  => 'https://www.meetup.com/Eastbay-WordPress-Meetup/events/236031233/',
+				'meetup'               => 'The East Bay WordPress Meetup Group',
+				'meetup_url'           => 'https://www.meetup.com/Eastbay-WordPress-Meetup/',
+				'start_unix_timestamp' => strtotime( 'next Monday 1pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Monday 2pm' ),
+
+				'location'             => array(
+					'location'  => 'Oakland, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.808453,
+					'longitude' => -122.26593,
+				),
+			),
+
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Part 3- Site Maintenance - Tools to Make It Easy',
+				'url'                  => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/events/237706839/',
+				'meetup'               => 'WordPress Bay Area Foothills Group',
+				'meetup_url'           => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/',
+				'start_unix_timestamp' => strtotime( 'next Tuesday 1:30pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Tuesday 2:30pm' ),
+
+				'location'             => array(
+					'location'  => 'Milpitas, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.432813,
+					'longitude' => -121.907095,
+				),
+			),
+
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'WordPress Q&A',
+				'url'                  => 'https://www.meetup.com/sanjosewp/events/245419844/',
+				'meetup'               => 'The San Jose WordPress Meetup',
+				'meetup_url'           => 'https://www.meetup.com/sanjosewp/',
+				'start_unix_timestamp' => strtotime( 'next Wednesday 5:30pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Wednesday 6:30pm' ),
+
+				'location'             => array(
+					'location'  => 'Milpitas, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.244194,
+					'longitude' => -121.889313,
+				),
+			),
+
+			array(
+				'type'                 => 'wordcamp',
+				'title'                => 'WordCamp San Diego',
+				'url'                  => 'https://2018.sandiego.wordcamp.org',
+				'meetup'               => null,
+				'meetup_url'           => null,
+				'start_unix_timestamp' => strtotime( 'next Thursday 9am' ),
+				'end_unix_timestamp'   => strtotime( 'next Thursday 10am' ),
+
+				'location'             => array(
+					'location'  => 'San Diego, CA',
+					'country'   => 'US',
+					'latitude'  => 32.7220419,
+					'longitude' => -117.1534513,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Test: get_events() shouldn't stick an extra WordCamp when there's already one that naturally
+	 * falls into the list.
+	 *
+	 * @covers WP_Community_Events::trim_events
+	 *
+	 * @since 4.9.7
+	 * @since 5.5.2 Tests `trim_events()` directly instead of indirectly via `get_events()`.
+	 */
+	public function test_trim_events_dont_pin_multiple_wordcamps() {
+		$trim_events = new ReflectionMethod( $this->instance, 'trim_events' );
+		$trim_events->setAccessible( true );
+
+		$actual = $trim_events->invoke( $this->instance, $this->_events_with_multiple_wordcamps() );
+
+		/*
+		 * The first meetup should be removed because it's expired, while the next 3 events are selected.
+		 * WordCamp LA should not be stuck to the list, because San Diego already appears naturally.
+		 */
+		$this->assertCount( 3, $actual );
+		$this->assertSame( $actual[0]['title'], 'WordCamp San Diego' );
+		$this->assertSame( $actual[1]['title'], 'Part 3- Site Maintenance - Tools to Make It Easy' );
+		$this->assertSame( $actual[2]['title'], 'WordPress Q&A' );
+	}
+
+	/**
+	 * Simulates a valid HTTP response where a WordCamp needs to be pinned higher than it's default position.
+	 * no need to pin extra camp b/c one already exists in response
+	 *
+	 * @since 4.9.7
+	 * @since 5.5.2 Tests `trim_events()` directly instead of indirectly via `get_events()`.
+	 *
+	 * @return array A mock HTTP response.
+	 */
+	public function _events_with_multiple_wordcamps() {
+		return array(
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Flexbox + CSS Grid: Magic for Responsive Layouts',
+				'url'                  => 'https://www.meetup.com/Eastbay-WordPress-Meetup/events/236031233/',
+				'meetup'               => 'The East Bay WordPress Meetup Group',
+				'meetup_url'           => 'https://www.meetup.com/Eastbay-WordPress-Meetup/',
+				'start_unix_timestamp' => strtotime( '2 days ago' ) - HOUR_IN_SECONDS,
+				'end_unix_timestamp'   => strtotime( '2 days ago' ),
+
+				'location'             => array(
+					'location'  => 'Oakland, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.808453,
+					'longitude' => -122.26593,
+				),
+			),
+
+			array(
+				'type'                 => 'wordcamp',
+				'title'                => 'WordCamp San Diego',
+				'url'                  => 'https://2018.sandiego.wordcamp.org',
+				'meetup'               => null,
+				'meetup_url'           => null,
+				'start_unix_timestamp' => strtotime( 'next Tuesday 9am' ),
+				'end_unix_timestamp'   => strtotime( 'next Tuesday 10am' ),
+
+				'location'             => array(
+					'location'  => 'San Diego, CA',
+					'country'   => 'US',
+					'latitude'  => 32.7220419,
+					'longitude' => -117.1534513,
+				),
+			),
+
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'Part 3- Site Maintenance - Tools to Make It Easy',
+				'url'                  => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/events/237706839/',
+				'meetup'               => 'WordPress Bay Area Foothills Group',
+				'meetup_url'           => 'https://www.meetup.com/Wordpress-Bay-Area-CA-Foothills/',
+				'start_unix_timestamp' => strtotime( 'next Wednesday 1:30pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Wednesday 2:30pm' ),
+
+				'location'             => array(
+					'location'  => 'Milpitas, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.432813,
+					'longitude' => -121.907095,
+				),
+			),
+
+			array(
+				'type'                 => 'meetup',
+				'title'                => 'WordPress Q&A',
+				'url'                  => 'https://www.meetup.com/sanjosewp/events/245419844/',
+				'meetup'               => 'The San Jose WordPress Meetup',
+				'meetup_url'           => 'https://www.meetup.com/sanjosewp/',
+				'start_unix_timestamp' => strtotime( 'next Thursday 5:30pm' ),
+				'end_unix_timestamp'   => strtotime( 'next Thursday 6:30pm' ),
+
+				'location'             => array(
+					'location'  => 'Milpitas, CA, USA',
+					'country'   => 'us',
+					'latitude'  => 37.244194,
+					'longitude' => -121.889313,
+				),
+			),
+
+			array(
+				'type'                 => 'wordcamp',
+				'title'                => 'WordCamp Los Angeles',
+				'url'                  => 'https://2018.la.wordcamp.org',
+				'meetup'               => null,
+				'meetup_url'           => null,
+				'start_unix_timestamp' => strtotime( 'next Friday 9am' ),
+				'end_unix_timestamp'   => strtotime( 'next Friday 10am' ),
+
+				'location'             => array(
+					'location'  => 'Los Angeles, CA',
+					'country'   => 'US',
+					'latitude'  => 34.050888,
+					'longitude' => -118.285426,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Test that get_unsafe_client_ip() properly anonymizes all possible address formats
+	 *
+	 * @dataProvider data_get_unsafe_client_ip
+	 *
+	 * @ticket 41083
+	 */
+	public function test_get_unsafe_client_ip( $raw_ip, $expected_result ) {
+		$_SERVER['REMOTE_ADDR']    = 'this should not be used';
+		$_SERVER['HTTP_CLIENT_IP'] = $raw_ip;
+		$actual_result             = WP_Community_Events::get_unsafe_client_ip();
+
+		$this->assertSame( $expected_result, $actual_result );
+	}
+
+	/**
+	 * Provide test cases for `test_get_unsafe_client_ip()`.
+	 *
+	 * @return array
+	 */
+	public function data_get_unsafe_client_ip() {
+		return array(
+			// Handle '::' returned from `wp_privacy_anonymize_ip()`.
+			array(
+				'or=\"[1000:0000:0000:0000:0000:0000:0000:0001',
+				false,
+			),
+
+			// Handle '0.0.0.0' returned from `wp_privacy_anonymize_ip()`.
+			array(
+				'unknown',
+				false,
+			),
+
+			// Valid IPv4.
+			array(
+				'198.143.164.252',
+				'198.143.164.0',
+			),
+
+			// Valid IPv6.
+			array(
+				'2a03:2880:2110:df07:face:b00c::1',
+				'2a03:2880:2110:df07::',
+			),
+		);
+	}
+}

+ 462 - 0
tests/phpunit/tests/admin/includesListTable.php

@@ -0,0 +1,462 @@
+<?php
+
+/**
+ * @group admin
+ */
+class Tests_Admin_includesListTable extends WP_UnitTestCase {
+	protected static $top           = array();
+	protected static $children      = array();
+	protected static $grandchildren = array();
+	protected static $post_ids      = array();
+
+	/**
+	 * @var WP_Posts_List_Table
+	 */
+	protected $table;
+
+	function setUp() {
+		parent::setUp();
+		$this->table = _get_list_table( 'WP_Posts_List_Table', array( 'screen' => 'edit-page' ) );
+	}
+
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		// Note that our top/children/grandchildren arrays are 1-indexed.
+
+		// Create top-level pages.
+		$num_posts = 5;
+		foreach ( range( 1, $num_posts ) as $i ) {
+			$p = $factory->post->create_and_get(
+				array(
+					'post_type'  => 'page',
+					'post_title' => sprintf( 'Top Level Page %d', $i ),
+				)
+			);
+
+			self::$top[ $i ]  = $p;
+			self::$post_ids[] = $p->ID;
+		}
+
+		// Create child pages.
+		$num_children = 3;
+		foreach ( self::$top as $top => $top_page ) {
+			foreach ( range( 1, $num_children ) as $i ) {
+				$p = $factory->post->create_and_get(
+					array(
+						'post_type'   => 'page',
+						'post_parent' => $top_page->ID,
+						'post_title'  => sprintf( 'Child %d', $i ),
+					)
+				);
+
+				self::$children[ $top ][ $i ] = $p;
+				self::$post_ids[]             = $p->ID;
+			}
+		}
+
+		// Create grand-child pages for the third and fourth top-level pages.
+		$num_grandchildren = 3;
+		foreach ( range( 3, 4 ) as $top ) {
+			foreach ( self::$children[ $top ] as $child => $child_page ) {
+				foreach ( range( 1, $num_grandchildren ) as $i ) {
+					$p = $factory->post->create_and_get(
+						array(
+							'post_type'   => 'page',
+							'post_parent' => $child_page->ID,
+							'post_title'  => sprintf( 'Grandchild %d', $i ),
+						)
+					);
+
+					self::$grandchildren[ $top ][ $child ][ $i ] = $p;
+					self::$post_ids[]                            = $p->ID;
+				}
+			}
+		}
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_list_hierarchical_pages_first_page() {
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 1,
+				'posts_per_page' => 2,
+			),
+			array(
+				self::$top[1]->ID,
+				self::$children[1][1]->ID,
+			)
+		);
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_list_hierarchical_pages_second_page() {
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 2,
+				'posts_per_page' => 2,
+			),
+			array(
+				self::$top[1]->ID,
+				self::$children[1][2]->ID,
+				self::$children[1][3]->ID,
+			)
+		);
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_search_hierarchical_pages_first_page() {
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 1,
+				'posts_per_page' => 2,
+				's'              => 'Child',
+			),
+			array(
+				self::$children[1][1]->ID,
+				self::$children[1][2]->ID,
+			)
+		);
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_search_hierarchical_pages_second_page() {
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 2,
+				'posts_per_page' => 2,
+				's'              => 'Top',
+			),
+			array(
+				self::$top[3]->ID,
+				self::$top[4]->ID,
+			)
+		);
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_grandchildren_hierarchical_pages_first_page() {
+		// Page 6 is the first page with grandchildren.
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 6,
+				'posts_per_page' => 2,
+			),
+			array(
+				self::$top[3]->ID,
+				self::$children[3][1]->ID,
+				self::$grandchildren[3][1][1]->ID,
+				self::$grandchildren[3][1][2]->ID,
+			)
+		);
+	}
+
+	/**
+	 * @ticket 15459
+	 */
+	function test_grandchildren_hierarchical_pages_second_page() {
+		// Page 7 is the second page with grandchildren.
+		$this->_test_list_hierarchical_page(
+			array(
+				'paged'          => 7,
+				'posts_per_page' => 2,
+			),
+			array(
+				self::$top[3]->ID,
+				self::$children[3][1]->ID,
+				self::$grandchildren[3][1][3]->ID,
+				self::$children[3][2]->ID,
+			)
+		);
+	}
+
+	/**
+	 * Helper function to test the output of a page which uses `WP_Posts_List_Table`.
+	 *
+	 * @param array $args         Query args for the list of pages.
+	 * @param array $expected_ids Expected IDs of pages returned.
+	 */
+	protected function _test_list_hierarchical_page( array $args, array $expected_ids ) {
+		$matches = array();
+
+		$_REQUEST['paged']   = $args['paged'];
+		$GLOBALS['per_page'] = $args['posts_per_page'];
+
+		$args = array_merge(
+			array(
+				'post_type' => 'page',
+			),
+			$args
+		);
+
+		// Mimic the behaviour of `wp_edit_posts_query()`:
+		if ( ! isset( $args['orderby'] ) ) {
+			$args['orderby']                = 'menu_order title';
+			$args['order']                  = 'asc';
+			$args['posts_per_page']         = -1;
+			$args['posts_per_archive_page'] = -1;
+		}
+
+		$pages = new WP_Query( $args );
+
+		ob_start();
+		$this->table->set_hierarchical_display( true );
+		$this->table->display_rows( $pages->posts );
+		$output = ob_get_clean();
+
+		// Clean up.
+		unset( $_REQUEST['paged'] );
+		unset( $GLOBALS['per_page'] );
+
+		preg_match_all( '|<tr[^>]*>|', $output, $matches );
+
+		$this->assertCount( count( $expected_ids ), array_keys( $matches[0] ) );
+
+		foreach ( $expected_ids as $id ) {
+			$this->assertContains( sprintf( 'id="post-%d"', $id ), $output );
+		}
+	}
+
+	/**
+	 * @ticket 37407
+	 */
+	function test_filter_button_should_not_be_shown_if_there_are_no_posts() {
+		// Set post type to a non-existent one.
+		$this->table->screen->post_type = 'foo';
+
+		ob_start();
+		$this->table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="post-query-submit"', $output );
+	}
+
+	/**
+	 * @ticket 37407
+	 */
+	function test_months_dropdown_should_not_be_shown_if_there_are_no_posts() {
+		// Set post type to a non-existent one.
+		$this->table->screen->post_type = 'foo';
+
+		ob_start();
+		$this->table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="filter-by-date"', $output );
+	}
+
+	/**
+	 * @ticket 37407
+	 */
+	function test_category_dropdown_should_not_be_shown_if_there_are_no_posts() {
+		// Set post type to a non-existent one.
+		$this->table->screen->post_type = 'foo';
+
+		ob_start();
+		$this->table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="cat"', $output );
+	}
+
+	/**
+	 * @ticket 38341
+	 */
+	public function test_empty_trash_button_should_not_be_shown_if_there_are_no_posts() {
+		// Set post type to a non-existent one.
+		$this->table->screen->post_type = 'foo';
+
+		ob_start();
+		$this->table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="delete_all"', $output );
+	}
+
+	/**
+	 * @ticket 40188
+	 */
+	public function test_filter_button_should_not_be_shown_if_there_are_no_comments() {
+		$table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
+
+		ob_start();
+		$table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="post-query-submit"', $output );
+	}
+
+	/**
+	 * @ticket 40188
+	 */
+	public function test_filter_button_should_be_shown_if_there_are_comments() {
+		$post_id    = self::factory()->post->create();
+		$comment_id = self::factory()->comment->create(
+			array(
+				'comment_post_ID'  => $post_id,
+				'comment_approved' => '1',
+			)
+		);
+
+		$table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
+		$table->prepare_items();
+
+		ob_start();
+		$table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertContains( 'id="post-query-submit"', $output );
+	}
+
+	/**
+	 * @ticket 40188
+	 */
+	public function test_filter_comment_type_dropdown_should_be_shown_if_there_are_comments() {
+		$post_id    = self::factory()->post->create();
+		$comment_id = self::factory()->comment->create(
+			array(
+				'comment_post_ID'  => $post_id,
+				'comment_approved' => '1',
+			)
+		);
+
+		$table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
+		$table->prepare_items();
+
+		ob_start();
+		$table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertContains( 'id="filter-by-comment-type"', $output );
+		$this->assertContains( "<option value='comment'>", $output );
+	}
+
+	/**
+	 * @ticket 38341
+	 */
+	public function test_empty_trash_button_should_not_be_shown_if_there_are_no_comments() {
+		$table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
+
+		ob_start();
+		$table->extra_tablenav( 'top' );
+		$output = ob_get_clean();
+
+		$this->assertNotContains( 'id="delete_all"', $output );
+	}
+
+	/**
+	 * @ticket 19278
+	 */
+	public function test_bulk_action_menu_supports_options_and_optgroups() {
+		$table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) );
+
+		add_filter(
+			'bulk_actions-edit-comments',
+			function() {
+				return array(
+					'delete'       => 'Delete',
+					'Change State' => array(
+						'feature' => 'Featured',
+						'sale'    => 'On Sale',
+					),
+				);
+			}
+		);
+
+		ob_start();
+		$table->bulk_actions();
+		$output = ob_get_clean();
+
+		$expected = <<<'OPTIONS'
+<option value="delete">Delete</option>
+	<optgroup label="Change State">
+		<option value="feature">Featured</option>
+		<option value="sale">On Sale</option>
+	</optgroup>
+OPTIONS;
+		$expected = str_replace( "\r\n", "\n", $expected );
+
+		$this->assertContains( $expected, $output );
+	}
+
+	/**
+	 * @ticket 45089
+	 */
+	public function test_sortable_columns() {
+		require_once ABSPATH . 'wp-admin/includes/class-wp-comments-list-table.php';
+
+		$override_sortable_columns = array(
+			'author'   => array( 'comment_author', true ),
+			'response' => 'comment_post_ID',
+			'date'     => array( 'comment_date', 'dEsC' ), // The ordering support should be case-insensitive.
+		);
+
+		// Stub the get_sortable_columns() method.
+		$object = $this->getMockBuilder( 'WP_Comments_List_Table' )
+			->setConstructorArgs( array( array( 'screen' => 'edit-comments' ) ) )
+			->setMethods( array( 'get_sortable_columns' ) )
+			->getMock();
+
+		// Change the null return value of the stubbed get_sortable_columns() method.
+		$object->method( 'get_sortable_columns' )
+			->willReturn( $override_sortable_columns );
+
+		$output = get_echo( array( $object, 'print_column_headers' ) );
+
+		$this->assertContains( '?orderby=comment_author&#038;order=desc', $output, 'Mismatch of the default link ordering for comment author column. Should be desc.' );
+		$this->assertContains( 'column-author sortable asc', $output, 'Mismatch of CSS classes for the comment author column.' );
+
+		$this->assertContains( '?orderby=comment_post_ID&#038;order=asc', $output, 'Mismatch of the default link ordering for comment response column. Should be asc.' );
+		$this->assertContains( 'column-response sortable desc', $output, 'Mismatch of CSS classes for the comment post ID column.' );
+
+		$this->assertContains( '?orderby=comment_date&#038;order=desc', $output, 'Mismatch of the default link ordering for comment date column. Should be asc.' );
+		$this->assertContains( 'column-date sortable asc', $output, 'Mismatch of CSS classes for the comment date column.' );
+	}
+
+	/**
+	 * @ticket 45089
+	 */
+	public function test_sortable_columns_with_current_ordering() {
+		require_once ABSPATH . 'wp-admin/includes/class-wp-comments-list-table.php';
+
+		$override_sortable_columns = array(
+			'author'   => array( 'comment_author', false ),
+			'response' => 'comment_post_ID',
+			'date'     => array( 'comment_date', 'asc' ), // We will override this with current ordering.
+		);
+
+		// Current ordering.
+		$_GET['orderby'] = 'comment_date';
+		$_GET['order']   = 'desc';
+
+		// Stub the get_sortable_columns() method.
+		$object = $this->getMockBuilder( 'WP_Comments_List_Table' )
+			->setConstructorArgs( array( array( 'screen' => 'edit-comments' ) ) )
+			->setMethods( array( 'get_sortable_columns' ) )
+			->getMock();
+
+		// Change the null return value of the stubbed get_sortable_columns() method.
+		$object->method( 'get_sortable_columns' )
+			->willReturn( $override_sortable_columns );
+
+		$output = get_echo( array( $object, 'print_column_headers' ) );
+
+		$this->assertContains( '?orderby=comment_author&#038;order=asc', $output, 'Mismatch of the default link ordering for comment author column. Should be asc.' );
+		$this->assertContains( 'column-author sortable desc', $output, 'Mismatch of CSS classes for the comment author column.' );
+
+		$this->assertContains( '?orderby=comment_post_ID&#038;order=asc', $output, 'Mismatch of the default link ordering for comment response column. Should be asc.' );
+		$this->assertContains( 'column-response sortable desc', $output, 'Mismatch of CSS classes for the comment post ID column.' );
+
+		$this->assertContains( '?orderby=comment_date&#038;order=asc', $output, 'Mismatch of the current link ordering for comment date column. Should be asc.' );
+		$this->assertContains( 'column-date sorted desc', $output, 'Mismatch of CSS classes for the comment date column.' );
+	}
+
+}

+ 293 - 0
tests/phpunit/tests/admin/includesSchema.php

@@ -0,0 +1,293 @@
+<?php
+
+/**
+ * @group admin
+ */
+class Tests_Admin_Includes_Schema extends WP_UnitTestCase {
+
+	private static $options;
+	private static $blogmeta;
+	private static $sitemeta;
+
+	/**
+	 * Make sure the schema code is loaded before the tests are run.
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		global $wpdb;
+
+		self::$options  = 'testprefix_options';
+		self::$blogmeta = 'testprefix_blogmeta';
+		self::$sitemeta = 'testprefix_sitemeta';
+
+		$options  = self::$options;
+		$blogmeta = self::$blogmeta;
+		$sitemeta = self::$sitemeta;
+
+		require_once ABSPATH . 'wp-admin/includes/schema.php';
+
+		$charset_collate  = $wpdb->get_charset_collate();
+		$max_index_length = 191;
+
+		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+		$wpdb->query(
+			"
+			CREATE TABLE {$options} (
+				option_id bigint(20) unsigned NOT NULL auto_increment,
+				option_name varchar(191) NOT NULL default '',
+				option_value longtext NOT NULL,
+				autoload varchar(20) NOT NULL default 'yes',
+				PRIMARY KEY  (option_id),
+				UNIQUE KEY option_name (option_name)
+			) {$charset_collate}
+			"
+		);
+		$wpdb->query(
+			"
+			CREATE TABLE {$blogmeta} (
+				meta_id bigint(20) unsigned NOT NULL auto_increment,
+				blog_id bigint(20) unsigned NOT NULL default '0',
+				meta_key varchar(255) default NULL,
+				meta_value longtext,
+				PRIMARY KEY  (meta_id),
+				KEY meta_key (meta_key({$max_index_length})),
+				KEY blog_id (blog_id)
+			) {$charset_collate}
+			"
+		);
+		$wpdb->query(
+			"
+			CREATE TABLE {$sitemeta} (
+				meta_id bigint(20) unsigned NOT NULL auto_increment,
+				site_id bigint(20) unsigned NOT NULL default '0',
+				meta_key varchar(255) default NULL,
+				meta_value longtext,
+				PRIMARY KEY  (meta_id),
+				KEY meta_key (meta_key({$max_index_length})),
+				KEY site_id (site_id)
+			) {$charset_collate}
+			"
+		);
+		// phpcs:enable
+	}
+
+	/**
+	 * Drop tables that were created before running the tests.
+	 */
+	public static function wpTearDownAfterClass() {
+		global $wpdb;
+
+		$options  = self::$options;
+		$blogmeta = self::$blogmeta;
+		$sitemeta = self::$sitemeta;
+
+		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+		$wpdb->query( "DROP TABLE IF EXISTS {$options}" );
+		$wpdb->query( "DROP TABLE IF EXISTS {$blogmeta}" );
+		$wpdb->query( "DROP TABLE IF EXISTS {$sitemeta}" );
+		// phpcs:enable
+	}
+
+	/**
+	 * @ticket 44893
+	 * @dataProvider data_populate_options
+	 */
+	function test_populate_options( $options, $expected ) {
+		global $wpdb;
+
+		$orig_options  = $wpdb->options;
+		$wpdb->options = self::$options;
+
+		populate_options( $options );
+
+		wp_cache_delete( 'alloptions', 'options' );
+
+		$results = array();
+		foreach ( $expected as $option => $value ) {
+			$results[ $option ] = get_option( $option );
+		}
+
+		$wpdb->query( "TRUNCATE TABLE {$wpdb->options}" );
+
+		$wpdb->options = $orig_options;
+
+		$this->assertSame( $expected, $results );
+	}
+
+	public function data_populate_options() {
+		return array(
+			array(
+				array(),
+				array(
+					// Random options to check.
+					'posts_per_rss'    => '10',
+					'rss_use_excerpt'  => '0',
+					'mailserver_url'   => 'mail.example.com',
+					'mailserver_login' => 'login@example.com',
+					'mailserver_pass'  => 'password',
+				),
+			),
+			array(
+				array(
+					'posts_per_rss'   => '7',
+					'rss_use_excerpt' => '1',
+				),
+				array(
+					// Random options to check.
+					'posts_per_rss'    => '7',
+					'rss_use_excerpt'  => '1',
+					'mailserver_url'   => 'mail.example.com',
+					'mailserver_login' => 'login@example.com',
+					'mailserver_pass'  => 'password',
+				),
+			),
+			array(
+				array(
+					'custom_option' => '1',
+				),
+				array(
+					// Random options to check.
+					'custom_option'    => '1',
+					'posts_per_rss'    => '10',
+					'rss_use_excerpt'  => '0',
+					'mailserver_url'   => 'mail.example.com',
+					'mailserver_login' => 'login@example.com',
+					'mailserver_pass'  => 'password',
+				),
+			),
+			array(
+				array(
+					'use_quicktags' => '1',
+				),
+				array(
+					// This option is disallowed and should never exist.
+					'use_quicktags' => false,
+				),
+			),
+			array(
+				array(
+					'rss_0123456789abcdef0123456789abcdef' => '1',
+					'rss_0123456789abcdef0123456789abcdef_ts' => '1',
+				),
+				array(
+					// These options would be obsolete magpie cache data and should never exist.
+					'rss_0123456789abcdef0123456789abcdef' => false,
+					'rss_0123456789abcdef0123456789abcdef_ts' => false,
+				),
+			),
+		);
+	}
+
+	/**
+	 * @ticket 44896
+	 * @group multisite
+	 * @group ms-required
+	 * @dataProvider data_populate_site_meta
+	 */
+	function test_populate_site_meta( $meta, $expected ) {
+		global $wpdb;
+
+		$orig_blogmeta  = $wpdb->blogmeta;
+		$wpdb->blogmeta = self::$blogmeta;
+
+		populate_site_meta( 42, $meta );
+
+		$results = array();
+		foreach ( $expected as $meta_key => $value ) {
+			$results[ $meta_key ] = get_site_meta( 42, $meta_key, true );
+		}
+
+		$wpdb->query( "TRUNCATE TABLE {$wpdb->blogmeta}" );
+
+		$wpdb->blogmeta = $orig_blogmeta;
+
+		$this->assertSame( $expected, $results );
+	}
+
+	public function data_populate_site_meta() {
+		return array(
+			array(
+				array(),
+				array(
+					'unknown_value' => '',
+				),
+			),
+			array(
+				array(
+					'custom_meta' => '1',
+				),
+				array(
+					'custom_meta' => '1',
+				),
+			),
+		);
+	}
+
+	/**
+	 * @ticket 44895
+	 * @group multisite
+	 * @dataProvider data_populate_network_meta
+	 */
+	function test_populate_network_meta( $meta, $expected ) {
+		global $wpdb;
+
+		$orig_sitemeta  = $wpdb->sitemeta;
+		$wpdb->sitemeta = self::$sitemeta;
+
+		populate_network_meta( 42, $meta );
+
+		$results = array();
+		foreach ( $expected as $meta_key => $value ) {
+			if ( is_multisite() ) {
+				$results[ $meta_key ] = get_network_option( 42, $meta_key );
+			} else {
+				$results[ $meta_key ] = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $meta_key, 42 ) );
+			}
+		}
+
+		$wpdb->query( "TRUNCATE TABLE {$wpdb->sitemeta}" );
+
+		$wpdb->sitemeta = $orig_sitemeta;
+
+		$this->assertSame( $expected, $results );
+	}
+
+	public function data_populate_network_meta() {
+		return array(
+			array(
+				array(),
+				array(
+					// Random meta to check.
+					'registration'      => 'none',
+					'blog_upload_space' => '100',
+					'fileupload_maxk'   => '1500',
+				),
+			),
+			array(
+				array(
+					'site_name' => 'My Great Network',
+					'WPLANG'    => 'fr_FR',
+				),
+				array(
+					// Random meta to check.
+					'site_name'         => 'My Great Network',
+					'registration'      => 'none',
+					'blog_upload_space' => '100',
+					'fileupload_maxk'   => '1500',
+					'WPLANG'            => 'fr_FR',
+				),
+			),
+			array(
+				array(
+					'custom_meta' => '1',
+				),
+				array(
+					// Random meta to check.
+					'custom_meta'       => '1',
+					'registration'      => 'none',
+					'blog_upload_space' => '100',
+					'fileupload_maxk'   => '1500',
+				),
+			),
+		);
+	}
+}

+ 58 - 0
tests/phpunit/tests/admin/includesUser.php

@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * @group admin
+ * @group user
+ */
+class Tests_Admin_IncludesUser extends WP_UnitTestCase {
+
+	/**
+	 * @ticket       42790
+	 * @dataProvider data_is_authorize_application_password_request_valid
+	 * @param array  $request    The request data to validate.
+	 * @param string $error_code The expected error code, empty if no error.
+	 */
+	public function test_is_authorize_application_password_request_valid( $request, $error_code ) {
+		$error = wp_is_authorize_application_password_request_valid( $request, get_userdata( 1 ) );
+
+		if ( $error_code ) {
+			$this->assertWPError( $error );
+			$this->assertEquals( $error_code, $error->get_error_code() );
+		} else {
+			$this->assertNotWPError( $error );
+		}
+	}
+
+	public function data_is_authorize_application_password_request_valid() {
+		return array(
+			array(
+				array(),
+				'',
+			),
+			array(
+				array( 'success_url' => 'http://example.org' ),
+				'invalid_redirect_scheme',
+			),
+			array(
+				array( 'reject_url' => 'http://example.org' ),
+				'invalid_redirect_scheme',
+			),
+			array(
+				array( 'success_url' => 'https://example.org' ),
+				'',
+			),
+			array(
+				array( 'reject_url' => 'https://example.org' ),
+				'',
+			),
+			array(
+				array( 'success_url' => 'wordpress://example' ),
+				'',
+			),
+			array(
+				array( 'reject_url' => 'wordpress://example' ),
+				'',
+			),
+		);
+	}
+}

+ 182 - 0
tests/phpunit/tests/admin/wpPrivacyRequestsTable.php

@@ -0,0 +1,182 @@
+<?php
+/**
+ * Test the `WP_Privacy_Requests_Table` class.
+ *
+ * @package WordPress\UnitTests
+ *
+ * @since 5.1.0
+ */
+
+/**
+ * Tests_Admin_WpPrivacyRequestsTable class.
+ *
+ * @group admin
+ * @group privacy
+ *
+ * @since 5.1.0
+ */
+class Tests_Admin_WpPrivacyRequestsTable extends WP_UnitTestCase {
+	/**
+	 * Get instance for mocked class.
+	 *
+	 * @since 5.1.0
+	 *
+	 * @return PHPUnit_Framework_MockObject_MockObject|WP_Privacy_Requests_Table Mocked class instance.
+	 */
+	public function get_mocked_class_instance() {
+		$args = array(
+			'plural'   => 'privacy_requests',
+			'singular' => 'privacy_request',
+			'screen'   => 'export_personal_data',
+		);
+
+		$instance = $this
+			->getMockBuilder( 'WP_Privacy_Requests_Table' )
+			->setConstructorArgs( array( $args ) )
+			->getMockForAbstractClass();
+
+		$reflection = new ReflectionClass( $instance );
+
+		// Set the request type as 'export_personal_data'.
+		$reflection_property = $reflection->getProperty( 'request_type' );
+		$reflection_property->setAccessible( true );
+		$reflection_property->setValue( $instance, 'export_personal_data' );
+
+		// Set the post type as 'user_request'.
+		$reflection_property = $reflection->getProperty( 'post_type' );
+		$reflection_property->setAccessible( true );
+		$reflection_property->setValue( $instance, 'user_request' );
+
+		return $instance;
+	}
+
+	/**
+	 * Test columns should be sortable.
+	 *
+	 * @since 5.1.0
+	 *
+	 * @param string|null $order    Order.
+	 * @param string|null $orderby  Order by.
+	 * @param string|null $search   Search term.
+	 * @param string      $expected Expected in SQL query.
+
+	 * @dataProvider data_test_columns_should_be_sortable
+	 * @covers WP_Privacy_Requests_Table::prepare_items
+	 * @ticket 43960
+	 */
+	public function test_columns_should_be_sortable( $order, $orderby, $search, $expected ) {
+		global $wpdb;
+
+		$table     = $this->get_mocked_class_instance();
+		$this->sql = '';
+
+		$_REQUEST['order']   = $order;
+		$_REQUEST['orderby'] = $orderby;
+		$_REQUEST['s']       = $search;
+
+		add_filter( 'posts_request', array( $this, 'filter_posts_request' ) );
+		$table->prepare_items();
+		remove_filter( 'posts_request', array( $this, 'filter_posts_request' ) );
+
+		unset( $_REQUEST['order'] );
+		unset( $_REQUEST['orderby'] );
+		unset( $_REQUEST['s'] );
+
+		$this->assertContains( "ORDER BY {$wpdb->posts}.{$expected}", $this->sql );
+	}
+
+	/**
+	 * Filter to grab the complete SQL query.
+	 *
+	 * @since 5.1.0
+	 *
+	 * @param string $request The complete SQL query.
+	 * @return string The complete SQL query.
+	 */
+	public function filter_posts_request( $request ) {
+		$this->sql = $request;
+		return $request;
+	}
+
+	/**
+	 * Data provider for `test_columns_should_be_sortable()`.
+	 *
+	 * @since 5.1.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 *         @type string|null Order.
+	 *         @type string|null Order by.
+	 *         @type string|null Search term.
+	 *         @type string      Expected in SQL query.
+	 *     }
+	 * }
+	 */
+	public function data_test_columns_should_be_sortable() {
+		return array(
+			// Default order (ID) DESC.
+			array(
+				'order'    => null,
+				'orderby'  => null,
+				's'        => null,
+				'expected' => 'post_date DESC',
+			),
+			// Default order (ID) DESC.
+			array(
+				'order'    => '',
+				'orderby'  => '',
+				's'        => '',
+				'expected' => 'post_date DESC',
+			),
+			// Order by requester (post_title) ASC.
+			array(
+				'order'    => 'ASC',
+				'orderby'  => 'requester',
+				's'        => '',
+				'expected' => 'post_title ASC',
+			),
+			// Order by requester (post_title) DESC.
+			array(
+				'order'    => 'DESC',
+				'orderby'  => 'requester',
+				's'        => null,
+				'expected' => 'post_title DESC',
+			),
+			// Order by requested (post_date) ASC.
+			array(
+				'order'    => 'ASC',
+				'orderby'  => 'requested',
+				's'        => null,
+				'expected' => 'post_date ASC',
+			),
+			// Order by requested (post_date) DESC.
+			array(
+				'order'    => 'DESC',
+				'orderby'  => 'requested',
+				's'        => null,
+				'expected' => 'post_date DESC',
+			),
+			// Search and order by relevance.
+			array(
+				'order'    => null,
+				'orderby'  => null,
+				's'        => 'foo',
+				'expected' => 'post_title LIKE',
+			),
+			// Search and order by requester (post_title) ASC.
+			array(
+				'order'    => 'ASC',
+				'orderby'  => 'requester',
+				's'        => 'foo',
+				'expected' => 'post_title ASC',
+			),
+			// Search and order by requested (post_date) ASC.
+			array(
+				'order'    => 'ASC',
+				'orderby'  => 'requested',
+				's'        => 'foo',
+				'expected' => 'post_date ASC',
+			),
+		);
+	}
+}

+ 71 - 0
tests/phpunit/tests/ajax/AddMeta.php

@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Add Meta AJAX functionality.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_AddMeta extends WP_Ajax_UnitTestCase {
+	/**
+	 * @ticket 43559
+	 */
+	public function test_post_add_meta_empty_is_allowed_ajax() {
+		$p = self::factory()->post->create();
+
+		// Become an administrator.
+		$this->_setRole( 'administrator' );
+
+		$_POST = array(
+			'post_id'              => $p,
+			'metakeyinput'         => 'testkey',
+			'metavalue'            => '',
+			'_ajax_nonce-add-meta' => wp_create_nonce( 'add-meta' ),
+		);
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'add-meta' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		$this->assertSame( '', get_post_meta( $p, 'testkey', true ) );
+	}
+
+	/**
+	 * @ticket 43559
+	 */
+	public function test_post_update_meta_empty_is_allowed_ajax() {
+		$p = self::factory()->post->create();
+
+		$m = add_post_meta( $p, 'testkey', 'hello' );
+
+		// Become an administrator.
+		$this->_setRole( 'administrator' );
+
+		$_POST = array(
+			'_ajax_nonce-add-meta' => wp_create_nonce( 'add-meta' ),
+			'post_id'              => $p,
+			'meta'                 => array(
+				$m => array(
+					'key'   => 'testkey',
+					'value' => '',
+				),
+			),
+		);
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'add-meta' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		$this->assertSame( '', get_post_meta( $p, 'testkey', true ) );
+	}
+}

+ 118 - 0
tests/phpunit/tests/ajax/Attachments.php

@@ -0,0 +1,118 @@
+<?php
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Ajax attachment handling.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_Attachments extends WP_Ajax_UnitTestCase {
+	/**
+	 * @ticket 36578
+	 */
+	public function test_wp_ajax_send_attachment_to_editor_should_return_an_image() {
+		// Become an administrator.
+		$post    = $_POST;
+		$user_id = self::factory()->user->create(
+			array(
+				'role'       => 'administrator',
+				'user_login' => 'user_36578_administrator',
+				'user_email' => 'user_36578_administrator@example.com',
+			)
+		);
+		wp_set_current_user( $user_id );
+		$_POST = array_merge( $_POST, $post );
+
+		$filename = DIR_TESTDATA . '/images/canola.jpg';
+		$contents = file_get_contents( $filename );
+
+		$upload     = wp_upload_bits( wp_basename( $filename ), null, $contents );
+		$attachment = $this->_make_attachment( $upload );
+
+		// Set up a default request.
+		$_POST['nonce']      = wp_create_nonce( 'media-send-to-editor' );
+		$_POST['html']       = 'Bar Baz';
+		$_POST['post_id']    = 0;
+		$_POST['attachment'] = array(
+			'id'         => $attachment,
+			'align'      => 'left',
+			'image-size' => 'large',
+			'image_alt'  => 'Foo bar',
+			'url'        => 'http://example.com/',
+		);
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'send-attachment-to-editor' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = get_image_send_to_editor( $attachment, '', '', 'left', 'http://example.com/', false, 'large', 'Foo bar' );
+
+		// Ensure everything is correct.
+		$this->assertTrue( $response['success'] );
+		$this->assertSame( $expected, $response['data'] );
+	}
+
+	/**
+	 * @ticket 36578
+	 */
+	public function test_wp_ajax_send_attachment_to_editor_should_return_a_link() {
+		$this->skipWithMultisite();
+
+		// Become an administrator.
+		$post    = $_POST;
+		$user_id = self::factory()->user->create(
+			array(
+				'role'       => 'administrator',
+				'user_login' => 'user_36578_administrator',
+				'user_email' => 'user_36578_administrator@example.com',
+			)
+		);
+		wp_set_current_user( $user_id );
+		$_POST = array_merge( $_POST, $post );
+
+		$filename = DIR_TESTDATA . '/formatting/entities.txt';
+		$contents = file_get_contents( $filename );
+
+		$upload     = wp_upload_bits( wp_basename( $filename ), null, $contents );
+		$attachment = $this->_make_attachment( $upload );
+
+		// Set up a default request.
+		$_POST['nonce']      = wp_create_nonce( 'media-send-to-editor' );
+		$_POST['html']       = 'Bar Baz';
+		$_POST['post_id']    = 0;
+		$_POST['attachment'] = array(
+			'id'         => $attachment,
+			'post_title' => 'Foo bar',
+			'url'        => get_attachment_link( $attachment ),
+		);
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'send-attachment-to-editor' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = sprintf(
+			'<a href="%s" rel="attachment wp-att-%d">Foo bar</a>',
+			get_attachment_link( $attachment ),
+			$attachment
+		);
+
+		// Ensure everything is correct.
+		$this->assertTrue( $response['success'] );
+		$this->assertSame( $expected, $response['data'] );
+	}
+}

+ 717 - 0
tests/phpunit/tests/ajax/CustomizeManager.php

@@ -0,0 +1,717 @@
+<?php
+/**
+ * Testing Ajax customize manager functionality.
+ *
+ * @package    WordPress
+ * @subpackage UnitTests
+ * @since      4.3.0
+ * @group      ajax
+ */
+class Tests_Ajax_CustomizeManager extends WP_Ajax_UnitTestCase {
+
+	/**
+	 * Instance of WP_Customize_Manager which is reset for each test.
+	 *
+	 * @var WP_Customize_Manager
+	 */
+	public $wp_customize;
+
+	/**
+	 * Admin user ID.
+	 *
+	 * @var int
+	 */
+	protected static $admin_user_id;
+
+	/**
+	 * Subscriber user ID.
+	 *
+	 * @var int
+	 */
+	protected static $subscriber_user_id;
+
+	/**
+	 * Last response parsed.
+	 *
+	 * @var array|null
+	 */
+	protected $_last_response_parsed;
+
+	/**
+	 * Set up before class.
+	 *
+	 * @param WP_UnitTest_Factory $factory Factory.
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$subscriber_user_id = $factory->user->create( array( 'role' => 'subscriber' ) );
+		self::$admin_user_id      = $factory->user->create( array( 'role' => 'administrator' ) );
+	}
+
+	/**
+	 * Set up the test fixture.
+	 */
+	public function setUp() {
+		parent::setUp();
+		require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
+	}
+
+	/**
+	 * Tear down.
+	 */
+	public function tearDown() {
+		$_REQUEST = array();
+		parent::tearDown();
+	}
+
+	/**
+	 * Helper to keep it DRY
+	 *
+	 * @param string $action Action.
+	 */
+	protected function make_ajax_call( $action ) {
+		$this->_last_response_parsed = null;
+		$this->_last_response        = '';
+		try {
+			$this->_handleAjax( $action );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+		if ( $this->_last_response ) {
+			$this->_last_response_parsed = json_decode( $this->_last_response, true );
+		}
+	}
+
+	/**
+	 * Overridden caps for user_has_cap.
+	 *
+	 * @var array
+	 */
+	protected $overridden_caps = array();
+
+	/**
+	 * Dynamically filter a user's capabilities.
+	 *
+	 * @param array $allcaps An array of all the user's capabilities.
+	 * @return array All caps.
+	 */
+	function filter_user_has_cap( $allcaps ) {
+		$allcaps = array_merge( $allcaps, $this->overridden_caps );
+		return $allcaps;
+	}
+
+	/**
+	 * Test WP_Customize_Manager::save().
+	 *
+	 * @ticket 30937
+	 * @covers WP_Customize_Manager::save
+	 */
+	function test_save_failures() {
+		global $wp_customize;
+		$wp_customize = new WP_Customize_Manager();
+		$wp_customize->register_controls();
+		add_filter( 'user_has_cap', array( $this, 'filter_user_has_cap' ) );
+
+		// Unauthenticated.
+		wp_set_current_user( 0 );
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'unauthenticated', $this->_last_response_parsed['data'] );
+
+		// Unauthorized.
+		wp_set_current_user( self::$subscriber_user_id );
+		$nonce             = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
+		$_POST['nonce']    = $nonce;
+		$_GET['nonce']     = $nonce;
+		$_REQUEST['nonce'] = $nonce;
+		$exception         = null;
+		try {
+			ob_start();
+			$wp_customize->setup_theme();
+		} catch ( WPAjaxDieContinueException $e ) {
+			$exception = $e;
+		}
+		$this->assertNotEmpty( $e );
+		$this->assertEquals( -1, $e->getMessage() );
+
+		// Not called setup_theme.
+		wp_set_current_user( self::$admin_user_id );
+		$nonce             = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
+		$_POST['nonce']    = $nonce;
+		$_GET['nonce']     = $nonce;
+		$_REQUEST['nonce'] = $nonce;
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'not_preview', $this->_last_response_parsed['data'] );
+
+		// Bad nonce.
+		$_POST['nonce']    = 'bad';
+		$_GET['nonce']     = 'bad';
+		$_REQUEST['nonce'] = 'bad';
+		$wp_customize->setup_theme();
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'invalid_nonce', $this->_last_response_parsed['data'] );
+
+		// User cannot create.
+		$nonce                            = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
+		$_POST['nonce']                   = $nonce;
+		$_GET['nonce']                    = $nonce;
+		$_REQUEST['nonce']                = $nonce;
+		$post_type_obj                    = get_post_type_object( 'customize_changeset' );
+		$post_type_obj->cap->create_posts = 'create_customize_changesets';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'cannot_create_changeset_post', $this->_last_response_parsed['data'] );
+		$this->overridden_caps[ $post_type_obj->cap->create_posts ] = true;
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$post_type_obj->cap->create_posts = 'customize'; // Restore.
+
+		// Changeset already published.
+		$wp_customize->set_post_value( 'blogname', 'Hello' );
+		$wp_customize->save_changeset_post( array( 'status' => 'publish' ) );
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_already_published', $this->_last_response_parsed['data']['code'] );
+		wp_update_post(
+			array(
+				'ID'          => $wp_customize->changeset_post_id(),
+				'post_status' => 'auto-draft',
+			)
+		);
+
+		// User cannot edit.
+		$post_type_obj                 = get_post_type_object( 'customize_changeset' );
+		$post_type_obj->cap->edit_post = 'edit_customize_changesets';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'cannot_edit_changeset_post', $this->_last_response_parsed['data'] );
+		$this->overridden_caps[ $post_type_obj->cap->edit_post ] = true;
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$post_type_obj->cap->edit_post = 'customize'; // Restore.
+
+		// Bad customize_changeset_data.
+		$_POST['customize_changeset_data'] = '[MALFORMED]';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'invalid_customize_changeset_data', $this->_last_response_parsed['data'] );
+
+		// Bad customize_changeset_status.
+		$_POST['customize_changeset_data']   = '{}';
+		$_POST['customize_changeset_status'] = 'unrecognized';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'bad_customize_changeset_status', $this->_last_response_parsed['data'] );
+
+		// Disallowed publish posts if not allowed.
+		$post_type_obj                       = get_post_type_object( 'customize_changeset' );
+		$post_type_obj->cap->publish_posts   = 'publish_customize_changesets';
+		$_POST['customize_changeset_status'] = 'publish';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_publish_unauthorized', $this->_last_response_parsed['data'] );
+		$_POST['customize_changeset_status'] = 'future';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_publish_unauthorized', $this->_last_response_parsed['data'] );
+		$post_type_obj->cap->publish_posts = 'customize'; // Restore.
+
+		// Validate date.
+		$_POST['customize_changeset_status'] = 'draft';
+		$_POST['customize_changeset_date']   = 'BAD DATE';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'bad_customize_changeset_date', $this->_last_response_parsed['data'] );
+		$_POST['customize_changeset_date'] = '2010-01-01 00:00:00';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'not_future_date', $this->_last_response_parsed['data']['code'] );
+		$_POST['customize_changeset_date'] = ( gmdate( 'Y' ) + 1 ) . '-01-01 00:00:00';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$_POST['customize_changeset_status'] = 'future';
+		$_POST['customize_changeset_date']   = '+10 minutes';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'future', get_post_status( $wp_customize->changeset_post_id() ) );
+		wp_update_post(
+			array(
+				'ID'          => $wp_customize->changeset_post_id(),
+				'post_status' => 'auto-draft',
+			)
+		);
+	}
+
+	/**
+	 * Set up valid user state.
+	 *
+	 * @param string $uuid Changeset UUID.
+	 * @return WP_Customize_Manager
+	 */
+	protected function set_up_valid_state( $uuid = null ) {
+		global $wp_customize;
+		wp_set_current_user( self::$admin_user_id );
+		$wp_customize = new WP_Customize_Manager(
+			array(
+				'changeset_uuid' => $uuid,
+			)
+		);
+		$wp_customize->register_controls();
+		$nonce             = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
+		$_POST['nonce']    = $nonce;
+		$_GET['nonce']     = $nonce;
+		$_REQUEST['nonce'] = $nonce;
+		$wp_customize->setup_theme();
+		return $wp_customize;
+	}
+
+	/**
+	 * Test WP_Customize_Manager::save().
+	 *
+	 * @ticket 30937
+	 * @covers WP_Customize_Manager::save
+	 */
+	function test_save_success_publish_create() {
+		$wp_customize = $this->set_up_valid_state();
+
+		$_POST['customize_changeset_status'] = 'publish';
+		$_POST['customize_changeset_title']  = 'Success Changeset';
+		$_POST['customize_changeset_data']   = wp_json_encode(
+			array(
+				'blogname' => array(
+					'value' => 'Successful Site Title',
+				),
+			)
+		);
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertInternalType( 'array', $this->_last_response_parsed['data'] );
+
+		$this->assertSame( 'publish', $this->_last_response_parsed['data']['changeset_status'] );
+		$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
+		$this->assertTrue( wp_is_uuid( $this->_last_response_parsed['data']['next_changeset_uuid'], 4 ) );
+		$this->assertSame( 'Success Changeset', get_post( $wp_customize->changeset_post_id() )->post_title );
+		$this->assertSame( 'Successful Site Title', get_option( 'blogname' ) );
+	}
+
+	/**
+	 * Test WP_Customize_Manager::save().
+	 *
+	 * @ticket 30937
+	 * @covers WP_Customize_Manager::save
+	 */
+	function test_save_success_publish_edit() {
+		$uuid = wp_generate_uuid4();
+
+		$post_id      = $this->factory()->post->create(
+			array(
+				'post_name'    => $uuid,
+				'post_title'   => 'Original',
+				'post_type'    => 'customize_changeset',
+				'post_status'  => 'auto-draft',
+				'post_content' => wp_json_encode(
+					array(
+						'blogname' => array(
+							'value' => 'New Site Title',
+						),
+					)
+				),
+			)
+		);
+		$wp_customize = $this->set_up_valid_state( $uuid );
+
+		$_POST['customize_changeset_status'] = 'publish';
+		$_POST['customize_changeset_title']  = 'Published';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertInternalType( 'array', $this->_last_response_parsed['data'] );
+
+		$this->assertSame( 'publish', $this->_last_response_parsed['data']['changeset_status'] );
+		$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
+		$this->assertTrue( wp_is_uuid( $this->_last_response_parsed['data']['next_changeset_uuid'], 4 ) );
+		$this->assertSame( 'New Site Title', get_option( 'blogname' ) );
+		$this->assertSame( 'Published', get_post( $post_id )->post_title );
+	}
+
+	/**
+	 * Test WP_Customize_Manager::save().
+	 *
+	 * @ticket 38943
+	 * @covers WP_Customize_Manager::save
+	 */
+	function test_success_save_post_date() {
+		$uuid         = wp_generate_uuid4();
+		$post_id      = $this->factory()->post->create(
+			array(
+				'post_name'    => $uuid,
+				'post_title'   => 'Original',
+				'post_type'    => 'customize_changeset',
+				'post_status'  => 'auto-draft',
+				'post_content' => wp_json_encode(
+					array(
+						'blogname' => array(
+							'value' => 'New Site Title',
+						),
+					)
+				),
+			)
+		);
+		$wp_customize = $this->set_up_valid_state( $uuid );
+
+		// Success future schedule date.
+		$future_date                         = ( gmdate( 'Y' ) + 1 ) . '-01-01 00:00:00';
+		$_POST['customize_changeset_status'] = 'future';
+		$_POST['customize_changeset_title']  = 'Future date';
+		$_POST['customize_changeset_date']   = $future_date;
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertArrayHasKey( 'changeset_date', $this->_last_response_parsed['data'] );
+		$changeset_post_schedule = get_post( $post_id );
+		$this->assertSame( $future_date, $changeset_post_schedule->post_date );
+
+		// Success future changeset change to draft keeping existing date.
+		unset( $_POST['customize_changeset_date'] );
+		$_POST['customize_changeset_status'] = 'draft';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertArrayNotHasKey( 'changeset_date', $this->_last_response_parsed['data'] );
+		$changeset_post_draft = get_post( $post_id );
+		$this->assertSame( $future_date, $changeset_post_draft->post_date );
+
+		// Success if date is not passed with schedule changeset and stored changeset have future date.
+		$_POST['customize_changeset_status'] = 'future';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertArrayHasKey( 'changeset_date', $this->_last_response_parsed['data'] );
+		$changeset_post_schedule = get_post( $post_id );
+		$this->assertSame( $future_date, $changeset_post_schedule->post_date );
+		// Success if draft with past date.
+		$now = current_time( 'mysql' );
+		wp_update_post(
+			array(
+				'ID'            => $post_id,
+				'post_status'   => 'draft',
+				'post_date'     => $now,
+				'post_date_gmt' => get_gmt_from_date( $now ),
+			)
+		);
+
+		// Fail if future request and existing date is past.
+		$_POST['customize_changeset_status'] = 'future';
+		unset( $_POST['customize_changeset_date'] );
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'not_future_date', $this->_last_response_parsed['data']['code'] );
+
+		// Success publish changeset reset date to current.
+		wp_update_post(
+			array(
+				'ID'            => $post_id,
+				'post_status'   => 'future',
+				'post_date'     => $future_date,
+				'post_date_gmt' => get_gmt_from_date( $future_date ),
+			)
+		);
+		unset( $_POST['customize_changeset_date'] );
+		$_POST['customize_changeset_status'] = 'publish';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
+		$this->assertTrue( wp_is_uuid( $this->_last_response_parsed['data']['next_changeset_uuid'], 4 ) );
+		$changeset_post_publish = get_post( $post_id );
+		$this->assertNotEquals( $future_date, $changeset_post_publish->post_date );
+
+		// Check response when trying to update an already-published post.
+		$this->assertSame( 'trash', get_post_status( $post_id ) );
+		$_POST['customize_changeset_status'] = 'publish';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_already_published', $this->_last_response_parsed['data']['code'] );
+		$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
+		$this->assertTrue( wp_is_uuid( $this->_last_response_parsed['data']['next_changeset_uuid'], 4 ) );
+	}
+
+	/**
+	 * Test WP_Customize_Manager::save().
+	 *
+	 * @ticket 39896
+	 * @covers WP_Customize_Manager::save
+	 */
+	public function test_save_autosave() {
+		$uuid = wp_generate_uuid4();
+
+		$post_id = $this->factory()->post->create(
+			array(
+				'post_name'    => $uuid,
+				'post_type'    => 'customize_changeset',
+				'post_status'  => 'draft',
+				'post_content' => wp_json_encode(
+					array(
+						'blogname' => array(
+							'value' => 'New Site Title',
+						),
+					)
+				),
+			)
+		);
+		$this->set_up_valid_state( $uuid );
+
+		$this->assertFalse( wp_get_post_autosave( $post_id ) );
+
+		$_POST['customize_changeset_data'] = wp_json_encode(
+			array(
+				'blogname' => array(
+					'value' => 'Autosaved Site Title',
+				),
+			)
+		);
+
+		$_POST['customize_changeset_autosave'] = 'on';
+		$this->make_ajax_call( 'customize_save' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'draft', $this->_last_response_parsed['data']['changeset_status'] );
+		$autosave_revision = wp_get_post_autosave( $post_id );
+		$this->assertInstanceOf( 'WP_Post', $autosave_revision );
+
+		$this->assertContains( 'New Site Title', get_post( $post_id )->post_content );
+		$this->assertContains( 'Autosaved Site Title', $autosave_revision->post_content );
+	}
+
+	/**
+	 * Test request for trashing a changeset.
+	 *
+	 * @ticket 39896
+	 * @covers WP_Customize_Manager::handle_changeset_trash_request
+	 */
+	public function test_handle_changeset_trash_request() {
+		$uuid         = wp_generate_uuid4();
+		$wp_customize = $this->set_up_valid_state( $uuid );
+
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'invalid_nonce', $this->_last_response_parsed['data']['code'] );
+
+		$nonce             = wp_create_nonce( 'trash_customize_changeset' );
+		$_POST['nonce']    = $nonce;
+		$_GET['nonce']     = $nonce;
+		$_REQUEST['nonce'] = $nonce;
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'non_existent_changeset', $this->_last_response_parsed['data']['code'] );
+
+		$wp_customize->register_controls(); // And settings too.
+		$wp_customize->set_post_value( 'blogname', 'HELLO' );
+		$wp_customize->save_changeset_post(
+			array(
+				'status' => 'save',
+			)
+		);
+
+		add_filter( 'map_meta_cap', array( $this, 'return_do_not_allow' ) );
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_trash_unauthorized', $this->_last_response_parsed['data']['code'] );
+		remove_filter( 'map_meta_cap', array( $this, 'return_do_not_allow' ) );
+
+		$lock_user_id  = static::factory()->user->create( array( 'role' => 'administrator' ) );
+		$previous_user = get_current_user_id();
+		wp_set_current_user( $lock_user_id );
+		$wp_customize->set_changeset_lock( $wp_customize->changeset_post_id() );
+		wp_set_current_user( $previous_user );
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_locked', $this->_last_response_parsed['data']['code'] );
+		delete_post_meta( $wp_customize->changeset_post_id(), '_edit_lock' );
+
+		wp_update_post(
+			array(
+				'ID'          => $wp_customize->changeset_post_id(),
+				'post_status' => 'trash',
+			)
+		);
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_already_trashed', $this->_last_response_parsed['data']['code'] );
+
+		wp_update_post(
+			array(
+				'ID'          => $wp_customize->changeset_post_id(),
+				'post_status' => 'draft',
+			)
+		);
+
+		$wp_trash_post_count = did_action( 'wp_trash_post' );
+		add_filter( 'pre_trash_post', '__return_false' );
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_trash_failure', $this->_last_response_parsed['data']['code'] );
+		remove_filter( 'pre_trash_post', '__return_false' );
+		$this->assertSame( $wp_trash_post_count, did_action( 'wp_trash_post' ) );
+
+		$wp_trash_post_count = did_action( 'wp_trash_post' );
+		$this->assertSame( 'draft', get_post_status( $wp_customize->changeset_post_id() ) );
+		$this->make_ajax_call( 'customize_trash' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'trash', get_post_status( $wp_customize->changeset_post_id() ) );
+		$this->assertSame( $wp_trash_post_count + 1, did_action( 'wp_trash_post' ) );
+	}
+
+	/**
+	 * Return caps array containing 'do_not_allow'.
+	 *
+	 * @return array Caps.
+	 */
+	public function return_do_not_allow() {
+		return array( 'do_not_allow' );
+	}
+
+	/**
+	 * Test request for dismissing autosave changesets.
+	 *
+	 * @ticket 39896
+	 * @covers WP_Customize_Manager::handle_dismiss_autosave_or_lock_request
+	 * @covers WP_Customize_Manager::dismiss_user_auto_draft_changesets
+	 */
+	public function test_handle_dismiss_autosave_or_lock_request() {
+		$uuid          = wp_generate_uuid4();
+		$wp_customize  = $this->set_up_valid_state( $uuid );
+		$valid_user_id = get_current_user_id();
+
+		// Temporarily remove user to test requirement that user is logged in. See #42450.
+		wp_set_current_user( 0 );
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'unauthenticated', $this->_last_response_parsed['data'] );
+		wp_set_current_user( $valid_user_id );
+
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'invalid_nonce', $this->_last_response_parsed['data'] );
+
+		$nonce             = wp_create_nonce( 'customize_dismiss_autosave_or_lock' );
+		$_POST['nonce']    = $nonce;
+		$_GET['nonce']     = $nonce;
+		$_REQUEST['nonce'] = $nonce;
+
+		$_POST['dismiss_lock']    = true;
+		$_GET['dismiss_lock']     = true;
+		$_REQUEST['dismiss_lock'] = true;
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'no_changeset_to_dismiss_lock', $this->_last_response_parsed['data'] );
+
+		$_POST['dismiss_autosave']    = true;
+		$_GET['dismiss_autosave']     = true;
+		$_REQUEST['dismiss_autosave'] = true;
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'no_auto_draft_to_delete', $this->_last_response_parsed['data'] );
+
+		$other_user_id = $this->factory()->user->create();
+
+		// Create auto-drafts.
+		$user_auto_draft_ids = array();
+		for ( $i = 0; $i < 3; $i++ ) {
+			$user_auto_draft_ids[] = $this->factory()->post->create(
+				array(
+					'post_name'    => wp_generate_uuid4(),
+					'post_type'    => 'customize_changeset',
+					'post_status'  => 'auto-draft',
+					'post_author'  => self::$admin_user_id,
+					'post_content' => wp_json_encode( array() ),
+				)
+			);
+		}
+		$other_user_auto_draft_ids = array();
+		for ( $i = 0; $i < 3; $i++ ) {
+			$other_user_auto_draft_ids[] = $this->factory()->post->create(
+				array(
+					'post_name'    => wp_generate_uuid4(),
+					'post_type'    => 'customize_changeset',
+					'post_status'  => 'auto-draft',
+					'post_author'  => $other_user_id,
+					'post_content' => wp_json_encode( array() ),
+				)
+			);
+		}
+		foreach ( array_merge( $user_auto_draft_ids, $other_user_auto_draft_ids ) as $post_id ) {
+			$this->assertFalse( (bool) get_post_meta( $post_id, '_customize_restore_dismissed', true ) );
+		}
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'auto_draft_dismissed', $this->_last_response_parsed['data'] );
+		foreach ( $user_auto_draft_ids as $post_id ) {
+			$this->assertSame( 'auto-draft', get_post_status( $post_id ) );
+			$this->assertTrue( (bool) get_post_meta( $post_id, '_customize_restore_dismissed', true ) );
+		}
+		foreach ( $other_user_auto_draft_ids as $post_id ) {
+			$this->assertSame( 'auto-draft', get_post_status( $post_id ) );
+			$this->assertFalse( (bool) get_post_meta( $post_id, '_customize_restore_dismissed', true ) );
+		}
+
+		// Subsequent test results in none dismissed.
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'no_auto_draft_to_delete', $this->_last_response_parsed['data'] );
+
+		// Save a changeset as a draft.
+		$r = $wp_customize->save_changeset_post(
+			array(
+				'data'   => array(
+					'blogname' => array(
+						'value' => 'Foo',
+					),
+				),
+				'status' => 'draft',
+			)
+		);
+
+		$_POST['dismiss_autosave']    = false;
+		$_GET['dismiss_autosave']     = false;
+		$_REQUEST['dismiss_autosave'] = false;
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'changeset_lock_dismissed', $this->_last_response_parsed['data'] );
+
+		$_POST['dismiss_autosave']    = true;
+		$_GET['dismiss_autosave']     = true;
+		$_REQUEST['dismiss_autosave'] = true;
+		$this->assertNotWPError( $r );
+		$this->assertFalse( wp_get_post_autosave( $wp_customize->changeset_post_id() ) );
+		$this->assertContains( 'Foo', get_post( $wp_customize->changeset_post_id() )->post_content );
+
+		// Since no autosave yet, confirm no action.
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'no_autosave_revision_to_delete', $this->_last_response_parsed['data'] );
+
+		// Add the autosave revision.
+		$r = $wp_customize->save_changeset_post(
+			array(
+				'data'     => array(
+					'blogname' => array(
+						'value' => 'Bar',
+					),
+				),
+				'autosave' => true,
+			)
+		);
+		$this->assertNotWPError( $r );
+		$autosave_revision = wp_get_post_autosave( $wp_customize->changeset_post_id() );
+		$this->assertInstanceOf( 'WP_Post', $autosave_revision );
+		$this->assertContains( 'Foo', get_post( $wp_customize->changeset_post_id() )->post_content );
+		$this->assertContains( 'Bar', $autosave_revision->post_content );
+
+		// Confirm autosave gets deleted.
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'autosave_revision_deleted', $this->_last_response_parsed['data'] );
+		$this->assertFalse( wp_get_post_autosave( $wp_customize->changeset_post_id() ) );
+
+		// Since no autosave yet, confirm no action.
+		$this->make_ajax_call( 'customize_dismiss_autosave_or_lock' );
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'no_autosave_revision_to_delete', $this->_last_response_parsed['data'] );
+	}
+}

+ 784 - 0
tests/phpunit/tests/ajax/CustomizeMenus.php

@@ -0,0 +1,784 @@
+<?php
+/**
+ * Testing Ajax customize menus functionality.
+ *
+ * @package    WordPress
+ * @subpackage UnitTests
+ * @since      4.3.0
+ * @group      ajax
+ */
+class Tests_Ajax_CustomizeMenus extends WP_Ajax_UnitTestCase {
+
+	/**
+	 * Instance of WP_Customize_Manager which is reset for each test.
+	 *
+	 * @var WP_Customize_Manager
+	 */
+	public $wp_customize;
+
+	/**
+	 * Page IDs.
+	 *
+	 * @var int[]
+	 */
+	public static $pages;
+
+	/**
+	 * Post IDs.
+	 *
+	 * @var int[]
+	 */
+	public static $posts;
+
+	/**
+	 * Term IDs.
+	 *
+	 * @var int[]
+	 */
+	public static $terms;
+
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		// Make some post objects.
+		self::$posts = $factory->post->create_many( 5 );
+		self::$pages = $factory->post->create_many( 5, array( 'post_type' => 'page' ) );
+
+		// Some terms too.
+		self::$terms = $factory->term->create_many( 5 );
+	}
+
+	/**
+	 * Set up the test fixture.
+	 */
+	public function setUp() {
+		parent::setUp();
+		require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		global $wp_customize;
+		$this->wp_customize = new WP_Customize_Manager();
+		$wp_customize       = $this->wp_customize;
+	}
+
+	/**
+	 * Helper to keep it DRY
+	 *
+	 * @param string $action Action.
+	 */
+	protected function make_ajax_call( $action ) {
+		// Make the request.
+		try {
+			$this->_handleAjax( $action );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+	}
+
+	/**
+	 * Testing capabilities check for ajax_load_available_items method
+	 *
+	 * @dataProvider data_ajax_load_available_items_cap_check
+	 *
+	 * @param string $role              The role we're checking caps against.
+	 * @param array  $expected_results  Expected results.
+	 */
+	function test_ajax_load_available_items_cap_check( $role, $expected_results ) {
+
+		if ( 'administrator' !== $role ) {
+			// If we're not an admin, we should get a wp_die( -1 ).
+			$this->expectException( 'WPAjaxDieStopException' );
+			$this->expectExceptionMessage( '-1' );
+		}
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => $role ) ) );
+
+		$_POST = array(
+			'action'                => 'load-available-menu-items-customizer',
+			'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+		);
+
+		$this->make_ajax_call( 'load-available-menu-items-customizer' );
+
+		// If we are an admin, we should get a proper response.
+		if ( 'administrator' === $role ) {
+			// Get the results.
+			$response = json_decode( $this->_last_response, true );
+
+			$this->assertSame( $expected_results, $response );
+		}
+
+	}
+
+	/**
+	 * Data provider for test_ajax_load_available_items_cap_check().
+	 *
+	 * Provides various post_args to induce error messages in the that can be
+	 * compared to the expected_results.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 *         @string string $role             The role that will test caps for.
+	 *         @array  array  $expected_results The expected results from the Ajax call.
+	 *     }
+	 * }
+	 */
+	function data_ajax_load_available_items_cap_check() {
+		return array(
+			array(
+				'subscriber',
+				array(),
+			),
+			array(
+				'contributor',
+				array(),
+			),
+			array(
+				'author',
+				array(),
+			),
+			array(
+				'editor',
+				array(),
+			),
+			array(
+				'administrator',
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_type_or_object_parameter',
+				),
+			),
+		);
+	}
+
+	/**
+	 * Testing the error messaging for ajax_load_available_items
+	 *
+	 * @dataProvider data_ajax_load_available_items_error_messages
+	 *
+	 * @param array $post_args POST args.
+	 * @param mixed $expected_results Expected results.
+	 */
+	function test_ajax_load_available_items_error_messages( $post_args, $expected_results ) {
+
+		$_POST = array_merge(
+			array(
+				'action'                => 'load-available-menu-items-customizer',
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			),
+			$post_args
+		);
+
+		// Make the request.
+		$this->make_ajax_call( 'load-available-menu-items-customizer' );
+
+		// Get the results.
+		$response = json_decode( $this->_last_response, true );
+
+		$this->assertSame( $expected_results, $response );
+	}
+
+	/**
+	 * Data provider for test_ajax_load_available_items_error_message().
+	 *
+	 * Provides various post_args to induce error messages in the that can be
+	 * compared to the expected_results.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 * @array array $post_args        The arguments that will merged with the $_POST array.
+	 * @array array $expected_results The expected results from the Ajax call.
+	 *     }
+	 * }
+	 */
+	function data_ajax_load_available_items_error_messages() {
+		return array(
+			// Testing empty obj_type and type.
+			array(
+				array(
+					'type'   => '',
+					'object' => '',
+				),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_type_or_object_parameter',
+				),
+			),
+			// Testing empty obj_type.
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => '',
+				),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_type_or_object_parameter',
+				),
+			),
+			// Testing empty type.
+			array(
+				array(
+					'type'   => '',
+					'object' => 'post',
+				),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_type_or_object_parameter',
+				),
+			),
+			// Testing empty type of a bulk request.
+			array(
+				array(
+					'item_types' => array(
+						array(
+							'type'   => 'post_type',
+							'object' => 'post',
+						),
+						array(
+							'type'   => 'post_type',
+							'object' => '',
+						),
+					),
+				),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_type_or_object_parameter',
+				),
+			),
+			// Testing incorrect type option.
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'invalid',
+				),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_invalid_post_type',
+				),
+			),
+		);
+	}
+
+	/**
+	 * Testing the success status.
+	 *
+	 * @dataProvider data_ajax_load_available_items_success_status
+	 *
+	 * @param array $post_args       POST args.
+	 * @param array $success_status  Success status.
+	 */
+	function test_ajax_load_available_items_success_status( $post_args, $success_status ) {
+
+		$_POST = array_merge(
+			array(
+				'action'                => 'load-available-menu-items-customizer',
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			),
+			$post_args
+		);
+
+		// Make the request.
+		$this->make_ajax_call( 'load-available-menu-items-customizer' );
+
+		// Get the results.
+		$response = json_decode( $this->_last_response, true );
+		$this->assertSame( $success_status, $response['success'] );
+
+	}
+
+	/**
+	 * Data provider for test_ajax_load_available_items_success_status().
+	 *
+	 * Provides various post_args to retrieve results and compare against
+	 * the success status.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 *         @type array $post_args      The arguments that will merged with the $_POST array.
+	 *         @type bool  $success_status The expected success status.
+	 *     }
+	 * }
+	 */
+	function data_ajax_load_available_items_success_status() {
+		return array(
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'post',
+				),
+				true,
+			),
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'page',
+				),
+				true,
+			),
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'custom',
+				),
+				false,
+			),
+			array(
+				array(
+					'type'   => 'taxonomy',
+					'object' => 'post_tag',
+				),
+				true,
+			),
+			// Testing a bulk request.
+			array(
+				array(
+					'item_types' => array(
+						array(
+							'type'   => 'post_type',
+							'object' => 'post',
+						),
+						array(
+							'type'   => 'post_type',
+							'object' => 'page',
+						),
+					),
+				),
+				true,
+			),
+		);
+	}
+
+	/**
+	 * Testing the array structure for a single item
+	 *
+	 * @dataProvider data_ajax_load_available_items_structure
+	 *
+	 * @param array $post_args POST args.
+	 */
+	function test2_ajax_load_available_items_structure( $post_args ) {
+		do_action( 'customize_register', $this->wp_customize );
+
+		$expected_keys = array(
+			'id',
+			'title',
+			'type',
+			'type_label',
+			'object',
+			'object_id',
+			'url',
+		);
+
+		$auto_draft_post = $this->wp_customize->nav_menus->insert_auto_draft_post(
+			array(
+				'post_title' => 'Test Auto Draft',
+				'post_type'  => 'post',
+			)
+		);
+		$this->wp_customize->set_post_value( 'nav_menus_created_posts', array( $auto_draft_post->ID ) );
+		$this->wp_customize->get_setting( 'nav_menus_created_posts' )->preview();
+
+		$_POST = array_merge(
+			array(
+				'action'                => 'load-available-menu-items-customizer',
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			),
+			$post_args
+		);
+
+		// Make the request.
+		$this->make_ajax_call( 'load-available-menu-items-customizer' );
+
+		// Get the results.
+		$response = json_decode( $this->_last_response, true );
+
+		$this->assertNotEmpty( current( $response['data']['items'] ) );
+
+		// Get the second index to avoid the home page edge case.
+		$first_prop = current( $response['data']['items'] );
+		$test_item  = $first_prop[1];
+
+		foreach ( $expected_keys as $key ) {
+			$this->assertArrayHasKey( $key, $test_item );
+			$this->assertNotEmpty( $test_item[ $key ] );
+		}
+
+		// Special test for the home page.
+		if ( 'page' === $test_item['object'] ) {
+			$first_prop = current( $response['data']['items'] );
+			$home       = $first_prop[0];
+			foreach ( $expected_keys as $key ) {
+				if ( 'object_id' !== $key ) {
+					$this->assertArrayHasKey( $key, $home );
+					if ( 'object' !== $key ) {
+						$this->assertNotEmpty( $home[ $key ] );
+					}
+				}
+			}
+		} elseif ( 'post' === $test_item['object'] ) {
+			$item_ids = wp_list_pluck( $response['data']['items']['post_type:post'], 'id' );
+			$this->assertContains( 'post-' . $auto_draft_post->ID, $item_ids );
+		}
+	}
+
+	/**
+	 * Data provider for test_ajax_load_available_items_structure().
+	 *
+	 * Provides various post_args to return a list of items to test the array structure of.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 *         @type array $post_args The arguments that will merged with the $_POST array.
+	 *     }
+	 * }
+	 */
+	function data_ajax_load_available_items_structure() {
+		return array(
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'post',
+				),
+			),
+			array(
+				array(
+					'type'   => 'post_type',
+					'object' => 'page',
+				),
+			),
+			array(
+				array(
+					'type'   => 'taxonomy',
+					'object' => 'post_tag',
+				),
+			),
+		);
+	}
+
+	/**
+	 * Testing the error messages for ajax_search_available_items
+	 *
+	 * @dataProvider data_ajax_search_available_items_caps_check
+	 *
+	 * @param string $role             Role.
+	 * @param array  $expected_results Expected results.
+	 */
+	function test_ajax_search_available_items_caps_check( $role, $expected_results ) {
+
+		if ( 'administrator' !== $role ) {
+			// If we're not an admin, we should get a wp_die( -1 ).
+			$this->expectException( 'WPAjaxDieStopException' );
+			$this->expectExceptionMessage( '-1' );
+		}
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => $role ) ) );
+
+		$_POST = array(
+			'action'                => 'search-available-menu-items-customizer',
+			'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+		);
+
+		$this->make_ajax_call( 'search-available-menu-items-customizer' );
+
+		// If we are an admin, we should get a proper response.
+		if ( 'administrator' === $role ) {
+			// Get the results.
+			$response = json_decode( $this->_last_response, true );
+
+			$this->assertSame( $expected_results, $response );
+		}
+	}
+
+	/**
+	 * Data provider for test_ajax_search_available_items_caps_check().
+	 *
+	 * Provides various post_args to induce error messages in the that can be
+	 * compared to the expected_results.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @todo Make this more DRY
+	 *
+	 * @return array {
+	 *     @type array {
+	 * @string string $role             The role that will test caps for.
+	 * @array  array  $expected_results The expected results from the Ajax call.
+	 *     }
+	 * }
+	 */
+	function data_ajax_search_available_items_caps_check() {
+		return array(
+			array(
+				'subscriber',
+				array(),
+			),
+			array(
+				'contributor',
+				array(),
+			),
+			array(
+				'author',
+				array(),
+			),
+			array(
+				'editor',
+				array(),
+			),
+			array(
+				'administrator',
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_search_parameter',
+				),
+			),
+		);
+	}
+
+	/**
+	 * Testing the results of various searches
+	 *
+	 * @dataProvider data_ajax_search_available_items_results
+	 *
+	 * @param array $post_args        POST args.
+	 * @param array $expected_results Expected results.
+	 */
+	function test_ajax_search_available_items_results( $post_args, $expected_results ) {
+		do_action( 'customize_register', $this->wp_customize );
+
+		self::factory()->post->create_many( 5, array( 'post_title' => 'Test Post' ) );
+		$included_auto_draft_post = $this->wp_customize->nav_menus->insert_auto_draft_post(
+			array(
+				'post_title' => 'Test Included Auto Draft',
+				'post_type'  => 'post',
+			)
+		);
+		$excluded_auto_draft_post = $this->wp_customize->nav_menus->insert_auto_draft_post(
+			array(
+				'post_title' => 'Excluded Auto Draft',
+				'post_type'  => 'post',
+			)
+		);
+		$this->wp_customize->set_post_value( 'nav_menus_created_posts', array( $included_auto_draft_post->ID, $excluded_auto_draft_post->ID ) );
+		$this->wp_customize->get_setting( 'nav_menus_created_posts' )->preview();
+
+		$_POST = array_merge(
+			array(
+				'action'                => 'search-available-menu-items-customizer',
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			),
+			$post_args
+		);
+
+		$this->make_ajax_call( 'search-available-menu-items-customizer' );
+
+		$response = json_decode( $this->_last_response, true );
+
+		if ( isset( $post_args['search'] ) && 'test' === $post_args['search'] ) {
+			$this->assertTrue( $response['success'] );
+			$this->assertSame( 6, count( $response['data']['items'] ) );
+			$item_ids = wp_list_pluck( $response['data']['items'], 'id' );
+			$this->assertContains( 'post-' . $included_auto_draft_post->ID, $item_ids );
+			$this->assertNotContains( 'post-' . $excluded_auto_draft_post->ID, $item_ids );
+		} else {
+			$this->assertSame( $expected_results, $response );
+		}
+	}
+
+	/**
+	 * Data provider for test_ajax_search_available_items_results().
+	 *
+	 * Provides various post_args to test the results.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 * @string string $post_args        The args that will be passed to Ajax.
+	 * @array  array  $expected_results The expected results from the Ajax call.
+	 *     }
+	 * }
+	 */
+	function data_ajax_search_available_items_results() {
+		return array(
+			array(
+				array(),
+				array(
+					'success' => false,
+					'data'    => 'nav_menus_missing_search_parameter',
+				),
+			),
+			array(
+				array(
+					'search' => 'all_the_things',
+				),
+				array(
+					'success' => false,
+					'data'    => array(
+						'message' => 'No results found.',
+					),
+				),
+			),
+			array(
+				array(
+					'search' => 'test',
+				),
+				array(
+					'success' => true,
+					array(),
+				),
+			),
+		);
+	}
+
+	/**
+	 * Testing successful ajax_insert_auto_draft_post() call.
+	 *
+	 * @covers WP_Customize_Nav_Menus::ajax_insert_auto_draft_post
+	 */
+	function test_ajax_insert_auto_draft_post_success() {
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+				'params'                => array(
+					'post_type'  => 'post',
+					'post_title' => 'Hello World',
+				),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+
+		$this->assertTrue( $response['success'] );
+		$this->assertArrayHasKey( 'post_id', $response['data'] );
+		$this->assertArrayHasKey( 'url', $response['data'] );
+		$post = get_post( $response['data']['post_id'] );
+		$this->assertSame( 'Hello World', $post->post_title );
+		$this->assertSame( 'post', $post->post_type );
+		$this->assertSame( '', $post->post_name );
+		$this->assertSame( 'hello-world', get_post_meta( $post->ID, '_customize_draft_post_name', true ) );
+		$this->assertSame( $this->wp_customize->changeset_uuid(), get_post_meta( $post->ID, '_customize_changeset_uuid', true ) );
+	}
+
+	/**
+	 * Testing unsuccessful ajax_insert_auto_draft_post() call.
+	 *
+	 * @covers WP_Customize_Nav_Menus::ajax_insert_auto_draft_post
+	 */
+	function test_ajax_insert_auto_draft_failures() {
+		// No nonce.
+		$_POST                = array();
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'bad_nonce', $response['data'] );
+
+		// Bad nonce.
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => 'bad',
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'bad_nonce', $response['data'] );
+
+		// Bad nonce.
+		wp_set_current_user( $this->factory()->user->create( array( 'role' => 'subscriber' ) ) );
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'customize_not_allowed', $response['data'] );
+
+		// Missing params.
+		wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'missing_params', $response['data'] );
+
+		// insufficient_post_permissions.
+		register_post_type( 'privilege', array( 'capability_type' => 'privilege' ) );
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+				'params'                => array(
+					'post_type' => 'privilege',
+				),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'insufficient_post_permissions', $response['data'] );
+
+		// insufficient_post_permissions.
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+				'params'                => array(
+					'post_type' => 'non-existent',
+				),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'missing_post_type_param', $response['data'] );
+
+		// missing_post_title.
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+				'params'                => array(
+					'post_type'  => 'post',
+					'post_title' => '    ',
+				),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'missing_post_title', $response['data'] );
+
+		// illegal_params.
+		$_POST                = wp_slash(
+			array(
+				'customize-menus-nonce' => wp_create_nonce( 'customize-menus' ),
+				'params'                => array(
+					'post_type'    => 'post',
+					'post_title'   => 'OK',
+					'post_name'    => 'bad',
+					'post_content' => 'bad',
+				),
+			)
+		);
+		$this->_last_response = '';
+		$this->make_ajax_call( 'customize-nav-menus-insert-auto-draft' );
+		$response = json_decode( $this->_last_response, true );
+		$this->assertFalse( $response['success'] );
+		$this->assertSame( 'illegal_params', $response['data'] );
+	}
+}

+ 158 - 0
tests/phpunit/tests/ajax/DeletePlugin.php

@@ -0,0 +1,158 @@
+<?php
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Ajax handler for deleting a plugin.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_Delete_Plugin extends WP_Ajax_UnitTestCase {
+
+	public function test_missing_nonce() {
+		$this->expectException( 'WPAjaxDieStopException' );
+		$this->expectExceptionMessage( '-1' );
+		$this->_handleAjax( 'delete-plugin' );
+	}
+
+	public function test_missing_plugin() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'delete-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'slug'         => '',
+				'errorCode'    => 'no_plugin_specified',
+				'errorMessage' => 'No plugin specified.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_missing_slug() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'foo/bar.php';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'delete-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'slug'         => '',
+				'errorCode'    => 'no_plugin_specified',
+				'errorMessage' => 'No plugin specified.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_missing_capability() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'foo/bar.php';
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'delete-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'delete'       => 'plugin',
+				'slug'         => 'foo',
+				'errorMessage' => 'Sorry, you are not allowed to delete plugins for this site.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_invalid_file() {
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = '../foo/bar.php';
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'delete-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'delete'       => 'plugin',
+				'slug'         => 'foo',
+				'errorMessage' => 'Sorry, you are not allowed to delete plugins for this site.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_delete_plugin() {
+		$this->skipWithMultisite();
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'foo.php';
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'delete-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => true,
+			'data'    => array(
+				'delete'     => 'plugin',
+				'slug'       => 'foo',
+				'plugin'     => 'foo.php',
+				'pluginName' => '',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+}

+ 173 - 0
tests/phpunit/tests/ajax/ManageThemes.php

@@ -0,0 +1,173 @@
+<?php
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Ajax handler for instlaling, updating, and deleting themes.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_Manage_Themes extends WP_Ajax_UnitTestCase {
+	private $orig_theme_dir;
+	private $theme_root;
+
+	function setUp() {
+		parent::setUp();
+
+		$this->theme_root     = DIR_TESTDATA . '/themedir1';
+		$this->orig_theme_dir = $GLOBALS['wp_theme_directories'];
+
+		// /themes is necessary as theme.php functions assume /themes is the root if there is only one root.
+		$GLOBALS['wp_theme_directories'] = array( WP_CONTENT_DIR . '/themes', $this->theme_root );
+
+		add_filter( 'theme_root', array( $this, 'filter_theme_root' ) );
+		add_filter( 'stylesheet_root', array( $this, 'filter_theme_root' ) );
+		add_filter( 'template_root', array( $this, 'filter_theme_root' ) );
+
+		wp_clean_themes_cache();
+		unset( $GLOBALS['wp_themes'] );
+	}
+
+	function tearDown() {
+		$GLOBALS['wp_theme_directories'] = $this->orig_theme_dir;
+		remove_filter( 'theme_root', array( $this, 'filter_theme_root' ) );
+		remove_filter( 'stylesheet_root', array( $this, 'filter_theme_root' ) );
+		remove_filter( 'template_root', array( $this, 'filter_theme_root' ) );
+		wp_clean_themes_cache();
+		unset( $GLOBALS['wp_themes'] );
+
+		parent::tearDown();
+	}
+
+	/**
+	 * Replace the normal theme root dir with our pre-made test dir.
+	 */
+	public function filter_theme_root() {
+		return $this->theme_root;
+	}
+
+	public function test_missing_slug() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-theme' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'slug'         => '',
+				'errorCode'    => 'no_theme_specified',
+				'errorMessage' => 'No theme specified.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_missing_capability() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-theme' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'theme',
+				'slug'         => 'foo',
+				'oldVersion'   => '',
+				'newVersion'   => '',
+				'errorMessage' => 'Sorry, you are not allowed to update themes for this site.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_update_theme() {
+		$this->skipWithMultisite();
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['slug']        = 'twentyten';
+
+		// Make the request.
+		try {
+
+			// Prevent wp_update_themes() from running.
+			wp_installing( true );
+			$this->_handleAjax( 'update-theme' );
+			wp_installing( false );
+
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$theme    = wp_get_theme( 'twentyten' );
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'theme',
+				'slug'         => 'twentyten',
+				'oldVersion'   => $theme->get( 'Version' ),
+				'newVersion'   => '',
+				'debug'        => array( 'The theme is at the latest version.' ),
+				'errorMessage' => 'The theme is at the latest version.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	function test_uppercase_theme_slug() {
+		$this->skipWithMultisite();
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['slug']        = 'camelCase';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-theme' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'theme',
+				'slug'         => 'camelCase',
+				'oldVersion'   => '1.0',
+				'newVersion'   => '',
+				'debug'        => array( 'The theme is at the latest version.' ),
+				'errorMessage' => 'The theme is at the latest version.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+}

+ 839 - 0
tests/phpunit/tests/ajax/PrivacyErasePersonalData.php

@@ -0,0 +1,839 @@
+<?php
+/**
+ * Testing Ajax handler for erasing personal data.
+ *
+ * @package WordPress\UnitTests
+ * @since 5.2.0
+ */
+
+/**
+ * Tests_Ajax_PrivacyExportPersonalData class.
+ *
+ * @since 5.2.0
+ *
+ * @group ajax
+ * @group privacy
+ *
+ * @covers ::wp_ajax_wp_privacy_erase_personal_data
+ */
+class Tests_Ajax_PrivacyErasePersonalData extends WP_Ajax_UnitTestCase {
+
+	/**
+	 * User Request ID.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $request_id
+	 */
+	protected static $request_id;
+
+	/**
+	 * User Request Email.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $request_email
+	 */
+	protected static $request_email;
+
+	/**
+	 * Ajax Action.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $action
+	 */
+	protected static $action;
+
+	/**
+	 * Eraser Index.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $eraser
+	 */
+	protected static $eraser;
+
+	/**
+	 * Eraser Key.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $eraser_key
+	 */
+	protected static $eraser_key;
+
+	/**
+	 * Eraser Friendly Name.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $eraser_friendly_name
+	 */
+	protected static $eraser_friendly_name;
+
+	/**
+	 * Page Index.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $page
+	 */
+	protected static $page;
+
+	/**
+	 * Last response parsed.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var array $_last_response_parsed
+	 */
+	protected $_last_response_parsed;
+
+	/**
+	 * An array key in the test eraser to unset.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $key_to_unset
+	 */
+	protected $key_to_unset;
+
+	/**
+	 * A value to change the test eraser callback to.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $new_callback_value
+	 */
+	protected $new_callback_value;
+
+	/**
+	 * Create user erase request fixtures.
+	 *
+	 * @param WP_UnitTest_Factory $factory Factory.
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$request_email        = 'requester@example.com';
+		self::$request_id           = wp_create_user_request( self::$request_email, 'remove_personal_data' );
+		self::$action               = 'wp-privacy-erase-personal-data';
+		self::$eraser               = 1;
+		self::$eraser_key           = 'custom-eraser';
+		self::$eraser_friendly_name = 'Custom Eraser';
+		self::$page                 = 1;
+	}
+
+	/**
+	 * Register a custom personal data eraser.
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		$this->key_to_unset = '';
+
+		// Make sure the erasers response is not modified and avoid sending emails.
+		remove_all_filters( 'wp_privacy_personal_data_erasure_page' );
+		remove_all_actions( 'wp_privacy_personal_data_erased' );
+
+		// Only use our custom privacy personal data eraser.
+		remove_all_filters( 'wp_privacy_personal_data_erasers' );
+		add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_custom_personal_data_eraser' ) );
+
+		$this->_setRole( 'administrator' );
+		// `erase_others_personal_data` meta cap in Multisite installation is only granted to those with `manage_network` capability.
+		if ( is_multisite() ) {
+			grant_super_admin( get_current_user_id() );
+		}
+	}
+
+	/**
+	 * Clean up after each test method.
+	 */
+	public function tearDown() {
+		remove_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_custom_personal_data_eraser' ) );
+		$this->new_callback_value = '';
+
+		if ( is_multisite() ) {
+			revoke_super_admin( get_current_user_id() );
+		}
+
+		parent::tearDown();
+	}
+
+	/**
+	 * Helper method for changing the test eraser's callback function.
+	 *
+	 * @param string|array $callback New test eraser callback index value.
+	 */
+	protected function _set_eraser_callback( $callback ) {
+		$this->new_callback_value = $callback;
+		add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'filter_eraser_callback_value' ), 20 );
+	}
+
+	/**
+	 * Change the test eraser callback to a specified value.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $erasers List of data erasers.
+	 *
+	 * @return array Array of data erasers.
+	 */
+	public function filter_eraser_callback_value( $erasers ) {
+		$erasers[ self::$eraser_key ]['callback'] = $this->new_callback_value;
+
+		return $erasers;
+	}
+
+	/**
+	 * Helper method for unsetting an array index in the test eraser.
+	 *
+	 * @param string|bool $key Test eraser key to unset.
+	 */
+	protected function _unset_eraser_key( $key ) {
+		$this->key_to_unset = $key;
+		add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'filter_unset_eraser_index' ), 20 );
+	}
+
+	/**
+	 * Unsets an array key in the test eraser.
+	 *
+	 * If the key is false, the eraser is set to false.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $erasers Erasers.
+	 *
+	 * @return array Erasers.
+	 */
+	public function filter_unset_eraser_index( $erasers ) {
+		if ( false === $this->key_to_unset ) {
+			$erasers[ self::$eraser_key ] = false;
+		} elseif ( ! empty( $this->key_to_unset ) ) {
+			unset( $erasers[ self::$eraser_key ][ $this->key_to_unset ] );
+		}
+
+		return $erasers;
+	}
+
+	/**
+	 * Helper method for erasing a key from the eraser response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $key Response key to unset.
+	 */
+	protected function _unset_response_key( $key ) {
+		$this->key_to_unset = $key;
+		$this->_set_eraser_callback( array( $this, 'filter_unset_response_index' ) );
+	}
+
+	/**
+	 * Unsets an array index in a response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 *
+	 * @return array Export data.
+	 */
+	public function filter_unset_response_index( $email_address, $page = 1 ) {
+		$response = $this->callback_personal_data_eraser( $email_address, $page );
+
+		if ( ! empty( $this->key_to_unset ) ) {
+			unset( $response[ $this->key_to_unset ] );
+		}
+
+		return $response;
+	}
+
+	/**
+	 * The function should send an error when the request ID is missing.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @ticket 43438
+	 */
+	public function test_error_when_missing_request_id() {
+		$this->assertNotWPError( self::$request_id );
+
+		// Set up a request.
+		$this->_make_ajax_call(
+			array(
+				'id' => null, // Missing request ID.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing request ID.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the request ID is less than 1.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @ticket 43438
+	 */
+	public function test_error_when_request_id_invalid() {
+		$this->assertNotWPError( self::$request_id );
+
+		// Set up a request.
+		$this->_make_ajax_call(
+			array(
+				'id' => -1, // Invalid request ID.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Invalid request ID.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the current user is missing required capabilities.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @ticket 43438
+	 */
+	public function test_error_when_current_user_missing_required_capabilities() {
+		$this->_setRole( 'author' );
+
+		$this->assertFalse( current_user_can( 'erase_others_personal_data' ) );
+		$this->assertFalse( current_user_can( 'delete_users' ) );
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Sorry, you are not allowed to perform this action.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * Test requests do not succeed on multisite when the current user is not a network admin.
+	 *
+	 * @ticket 43438
+	 * @group multisite
+	 * @group ms-required
+	 */
+	public function test_error_when_current_user_missing_required_capabilities_multisite() {
+		revoke_super_admin( get_current_user_id() );
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Sorry, you are not allowed to perform this action.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the nonce does not validate.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_failure_with_invalid_nonce() {
+		$this->expectException( 'WPAjaxDieStopException' );
+		$this->expectExceptionMessage( '-1' );
+
+		$this->_make_ajax_call(
+			array(
+				'security' => 'invalid-nonce',
+			)
+		);
+	}
+
+	/**
+	 * The function should send an error when the request type is incorrect.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_incorrect_request_type() {
+		$request_id = wp_create_user_request(
+			'export-request@example.com',
+			'export_personal_data' // Incorrect request type, expects 'remove_personal_data'.
+		);
+
+		$this->_make_ajax_call(
+			array(
+				'security' => wp_create_nonce( 'wp-privacy-erase-personal-data-' . $request_id ),
+				'id'       => $request_id,
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Invalid request type.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the request email is invalid.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_invalid_email() {
+		wp_update_post(
+			array(
+				'ID'         => self::$request_id,
+				'post_title' => '', // Invalid requester's email address.
+			)
+		);
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Invalid email address in request.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the eraser index is missing.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_missing_eraser_index() {
+		$this->_make_ajax_call(
+			array(
+				'eraser' => null, // Missing eraser index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing eraser index.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the page index is missing.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_missing_page_index() {
+		$this->_make_ajax_call(
+			array(
+				'page' => null, // Missing page index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing page index.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the eraser index is negative.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_negative_eraser_index() {
+		$this->_make_ajax_call(
+			array(
+				'eraser' => -1, // Negative eraser index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Eraser index cannot be less than one.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the eraser index is out of range.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_index_out_of_range() {
+		$this->_make_ajax_call(
+			array(
+				'eraser' => PHP_INT_MAX, // Out of range eraser index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Eraser index is out of range.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the page index is less than one.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_page_index_less_than_one() {
+		$this->_make_ajax_call(
+			array(
+				'page' => 0, // Page index less than one.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Page index cannot be less than one.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when an eraser is not an array.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_not_array() {
+		$this->_unset_eraser_key( false );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected an array describing the eraser at index %s.',
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an eraser is missing a friendly name.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_missing_friendly_name() {
+		$this->_unset_eraser_key( 'eraser_friendly_name' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Eraser array at index %s does not include a friendly name.',
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an eraser is missing a callback.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_missing_callback() {
+		$this->_unset_eraser_key( 'callback' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Eraser does not include a callback: %s.',
+				self::$eraser_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an eraser, at a given index, has an invalid callback.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_index_invalid_callback() {
+		$this->_set_eraser_callback( false );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Eraser callback is not valid: %s.',
+				self::$eraser_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an eraser, at a given index, is missing an array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_index_invalid_response() {
+		$this->_set_eraser_callback( '__return_null' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Did not receive array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when missing an items_removed index.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_items_removed_missing() {
+		$this->_unset_response_key( 'items_removed' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected items_removed key in response array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when missing an items_retained index.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_items_retained_missing() {
+		$this->_unset_response_key( 'items_retained' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected items_retained key in response array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when missing a messages index.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_messages_missing() {
+		$this->_unset_response_key( 'messages' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected messages key in response array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when the messages index is not an array.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_messages_not_array() {
+		$this->_set_eraser_callback( array( $this, 'filter_response_messages_invalid' ) );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected messages key to reference an array in response array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * Change the messages index to an invalid value (not an array).
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 *
+	 * @return array Export data.
+	 */
+	public function filter_response_messages_invalid( $email_address, $page = 1 ) {
+		$response             = $this->callback_personal_data_eraser( $email_address, $page );
+		$response['messages'] = true;
+
+		return $response;
+	}
+
+	/**
+	 * The function should send an error when an eraser is missing 'done' in array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_eraser_missing_done_response() {
+		$this->_unset_response_key( 'done' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected done flag in response array from %1$s eraser (index %2$d).',
+				self::$eraser_friendly_name,
+				self::$eraser
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should successfully send erasers response data when the current user has the required
+	 * capabilities.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @ticket 43438
+	 */
+	public function test_success_when_current_user_has_required_capabilities() {
+		$this->assertTrue( current_user_can( 'erase_others_personal_data' ) );
+		$this->assertTrue( current_user_can( 'delete_users' ) );
+
+		$this->_make_ajax_call();
+
+		$this->assertSame(
+			sprintf( 'A message regarding retained data for %s.', self::$request_email ),
+			$this->_last_response_parsed['data']['messages'][0]
+		);
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertTrue( $this->_last_response_parsed['data']['items_removed'] );
+		$this->assertTrue( $this->_last_response_parsed['data']['items_retained'] );
+		$this->assertTrue( $this->_last_response_parsed['data']['done'] );
+	}
+
+	/**
+	 * The function should successfully send erasers response data when no items to erase.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @ticket 43438
+	 */
+	public function test_success_when_no_items_to_erase() {
+
+		$this->_make_ajax_call( array( 'page' => 2 ) );
+
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertFalse( $this->_last_response_parsed['data']['items_removed'] );
+		$this->assertFalse( $this->_last_response_parsed['data']['items_retained'] );
+		$this->assertEmpty( $this->_last_response_parsed['data']['messages'] );
+		$this->assertTrue( $this->_last_response_parsed['data']['done'] );
+	}
+
+	/**
+	 * Test that the function's output should be filterable with the `wp_privacy_personal_data_erasure_page` filter.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_output_should_be_filterable() {
+		add_filter( 'wp_privacy_personal_data_erasure_page', array( $this, 'filter_eraser_data_response' ), 20, 6 );
+		$this->_make_ajax_call();
+
+		$expected_new_index = self::$request_email . '-' . self::$request_id . '-' . self::$eraser_key;
+
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'filtered removed', $this->_last_response_parsed['data']['items_removed'] );
+		$this->assertSame( 'filtered retained', $this->_last_response_parsed['data']['items_retained'] );
+		$this->assertSame( array( 'filtered messages' ), $this->_last_response_parsed['data']['messages'] );
+		$this->assertSame( 'filtered done', $this->_last_response_parsed['data']['done'] );
+		$this->assertSame( $expected_new_index, $this->_last_response_parsed['data']['new_index'] );
+	}
+
+	/**
+	 * Filters the eraser response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array  $response        The personal data for the given eraser and page.
+	 * @param int    $eraser_index    The index of the eraser that provided this data.
+	 * @param string $email_address   The email address associated with this personal data.
+	 * @param int    $page            The page for this response.
+	 * @param int    $request_id      The privacy request post ID associated with this request.
+	 * @param string $eraser_key      The key (slug) of the eraser that provided this data.
+	 *
+	 * @return array Filtered erase response.
+	 */
+	public function filter_eraser_data_response( $response, $eraser_index, $email_address, $page, $request_id, $eraser_key ) {
+		$response['items_removed']  = 'filtered removed';
+		$response['items_retained'] = 'filtered retained';
+		$response['messages']       = array( 'filtered messages' );
+		$response['done']           = 'filtered done';
+		$response['new_index']      = $email_address . '-' . $request_id . '-' . $eraser_key;
+
+		return $response;
+	}
+
+	/**
+	 * Register handler for a custom personal data eraser.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $erasers An array of personal data erasers.
+	 *
+	 * @return array An array of personal data erasers.
+	 */
+	public function register_custom_personal_data_eraser( $erasers ) {
+		$erasers[ self::$eraser_key ] = array(
+			'eraser_friendly_name' => self::$eraser_friendly_name,
+			'callback'             => array( $this, 'callback_personal_data_eraser' ),
+		);
+		return $erasers;
+	}
+
+	/**
+	 * Custom Personal Data Eraser.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param  string $email_address The comment author email address.
+	 * @param  int    $page          Page number.
+	 *
+	 * @return array Erase data.
+	 */
+	public function callback_personal_data_eraser( $email_address, $page = 1 ) {
+		if ( 1 === $page ) {
+			return array(
+				'items_removed'  => true,
+				'items_retained' => true,
+				'messages'       => array( sprintf( 'A message regarding retained data for %s.', $email_address ) ),
+				'done'           => true,
+			);
+		}
+
+		return array(
+			'items_removed'  => false,
+			'items_retained' => false,
+			'messages'       => array(),
+			'done'           => true,
+		);
+	}
+
+	/**
+	 * Helper function for Ajax handler.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $args Ajax request arguments.
+	 */
+	protected function _make_ajax_call( $args = array() ) {
+		$this->_last_response_parsed = null;
+		$this->_last_response        = '';
+
+		$defaults = array(
+			'action'   => self::$action,
+			'security' => wp_create_nonce( self::$action . '-' . self::$request_id ),
+			'page'     => self::$page,
+			'id'       => self::$request_id,
+			'eraser'   => self::$eraser,
+		);
+
+		$_POST = wp_parse_args( $args, $defaults );
+
+		try {
+			$this->_handleAjax( self::$action );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		if ( $this->_last_response ) {
+			$this->_last_response_parsed = json_decode( $this->_last_response, true );
+		}
+	}
+}

+ 842 - 0
tests/phpunit/tests/ajax/PrivacyExportPersonalData.php

@@ -0,0 +1,842 @@
+<?php
+/**
+ * Testing Ajax handler for exporting personal data.
+ *
+ * @package WordPress\UnitTests
+ * @since 5.2.0
+ */
+
+/**
+ * Tests_Ajax_PrivacyExportPersonalData class.
+ *
+ * @since 5.2.0
+ *
+ * @group ajax
+ * @group privacy
+ *
+ * @covers ::wp_ajax_wp_privacy_export_personal_data
+ */
+class Tests_Ajax_PrivacyExportPersonalData extends WP_Ajax_UnitTestCase {
+
+	/**
+	 * User Request ID.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $request_id
+	 */
+	protected static $request_id;
+
+	/**
+	 * User Request Email.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $request_email
+	 */
+	protected static $request_email;
+
+	/**
+	 * Ajax Action.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $action
+	 */
+	protected static $action;
+
+	/**
+	 * Exporter Index.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $exporter
+	 */
+	protected static $exporter;
+
+	/**
+	 * Exporter Key.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $exporter_key
+	 */
+	protected static $exporter_key;
+
+	/**
+	 * Exporter Friendly Name.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $exporter_friendly_name
+	 */
+	protected static $exporter_friendly_name;
+
+	/**
+	 * Page Index.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var int $page
+	 */
+	protected static $page;
+
+	/**
+	 * Send As Email.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var bool $send_as_email
+	 */
+	protected static $send_as_email;
+
+	/**
+	 * Last response parsed.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var array $_last_response_parsed
+	 */
+	protected $_last_response_parsed;
+
+	/**
+	 * An array key in the test exporter to unset.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $key_to_unset
+	 */
+	protected $key_to_unset;
+
+	/**
+	 * A value to change the test exporter callback to.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @var string $new_callback_value
+	 */
+	protected $new_callback_value;
+
+	/**
+	 * Create user export request fixtures.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param WP_UnitTest_Factory $factory Factory.
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$request_email          = 'requester@example.com';
+		self::$request_id             = wp_create_user_request( self::$request_email, 'export_personal_data' );
+		self::$action                 = 'wp-privacy-export-personal-data';
+		self::$exporter               = 1;
+		self::$exporter_key           = 'custom-exporter';
+		self::$exporter_friendly_name = 'Custom Exporter';
+		self::$page                   = 1;
+		self::$send_as_email          = false;
+	}
+
+	/**
+	 * Setup before each test method.
+	 *
+	 * @since 5.2.0
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		$this->key_to_unset       = '';
+		$this->new_callback_value = '';
+
+		// Make sure the exporter response is not modified and avoid e.g. writing export file to disk.
+		remove_all_filters( 'wp_privacy_personal_data_export_page' );
+
+		// Only use our custom privacy personal data exporter.
+		remove_all_filters( 'wp_privacy_personal_data_exporters' );
+		add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'filter_register_custom_personal_data_exporter' ) );
+
+		$this->_setRole( 'administrator' );
+		// `export_others_personal_data` meta cap in Multisite installation is only granted to those with `manage_network` capability.
+		if ( is_multisite() ) {
+			grant_super_admin( get_current_user_id() );
+		}
+	}
+
+	/**
+	 * Clean up after each test method.
+	 */
+	public function tearDown() {
+		remove_filter( 'wp_privacy_personal_data_exporters', array( $this, 'filter_register_custom_personal_data_exporter' ) );
+
+		if ( is_multisite() ) {
+			revoke_super_admin( get_current_user_id() );
+		}
+		parent::tearDown();
+	}
+
+	/**
+	 * Helper method for changing the test exporter's callback function.
+	 *
+	 * @param string|array $callback New test exporter callback function.
+	 */
+	protected function _set_exporter_callback( $callback ) {
+		$this->new_callback_value = $callback;
+		add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'filter_exporter_callback_value' ), 20 );
+	}
+
+	/**
+	 * Change the test exporter callback to a specified value.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $exporters List of data exporters.
+	 * @return array List of data exporters.
+	 */
+	public function filter_exporter_callback_value( $exporters ) {
+		$exporters[ self::$exporter_key ]['callback'] = $this->new_callback_value;
+
+		return $exporters;
+	}
+
+	/**
+	 * Helper method for unsetting an array index in the test exporter.
+	 *
+	 * @param string $key Test exporter key to unset.
+	 */
+	protected function _unset_exporter_key( $key ) {
+		$this->key_to_unset = $key;
+		add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'filter_unset_exporter_key' ), 20 );
+	}
+
+	/**
+	 * Unset a specified key in the test exporter array.
+	 *
+	 * @param array $exporters List of data exporters.
+	 *
+	 * @return array List of data exporters.
+	 */
+	public function filter_unset_exporter_key( $exporters ) {
+		if ( false === $this->key_to_unset ) {
+			$exporters[ self::$exporter_key ] = false;
+		} elseif ( ! empty( $this->key_to_unset ) ) {
+			unset( $exporters[ self::$exporter_key ][ $this->key_to_unset ] );
+		}
+
+		return $exporters;
+	}
+
+	/**
+	 * The function should send an error when the request ID is missing.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_missing_request_id() {
+		$this->_make_ajax_call(
+			array(
+				'id' => null, // Missing request ID.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing request ID.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the request ID is less than 1.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_invalid_id() {
+		$this->_make_ajax_call(
+			array(
+				'id' => -1, // Invalid request ID, less than 1.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Invalid request ID.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the current user is missing the required capability.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_current_user_missing_required_capability() {
+		$this->_setRole( 'author' );
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertFalse( current_user_can( 'export_others_personal_data' ) );
+		$this->assertSame( 'Sorry, you are not allowed to perform this action.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * Test requests do not succeed on multisite when the current user is not a network admin.
+	 *
+	 * @ticket 43438
+	 * @group multisite
+	 * @group ms-required
+	 */
+	public function test_error_when_current_user_missing_required_capability_multisite() {
+		revoke_super_admin( get_current_user_id() );
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Sorry, you are not allowed to perform this action.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the nonce does not validate.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_failure_with_invalid_nonce() {
+		$this->expectException( 'WPAjaxDieStopException' );
+		$this->expectExceptionMessage( '-1' );
+
+		$this->_make_ajax_call(
+			array(
+				'security' => 'invalid-nonce',
+			)
+		);
+	}
+
+	/**
+	 * The function should send an error when the request type is incorrect.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_incorrect_request_type() {
+		$request_id = wp_create_user_request(
+			'erase-request@example.com',
+			'remove_personal_data' // Incorrect request type, expects 'export_personal_data'.
+		);
+
+		$this->_make_ajax_call(
+			array(
+				'security' => wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ),
+				'id'       => $request_id,
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Invalid request type.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the requester's email address is invalid.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_invalid_email_address() {
+		wp_update_post(
+			array(
+				'ID'         => self::$request_id,
+				'post_title' => '', // Invalid requester's email address.
+			)
+		);
+
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'A valid email address must be given.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the exporter index is missing.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_missing_exporter_index() {
+		$this->_make_ajax_call(
+			array(
+				'exporter' => null, // Missing exporter index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing exporter index.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the page index is missing.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_missing_page_index() {
+		$this->_make_ajax_call(
+			array(
+				'page' => null, // Missing page index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Missing page index.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when an exporter has improperly used the `wp_privacy_personal_data_exporters` filter.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_has_improperly_used_exporters_filter() {
+		// Improper filter usage: returns false instead of an expected array.
+		add_filter( 'wp_privacy_personal_data_exporters', '__return_false', 999 );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'An exporter has improperly used the registration filter.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the exporter index is negative.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_negative_exporter_index() {
+		$this->_make_ajax_call(
+			array(
+				'exporter' => -1, // Negative exporter index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Exporter index cannot be negative.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the exporter index is out of range.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_index_out_of_range() {
+		$this->_make_ajax_call(
+			array(
+				'exporter' => PHP_INT_MAX, // Out of range exporter index.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Exporter index is out of range.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when the page index is less than one.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_page_index_less_than_one() {
+		$this->_make_ajax_call(
+			array(
+				'page' => 0, // Page index less than one.
+			)
+		);
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'Page index cannot be less than one.', $this->_last_response_parsed['data'] );
+	}
+
+	/**
+	 * The function should send an error when an exporter is not an array.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_not_array() {
+		$this->_unset_exporter_key( false );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected an array describing the exporter at index %s.',
+				self::$exporter_key
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an exporter is missing a friendly name.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_missing_friendly_name() {
+		$this->_unset_exporter_key( 'exporter_friendly_name' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Exporter array at index %s does not include a friendly name.',
+				self::$exporter_key
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an exporter is missing a callback.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_missing_callback() {
+		$this->_unset_exporter_key( 'callback' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Exporter does not include a callback: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an exporter, at a given index, has an invalid callback.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_index_invalid_callback() {
+		$this->_set_exporter_callback( false );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Exporter callback is not a valid callback: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * When an exporter callback returns a WP_Error, it should be passed as the error.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_callback_returns_wp_error() {
+		$this->_set_exporter_callback( array( $this, 'callback_return_wp_error' ) );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'passed_message', $this->_last_response_parsed['data'][0]['code'] );
+		$this->assertSame( 'This is a WP_Error message.', $this->_last_response_parsed['data'][0]['message'] );
+	}
+
+	/**
+	 * Callback for exporter's response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 * @return WP_Error WP_Error instance.
+	 */
+	public function callback_return_wp_error( $email_address, $page = 1 ) {
+		return new WP_Error( 'passed_message', 'This is a WP_Error message.' );
+	}
+
+	/**
+	 * The function should send an error when an exporter, at a given index, is missing an array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_index_invalid_response() {
+		$this->_set_exporter_callback( '__return_null' );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected response as an array from exporter: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * The function should send an error when an exporter is missing data in array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_missing_data_response() {
+		$this->_set_exporter_callback( array( $this, 'callback_missing_data_response' ) );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected data in response array from exporter: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * Callback for exporter's response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 *
+	 * @return array Export data.
+	 */
+	public function callback_missing_data_response( $email_address, $page = 1 ) {
+		$response = $this->callback_custom_personal_data_exporter( $email_address, $page );
+		unset( $response['data'] ); // Missing data part of response.
+
+		return $response;
+	}
+
+	/**
+	 * The function should send an error when an exporter is missing 'data' array in array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_function_should_error_when_exporter_missing_data_array_response() {
+		$this->_set_exporter_callback( array( $this, 'callback_missing_data_array_response' ) );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected data array in response array from exporter: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * Callback for exporter's response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param  string $email_address The requester's email address.
+	 * @param  int    $page          Page number.
+	 *
+	 * @return array Export data.
+	 */
+	public function callback_missing_data_array_response( $email_address, $page = 1 ) {
+		$response         = $this->callback_custom_personal_data_exporter( $email_address, $page );
+		$response['data'] = false; // Not an array.
+		return $response;
+	}
+
+	/**
+	 * The function should send an error when an exporter is missing 'done' in array response.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_error_when_exporter_missing_done_response() {
+		$this->_set_exporter_callback( array( $this, 'callback_missing_done_response' ) );
+		$this->_make_ajax_call();
+
+		$this->assertFalse( $this->_last_response_parsed['success'] );
+		$this->assertSame(
+			sprintf(
+				'Expected done (boolean) in response array from exporter: %s.',
+				self::$exporter_friendly_name
+			),
+			$this->_last_response_parsed['data']
+		);
+	}
+
+	/**
+	 * Remove the response's done flag.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 *
+	 * @return array Export data.
+	 */
+	public function callback_missing_done_response( $email_address, $page = 1 ) {
+		$response = $this->callback_custom_personal_data_exporter( $email_address, $page );
+		unset( $response['done'] );
+
+		return $response;
+	}
+
+	/**
+	 * The function should successfully send exporter data response when the current user has the required capability.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_succeeds_when_current_user_has_required_capability() {
+		$this->assertTrue( current_user_can( 'export_others_personal_data' ) );
+
+		$this->_make_ajax_call();
+
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( 'custom-exporter-item-id', $this->_last_response_parsed['data']['data']['item_id'] );
+		$this->assertSame( 'Email', $this->_last_response_parsed['data']['data']['data'][0]['name'] );
+		$this->assertSame( self::$request_email, $this->_last_response_parsed['data']['data']['data'][0]['value'] );
+	}
+
+	/**
+	 * The function should successfully send exporter data response when no items to export.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_success_when_no_items_to_export() {
+
+		$this->_make_ajax_call( array( 'page' => 2 ) );
+
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertEmpty( $this->_last_response_parsed['data']['data'] );
+		$this->assertTrue( $this->_last_response_parsed['data']['done'] );
+	}
+
+	/**
+	 * The function's output should be filterable with the `wp_privacy_personal_data_export_page` filter.
+	 *
+	 * @since 5.2.0
+	 */
+	public function test_output_should_be_filterable() {
+		add_filter( 'wp_privacy_personal_data_export_page', array( $this, 'filter_exporter_data_response' ), 20, 7 );
+		$this->_make_ajax_call();
+
+		$expected_group_label = sprintf(
+			'%s-%s-%s-%s-%s-%s',
+			self::$exporter,
+			self::$page,
+			self::$request_email,
+			self::$request_id,
+			self::$send_as_email,
+			self::$exporter_key
+		);
+
+		$this->assertTrue( $this->_last_response_parsed['success'] );
+		$this->assertSame( $expected_group_label, $this->_last_response_parsed['data']['group_label'] );
+		$this->assertSame( 'filtered_group_id', $this->_last_response_parsed['data']['group_id'] );
+		$this->assertSame( 'filtered_item_id', $this->_last_response_parsed['data']['item_id'] );
+		$this->assertSame( 'filtered_name', $this->_last_response_parsed['data']['data'][0]['name'] );
+		$this->assertSame( 'filtered_value', $this->_last_response_parsed['data']['data'][0]['value'] );
+	}
+
+	/**
+	 * Filter exporter's data response.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array  $response        The personal data for the given exporter and page.
+	 * @param int    $exporter_index  The index of the exporter that provided this data.
+	 * @param string $email_address   The email address associated with this personal data.
+	 * @param int    $page            The page for this response.
+	 * @param int    $request_id      The privacy request post ID associated with this request.
+	 * @param bool   $send_as_email   Whether the final results of the export should be emailed to the user.
+	 * @param string $exporter_key    The key (slug) of the exporter that provided this data.
+	 *
+	 * @return array The personal data for the given exporter and page.
+	 */
+	public function filter_exporter_data_response( $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key ) {
+		$group_label                  = sprintf(
+			'%s-%s-%s-%s-%s-%s',
+			$exporter_index,
+			$page,
+			$email_address,
+			$request_id,
+			$send_as_email,
+			$exporter_key
+		);
+		$response['group_label']      = $group_label;
+		$response['group_id']         = 'filtered_group_id';
+		$response['item_id']          = 'filtered_item_id';
+		$response['data'][0]['name']  = 'filtered_name';
+		$response['data'][0]['value'] = 'filtered_value';
+
+		return $response;
+	}
+
+	/**
+	 * Filter to register a custom personal data exporter.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $exporters An array of personal data exporters.
+	 *
+	 * @return array An array of personal data exporters.
+	 */
+	public function filter_register_custom_personal_data_exporter( $exporters ) {
+		$exporters[ self::$exporter_key ] = array(
+			'exporter_friendly_name' => self::$exporter_friendly_name,
+			'callback'               => array( $this, 'callback_custom_personal_data_exporter' ),
+		);
+		return $exporters;
+	}
+
+	/**
+	 * Callback for a custom personal data exporter.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param string $email_address The requester's email address.
+	 * @param int    $page          Page number.
+	 *
+	 * @return array Export data response.
+	 */
+	public function callback_custom_personal_data_exporter( $email_address, $page = 1 ) {
+		$data_to_export = array();
+
+		if ( 1 === $page ) {
+			$data_to_export = array(
+				'group_id'    => self::$exporter_key . '-group-id',
+				'group_label' => self::$exporter_key . '-group-label',
+				'item_id'     => self::$exporter_key . '-item-id',
+				'data'        => array(
+					array(
+						'name'  => 'Email',
+						'value' => $email_address,
+					),
+				),
+			);
+		}
+
+		return array(
+			'data' => $data_to_export,
+			'done' => true,
+		);
+	}
+
+	/**
+	 * Helper function for Ajax handler.
+	 *
+	 * @since 5.2.0
+	 *
+	 * @param array $args Ajax request arguments.
+	 */
+	protected function _make_ajax_call( $args = array() ) {
+		$this->_last_response_parsed = null;
+		$this->_last_response        = '';
+
+		$defaults = array(
+			'action'      => self::$action,
+			'security'    => wp_create_nonce( self::$action . '-' . self::$request_id ),
+			'exporter'    => self::$exporter,
+			'page'        => self::$page,
+			'sendAsEmail' => self::$send_as_email,
+			'id'          => self::$request_id,
+		);
+
+		$_POST = wp_parse_args( $args, $defaults );
+
+		try {
+			$this->_handleAjax( self::$action );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		if ( $this->_last_response ) {
+			$this->_last_response_parsed = json_decode( $this->_last_response, true );
+		}
+	}
+}

+ 86 - 0
tests/phpunit/tests/ajax/QuickEdit.php

@@ -0,0 +1,86 @@
+<?php
+
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Quick Edit AJAX functionality.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_QuickEdit extends WP_Ajax_UnitTestCase {
+
+	/**
+	 * @ticket 26948
+	 */
+	public function test_dont_process_terms_if_taxonomy_does_not_allow_show_on_quick_edit() {
+		register_taxonomy(
+			'wptests_tax_1',
+			'post',
+			array(
+				'show_in_quick_edit' => false,
+				'hierarchical'       => true,
+			)
+		);
+		register_taxonomy(
+			'wptests_tax_2',
+			'post',
+			array(
+				'show_in_quick_edit' => true,
+				'hierarchical'       => true,
+			)
+		);
+
+		$t1 = self::factory()->term->create(
+			array(
+				'taxonomy' => 'wptests_tax_1',
+			)
+		);
+		$t2 = self::factory()->term->create(
+			array(
+				'taxonomy' => 'wptests_tax_2',
+			)
+		);
+
+		// Become an administrator.
+		$this->_setRole( 'administrator' );
+
+		$post = self::factory()->post->create_and_get(
+			array(
+				'post_author' => get_current_user_id(),
+			)
+		);
+
+		// Set up a request.
+		$_POST['_inline_edit'] = wp_create_nonce( 'inlineeditnonce' );
+		$_POST['post_ID']      = $post->ID;
+		$_POST['post_type']    = $post->post_type;
+		$_POST['content']      = $post->post_content;
+		$_POST['excerpt']      = $post->post_excerpt;
+		$_POST['_status']      = $post->post_status;
+		$_POST['post_status']  = $post->post_status;
+		$_POST['screen']       = 'post';
+		$_POST['post_view']    = 'excerpt';
+		$_POST['tax_input']    = array(
+			'wptests_tax_1' => array( $t1 ),
+			'wptests_tax_2' => array( $t2 ),
+		);
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'inline-save' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// 'wptests_tax_1' terms should have been refused.
+		$post_terms_1 = wp_get_object_terms( $post->ID, 'wptests_tax_1' );
+		$this->assertEmpty( $post_terms_1 );
+
+		// 'wptests_tax_2' terms should have been added successfully.
+		$post_terms_2 = wp_get_object_terms( $post->ID, 'wptests_tax_2' );
+		$this->assertSameSets( array( $t2 ), wp_list_pluck( $post_terms_2, 'term_id' ) );
+	}
+}

+ 169 - 0
tests/phpunit/tests/ajax/UpdatePlugin.php

@@ -0,0 +1,169 @@
+<?php
+/**
+ * Admin Ajax functions to be tested.
+ */
+require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';
+
+/**
+ * Testing Ajax handler for updating a plugin.
+ *
+ * @group ajax
+ */
+class Tests_Ajax_Update_Plugin extends WP_Ajax_UnitTestCase {
+
+	public function test_missing_nonce() {
+		$this->expectException( 'WPAjaxDieStopException' );
+		$this->expectExceptionMessage( '-1' );
+		$this->_handleAjax( 'update-plugin' );
+	}
+
+	public function test_missing_plugin() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'slug'         => '',
+				'errorCode'    => 'no_plugin_specified',
+				'errorMessage' => 'No plugin specified.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_missing_slug() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'foo/bar.php';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'slug'         => '',
+				'errorCode'    => 'no_plugin_specified',
+				'errorMessage' => 'No plugin specified.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_missing_capability() {
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'foo/bar.php';
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'plugin',
+				'slug'         => 'foo',
+				'oldVersion'   => '',
+				'newVersion'   => '',
+				'errorMessage' => 'Sorry, you are not allowed to update plugins for this site.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_invalid_file() {
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = '../foo/bar.php';
+		$_POST['slug']        = 'foo';
+
+		// Make the request.
+		try {
+			$this->_handleAjax( 'update-plugin' );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'plugin',
+				'slug'         => 'foo',
+				'oldVersion'   => '',
+				'newVersion'   => '',
+				'errorMessage' => 'Sorry, you are not allowed to update plugins for this site.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+
+	public function test_update_plugin() {
+		$this->skipWithMultisite();
+		$this->_setRole( 'administrator' );
+
+		$_POST['_ajax_nonce'] = wp_create_nonce( 'updates' );
+		$_POST['plugin']      = 'hello.php';
+		$_POST['slug']        = 'hello-dolly';
+
+		// Make the request.
+		try {
+			// Prevent wp_update_plugins() from running.
+			wp_installing( true );
+			$this->_handleAjax( 'update-plugin' );
+			wp_installing( false );
+		} catch ( WPAjaxDieContinueException $e ) {
+			unset( $e );
+		}
+
+		// Get the response.
+		$response = json_decode( $this->_last_response, true );
+
+		$expected = array(
+			'success' => false,
+			'data'    => array(
+				'update'       => 'plugin',
+				'slug'         => 'hello-dolly',
+				'oldVersion'   => 'Version 1.7.2',
+				'newVersion'   => '',
+				'plugin'       => 'hello.php',
+				'pluginName'   => 'Hello Dolly',
+				'debug'        => array( 'The plugin is at the latest version.' ),
+				'errorMessage' => 'The plugin is at the latest version.',
+			),
+		);
+
+		$this->assertSameSets( $expected, $response );
+	}
+}

+ 283 - 0
tests/phpunit/tests/avatar.php

@@ -0,0 +1,283 @@
+<?php
+
+/**
+ * Test avatar related functions
+ *
+ * @group avatar
+ */
+class Tests_Avatar extends WP_UnitTestCase {
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_gravatar_url() {
+		$url = get_avatar_url( 1 );
+		$this->assertSame( preg_match( '|^http?://[0-9]+.gravatar.com/avatar/[0-9a-f]{32}\?|', $url ), 1 );
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_size() {
+		$url = get_avatar_url( 1 );
+		$this->assertSame( preg_match( '|\?.*s=96|', $url ), 1 );
+
+		$args = array( 'size' => 100 );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|\?.*s=100|', $url ), 1 );
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_default() {
+		$url = get_avatar_url( 1 );
+		$this->assertSame( preg_match( '|\?.*d=mm|', $url ), 1 );
+
+		$args = array( 'default' => 'wavatar' );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|\?.*d=wavatar|', $url ), 1 );
+
+		$this->assertSame( preg_match( '|\?.*f=y|', $url ), 0 );
+		$args = array( 'force_default' => true );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|\?.*f=y|', $url ), 1 );
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_rating() {
+		$url = get_avatar_url( 1 );
+		$this->assertSame( preg_match( '|\?.*r=g|', $url ), 1 );
+
+		$args = array( 'rating' => 'M' );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|\?.*r=m|', $url ), 1 );
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_scheme() {
+		$url = get_avatar_url( 1 );
+		$this->assertSame( preg_match( '|^http://|', $url ), 1 );
+
+		$args = array( 'scheme' => 'https' );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|^https://|', $url ), 1 );
+
+		$args = array( 'scheme' => 'lolcat' );
+		$url  = get_avatar_url( 1, $args );
+		$this->assertSame( preg_match( '|^lolcat://|', $url ), 0 );
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_user() {
+		$url = get_avatar_url( 1 );
+
+		$url2 = get_avatar_url( WP_TESTS_EMAIL );
+		$this->assertSame( $url, $url2 );
+
+		$url2 = get_avatar_url( md5( WP_TESTS_EMAIL ) . '@md5.gravatar.com' );
+		$this->assertSame( $url, $url2 );
+
+		$user = get_user_by( 'id', 1 );
+		$url2 = get_avatar_url( $user );
+		$this->assertSame( $url, $url2 );
+
+		$post_id = self::factory()->post->create( array( 'post_author' => 1 ) );
+		$post    = get_post( $post_id );
+		$url2    = get_avatar_url( $post );
+		$this->assertSame( $url, $url2 );
+
+		$comment_id = self::factory()->comment->create(
+			array(
+				'comment_post_ID' => $post_id,
+				'user_id'         => 1,
+			)
+		);
+		$comment    = get_comment( $comment_id );
+		$url2       = get_avatar_url( $comment );
+		$this->assertSame( $url, $url2 );
+	}
+
+	protected $fake_url;
+	/**
+	 * @ticket 21195
+	 */
+	public function test_pre_get_avatar_url_filter() {
+		$this->fake_url = 'haha wat';
+
+		add_filter( 'pre_get_avatar_data', array( $this, 'pre_get_avatar_url_filter' ), 10, 1 );
+		$url = get_avatar_url( 1 );
+		remove_filter( 'pre_get_avatar_data', array( $this, 'pre_get_avatar_url_filter' ), 10 );
+
+		$this->assertSame( $url, $this->fake_url );
+	}
+	public function pre_get_avatar_url_filter( $args ) {
+		$args['url'] = $this->fake_url;
+		return $args;
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_url_filter() {
+		$this->fake_url = 'omg lol';
+
+		add_filter( 'get_avatar_url', array( $this, 'get_avatar_url_filter' ), 10, 1 );
+		$url = get_avatar_url( 1 );
+		remove_filter( 'get_avatar_url', array( $this, 'get_avatar_url_filter' ), 10 );
+
+		$this->assertSame( $url, $this->fake_url );
+	}
+	public function get_avatar_url_filter( $url ) {
+		return $this->fake_url;
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_comment_types_filter() {
+		$url = get_avatar_url( 1 );
+
+		$post_id    = self::factory()->post->create( array( 'post_author' => 1 ) );
+		$comment_id = self::factory()->comment->create(
+			array(
+				'comment_post_ID' => $post_id,
+				'user_id'         => 1,
+				'comment_type'    => 'pingback',
+			)
+		);
+		$comment    = get_comment( $comment_id );
+
+		$url2 = get_avatar_url( $comment );
+		$this->assertFalse( $url2 );
+
+		add_filter( 'get_avatar_comment_types', array( $this, 'get_avatar_comment_types_filter' ), 10, 1 );
+		$url2 = get_avatar_url( $comment );
+		remove_filter( 'get_avatar_comment_types', array( $this, 'get_avatar_comment_types_filter' ), 10 );
+
+		$this->assertSame( $url, $url2 );
+	}
+	public function get_avatar_comment_types_filter( $comment_types ) {
+		$comment_types[] = 'pingback';
+		return $comment_types;
+	}
+
+	public function test_get_avatar() {
+		$img = get_avatar( 1 );
+		$this->assertSame( preg_match( "|^<img alt='[^']*' src='[^']*' srcset='[^']*' class='[^']*' height='[^']*' width='[^']*' loading='lazy'/>$|", $img ), 1 );
+	}
+
+	public function test_get_avatar_size() {
+		$size = '100';
+		$img  = get_avatar( 1, $size );
+		$this->assertSame( preg_match( "|^<img .*height='$size'.*width='$size'|", $img ), 1 );
+	}
+
+	public function test_get_avatar_alt() {
+		$alt = 'Mr Hyde';
+		$img = get_avatar( 1, 96, '', $alt );
+		$this->assertSame( preg_match( "|^<img alt='$alt'|", $img ), 1 );
+	}
+
+	public function test_get_avatar_class() {
+		$class = 'first';
+		$img   = get_avatar( 1, 96, '', '', array( 'class' => $class ) );
+		$this->assertSame( preg_match( "|^<img .*class='[^']*{$class}[^']*'|", $img ), 1 );
+	}
+
+	public function test_get_avatar_default_class() {
+		$img = get_avatar( 1, 96, '', '', array( 'force_default' => true ) );
+		$this->assertSame( preg_match( "|^<img .*class='[^']*avatar-default[^']*'|", $img ), 1 );
+	}
+
+	public function test_get_avatar_force_display() {
+		$old = get_option( 'show_avatars' );
+		update_option( 'show_avatars', false );
+
+		$this->assertFalse( get_avatar( 1 ) );
+
+		$this->assertNotEmpty( get_avatar( 1, 96, '', '', array( 'force_display' => true ) ) );
+
+		update_option( 'show_avatars', $old );
+	}
+
+
+	protected $fake_img;
+	/**
+	 * @ticket 21195
+	 */
+	public function test_pre_get_avatar_filter() {
+		$this->fake_img = 'YOU TOO?!';
+
+		add_filter( 'pre_get_avatar', array( $this, 'pre_get_avatar_filter' ), 10, 1 );
+		$img = get_avatar( 1 );
+		remove_filter( 'pre_get_avatar', array( $this, 'pre_get_avatar_filter' ), 10 );
+
+		$this->assertSame( $img, $this->fake_img );
+	}
+	public function pre_get_avatar_filter( $img ) {
+		return $this->fake_img;
+	}
+
+	/**
+	 * @ticket 21195
+	 */
+	public function test_get_avatar_filter() {
+		$this->fake_url = 'YA RLY';
+
+		add_filter( 'get_avatar', array( $this, 'get_avatar_filter' ), 10, 1 );
+		$img = get_avatar( 1 );
+		remove_filter( 'get_avatar', array( $this, 'get_avatar_filter' ), 10 );
+
+		$this->assertSame( $img, $this->fake_url );
+	}
+	public function get_avatar_filter( $img ) {
+		return $this->fake_url;
+	}
+
+	/**
+	 * The `get_avatar_data()` function should return gravatar url when comment type allowed to retrieve avatars.
+	 *
+	 * @ticket 44033
+	 */
+	public function test_get_avatar_data_should_return_gravatar_url_when_input_avatar_comment_type() {
+		$comment_type = 'comment';
+		$comment      = self::factory()->comment->create_and_get(
+			array(
+				'comment_author_email' => 'commenter@example.com',
+				'comment_type'         => $comment_type,
+			)
+		);
+
+		$actual_data = get_avatar_data( $comment );
+
+		$this->assertTrue( is_avatar_comment_type( $comment_type ) );
+		$this->assertRegexp( '|^http?://[0-9]+.gravatar.com/avatar/[0-9a-f]{32}\?|', $actual_data['url'] );
+	}
+
+	/**
+	 * The `get_avatar_data()` function should return invalid url when comment type not allowed to retrieve avatars.
+	 *
+	 * @ticket 44033
+	 */
+	public function test_get_avatar_data_should_return_invalid_url_when_input_not_avatar_comment_type() {
+		$comment_type = 'review';
+		$comment      = self::factory()->comment->create_and_get(
+			array(
+				'comment_author_email' => 'commenter@example.com',
+				'comment_type'         => $comment_type,
+			)
+		);
+
+		$actual_data = get_avatar_data( $comment );
+
+		$this->assertFalse( is_avatar_comment_type( $comment_type ) );
+		$this->assertFalse( $actual_data['url'] );
+	}
+
+}

+ 215 - 0
tests/phpunit/tests/blocks/block-context.php

@@ -0,0 +1,215 @@
+<?php
+/**
+ * WP_Block_Context Tests
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.5.0
+ */
+
+/**
+ * Tests for WP_Block_Context
+ *
+ * @since 5.5.0
+ *
+ * @group blocks
+ */
+class WP_Block_Context_Test extends WP_UnitTestCase {
+
+	/**
+	 * Registered block names.
+	 *
+	 * @var string[]
+	 */
+	private $registered_block_names = array();
+
+	/**
+	 * Sets up each test method.
+	 */
+	public function setUp() {
+		global $post;
+
+		parent::setUp();
+
+		$args = array(
+			'post_content' => 'example',
+			'post_excerpt' => '',
+		);
+
+		$post = $this->factory()->post->create_and_get( $args );
+		setup_postdata( $post );
+	}
+
+	/**
+	 * Tear down each test method.
+	 */
+	public function tearDown() {
+		while ( ! empty( $this->registered_block_names ) ) {
+			$block_name = array_pop( $this->registered_block_names );
+			unregister_block_type( $block_name );
+		}
+
+		parent::tearDown();
+	}
+
+	/**
+	 * Registers a block type.
+	 *
+	 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively a
+	 *                                   complete WP_Block_Type instance. In case a WP_Block_Type
+	 *                                   is provided, the $args parameter will be ignored.
+	 * @param array                $args {
+	 *     Optional. Array of block type arguments. Any arguments may be defined, however the
+	 *     ones described below are supported by default. Default empty array.
+	 *
+	 *     @type callable $render_callback Callback used to render blocks of this block type.
+	 * }
+	 */
+	protected function register_block_type( $name, $args ) {
+		register_block_type( $name, $args );
+
+		$this->registered_block_names[] = $name;
+	}
+
+	/**
+	 * Tests that a block which provides context makes that context available to
+	 * its inner blocks.
+	 *
+	 * @ticket 49927
+	 */
+	function test_provides_block_context() {
+		$provided_context = array();
+
+		$this->register_block_type(
+			'gutenberg/test-context-provider',
+			array(
+				'attributes'       => array(
+					'contextWithAssigned'   => array(
+						'type' => 'number',
+					),
+					'contextWithDefault'    => array(
+						'type'    => 'number',
+						'default' => 0,
+					),
+					'contextWithoutDefault' => array(
+						'type' => 'number',
+					),
+					'contextNotRequested'   => array(
+						'type' => 'number',
+					),
+				),
+				'provides_context' => array(
+					'gutenberg/contextWithAssigned'   => 'contextWithAssigned',
+					'gutenberg/contextWithDefault'    => 'contextWithDefault',
+					'gutenberg/contextWithoutDefault' => 'contextWithoutDefault',
+					'gutenberg/contextNotRequested'   => 'contextNotRequested',
+				),
+			)
+		);
+
+		$this->register_block_type(
+			'gutenberg/test-context-consumer',
+			array(
+				'uses_context'    => array(
+					'gutenberg/contextWithDefault',
+					'gutenberg/contextWithAssigned',
+					'gutenberg/contextWithoutDefault',
+				),
+				'render_callback' => function( $attributes, $content, $block ) use ( &$provided_context ) {
+					$provided_context[] = $block->context;
+
+					return '';
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks(
+			'<!-- wp:gutenberg/test-context-provider {"contextWithAssigned":10} -->' .
+			'<!-- wp:gutenberg/test-context-consumer /-->' .
+			'<!-- /wp:gutenberg/test-context-provider -->'
+		);
+
+		render_block( $parsed_blocks[0] );
+
+		$this->assertSame(
+			array(
+				'gutenberg/contextWithDefault'  => 0,
+				'gutenberg/contextWithAssigned' => 10,
+			),
+			$provided_context[0]
+		);
+	}
+
+	/**
+	 * Tests that a block can receive default-provided context through
+	 * render_block.
+	 *
+	 * @ticket 49927
+	 */
+	function test_provides_default_context() {
+		global $post;
+
+		$provided_context = array();
+
+		$this->register_block_type(
+			'gutenberg/test-context-consumer',
+			array(
+				'uses_context'    => array( 'postId', 'postType' ),
+				'render_callback' => function( $attributes, $content, $block ) use ( &$provided_context ) {
+					$provided_context[] = $block->context;
+
+					return '';
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:gutenberg/test-context-consumer /-->' );
+
+		render_block( $parsed_blocks[0] );
+
+		$this->assertSame(
+			array(
+				'postId'   => $post->ID,
+				'postType' => $post->post_type,
+			),
+			$provided_context[0]
+		);
+	}
+
+	/**
+	 * Tests that default block context can be filtered.
+	 *
+	 * @ticket 49927
+	 */
+	function test_default_context_is_filterable() {
+		$provided_context = array();
+
+		$this->register_block_type(
+			'gutenberg/test-context-consumer',
+			array(
+				'uses_context'    => array( 'example' ),
+				'render_callback' => function( $attributes, $content, $block ) use ( &$provided_context ) {
+					$provided_context[] = $block->context;
+
+					return '';
+				},
+			)
+		);
+
+		$filter_block_context = function( $context ) {
+			$context['example'] = 'ok';
+			return $context;
+		};
+
+		$parsed_blocks = parse_blocks( '<!-- wp:gutenberg/test-context-consumer /-->' );
+
+		add_filter( 'render_block_context', $filter_block_context );
+
+		render_block( $parsed_blocks[0] );
+
+		remove_filter( 'render_block_context', $filter_block_context );
+
+		$this->assertSame( array( 'example' => 'ok' ), $provided_context[0] );
+	}
+
+}

+ 112 - 0
tests/phpunit/tests/blocks/block-list.php

@@ -0,0 +1,112 @@
+<?php
+/**
+ * WP_Block_List tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.5.0
+ */
+
+/**
+ * Tests for WP_Block_List
+ *
+ * @since 5.5.0
+ *
+ * @group blocks
+ */
+class WP_Block_List_Test extends WP_UnitTestCase {
+
+	/**
+	 * Fake block type registry.
+	 *
+	 * @var WP_Block_Type_Registry
+	 */
+	private $registry = null;
+
+	/**
+	 * Set up each test method.
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		$this->registry = new WP_Block_Type_Registry();
+		$this->registry->register( 'core/example', array() );
+	}
+
+	/**
+	 * Tear down each test method.
+	 */
+	public function tearDown() {
+		$this->registry = null;
+
+		parent::tearDown();
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_array_access() {
+		$parsed_blocks = parse_blocks( '<!-- wp:example /-->' );
+		$context       = array();
+		$blocks        = new WP_Block_List( $parsed_blocks, $context, $this->registry );
+
+		// Test "offsetExists".
+		$this->assertTrue( isset( $blocks[0] ) );
+
+		// Test "offsetGet".
+		$this->assertSame( 'core/example', $blocks[0]->name );
+
+		// Test "offsetSet".
+		$parsed_blocks[0]['blockName'] = 'core/updated';
+		$blocks[0]                     = new WP_Block( $parsed_blocks[0], $context, $this->registry );
+		$this->assertSame( 'core/updated', $blocks[0]->name );
+
+		// Test "offsetUnset".
+		unset( $blocks[0] );
+		$this->assertFalse( isset( $blocks[0] ) );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_iterable() {
+		$parsed_blocks = parse_blocks( '<!-- wp:example --><!-- wp:example /--><!-- /wp:example -->' );
+		$context       = array();
+		$blocks        = new WP_Block_List( $parsed_blocks, $context, $this->registry );
+		$assertions    = 0;
+
+		foreach ( $blocks as $block ) {
+			$this->assertSame( 'core/example', $block->name );
+			$assertions++;
+			foreach ( $block->inner_blocks as $inner_block ) {
+				$this->assertSame( 'core/example', $inner_block->name );
+				$assertions++;
+			}
+		}
+
+		$blocks->rewind();
+		while ( $blocks->valid() ) {
+			$key   = $blocks->key();
+			$block = $blocks->current();
+			$this->assertSame( 0, $key );
+			$assertions++;
+			$this->assertSame( 'core/example', $block->name );
+			$assertions++;
+			$blocks->next();
+		}
+
+		$this->assertSame( 4, $assertions );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_countable() {
+		$parsed_blocks = parse_blocks( '<!-- wp:example /-->' );
+		$context       = array();
+		$blocks        = new WP_Block_List( $parsed_blocks, $context, $this->registry );
+
+		$this->assertSame( 1, count( $blocks ) );
+	}
+
+}

+ 119 - 0
tests/phpunit/tests/blocks/block-parser.php

@@ -0,0 +1,119 @@
+<?php
+/**
+ * WP_Block_Parser tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for WP_Block_Parser
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Parser extends WP_UnitTestCase {
+	/**
+	 * The location of the fixtures to test with.
+	 *
+	 * @since 5.0.0
+	 * @var string
+	 */
+	protected static $fixtures_dir;
+
+	/**
+	 * @ticket 45109
+	 */
+	public function data_parsing_test_filenames() {
+		self::$fixtures_dir = DIR_TESTDATA . '/blocks/fixtures';
+
+		$fixture_filenames = array_merge(
+			glob( self::$fixtures_dir . '/*.json' ),
+			glob( self::$fixtures_dir . '/*.html' )
+		);
+
+		$fixture_filenames = array_values(
+			array_unique(
+				array_map(
+					array( $this, 'clean_fixture_filename' ),
+					$fixture_filenames
+				)
+			)
+		);
+
+		return array_map(
+			array( $this, 'pass_parser_fixture_filenames' ),
+			$fixture_filenames
+		);
+	}
+
+	/**
+	 * @dataProvider data_parsing_test_filenames
+	 * @ticket 45109
+	 */
+	public function test_default_parser_output( $html_filename, $parsed_json_filename ) {
+		$html_path        = self::$fixtures_dir . '/' . $html_filename;
+		$parsed_json_path = self::$fixtures_dir . '/' . $parsed_json_filename;
+
+		foreach ( array( $html_path, $parsed_json_path ) as $filename ) {
+			if ( ! file_exists( $filename ) ) {
+				throw new Exception( "Missing fixture file: '$filename'" );
+			}
+		}
+
+		$html            = self::strip_r( file_get_contents( $html_path ) );
+		$expected_parsed = json_decode( self::strip_r( file_get_contents( $parsed_json_path ) ), true );
+
+		$parser = new WP_Block_Parser();
+		$result = json_decode( json_encode( $parser->parse( $html ) ), true );
+
+		$this->assertSame(
+			$expected_parsed,
+			$result,
+			"File '$parsed_json_filename' does not match expected value"
+		);
+	}
+
+	/**
+	 * Helper function to remove relative paths and extension from a filename, leaving just the fixture name.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param string $filename The filename to clean.
+	 * @return string The cleaned fixture name.
+	 */
+	protected function clean_fixture_filename( $filename ) {
+		$filename = wp_basename( $filename );
+		$filename = preg_replace( '/\..+$/', '', $filename );
+		return $filename;
+	}
+
+	/**
+	 * Helper function to return the filenames needed to test the parser output.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @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 ) {
+		return array(
+			"$filename.html",
+			"$filename.parsed.json",
+		);
+	}
+
+	/**
+	 * Helper function to remove '\r' characters from a string.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param string $input The string to remove '\r' from.
+	 * @return string The input string, with '\r' characters removed.
+	 */
+	protected function strip_r( $input ) {
+		return str_replace( "\r", '', $input );
+	}
+}

+ 191 - 0
tests/phpunit/tests/blocks/block-type-registry.php

@@ -0,0 +1,191 @@
+<?php
+/**
+ * WP_Block_Type_Registry Tests
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for WP_Block_Type_Registry
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Type_Registry extends WP_UnitTestCase {
+
+	/**
+	 * Fake block type registry.
+	 *
+	 * @since 5.0.0
+	 * @var WP_Block_Type_Registry
+	 */
+	private $registry = null;
+
+	/**
+	 * Set up each test method.
+	 *
+	 * @since 5.0.0
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		$this->registry = new WP_Block_Type_Registry();
+	}
+
+	/**
+	 * Tear down each test method.
+	 *
+	 * @since 5.0.0
+	 */
+	public function tearDown() {
+		$this->registry = null;
+
+		parent::tearDown();
+	}
+
+	/**
+	 * Should reject numbers
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::register
+	 */
+	public function test_invalid_non_string_names() {
+		$result = $this->registry->register( 1, array() );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should reject blocks without a namespace
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::register
+	 */
+	public function test_invalid_names_without_namespace() {
+		$result = $this->registry->register( 'paragraph', array() );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should reject blocks with invalid characters
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::register
+	 */
+	public function test_invalid_characters() {
+		$result = $this->registry->register( 'still/_doing_it_wrong', array() );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should reject blocks with uppercase characters
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::register
+	 */
+	public function test_uppercase_characters() {
+		$result = $this->registry->register( 'Core/Paragraph', array() );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should accept valid block names
+	 *
+	 * @ticket 45097
+	 */
+	public function test_register_block_type() {
+		$name     = 'core/paragraph';
+		$settings = array(
+			'icon' => 'editor-paragraph',
+		);
+
+		$block_type = $this->registry->register( $name, $settings );
+		$this->assertSame( $name, $block_type->name );
+		$this->assertSame( $settings['icon'], $block_type->icon );
+		$this->assertSame( $block_type, $this->registry->get_registered( $name ) );
+	}
+
+	/**
+	 * Should fail to re-register the same block
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::register
+	 */
+	public function test_register_block_type_twice() {
+		$name     = 'core/paragraph';
+		$settings = array(
+			'icon' => 'editor-paragraph',
+		);
+
+		$result = $this->registry->register( $name, $settings );
+		$this->assertNotFalse( $result );
+		$result = $this->registry->register( $name, $settings );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should accept a WP_Block_Type instance
+	 *
+	 * @ticket 45097
+	 */
+	public function test_register_block_type_instance() {
+		$block_type = new WP_Fake_Block_Type( 'core/fake' );
+
+		$result = $this->registry->register( $block_type );
+		$this->assertSame( $block_type, $result );
+	}
+
+	/**
+	 * Unregistering should fail if a block is not registered
+	 *
+	 * @ticket 45097
+	 *
+	 * @expectedIncorrectUsage WP_Block_Type_Registry::unregister
+	 */
+	public function test_unregister_not_registered_block() {
+		$result = $this->registry->unregister( 'core/unregistered' );
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Should unregister existing blocks
+	 *
+	 * @ticket 45097
+	 */
+	public function test_unregister_block_type() {
+		$name     = 'core/paragraph';
+		$settings = array(
+			'icon' => 'editor-paragraph',
+		);
+
+		$this->registry->register( $name, $settings );
+		$block_type = $this->registry->unregister( $name );
+		$this->assertSame( $name, $block_type->name );
+		$this->assertSame( $settings['icon'], $block_type->icon );
+		$this->assertFalse( $this->registry->is_registered( $name ) );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_get_all_registered() {
+		$names    = array( 'core/paragraph', 'core/image', 'core/blockquote' );
+		$settings = array(
+			'icon' => 'random',
+		);
+
+		foreach ( $names as $name ) {
+			$this->registry->register( $name, $settings );
+		}
+
+		$registered = $this->registry->get_all_registered();
+		$this->assertSameSets( $names, array_keys( $registered ) );
+	}
+}

+ 422 - 0
tests/phpunit/tests/blocks/block-type.php

@@ -0,0 +1,422 @@
+<?php
+/**
+ * WP_Block_Type Tests
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for WP_Block_Type
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Type extends WP_UnitTestCase {
+
+	/**
+	 * Editor user ID.
+	 *
+	 * @since 5.0.0
+	 * @var int
+	 */
+	protected static $editor_user_id;
+
+	/**
+	 * ID for a post containing blocks.
+	 *
+	 * @since 5.0.0
+	 * @var int
+	 */
+	protected static $post_with_blocks;
+
+	/**
+	 * ID for a post without blocks.
+	 *
+	 * @since 5.0.0
+	 * @var int
+	 */
+	protected static $post_without_blocks;
+
+	/**
+	 * Set up before class.
+	 *
+	 * @since 5.0.0
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$editor_user_id = $factory->user->create(
+			array(
+				'role' => 'editor',
+			)
+		);
+
+		self::$post_with_blocks = $factory->post->create(
+			array(
+				'post_title'   => 'Example',
+				'post_content' => "<!-- wp:core/text {\"dropCap\":true} -->\n<p class=\"has-drop-cap\">Tester</p>\n<!-- /wp:core/text -->",
+			)
+		);
+
+		self::$post_without_blocks = $factory->post->create(
+			array(
+				'post_title'   => 'Example',
+				'post_content' => 'Tester',
+			)
+		);
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_set_props() {
+		$name = 'core/fake';
+		$args = array(
+			'render_callback' => array( $this, 'render_fake_block' ),
+			'foo'             => 'bar',
+		);
+
+		$block_type = new WP_Block_Type( $name, $args );
+
+		$this->assertSame( $name, $block_type->name );
+		$this->assertSame( $args['render_callback'], $block_type->render_callback );
+		$this->assertSame( $args['foo'], $block_type->foo );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_render() {
+		$attributes = array(
+			'foo' => 'bar',
+			'bar' => 'foo',
+		);
+
+		$block_type = new WP_Block_Type(
+			'core/fake',
+			array(
+				'render_callback' => array( $this, 'render_fake_block' ),
+			)
+		);
+		$output     = $block_type->render( $attributes );
+		$this->assertSame( $attributes, json_decode( $output, true ) );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_render_with_content() {
+		$attributes = array(
+			'foo' => 'bar',
+			'bar' => 'foo',
+		);
+
+		$content = 'baz';
+
+		$expected = array_merge( $attributes, array( '_content' => $content ) );
+
+		$block_type = new WP_Block_Type(
+			'core/fake',
+			array(
+				'render_callback' => array( $this, 'render_fake_block_with_content' ),
+			)
+		);
+		$output     = $block_type->render( $attributes, $content );
+		$this->assertSame( $expected, json_decode( $output, true ) );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_render_for_static_block() {
+		$block_type = new WP_Block_Type( 'core/fake', array() );
+		$output     = $block_type->render();
+
+		$this->assertSame( '', $output );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_is_dynamic_for_static_block() {
+		$block_type = new WP_Block_Type( 'core/fake', array() );
+
+		$this->assertFalse( $block_type->is_dynamic() );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_is_dynamic_for_dynamic_block() {
+		$block_type = new WP_Block_Type(
+			'core/fake',
+			array(
+				'render_callback' => array( $this, 'render_fake_block' ),
+			)
+		);
+
+		$this->assertTrue( $block_type->is_dynamic() );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_prepare_attributes() {
+		$attributes = array(
+			'correct'            => 'include',
+			'wrongType'          => 5,
+			'wrongTypeDefaulted' => 5,
+			/* missingDefaulted */
+			'undefined'          => 'include',
+			'intendedNull'       => null,
+		);
+
+		$block_type = new WP_Block_Type(
+			'core/fake',
+			array(
+				'attributes' => array(
+					'correct'            => array(
+						'type' => 'string',
+					),
+					'wrongType'          => array(
+						'type' => 'string',
+					),
+					'wrongTypeDefaulted' => array(
+						'type'    => 'string',
+						'default' => 'defaulted',
+					),
+					'missingDefaulted'   => array(
+						'type'    => 'string',
+						'default' => 'define',
+					),
+					'intendedNull'       => array(
+						'type'    => array( 'string', 'null' ),
+						'default' => 'wrong',
+					),
+				),
+			)
+		);
+
+		$prepared_attributes = $block_type->prepare_attributes_for_render( $attributes );
+
+		$this->assertEquals(
+			array(
+				'correct'            => 'include',
+				/* wrongType */
+				'wrongTypeDefaulted' => 'defaulted',
+				'missingDefaulted'   => 'define',
+				'undefined'          => 'include',
+				'intendedNull'       => null,
+			),
+			$prepared_attributes
+		);
+	}
+
+	/**
+	 * @ticket 45145
+	 */
+	function test_prepare_attributes_none_defined() {
+		$attributes = array( 'exists' => 'keep' );
+
+		$block_type = new WP_Block_Type( 'core/dummy', array() );
+
+		$prepared_attributes = $block_type->prepare_attributes_for_render( $attributes );
+
+		$this->assertSame( $attributes, $prepared_attributes );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_has_block_with_mixed_content() {
+		$mixed_post_content = 'before' .
+		'<!-- wp:core/fake --><!-- /wp:core/fake -->' .
+		'<!-- wp:core/fake_atts {"value":"b1"} --><!-- /wp:core/fake_atts -->' .
+		'<!-- wp:core/fake-child -->
+		<p>testing the test</p>
+		<!-- /wp:core/fake-child -->' .
+		'between' .
+		'<!-- wp:core/self-close-fake /-->' .
+		'<!-- wp:custom/fake {"value":"b2"} /-->' .
+		'after';
+
+		$this->assertTrue( has_block( 'core/fake', $mixed_post_content ) );
+
+		$this->assertTrue( has_block( 'core/fake_atts', $mixed_post_content ) );
+
+		$this->assertTrue( has_block( 'core/fake-child', $mixed_post_content ) );
+
+		$this->assertTrue( has_block( 'core/self-close-fake', $mixed_post_content ) );
+
+		$this->assertTrue( has_block( 'custom/fake', $mixed_post_content ) );
+
+		// checking for a partial block name should fail.
+		$this->assertFalse( has_block( 'core/fak', $mixed_post_content ) );
+
+		// checking for a wrong namespace should fail.
+		$this->assertFalse( has_block( 'custom/fake_atts', $mixed_post_content ) );
+
+		// checking for namespace only should not work. Or maybe ... ?
+		$this->assertFalse( has_block( 'core', $mixed_post_content ) );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_has_block_with_invalid_content() {
+		// some content with invalid HMTL comments and a single valid block.
+		$invalid_content = 'before' .
+		'<!- - wp:core/weird-space --><!-- /wp:core/weird-space -->' .
+		'<!--wp:core/untrimmed-left --><!-- /wp:core/untrimmed -->' .
+		'<!-- wp:core/fake --><!-- /wp:core/fake -->' .
+		'<!-- wp:core/untrimmed-right--><!-- /wp:core/untrimmed2 -->' .
+		'after';
+
+		$this->assertFalse( has_block( 'core/text', self::$post_without_blocks ) );
+
+		$this->assertFalse( has_block( 'core/weird-space', $invalid_content ) );
+
+		$this->assertFalse( has_block( 'core/untrimmed-left', $invalid_content ) );
+
+		$this->assertFalse( has_block( 'core/untrimmed-right', $invalid_content ) );
+
+		$this->assertTrue( has_block( 'core/fake', $invalid_content ) );
+	}
+
+	/**
+	 * @ticket 45097
+	 */
+	public function test_post_has_block() {
+		// should fail for a non-existent block `custom/fake`.
+		$this->assertFalse( has_block( 'custom/fake', self::$post_with_blocks ) );
+
+		// this functions should not work without the second param until the $post global is set.
+		$this->assertFalse( has_block( 'core/text' ) );
+		$this->assertFalse( has_block( 'core/fake' ) );
+
+		global $post;
+		$post = get_post( self::$post_with_blocks );
+
+		// check if the function correctly detects content from the $post global.
+		$this->assertTrue( has_block( 'core/text' ) );
+		// even if it detects a proper $post global it should still be false for a missing block.
+		$this->assertFalse( has_block( 'core/fake' ) );
+	}
+
+	public function test_post_has_block_serialized_name() {
+		$content = '<!-- wp:serialized /--><!-- wp:core/normalized /--><!-- wp:plugin/third-party /-->';
+
+		$this->assertTrue( has_block( 'core/serialized', $content ) );
+
+		/*
+		 * Technically, `has_block` should receive a "full" (normalized, parsed)
+		 * block name. But this test conforms to expected pre-5.3.1 behavior.
+		 */
+		$this->assertTrue( has_block( 'serialized', $content ) );
+		$this->assertTrue( has_block( 'core/normalized', $content ) );
+		$this->assertTrue( has_block( 'normalized', $content ) );
+		$this->assertFalse( has_block( 'plugin/normalized', $content ) );
+		$this->assertFalse( has_block( 'plugin/serialized', $content ) );
+		$this->assertFalse( has_block( 'third-party', $content ) );
+		$this->assertFalse( has_block( 'core/third-party', $content ) );
+	}
+
+	/**
+	 * Renders a test block without content.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param array $attributes Block attributes. Default empty array.
+	 * @return string JSON encoded list of attributes.
+	 */
+	public function render_fake_block( $attributes ) {
+		return json_encode( $attributes );
+	}
+
+	/**
+	 * Renders a test block with content.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param array  $attributes Block attributes. Default empty array.
+	 * @param string $content    Block content. Default empty string.
+	 * @return string JSON encoded list of attributes.
+	 */
+	public function render_fake_block_with_content( $attributes, $content ) {
+		$attributes['_content'] = $content;
+
+		return json_encode( $attributes );
+	}
+
+	/**
+	 * @ticket 48529
+	 */
+	public function test_register_block() {
+		$block_type = new WP_Block_Type(
+			'core/fake',
+			array(
+				'title'       => 'Test title',
+				'category'    => 'Test category',
+				'parent'      => array( 'core/third-party' ),
+				'icon'        => 'icon.png',
+				'description' => 'test description',
+				'keywords'    => array( 'test keyword' ),
+				'textdomain'  => 'test_domain',
+				'supports'    => array( 'alignment' => true ),
+			)
+		);
+
+		$this->assertSame( 'Test title', $block_type->title );
+		$this->assertSame( 'Test category', $block_type->category );
+		$this->assertSameSets( array( 'core/third-party' ), $block_type->parent );
+		$this->assertSame( 'icon.png', $block_type->icon );
+		$this->assertSame( 'test description', $block_type->description );
+		$this->assertSameSets( array( 'test keyword' ), $block_type->keywords );
+		$this->assertSame( 'test_domain', $block_type->textdomain );
+		$this->assertSameSets( array( 'alignment' => true ), $block_type->supports );
+	}
+
+	/**
+	 * Testing the block version.
+	 *
+	 * @ticket 43887
+	 *
+	 * @dataProvider data_block_version
+	 *
+	 * @param string|null $content  Content.
+	 * @param int         $expected Expected block version.
+	 */
+	public function test_block_version( $content, $expected ) {
+		$this->assertSame( $expected, block_version( $content ) );
+	}
+
+	/**
+	 * Test cases for test_block_version().
+	 *
+	 * @since 5.0.0
+	 *
+	 * @return array {
+	 *     @type array {
+	 *         @type string|null Content.
+	 *         @type int         Expected block version.
+	 *     }
+	 * }
+	 */
+	public function data_block_version() {
+		return array(
+			// Null.
+			array( null, 0 ),
+			// Empty post content.
+			array( '', 0 ),
+			// Post content without blocks.
+			array( '<hr class="wp-block-separator" />', 0 ),
+			// Post content with a block.
+			array( '<!-- wp:core/separator -->', 1 ),
+			// Post content with a fake block.
+			array( '<!-- wp:core/fake --><!-- /wp:core/fake -->', 1 ),
+			// Post content with an invalid block.
+			array( '<!- - wp:core/separator -->', 0 ),
+		);
+	}
+}

+ 416 - 0
tests/phpunit/tests/blocks/block.php

@@ -0,0 +1,416 @@
+<?php
+/**
+ * WP_Block Tests
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.5.0
+ */
+
+/**
+ * Tests for WP_Block
+ *
+ * @since 5.5.0
+ *
+ * @group blocks
+ */
+class WP_Block_Test extends WP_UnitTestCase {
+
+	/**
+	 * Fake block type registry.
+	 *
+	 * @var WP_Block_Type_Registry
+	 */
+	private $registry = null;
+
+	/**
+	 * Set up each test method.
+	 */
+	public function setUp() {
+		parent::setUp();
+
+		$this->registry = new WP_Block_Type_Registry();
+	}
+
+	/**
+	 * Tear down each test method.
+	 */
+	public function tearDown() {
+		$this->registry = null;
+
+		parent::tearDown();
+	}
+
+	function filter_render_block( $content, $parsed_block ) {
+		return 'Original: "' . $content . '", from block "' . $parsed_block['blockName'] . '"';
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_assigns_properties_from_parsed_block() {
+		$this->registry->register( 'core/example', array() );
+
+		$parsed_blocks = parse_blocks( '<!-- wp:example {"ok":true} -->a<!-- wp:example /-->b<!-- /wp:example -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( $parsed_block, $block->parsed_block );
+		$this->assertSame( $parsed_block['blockName'], $block->name );
+		$this->assertSame( $parsed_block['attrs'], $block->attributes );
+		$this->assertSame( $parsed_block['innerContent'], $block->inner_content );
+		$this->assertSame( $parsed_block['innerHTML'], $block->inner_html );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_assigns_block_type_from_registry() {
+		$block_type_settings = array(
+			'attributes' => array(
+				'defaulted' => array(
+					'type'    => 'number',
+					'default' => 10,
+				),
+			),
+		);
+		$this->registry->register( 'core/example', $block_type_settings );
+
+		$parsed_block = array( 'blockName' => 'core/example' );
+		$context      = array();
+		$block        = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertInstanceOf( WP_Block_Type::class, $block->block_type );
+		$this->assertSame(
+			$block_type_settings['attributes'],
+			$block->block_type->attributes
+		);
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_lazily_assigns_attributes_with_defaults() {
+		$this->registry->register(
+			'core/example',
+			array(
+				'attributes' => array(
+					'defaulted' => array(
+						'type'    => 'number',
+						'default' => 10,
+					),
+				),
+			)
+		);
+
+		$parsed_block = array(
+			'blockName' => 'core/example',
+			'attrs'     => array(
+				'explicit' => 20,
+			),
+		);
+		$context      = array();
+		$block        = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame(
+			array(
+				'explicit'  => 20,
+				'defaulted' => 10,
+			),
+			$block->attributes
+		);
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_lazily_assigns_attributes_with_only_defaults() {
+		$this->registry->register(
+			'core/example',
+			array(
+				'attributes' => array(
+					'defaulted' => array(
+						'type'    => 'number',
+						'default' => 10,
+					),
+				),
+			)
+		);
+
+		$parsed_block = array(
+			'blockName' => 'core/example',
+			'attrs'     => array(),
+		);
+		$context      = array();
+		$block        = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( array( 'defaulted' => 10 ), $block->attributes );
+		// Intentionally call a second time, to ensure property was assigned.
+		$this->assertSame( array( 'defaulted' => 10 ), $block->attributes );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_assigns_context_from_block_type() {
+		$this->registry->register(
+			'core/example',
+			array(
+				'uses_context' => array( 'requested' ),
+			)
+		);
+
+		$parsed_block = array( 'blockName' => 'core/example' );
+		$context      = array(
+			'requested'   => 'included',
+			'unrequested' => 'not included',
+		);
+		$block        = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( array( 'requested' => 'included' ), $block->context );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_maps_inner_blocks() {
+		$this->registry->register( 'core/example', array() );
+
+		$parsed_blocks = parse_blocks( '<!-- wp:example {"ok":true} -->a<!-- wp:example /-->b<!-- /wp:example -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertCount( 1, $block->inner_blocks );
+		$this->assertInstanceOf( WP_Block::class, $block->inner_blocks[0] );
+		$this->assertSame( 'core/example', $block->inner_blocks[0]->name );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_prepares_context_for_inner_blocks() {
+		$this->registry->register(
+			'core/outer',
+			array(
+				'attributes'       => array(
+					'recordId' => array(
+						'type' => 'number',
+					),
+				),
+				'provides_context' => array(
+					'core/recordId' => 'recordId',
+				),
+			)
+		);
+		$this->registry->register(
+			'core/inner',
+			array(
+				'uses_context' => array( 'core/recordId' ),
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:outer {"recordId":10} --><!-- wp:inner /--><!-- /wp:outer -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array( 'unrequested' => 'not included' );
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertCount( 0, $block->context );
+		$this->assertSame(
+			array( 'core/recordId' => 10 ),
+			$block->inner_blocks[0]->context
+		);
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_constructor_assigns_merged_context() {
+		$this->registry->register(
+			'core/example',
+			array(
+				'attributes'       => array(
+					'value' => array(
+						'type' => array( 'string', 'null' ),
+					),
+				),
+				'provides_context' => array(
+					'core/value' => 'value',
+				),
+				'uses_context'     => array( 'core/value' ),
+			)
+		);
+
+		$parsed_blocks = parse_blocks(
+			'<!-- wp:example {"value":"merged"} -->' .
+			'<!-- wp:example {"value":null} -->' .
+			'<!-- wp:example /-->' .
+			'<!-- /wp:example -->' .
+			'<!-- /wp:example -->'
+		);
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array( 'core/value' => 'original' );
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame(
+			array( 'core/value' => 'original' ),
+			$block->context
+		);
+		$this->assertSame(
+			array( 'core/value' => 'merged' ),
+			$block->inner_blocks[0]->context
+		);
+		$this->assertSame(
+			array( 'core/value' => null ),
+			$block->inner_blocks[0]->inner_blocks[0]->context
+		);
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_render_static_block_type_returns_own_content() {
+		$this->registry->register( 'core/static', array() );
+		$this->registry->register(
+			'core/dynamic',
+			array(
+				'render_callback' => function() {
+					return 'b';
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:static -->a<!-- wp:dynamic /-->c<!-- /wp:static -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( 'abc', $block->render() );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_render_passes_block_for_render_callback() {
+		$this->registry->register(
+			'core/greeting',
+			array(
+				'render_callback' => function( $attributes, $content, $block ) {
+					return sprintf( 'Hello from %s', $block->name );
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:greeting /-->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( 'Hello from core/greeting', $block->render() );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_render_applies_render_block_filter() {
+		$this->registry->register( 'core/example', array() );
+
+		add_filter( 'render_block', array( $this, 'filter_render_block' ), 10, 2 );
+
+		$parsed_blocks = parse_blocks( '<!-- wp:example -->Static<!-- wp:example -->Inner<!-- /wp:example --><!-- /wp:example -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$rendered_content = $block->render();
+
+		remove_filter( 'render_block', array( $this, 'filter_render_block' ) );
+
+		$this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content );
+	}
+
+	/**
+	 * @ticket 46187
+	 */
+	function test_render_applies_dynamic_render_block_filter() {
+		$this->registry->register( 'core/example', array() );
+
+		add_filter( 'render_block_core/example', array( $this, 'filter_render_block' ), 10, 2 );
+
+		$parsed_blocks = parse_blocks( '<!-- wp:example -->Static<!-- wp:example -->Inner<!-- /wp:example --><!-- /wp:example -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$rendered_content = $block->render();
+
+		remove_filter( 'render_block_core/example', array( $this, 'filter_render_block' ) );
+
+		$this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_passes_attributes_to_render_callback() {
+		$this->registry->register(
+			'core/greeting',
+			array(
+				'attributes'      => array(
+					'toWhom'      => array(
+						'type' => 'string',
+					),
+					'punctuation' => array(
+						'type'    => 'string',
+						'default' => '!',
+					),
+				),
+				'render_callback' => function( $block_attributes ) {
+					return sprintf(
+						'Hello %s%s',
+						$block_attributes['toWhom'],
+						$block_attributes['punctuation']
+					);
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:greeting {"toWhom":"world"} /-->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( 'Hello world!', $block->render() );
+	}
+
+	/**
+	 * @ticket 49927
+	 */
+	function test_passes_content_to_render_callback() {
+		$this->registry->register(
+			'core/outer',
+			array(
+				'render_callback' => function( $block_attributes, $content ) {
+					return $content;
+				},
+			)
+		);
+		$this->registry->register(
+			'core/inner',
+			array(
+				'render_callback' => function() {
+					return 'b';
+				},
+			)
+		);
+
+		$parsed_blocks = parse_blocks( '<!-- wp:outer -->a<!-- wp:inner /-->c<!-- /wp:outer -->' );
+		$parsed_block  = $parsed_blocks[0];
+		$context       = array();
+		$block         = new WP_Block( $parsed_block, $context, $this->registry );
+
+		$this->assertSame( 'abc', $block->render() );
+	}
+
+}

+ 499 - 0
tests/phpunit/tests/blocks/register.php

@@ -0,0 +1,499 @@
+<?php
+/**
+ * Block registry tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for register_block_type(), unregister_block_type(), get_dynamic_block_names()
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Register extends WP_UnitTestCase {
+
+	/**
+	 * ID for a test post.
+	 *
+	 * @since 5.0.0
+	 * @var int
+	 */
+	protected static $post_id;
+
+	/**
+	 * Set up before class.
+	 *
+	 * @since 5.0.0
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$post_id = $factory->post->create(
+			array(
+				'post_content' => file_get_contents( DIR_TESTDATA . '/blocks/do-blocks-original.html' ),
+			)
+		);
+	}
+
+	/**
+	 * Tear down after class.
+	 *
+	 * @since 5.0.0
+	 */
+	public static function wpTearDownAfterClass() {
+		// Also deletes revisions.
+		wp_delete_post( self::$post_id, true );
+	}
+
+	/**
+	 * Empty render function for tests to use.
+	 */
+	function render_stub() {}
+
+	/**
+	 * Tear down after each test.
+	 *
+	 * @since 5.0.0
+	 */
+	function tearDown() {
+		$registry = WP_Block_Type_Registry::get_instance();
+
+		foreach ( array( 'core/test-static', 'core/test-dynamic', 'tests/notice' ) as $block_name ) {
+			if ( $registry->is_registered( $block_name ) ) {
+				$registry->unregister( $block_name );
+			}
+		}
+
+		parent::tearDown();
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	function test_register_affects_main_registry() {
+		$name     = 'core/test-static';
+		$settings = array(
+			'icon' => 'text',
+		);
+
+		register_block_type( $name, $settings );
+
+		$registry = WP_Block_Type_Registry::get_instance();
+		$this->assertTrue( $registry->is_registered( $name ) );
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	function test_unregister_affects_main_registry() {
+		$name     = 'core/test-static';
+		$settings = array(
+			'icon' => 'text',
+		);
+
+		register_block_type( $name, $settings );
+		unregister_block_type( $name );
+
+		$registry = WP_Block_Type_Registry::get_instance();
+		$this->assertFalse( $registry->is_registered( $name ) );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_does_not_remove_block_asset_path_prefix() {
+		$result = remove_block_asset_path_prefix( 'script-handle' );
+
+		$this->assertSame( 'script-handle', $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_removes_block_asset_path_prefix() {
+		$result = remove_block_asset_path_prefix( 'file:./block.js' );
+
+		$this->assertSame( './block.js', $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_generate_block_asset_handle() {
+		$block_name = 'unit-tests/my-block';
+
+		$this->assertSame(
+			'unit-tests-my-block-editor-script',
+			generate_block_asset_handle( $block_name, 'editorScript' )
+		);
+		$this->assertSame(
+			'unit-tests-my-block-script',
+			generate_block_asset_handle( $block_name, 'script' )
+		);
+		$this->assertSame(
+			'unit-tests-my-block-editor-style',
+			generate_block_asset_handle( $block_name, 'editorStyle' )
+		);
+		$this->assertSame(
+			'unit-tests-my-block-style',
+			generate_block_asset_handle( $block_name, 'style' )
+		);
+	}
+
+	/**
+	 * @ticket 50328
+	 */
+	function test_generate_block_asset_handle_core_block() {
+		$block_name = 'core/paragraph';
+
+		$this->assertSame(
+			'wp-block-paragraph-editor',
+			generate_block_asset_handle( $block_name, 'editorScript' )
+		);
+		$this->assertSame(
+			'wp-block-paragraph',
+			generate_block_asset_handle( $block_name, 'script' )
+		);
+		$this->assertSame(
+			'wp-block-paragraph-editor',
+			generate_block_asset_handle( $block_name, 'editorStyle' )
+		);
+		$this->assertSame(
+			'wp-block-paragraph',
+			generate_block_asset_handle( $block_name, 'style' )
+		);
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_field_not_found_register_block_script_handle() {
+		$result = register_block_script_handle( array(), 'script' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_empty_value_register_block_script_handle() {
+		$metadata = array( 'script' => '' );
+		$result   = register_block_script_handle( $metadata, 'script' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * @expectedIncorrectUsage register_block_script_handle
+	 * @ticket 50263
+	 */
+	function test_missing_asset_file_register_block_script_handle() {
+		$metadata = array(
+			'file'   => __FILE__,
+			'name'   => 'unit-tests/test-block',
+			'script' => 'file:./blocks/notice/missing-asset.js',
+		);
+		$result   = register_block_script_handle( $metadata, 'script' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_handle_passed_register_block_script_handle() {
+		$metadata = array(
+			'editorScript' => 'test-script-handle',
+		);
+		$result   = register_block_script_handle( $metadata, 'editorScript' );
+
+		$this->assertSame( 'test-script-handle', $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_success_register_block_script_handle() {
+		$metadata = array(
+			'file'   => DIR_TESTDATA . '/blocks/notice/block.json',
+			'name'   => 'unit-tests/test-block',
+			'script' => 'file:./block.js',
+		);
+		$result   = register_block_script_handle( $metadata, 'script' );
+
+		$this->assertSame( 'unit-tests-test-block-script', $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_field_not_found_register_block_style_handle() {
+		$result = register_block_style_handle( array(), 'style' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_empty_value_found_register_block_style_handle() {
+		$metadata = array( 'style' => '' );
+		$result   = register_block_style_handle( $metadata, 'style' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_handle_passed_register_block_style_handle() {
+		$metadata = array(
+			'style' => 'test-style-handle',
+		);
+		$result   = register_block_style_handle( $metadata, 'style' );
+
+		$this->assertSame( 'test-style-handle', $result );
+	}
+
+	/**
+	 * @ticket 50263
+	 */
+	function test_success_register_block_style_handle() {
+		$metadata = array(
+			'file'  => DIR_TESTDATA . '/blocks/notice/block.json',
+			'name'  => 'unit-tests/test-block',
+			'style' => 'file:./block.css',
+		);
+		$result   = register_block_style_handle( $metadata, 'style' );
+
+		$this->assertSame( 'unit-tests-test-block-style', $result );
+		$this->assertSame( 'replace', wp_styles()->get_data( 'unit-tests-test-block-style', 'rtl' ) );
+	}
+
+	/**
+	 * Tests that the function returns false when the `block.json` is not found
+	 * in the WordPress core.
+	 *
+	 * @ticket 50263
+	 */
+	function test_metadata_not_found_in_wordpress_core() {
+		$result = register_block_type_from_metadata( 'unknown' );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Tests that the function returns false when the `block.json` is not found
+	 * in the current directory.
+	 *
+	 * @ticket 50263
+	 */
+	function test_metadata_not_found_in_the_current_directory() {
+		$result = register_block_type_from_metadata( __DIR__ );
+
+		$this->assertFalse( $result );
+	}
+
+	/**
+	 * Tests that the function returns the registered block when the `block.json`
+	 * is found in the fixtures directory.
+	 *
+	 * @ticket 50263
+	 */
+	function test_block_registers_with_metadata_fixture() {
+		$result = register_block_type_from_metadata(
+			DIR_TESTDATA . '/blocks/notice'
+		);
+
+		$this->assertInstanceOf( 'WP_Block_Type', $result );
+		$this->assertSame( 2, $result->api_version );
+		$this->assertSame( 'tests/notice', $result->name );
+		$this->assertSame( 'Notice', $result->title );
+		$this->assertSame( 'common', $result->category );
+		$this->assertSameSets( array( 'core/group' ), $result->parent );
+		$this->assertSame( 'star', $result->icon );
+		$this->assertSame( 'Shows warning, error or success noticesโ€ฆ', $result->description );
+		$this->assertSameSets( array( 'alert', 'message' ), $result->keywords );
+		$this->assertSame(
+			array(
+				'message' => array(
+					'type'     => 'string',
+					'source'   => 'html',
+					'selector' => '.message',
+				),
+			),
+			$result->attributes
+		);
+		$this->assertSame(
+			array(
+				'tests/message' => 'message',
+			),
+			$result->provides_context
+		);
+		$this->assertSameSets( array( 'groupId' ), $result->uses_context );
+		$this->assertSame(
+			array(
+				'align'             => true,
+				'lightBlockWrapper' => true,
+			),
+			$result->supports
+		);
+		$this->assertSame(
+			array(
+				array(
+					'name'      => 'default',
+					'label'     => 'Default',
+					'isDefault' => true,
+				),
+				array(
+					'name'  => 'other',
+					'label' => 'Other',
+				),
+			),
+			$result->styles
+		);
+		$this->assertSame(
+			array(
+				'attributes' => array(
+					'message' => 'This is a notice!',
+				),
+			),
+			$result->example
+		);
+		$this->assertSame( 'tests-notice-editor-script', $result->editor_script );
+		$this->assertSame( 'tests-notice-script', $result->script );
+		$this->assertSame( 'tests-notice-editor-style', $result->editor_style );
+		$this->assertSame( 'tests-notice-style', $result->style );
+	}
+
+	/**
+	 * @ticket 52301
+	 */
+	function test_block_registers_with_metadata_i18n_support() {
+		function filter_set_locale_to_polish() {
+			return 'pl_PL';
+		}
+		add_filter( 'locale', 'filter_set_locale_to_polish' );
+		load_textdomain( 'notice', WP_LANG_DIR . '/plugins/notice-pl_PL.mo' );
+
+		$result = register_block_type_from_metadata(
+			DIR_TESTDATA . '/blocks/notice'
+		);
+
+		unload_textdomain( 'notice' );
+		remove_filter( 'locale', 'filter_set_locale_to_polish' );
+
+		$this->assertInstanceOf( 'WP_Block_Type', $result );
+		$this->assertSame( 'tests/notice', $result->name );
+		$this->assertSame( 'Powiadomienie', $result->title );
+		$this->assertSame( 'Wyล›wietla ostrzeลผenie, bล‚ฤ…d lub powiadomienie o sukcesieโ€ฆ', $result->description );
+		$this->assertSameSets( array( 'ostrzeลผenie', 'wiadomoล›ฤ‡' ), $result->keywords );
+		$this->assertSame(
+			array(
+				array(
+					'name'      => 'default',
+					'label'     => 'Domyล›lny',
+					'isDefault' => true,
+				),
+				array(
+					'name'  => 'other',
+					'label' => 'Inny',
+				),
+			),
+			$result->styles
+		);
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	function test_get_dynamic_block_names() {
+		register_block_type( 'core/test-static', array() );
+		register_block_type( 'core/test-dynamic', array( 'render_callback' => array( $this, 'render_stub' ) ) );
+
+		$dynamic_block_names = get_dynamic_block_names();
+
+		$this->assertContains( 'core/test-dynamic', $dynamic_block_names );
+		$this->assertNotContains( 'core/test-static', $dynamic_block_names );
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	function test_has_blocks() {
+		// Test with passing post ID.
+		$this->assertTrue( has_blocks( self::$post_id ) );
+
+		// Test with passing WP_Post object.
+		$this->assertTrue( has_blocks( get_post( self::$post_id ) ) );
+
+		// Test with passing content string.
+		$this->assertTrue( has_blocks( get_post( self::$post_id ) ) );
+
+		// Test default.
+		$this->assertFalse( has_blocks() );
+		$query = new WP_Query( array( 'post__in' => array( self::$post_id ) ) );
+		$query->the_post();
+		$this->assertTrue( has_blocks() );
+
+		// Test string (without blocks).
+		$content = file_get_contents( DIR_TESTDATA . '/blocks/do-blocks-expected.html' );
+		$this->assertFalse( has_blocks( $content ) );
+	}
+
+	/**
+	 * @ticket 49615
+	 */
+	public function test_filter_block_registration() {
+		$filter_registration = function( $args, $name ) {
+			$args['attributes'] = array( $name => array( 'type' => 'boolean' ) );
+			return $args;
+		};
+
+		add_filter( 'register_block_type_args', $filter_registration, 10, 2 );
+		register_block_type( 'core/test-filtered', array() );
+		remove_filter( 'register_block_type_args', $filter_registration );
+
+		$registry   = WP_Block_Type_Registry::get_instance();
+		$block_type = $registry->get_registered( 'core/test-filtered' );
+		$this->assertSame( 'boolean', $block_type->attributes['core/test-filtered']['type'] );
+	}
+
+	/**
+	 * @ticket 52138
+	 */
+	public function test_filter_block_registration_metadata() {
+		$filter_metadata_registration = function( $metadata ) {
+			$metadata['apiVersion'] = 3;
+			return $metadata;
+		};
+
+		add_filter( 'block_type_metadata', $filter_metadata_registration, 10, 2 );
+		$result = register_block_type_from_metadata(
+			DIR_TESTDATA . '/blocks/notice'
+		);
+		remove_filter( 'block_type_metadata', $filter_metadata_registration );
+
+		$this->assertSame( 3, $result->api_version );
+	}
+
+	/**
+	 * @ticket 52138
+	 */
+	public function test_filter_block_registration_metadata_settings() {
+		$filter_metadata_registration = function( $settings, $metadata ) {
+			$settings['api_version'] = $metadata['apiVersion'] + 1;
+			return $settings;
+		};
+
+		add_filter( 'block_type_metadata_settings', $filter_metadata_registration, 10, 2 );
+		$result = register_block_type_from_metadata(
+			DIR_TESTDATA . '/blocks/notice'
+		);
+		remove_filter( 'block_type_metadata_settings', $filter_metadata_registration );
+
+		$this->assertSame( 3, $result->api_version );
+	}
+}

+ 134 - 0
tests/phpunit/tests/blocks/render-reusable.php

@@ -0,0 +1,134 @@
+<?php
+/**
+ * Reusable block rendering tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for reusable block rendering.
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Render_Reusable_Blocks extends WP_UnitTestCase {
+	/**
+	 * Fake user ID.
+	 *
+	 * @var int
+	 */
+	protected static $user_id;
+
+	/**
+	 * Fake block ID.
+	 *
+	 * @var int
+	 */
+	protected static $block_id;
+
+	/**
+	 * Fake post ID.
+	 *
+	 * @var int
+	 */
+	protected static $post_id;
+
+	/**
+	 * Create fake data before tests run.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param WP_UnitTest_Factory $factory Helper that creates fake data.
+	 */
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::$user_id = $factory->user->create(
+			array(
+				'role' => 'editor',
+			)
+		);
+
+		self::$post_id = $factory->post->create(
+			array(
+				'post_author'  => self::$user_id,
+				'post_type'    => 'post',
+				'post_status'  => 'publish',
+				'post_title'   => 'Test Post',
+				'post_content' => '<p>Hello world!</p>',
+			)
+		);
+
+		self::$block_id = $factory->post->create(
+			array(
+				'post_author'  => self::$user_id,
+				'post_type'    => 'wp_block',
+				'post_status'  => 'publish',
+				'post_title'   => 'Test Block',
+				'post_content' => '<!-- wp:core/paragraph --><p>Hello world!</p><!-- /wp:core/paragraph -->',
+			)
+		);
+	}
+
+	/**
+	 * Delete fake data after tests run.
+	 *
+	 * @since 5.0.0
+	 */
+	public static function wpTearDownAfterClass() {
+		wp_delete_post( self::$block_id, true );
+		wp_delete_post( self::$post_id, true );
+		self::delete_user( self::$user_id );
+	}
+
+	public function test_render() {
+		$block_type = WP_Block_Type_Registry::get_instance()->get_registered( 'core/block' );
+		$output     = $block_type->render( array( 'ref' => self::$block_id ) );
+		$this->assertSame( '<p>Hello world!</p>', $output );
+	}
+
+	/**
+	 * Make sure that a reusable block can be rendered twice in a row.
+	 *
+	 * @ticket 52364
+	 */
+	public function test_render_subsequent() {
+		$block_type = WP_Block_Type_Registry::get_instance()->get_registered( 'core/block' );
+		$output     = $block_type->render( array( 'ref' => self::$block_id ) );
+		$output    .= $block_type->render( array( 'ref' => self::$block_id ) );
+		$this->assertSame( '<p>Hello world!</p><p>Hello world!</p>', $output );
+	}
+
+	/**
+	 * Throw a warning if blocks are recursively nested.
+	 *
+	 * @ticket 52364
+	 */
+	public function test_recursive_render_warning() {
+		$recursive_reusable_block = array(
+			'ID'           => self::$block_id,
+			'post_content' => '<!-- wp:block {"ref":' . self::$block_id . '} /-->',
+		);
+		wp_update_post( $recursive_reusable_block );
+
+		$block_type = WP_Block_Type_Registry::get_instance()->get_registered( 'core/block' );
+
+		// The block_render method for `core/block` triggers a user warning if it
+		// encounters a recursively nested block.
+		$this->expectException( 'PHPUnit_Framework_Error_Warning' );
+		$block_type->render( array( 'ref' => self::$block_id ) );
+	}
+
+	public function test_ref_empty() {
+		$block_type = WP_Block_Type_Registry::get_instance()->get_registered( 'core/block' );
+		$output     = $block_type->render( array() );
+		$this->assertSame( '', $output );
+	}
+
+	public function test_ref_wrong_post_type() {
+		$block_type = WP_Block_Type_Registry::get_instance()->get_registered( 'core/block' );
+		$output     = $block_type->render( array( 'ref' => self::$post_id ) );
+		$this->assertSame( '', $output );
+	}
+}

+ 503 - 0
tests/phpunit/tests/blocks/render.php

@@ -0,0 +1,503 @@
+<?php
+/**
+ * Block rendering tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.0.0
+ */
+
+/**
+ * Tests for block rendering functions
+ *
+ * @since 5.0.0
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Render extends WP_UnitTestCase {
+	/**
+	 * The location of the fixtures to test with.
+	 *
+	 * @since 5.0.0
+	 * @var string
+	 */
+	protected static $fixtures_dir;
+
+	/**
+	 * Test block instance number.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @var int
+	 */
+	protected $test_block_instance_number = 0;
+
+	/**
+	 * Tear down after each test.
+	 *
+	 * @since 5.0.0
+	 */
+	public function tearDown() {
+		$this->test_block_instance_number = 0;
+
+		$registry = WP_Block_Type_Registry::get_instance();
+		if ( $registry->is_registered( 'core/test' ) ) {
+			$registry->unregister( 'core/test' );
+		}
+		if ( $registry->is_registered( 'core/dynamic' ) ) {
+			$registry->unregister( 'core/dynamic' );
+		}
+
+		parent::tearDown();
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function test_do_blocks_removes_comments() {
+		$original_html = file_get_contents( DIR_TESTDATA . '/blocks/do-blocks-original.html' );
+		$expected_html = file_get_contents( DIR_TESTDATA . '/blocks/do-blocks-expected.html' );
+
+		$actual_html = do_blocks( $original_html );
+
+		$this->assertSameIgnoreEOL( $expected_html, $actual_html );
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function test_the_content() {
+		add_shortcode( 'someshortcode', array( $this, 'handle_shortcode' ) );
+
+		$classic_content = "Foo\n\n[someshortcode]\n\nBar\n\n[/someshortcode]\n\nBaz";
+		$block_content   = "<!-- wp:core/paragraph -->\n<p>Foo</p>\n<!-- /wp:core/paragraph -->\n\n<!-- wp:core/shortcode -->[someshortcode]\n\nBar\n\n[/someshortcode]<!-- /wp:core/shortcode -->\n\n<!-- wp:core/paragraph -->\n<p>Baz</p>\n<!-- /wp:core/paragraph -->";
+
+		$classic_filtered_content = apply_filters( 'the_content', $classic_content );
+		$block_filtered_content   = apply_filters( 'the_content', $block_content );
+
+		// Block rendering add some extra blank lines, but we're not worried about them.
+		$block_filtered_content = preg_replace( "/\n{2,}/", "\n", $block_filtered_content );
+
+		remove_shortcode( 'someshortcode' );
+
+		$this->assertSame( trim( $classic_filtered_content ), trim( $block_filtered_content ) );
+	}
+
+	function handle_shortcode( $atts, $content ) {
+		return $content;
+	}
+
+	/**
+	 * @ticket 45495
+	 */
+	function test_nested_calls_to_the_content() {
+		register_block_type(
+			'core/test',
+			array(
+				'render_callback' => array(
+					$this,
+					'dynamic_the_content_call',
+				),
+			)
+		);
+
+		$content = "foo\n\nbar";
+
+		$the_content = apply_filters( 'the_content', '<!-- wp:core/test -->' . $content . '<!-- /wp:core/test -->' );
+
+		$this->assertSame( $content, $the_content );
+	}
+
+	function dynamic_the_content_call( $attrs, $content ) {
+		apply_filters( 'the_content', '' );
+		return $content;
+	}
+
+	public function test_can_nest_at_least_so_deep() {
+		$minimum_depth = 99;
+
+		$content = 'deep inside';
+		for ( $i = 0; $i < $minimum_depth; $i++ ) {
+			$content = '<!-- wp:core/test -->' . $content . '<!-- /wp:core/test -->';
+		}
+
+		$this->assertSame( 'deep inside', do_blocks( $content ) );
+	}
+
+	public function test_can_nest_at_least_so_deep_with_dynamic_blocks() {
+		$minimum_depth = 99;
+
+		$content = '0';
+		for ( $i = 0; $i < $minimum_depth; $i++ ) {
+			$content = '<!-- wp:core/test -->' . $content . '<!-- /wp:core/test -->';
+		}
+
+		register_block_type(
+			'core/test',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_dynamic_incrementer',
+				),
+			)
+		);
+
+		$this->assertSame( $minimum_depth, (int) do_blocks( $content ) );
+	}
+
+	public function render_dynamic_incrementer( $attrs, $content ) {
+		return (string) ( 1 + (int) $content );
+	}
+
+	/**
+	 * @ticket 45290
+	 */
+	public function test_blocks_arent_autopeed() {
+		$expected_content = 'test';
+		$test_content     = "<!-- wp:fake/block -->\n$expected_content\n<!-- /wp:fake/block -->";
+
+		$current_priority = has_action( 'the_content', 'wpautop' );
+
+		$filtered_content = trim( apply_filters( 'the_content', $test_content ) );
+
+		$this->assertSame( $expected_content, $filtered_content );
+
+		// Check that wpautop() is still defined in the same place.
+		$this->assertSame( $current_priority, has_action( 'the_content', 'wpautop' ) );
+		// ... and that the restore function has removed itself.
+		$this->assertFalse( has_action( 'the_content', '_restore_wpautop_hook' ) );
+
+		$test_content     = 'test';
+		$expected_content = "<p>$test_content</p>";
+
+		$current_priority = has_action( 'the_content', 'wpautop' );
+
+		$filtered_content = trim( apply_filters( 'the_content', $test_content ) );
+
+		$this->assertSame( $expected_content, $filtered_content );
+
+		$this->assertSame( $current_priority, has_action( 'the_content', 'wpautop' ) );
+		$this->assertFalse( has_action( 'the_content', '_restore_wpautop_hook' ) );
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function data_do_block_test_filenames() {
+		self::$fixtures_dir = DIR_TESTDATA . '/blocks/fixtures';
+
+		$fixture_filenames = array_merge(
+			glob( self::$fixtures_dir . '/*.json' ),
+			glob( self::$fixtures_dir . '/*.html' )
+		);
+
+		$fixture_filenames = array_values(
+			array_unique(
+				array_map(
+					array( $this, 'clean_fixture_filename' ),
+					$fixture_filenames
+				)
+			)
+		);
+
+		return array_map(
+			array( $this, 'pass_parser_fixture_filenames' ),
+			$fixture_filenames
+		);  }
+
+	/**
+	 * @dataProvider data_do_block_test_filenames
+	 * @ticket 45109
+	 */
+	public function test_do_block_output( $html_filename, $server_html_filename ) {
+		$html_path        = self::$fixtures_dir . '/' . $html_filename;
+		$server_html_path = self::$fixtures_dir . '/' . $server_html_filename;
+
+		foreach ( array( $html_path, $server_html_path ) as $filename ) {
+			if ( ! file_exists( $filename ) ) {
+				throw new Exception( "Missing fixture file: '$filename'" );
+			}
+		}
+
+		$html          = do_blocks( self::strip_r( file_get_contents( $html_path ) ) );
+		$expected_html = self::strip_r( file_get_contents( $server_html_path ) );
+
+		$this->assertSame(
+			$expected_html,
+			$html,
+			"File '$html_path' does not match expected value"
+		);
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function test_dynamic_block_rendering() {
+		$settings = array(
+			'render_callback' => array(
+				$this,
+				'render_test_block',
+			),
+		);
+		register_block_type( 'core/test', $settings );
+
+		// The duplicated dynamic blocks below are there to ensure that do_blocks() replaces each one-by-one.
+		$post_content =
+			'before' .
+			'<!-- wp:core/test {"value":"b1"} --><!-- /wp:core/test -->' .
+			'<!-- wp:core/test {"value":"b1"} --><!-- /wp:core/test -->' .
+			'between' .
+			'<!-- wp:core/test {"value":"b2"} /-->' .
+			'<!-- wp:core/test {"value":"b2"} /-->' .
+			'after';
+
+		$updated_post_content = do_blocks( $post_content );
+		$this->assertSame(
+			$updated_post_content,
+			'before' .
+			'1:b1' .
+			'2:b1' .
+			'between' .
+			'3:b2' .
+			'4:b2' .
+			'after'
+		);
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function test_global_post_persistence() {
+		global $post;
+
+		register_block_type(
+			'core/test',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_test_block_wp_query',
+				),
+			)
+		);
+
+		$posts = self::factory()->post->create_many( 5 );
+		$post  = get_post( end( $posts ) );
+
+		$global_post = $post;
+		do_blocks( '<!-- wp:core/test /-->' );
+
+		$this->assertSame( $global_post, $post );
+	}
+
+	public function test_render_latest_comments_on_password_protected_post() {
+		$post_id      = self::factory()->post->create(
+			array(
+				'post_password' => 'password',
+			)
+		);
+		$comment_text = wp_generate_password( 10, false );
+		self::factory()->comment->create(
+			array(
+				'comment_post_ID' => $post_id,
+				'comment_content' => $comment_text,
+			)
+		);
+		$comments = do_blocks( '<!-- wp:latest-comments {"commentsToShow":1,"displayExcerpt":true} /-->' );
+
+		$this->assertNotContains( $comment_text, $comments );
+	}
+
+	/**
+	 * @ticket 45109
+	 */
+	public function test_dynamic_block_renders_string() {
+		$settings = array(
+			'render_callback' => array(
+				$this,
+				'render_test_block_numeric',
+			),
+		);
+
+		register_block_type( 'core/test', $settings );
+		$block_type = new WP_Block_Type( 'core/test', $settings );
+
+		$rendered = $block_type->render();
+
+		$this->assertSame( '10', $rendered );
+		$this->assertInternalType( 'string', $rendered );
+	}
+
+	public function test_dynamic_block_gets_inner_html() {
+		register_block_type(
+			'core/dynamic',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_serialize_dynamic_block',
+				),
+			)
+		);
+
+		$output = do_blocks( '<!-- wp:dynamic -->inner<!-- /wp:dynamic -->' );
+
+		$data = unserialize( base64_decode( $output ) );
+
+		$this->assertSame( 'inner', $data[1] );
+	}
+
+	public function test_dynamic_block_gets_rendered_inner_blocks() {
+		register_block_type(
+			'core/test',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_test_block_numeric',
+				),
+			)
+		);
+
+		register_block_type(
+			'core/dynamic',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_serialize_dynamic_block',
+				),
+			)
+		);
+
+		$output = do_blocks( '<!-- wp:dynamic -->before<!-- wp:test /-->after<!-- /wp:dynamic -->' );
+
+		$data = unserialize( base64_decode( $output ) );
+
+		$this->assertSame( 'before10after', $data[1] );
+	}
+
+	public function test_dynamic_block_gets_rendered_inner_dynamic_blocks() {
+		register_block_type(
+			'core/dynamic',
+			array(
+				'render_callback' => array(
+					$this,
+					'render_serialize_dynamic_block',
+				),
+			)
+		);
+
+		$output = do_blocks( '<!-- wp:dynamic -->before<!-- wp:dynamic -->deep inner<!-- /wp:dynamic -->after<!-- /wp:dynamic -->' );
+
+		$data = unserialize( base64_decode( $output ) );
+
+		$inner = $this->render_serialize_dynamic_block( array(), 'deep inner' );
+
+		$this->assertSame( $data[1], 'before' . $inner . 'after' );
+	}
+
+	/**
+	 * Helper function to remove relative paths and extension from a filename, leaving just the fixture name.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param string $filename The filename to clean.
+	 * @return string The cleaned fixture name.
+	 */
+	protected function clean_fixture_filename( $filename ) {
+		$filename = wp_basename( $filename );
+		$filename = preg_replace( '/\..+$/', '', $filename );
+		return $filename;
+	}
+
+	/**
+	 * Helper function to return the filenames needed to test the parser output.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @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 ) {
+		return array(
+			"$filename.html",
+			"$filename.server.html",
+		);
+	}
+
+	/**
+	 * Helper function to remove '\r' characters from a string.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param string $input The string to remove '\r' from.
+	 * @return string The input string, with '\r' characters removed.
+	 */
+	protected function strip_r( $input ) {
+		return str_replace( "\r", '', $input );
+	}
+
+	/**
+	 * Test block rendering function.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @param array $attributes Block attributes.
+	 * @return string Block output.
+	 */
+	public function render_test_block( $attributes ) {
+		$this->test_block_instance_number += 1;
+		return $this->test_block_instance_number . ':' . $attributes['value'];
+	}
+
+	/**
+	 * Test block rendering function, returning numeric value.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @return int Block output.
+	 */
+	public function render_test_block_numeric() {
+		return 10;
+	}
+
+	/**
+	 * Test block rendering function, returning base64 encoded serialised value.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @return string Block output.
+	 */
+	public function render_serialize_dynamic_block( $attributes, $content ) {
+		return base64_encode( serialize( array( $attributes, $content ) ) );
+	}
+
+	/**
+	 * Test block rendering function, creating a new WP_Query instance.
+	 *
+	 * @since 5.0.0
+	 *
+	 * @return string Block output.
+	 */
+	public function render_test_block_wp_query() {
+		$content = '';
+		$recent  = new WP_Query(
+			array(
+				'numberposts'      => 10,
+				'orderby'          => 'ID',
+				'order'            => 'DESC',
+				'post_type'        => 'post',
+				'post_status'      => 'draft, publish, future, pending, private',
+				'suppress_filters' => true,
+			)
+		);
+
+		while ( $recent->have_posts() ) {
+			$recent->the_post();
+
+			$content .= get_the_title();
+		}
+
+		wp_reset_postdata();
+
+		return $content;
+	}
+
+}

+ 60 - 0
tests/phpunit/tests/blocks/serialization.php

@@ -0,0 +1,60 @@
+<?php
+/**
+ * Block serialization tests.
+ *
+ * @package WordPress
+ * @subpackage Blocks
+ * @since 5.3.3
+ */
+
+/**
+ * Tests for block serialization functions
+ *
+ * @since 5.3.3
+ *
+ * @group blocks
+ */
+class WP_Test_Block_Serialization extends WP_UnitTestCase {
+
+	/**
+	 * @dataProvider data_serialize_identity_from_parsed
+	 */
+	function test_serialize_identity_from_parsed( $original ) {
+		$blocks = parse_blocks( $original );
+
+		$actual   = serialize_blocks( $blocks );
+		$expected = $original;
+
+		$this->assertSame( $expected, $actual );
+	}
+
+	function data_serialize_identity_from_parsed() {
+		return array(
+			// Void block.
+			array( '<!-- wp:void /-->' ),
+
+			// Freeform content ($block_name = null).
+			array( 'Example.' ),
+
+			// Block with content.
+			array( '<!-- wp:content -->Example.<!-- /wp:content -->' ),
+
+			// Block with attributes.
+			array( '<!-- wp:attributes {"key":"value"} /-->' ),
+
+			// Block with inner blocks.
+			array( "<!-- wp:outer --><!-- wp:inner {\"key\":\"value\"} -->Example.<!-- /wp:inner -->\n\nExample.\n\n<!-- wp:void /--><!-- /wp:outer -->" ),
+
+			// Block with attribute values that may conflict with HTML comment.
+			array( '<!-- wp:attributes {"key":"\\u002d\\u002d\\u003c\\u003e\\u0026\\u0022"} /-->' ),
+		);
+	}
+
+	function test_serialized_block_name() {
+		$this->assertNull( strip_core_block_namespace( null ) );
+		$this->assertSame( 'example', strip_core_block_namespace( 'example' ) );
+		$this->assertSame( 'example', strip_core_block_namespace( 'core/example' ) );
+		$this->assertSame( 'plugin/example', strip_core_block_namespace( 'plugin/example' ) );
+	}
+
+}

+ 151 - 0
tests/phpunit/tests/bookmark/getBookmarks.php

@@ -0,0 +1,151 @@
+<?php
+
+/**
+ * @group bookmark
+ */
+class Tests_Bookmark_GetBookmarks extends WP_UnitTestCase {
+	public function test_should_hit_cache() {
+		global $wpdb;
+
+		$bookmarks = self::factory()->bookmark->create_many( 2 );
+
+		$found1 = get_bookmarks(
+			array(
+				'orderby' => 'link_id',
+			)
+		);
+
+		$num_queries = $wpdb->num_queries;
+
+		$found2 = get_bookmarks(
+			array(
+				'orderby' => 'link_id',
+			)
+		);
+
+		$this->assertSameSets( $found1, $found2 );
+		$this->assertSame( $num_queries, $wpdb->num_queries );
+	}
+
+	public function test_adding_bookmark_should_bust_get_bookmarks_cache() {
+		global $wpdb;
+
+		$bookmarks = self::factory()->bookmark->create_many( 2 );
+
+		// Prime cache.
+		$found1 = get_bookmarks(
+			array(
+				'orderby' => 'link_id',
+			)
+		);
+
+		$num_queries = $wpdb->num_queries;
+
+		$bookmarks[] = wp_insert_link(
+			array(
+				'link_name' => 'foo',
+				'link_url'  => 'http://example.com',
+			)
+		);
+
+		$found2 = get_bookmarks(
+			array(
+				'orderby' => 'link_id',
+			)
+		);
+
+		$this->assertEqualSets( $bookmarks, wp_list_pluck( $found2, 'link_id' ) );
+		$this->assertTrue( $num_queries < $wpdb->num_queries );
+	}
+
+	/**
+	 * @ticket 18356
+	 */
+	public function test_orderby_rand_should_not_be_cached() {
+		global $wpdb;
+
+		$bookmarks = self::factory()->bookmark->create_many( 2 );
+
+		$found1 = get_bookmarks(
+			array(
+				'orderby' => 'rand',
+			)
+		);
+
+		$num_queries = $wpdb->num_queries;
+
+		$found2 = get_bookmarks(
+			array(
+				'orderby' => 'rand',
+			)
+		);
+
+		// Equal sets != same order.
+		$this->assertEqualSets( $found1, $found2 );
+		$this->assertTrue( $num_queries < $wpdb->num_queries );
+	}
+
+	public function test_exclude_param_gets_properly_parsed_as_list() {
+		$bookmarks = self::factory()->bookmark->create_many( 3 );
+
+		$found = get_bookmarks(
+			array(
+				'exclude' => ',,',
+			)
+		);
+
+		$found_ids = array();
+		foreach ( $found as $bookmark ) {
+			$found_ids[] = $bookmark->link_id;
+		}
+
+		// Equal sets != same order.
+		$this->assertEqualSets( $bookmarks, $found_ids );
+	}
+
+	public function test_include_param_gets_properly_parsed_as_list() {
+		$bookmarks = self::factory()->bookmark->create_many( 3 );
+
+		$found = get_bookmarks(
+			array(
+				'include' => ',,',
+			)
+		);
+
+		$found_ids = array();
+		foreach ( $found as $bookmark ) {
+			$found_ids[] = $bookmark->link_id;
+		}
+
+		// Equal sets != same order.
+		$this->assertEqualSets( $bookmarks, $found_ids );
+	}
+
+	public function test_category_param_propelry_gets_parsed_as_list() {
+		$bookmarks  = self::factory()->bookmark->create_many( 3 );
+		$categories = self::factory()->term->create_many(
+			3,
+			array(
+				'taxonomy' => 'link_category',
+			)
+		);
+
+		$add = wp_add_object_terms( $bookmarks[0], $categories[0], 'link_category' );
+		$add = wp_add_object_terms( $bookmarks[1], $categories[1], 'link_category' );
+		$add = wp_add_object_terms( $bookmarks[2], $categories[2], 'link_category' );
+
+		$found = get_bookmarks(
+			array(
+				'category' => ',,',
+			)
+		);
+
+		$found_ids = array();
+		foreach ( $found as $bookmark ) {
+			$found_ids[] = $bookmark->link_id;
+		}
+
+		// Equal sets != same order.
+		$this->assertEqualSets( $bookmarks, $found_ids );
+	}
+}

+ 111 - 0
tests/phpunit/tests/canonical/category.php

@@ -0,0 +1,111 @@
+<?php
+
+/**
+ * @group canonical
+ */
+class Tests_Canonical_Category extends WP_Canonical_UnitTestCase {
+	public $structure = '/%category%/%postname%/';
+
+	public static $posts = array();
+	public static $cats  = array();
+
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+
+		self::$posts[0] = $factory->post->create( array( 'post_name' => 'post0' ) );
+		self::$posts[1] = $factory->post->create( array( 'post_name' => 'post1' ) );
+		self::$cats[0]  = $factory->category->create( array( 'slug' => 'cat0' ) );
+		self::$cats[1]  = $factory->category->create( array( 'slug' => 'cat1' ) );
+		self::$cats[2]  = $factory->category->create( array( 'slug' => 'cat2' ) );
+
+		wp_set_post_categories( self::$posts[0], self::$cats[2] );
+		wp_set_post_categories( self::$posts[0], self::$cats[0] );
+		wp_set_post_categories( self::$posts[1], self::$cats[1] );
+	}
+
+	/**
+	 * @dataProvider data_canonical_category
+	 */
+	public function test_canonical_category( $test_url, $expected, $ticket = 0, $expected_doing_it_wrong = array() ) {
+		$this->assertCanonical( $test_url, $expected, $ticket, $expected_doing_it_wrong );
+	}
+
+	public function data_canonical_category() {
+		/*
+		 * Data format:
+		 * [0]: Test URL.
+		 * [1]: Expected results: Any of the following can be used.
+		 *      array( 'url': expected redirection location, 'qv': expected query vars to be set via the rewrite AND $_GET );
+		 *      array( expected query vars to be set, same as 'qv' above )
+		 *      (string) expected redirect location
+		 * [2]: (optional) The ticket the test refers to, Can be skipped if unknown.
+		 * [3]: (optional) Array of class/function names expected to throw `_doing_it_wrong()` notices.
+		 */
+
+		return array(
+			// Valid category.
+			array(
+				'/cat0/post0/',
+				array(
+					'url' => '/cat0/post0/',
+					'qv'  => array(
+						'category_name' => 'cat0',
+						'name'          => 'post0',
+						'page'          => '',
+					),
+				),
+			),
+
+			// Category other than the first one will redirect to first "canonical" category.
+			array(
+				'/cat2/post0/',
+				array(
+					'url' => '/cat0/post0/',
+					'qv'  => array(
+						'category_name' => 'cat0',
+						'name'          => 'post0',
+						'page'          => '',
+					),
+				),
+			),
+
+			// Incorrect category will redirect to correct one.
+			array(
+				'/cat1/post0/',
+				array(
+					'url' => '/cat0/post0/',
+					'qv'  => array(
+						'category_name' => 'cat0',
+						'name'          => 'post0',
+						'page'          => '',
+					),
+				),
+			),
+
+			// Nonexistent category will redirect to correct one.
+			array(
+				'/foo/post0/',
+				array(
+					'url' => '/cat0/post0/',
+					'qv'  => array(
+						'category_name' => 'cat0',
+						'name'          => 'post0',
+						'page'          => '',
+					),
+				),
+			),
+
+			// Embed URLs should not redirect to post permalinks.
+			array(
+				'/cat0/post0/embed/',
+				array(
+					'url' => '/cat0/post0/embed/',
+					'qv'  => array(
+						'category_name' => 'cat0',
+						'name'          => 'post0',
+						'embed'         => 'true',
+					),
+				),
+			),
+		);
+	}
+}

+ 54 - 0
tests/phpunit/tests/canonical/https.php

@@ -0,0 +1,54 @@
+<?php
+
+/**
+ * @group canonical
+ * @group rewrite
+ * @group query
+ */
+class Tests_Canonical_HTTPS extends WP_Canonical_UnitTestCase {
+	function setUp() {
+		parent::setUp();
+
+		$this->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' );
+		create_initial_taxonomies();
+
+		$this->http  = set_url_scheme( home_url( 'sample-page/' ), 'http' );
+		$this->https = set_url_scheme( home_url( 'sample-page/' ), 'https' );
+	}
+
+	public function set_https( $url ) {
+		return set_url_scheme( $url, 'https' );
+	}
+
+	/**
+	 * @ticket 27954
+	 */
+	public function test_http_request_with_http_home() {
+		$redirect = redirect_canonical( $this->http, false );
+
+		$this->assertNull( $redirect );
+	}
+
+	/**
+	 * @ticket 27954
+	 */
+	public function test_https_request_with_http_home() {
+		$redirect = redirect_canonical( $this->https, false );
+
+		$this->assertNull( $redirect );
+	}
+
+	/**
+	 * @ticket 27954
+	 */
+	public function test_https_request_with_https_home() {
+		add_filter( 'home_url', array( $this, 'set_https' ) );
+
+		$redirect = redirect_canonical( $this->https, false );
+
+		$this->assertNull( $redirect );
+
+		remove_filter( 'home_url', array( $this, 'set_https' ) );
+	}
+
+}

+ 30 - 0
tests/phpunit/tests/canonical/paged.php

@@ -0,0 +1,30 @@
+<?php
+/**
+ * @group canonical
+ * @group rewrite
+ * @group query
+ */
+class Tests_Canonical_Paged extends WP_Canonical_UnitTestCase {
+
+	function test_redirect_canonical_with_nextpage_pagination() {
+		$para = 'This is a paragraph.
+			This is a paragraph.
+			This is a paragraph.';
+		$next = '<!--nextpage-->';
+
+		$post_id = self::factory()->post->create(
+			array(
+				'post_status'  => 'publish',
+				'post_content' => "{$para}{$next}{$para}{$next}{$para}",
+			)
+		);
+
+		$link = parse_url( get_permalink( $post_id ), PHP_URL_PATH );
+
+		// Existing page should be displayed as is.
+		$this->assertCanonical( $link . '3/', $link . '3/' );
+		// Non-existing page should redirect to the permalink.
+		$this->assertCanonical( $link . '4/', $link );
+	}
+
+}

+ 973 - 0
tests/phpunit/tests/canonical/postStatus.php

@@ -0,0 +1,973 @@
+<?php
+
+/**
+ * @group canonical
+ * @group rewrite
+ * @group query
+ */
+class Tests_Canonical_PostStatus extends WP_Canonical_UnitTestCase {
+
+	/**
+	 * User IDs.
+	 *
+	 * @var array
+	 */
+	public static $users;
+
+	/**
+	 * Post Objects.
+	 *
+	 * @var array
+	 */
+	public static $posts;
+
+	public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) {
+		self::setup_custom_types();
+		self::$users = array(
+			'anon'           => 0,
+			'subscriber'     => $factory->user->create( array( 'role' => 'subscriber' ) ),
+			'content_author' => $factory->user->create( array( 'role' => 'author' ) ),
+			'editor'         => $factory->user->create( array( 'role' => 'editor' ) ),
+		);
+
+		$post_statuses = array( 'publish', 'future', 'draft', 'pending', 'private', 'auto-draft', 'a-private-status' );
+		foreach ( $post_statuses as $post_status ) {
+			$post_date = '';
+			if ( 'future' === $post_status ) {
+				$post_date = strftime( '%Y-%m-%d %H:%M:%S', strtotime( '+1 year' ) );
+			}
+
+			self::$posts[ $post_status ] = $factory->post->create_and_get(
+				array(
+					'post_type'    => 'post',
+					'post_title'   => "$post_status post",
+					'post_name'    => "$post_status-post",
+					'post_status'  => $post_status,
+					'post_content' => "Prevent canonical redirect exposing post slugs.\n\n<!--nextpage-->Page 2",
+					'post_author'  => self::$users['content_author'],
+					'post_date'    => $post_date,
+				)
+			);
+
+			// Add fake attachment to the post (file upload not needed).
+			self::$posts[ "$post_status-attachment" ] = $factory->post->create_and_get(
+				array(
+					'post_type'    => 'attachment',
+					'post_title'   => "$post_status inherited attachment",
+					'post_name'    => "$post_status-inherited-attachment",
+					'post_status'  => 'inherit',
+					'post_content' => "Prevent canonical redirect exposing post via attachments.\n\n<!--nextpage-->Page 2",
+					'post_author'  => self::$users['content_author'],
+					'post_parent'  => self::$posts[ $post_status ]->ID,
+					'post_date'    => $post_date,
+				)
+			);
+
+			// Set up a page with same.
+			self::$posts[ "$post_status-page" ] = $factory->post->create_and_get(
+				array(
+					'post_type'    => 'page',
+					'post_title'   => "$post_status page",
+					'post_name'    => "$post_status-page",
+					'post_status'  => $post_status,
+					'post_content' => "Prevent canonical redirect exposing page slugs.\n\n<!--nextpage-->Page 2",
+					'post_author'  => self::$users['content_author'],
+					'post_date'    => $post_date,
+				)
+			);
+		}
+
+		// Create a public CPT using a private status.
+		self::$posts['a-public-cpt'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'a-public-cpt',
+				'post_title'   => 'a-public-cpt',
+				'post_name'    => 'a-public-cpt',
+				'post_status'  => 'private',
+				'post_content' => 'Prevent canonical redirect exposing a-public-cpt titles.',
+				'post_author'  => self::$users['content_author'],
+			)
+		);
+
+		// Add fake attachment to the public cpt (file upload not needed).
+		self::$posts['a-public-cpt-attachment'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'attachment',
+				'post_title'   => 'a-public-cpt post inherited attachment',
+				'post_name'    => 'a-public-cpt-inherited-attachment',
+				'post_status'  => 'inherit',
+				'post_content' => "Prevent canonical redirect exposing post via attachments.\n\n<!--nextpage-->Page 2",
+				'post_author'  => self::$users['content_author'],
+				'post_parent'  => self::$posts['a-public-cpt']->ID,
+			)
+		);
+
+		// Create a private CPT with a public status.
+		self::$posts['a-private-cpt'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'a-private-cpt',
+				'post_title'   => 'a-private-cpt',
+				'post_name'    => 'a-private-cpt',
+				'post_status'  => 'publish',
+				'post_content' => 'Prevent canonical redirect exposing a-private-cpt titles.',
+				'post_author'  => self::$users['content_author'],
+			)
+		);
+
+		// Add fake attachment to the private cpt (file upload not needed).
+		self::$posts['a-private-cpt-attachment'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'attachment',
+				'post_title'   => 'a-private-cpt post inherited attachment',
+				'post_name'    => 'a-private-cpt-inherited-attachment',
+				'post_status'  => 'inherit',
+				'post_content' => "Prevent canonical redirect exposing post via attachments.\n\n<!--nextpage-->Page 2",
+				'post_author'  => self::$users['content_author'],
+				'post_parent'  => self::$posts['a-private-cpt']->ID,
+			)
+		);
+
+		// Post for trashing.
+		self::$posts['trash'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'post',
+				'post_title'   => 'trash post',
+				'post_name'    => 'trash-post',
+				'post_status'  => 'publish',
+				'post_content' => "Prevent canonical redirect exposing post slugs.\n\n<!--nextpage-->Page 2",
+				'post_author'  => self::$users['content_author'],
+			)
+		);
+
+		self::$posts['trash-attachment'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'attachment',
+				'post_title'   => 'trash post inherited attachment',
+				'post_name'    => 'trash-post-inherited-attachment',
+				'post_status'  => 'inherit',
+				'post_content' => "Prevent canonical redirect exposing post via attachments.\n\n<!--nextpage-->Page 2",
+				'post_author'  => self::$users['content_author'],
+				'post_parent'  => self::$posts['trash']->ID,
+			)
+		);
+
+		// Page for trashing.
+		self::$posts['trash-page'] = $factory->post->create_and_get(
+			array(
+				'post_type'    => 'page',
+				'post_title'   => 'trash page',
+				'post_name'    => 'trash-page',
+				'post_status'  => 'publish',
+				'post_content' => "Prevent canonical redirect exposing page slugs.\n\n<!--nextpage-->Page 2",
+				'post_author'  => self::$users['content_author'],
+			)
+		);
+		wp_trash_post( self::$posts['trash']->ID );
+		wp_trash_post( self::$posts['trash-page']->ID );
+	}
+
+	function setUp() {
+		parent::setUp();
+		self::setup_custom_types();
+	}
+
+	/**
+	 * Set up a custom post type and private status.
+	 *
+	 * This needs to be called both in the class setup and
+	 * test setup.
+	 */
+	public static function setup_custom_types() {
+		// Register public custom post type.
+		register_post_type(
+			'a-public-cpt',
+			array(
+				'public'  => true,
+				'rewrite' => array(
+					'slug' => 'a-public-cpt',
+				),
+			)
+		);
+
+		// Register private custom post type.
+		register_post_type(
+			'a-private-cpt',
+			array(
+				'public'             => false,
+				'publicly_queryable' => false,
+				'rewrite'            => array(
+					'slug' => 'a-private-cpt',
+				),
+				'map_meta_cap'       => true,
+			)
+		);
+
+		// Register custom private post status.
+		register_post_status(
+			'a-private-status',
+			array(
+				'private' => true,
+			)
+		);
+	}
+
+	/**
+	 * Test canonical redirect does not reveal private posts presence.
+	 *
+	 * @ticket 5272
+	 * @dataProvider data_canonical_redirects_to_plain_permalinks
+	 *
+	 * @param string $post_key  Post key used for creating fixtures.
+	 * @param string $user_role User role.
+	 * @param string $requested Requested URL.
+	 * @param string $expected  Expected URL.
+	 */
+	public function test_canonical_redirects_to_plain_permalinks( $post_key, $user_role, $requested, $expected ) {
+		wp_set_current_user( self::$users[ $user_role ] );
+		$this->set_permalink_structure( '' );
+		$post = self::$posts[ $post_key ];
+		clean_post_cache( $post->ID );
+
+		/*
+		 * The dataProvider runs before the fixures are set up, therefore the
+		 * post object IDs are placeholders that needs to be replaced.
+		 */
+		$requested = str_replace( '%ID%', $post->ID, $requested );
+		$expected  = str_replace( '%ID%', $post->ID, $expected );
+
+		$this->assertCanonical( $requested, $expected );
+	}
+
+	/**
+	 * Data provider for test_canonical_redirects_to_plain_permalinks.
+	 *
+	 * @return array[] Array of arguments for tests {
+	 *     @type string $post_key  Post key used for creating fixtures.
+	 *     @type string $user_role User role.
+	 *     @type string $requested Requested URL.
+	 *     @type string $expected  Expected URL.
+	 * }
+	 */
+	function data_canonical_redirects_to_plain_permalinks() {
+		$data              = array();
+		$all_user_list     = array( 'anon', 'subscriber', 'content_author', 'editor' );
+		$select_allow_list = array( 'content_author', 'editor' );
+		$select_block_list = array( 'anon', 'subscriber' );
+		// All post/page keys
+		$all_user_post_status_keys    = array( 'publish' );
+		$select_user_post_status_keys = array( 'private', 'a-private-status' );
+		$no_user_post_status_keys     = array( 'future', 'draft', 'pending', 'auto-draft' ); // Excludes trash for attachment rules.
+		$select_user_post_type_keys   = array( 'a-public-cpt' );
+		$no_user_post_type_keys       = array( 'a-private-cpt' );
+
+		foreach ( $all_user_post_status_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				/*
+				 * In the event `redirect_canonical()` is updated to redirect plain permalinks
+				 * to a canonical plain version, these expected values can be changed.
+				 */
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				// Ensure rss redirects to rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss2&p=%ID%',
+				);
+
+				// Ensure rss redirects to rss2.
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss2&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( $select_user_post_status_keys as $post_key ) {
+			foreach ( $select_allow_list as $user ) {
+				/*
+				 * In the event `redirect_canonical()` is updated to redirect plain permalinks
+				 * to a canonical plain version, these expected values can be changed.
+				 */
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				// Ensure rss redirects to rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss2&p=%ID%',
+				);
+
+				// Ensure rss redirects to rss2.
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss2&page_id=%ID%',
+				);
+			}
+
+			foreach ( $select_block_list as $user ) {
+				/*
+				 * In the event `redirect_canonical()` is updated to redirect plain permalinks
+				 * to a canonical plain version, these expected values MUST NOT be changed.
+				 */
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( $no_user_post_status_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				/*
+				 * In the event `redirect_canonical()` is updated to redirect plain permalinks
+				 * to a canonical plain version, these expected values MUST NOT be changed.
+				 */
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( array( 'trash' ) as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				/*
+				 * In the event `redirect_canonical()` is updated to redirect plain permalinks
+				 * to a canonical plain version, these expected values MUST NOT be changed.
+				 */
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				// Ensure post's existence is not demonstrated by changing rss to rss2.
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( $select_user_post_type_keys as $post_key ) {
+			foreach ( $select_allow_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?a-public-cpt=a-public-cpt',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/?name=$post_key&post_type=$post_key",
+				);
+
+				// Ensure rss is replaced by rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?a-public-cpt=a-public-cpt&feed=rss2',
+				);
+			}
+
+			foreach ( $select_block_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/?name=$post_key&post_type=$post_key",
+				);
+
+				// Ensure rss is not replaced with rss2.
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+			}
+		}
+
+		foreach ( $no_user_post_type_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/?name=$post_key&post_type=$post_key",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+			}
+		}
+
+		return $data;
+	}
+
+	/**
+	 * Test canonical redirect does not reveal private slugs.
+	 *
+	 * @ticket 5272
+	 * @dataProvider data_canonical_redirects_to_pretty_permalinks
+	 *
+	 * @param string $post_key  Post key used for creating fixtures.
+	 * @param string $user_role User role.
+	 * @param string $requested Requested URL.
+	 * @param string $expected  Expected URL.
+	 */
+	public function test_canonical_redirects_to_pretty_permalinks( $post_key, $user_role, $requested, $expected ) {
+		wp_set_current_user( self::$users[ $user_role ] );
+		$this->set_permalink_structure( '/%postname%/' );
+		$post = self::$posts[ $post_key ];
+		clean_post_cache( $post->ID );
+
+		/*
+		 * The dataProvider runs before the fixures are set up, therefore the
+		 * post object IDs are placeholders that needs to be replaced.
+		 */
+		$requested = str_replace( '%ID%', $post->ID, $requested );
+		$expected  = str_replace( '%ID%', $post->ID, $expected );
+
+		$this->assertCanonical( $requested, $expected );
+	}
+
+	/**
+	 * Data provider for test_canonical_redirects_to_pretty_permalinks.
+	 *
+	 * @return array[] Array of arguments for tests {
+	 *     @type string $post_key  Post key used for creating fixtures.
+	 *     @type string $user_role User role.
+	 *     @type string $requested Requested URL.
+	 *     @type string $expected  Expected URL.
+	 * }
+	 */
+	function data_canonical_redirects_to_pretty_permalinks() {
+		$data              = array();
+		$all_user_list     = array( 'anon', 'subscriber', 'content_author', 'editor' );
+		$select_allow_list = array( 'content_author', 'editor' );
+		$select_block_list = array( 'anon', 'subscriber' );
+		// All post/page keys
+		$all_user_post_status_keys    = array( 'publish' );
+		$select_user_post_status_keys = array( 'private', 'a-private-status' );
+		$no_user_post_status_keys     = array( 'future', 'draft', 'pending', 'auto-draft' ); // Excludes trash for attachment rules.
+		$select_user_post_type_keys   = array( 'a-public-cpt' );
+		$no_user_post_type_keys       = array( 'a-private-cpt' );
+
+		foreach ( $all_user_post_status_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					"/$post_key-post/",
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					"/$post_key-post/$post_key-inherited-attachment/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					"/$post_key-page/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?page_id=%ID%',
+					"/$post_key-page/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/$post_key-post/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					"/$post_key-post/feed/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					"/$post_key-page/feed/",
+				);
+			}
+		}
+
+		foreach ( $select_user_post_status_keys as $post_key ) {
+			foreach ( $select_allow_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					"/$post_key-post/",
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					"/$post_key-post/$post_key-inherited-attachment/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					"/$post_key-page/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?page_id=%ID%',
+					"/$post_key-page/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/$post_key-post/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					"/$post_key-post/feed/",
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					"/$post_key-page/feed/",
+				);
+			}
+
+			foreach ( $select_block_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?page_id=%ID%',
+					'/?page_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( $select_user_post_type_keys as $post_key ) {
+			foreach ( $select_allow_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					"/$post_key/$post_key/",
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					"/$post_key/$post_key/$post_key-inherited-attachment/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/$post_key/$post_key/?post_type=$post_key",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					"/$post_key/$post_key/feed/",
+				);
+			}
+
+			foreach ( $select_block_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/?name=$post_key&post_type=$post_key",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+			}
+		}
+
+		foreach ( $no_user_post_type_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+					// "/$post_key-inherited-attachment/",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key&post_type=$post_key",
+					"/?name=$post_key&post_type=$post_key",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+			}
+		}
+
+		foreach ( $no_user_post_status_keys as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?page_id=%ID%',
+					'/?page_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		foreach ( array( 'trash' ) as $post_key ) {
+			foreach ( $all_user_list as $user ) {
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?p=%ID%',
+					'/?p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/?attachment_id=%ID%',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/trash-post/trash-post-inherited-attachment/',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-attachment",
+					$user,
+					'/trash-post__trashed/trash-post-inherited-attachment/',
+					'/?attachment_id=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?post_type=page&p=%ID%',
+					'/?post_type=page&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?page_id=%ID%',
+					'/?page_id=%ID%',
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					"/?name=$post_key-post",
+					"/?name=$post_key-post",
+				);
+
+				$data[] = array(
+					$post_key,
+					$user,
+					'/?feed=rss&p=%ID%',
+					'/?feed=rss&p=%ID%',
+				);
+
+				$data[] = array(
+					"$post_key-page",
+					$user,
+					'/?feed=rss&page_id=%ID%',
+					'/?feed=rss&page_id=%ID%',
+				);
+			}
+		}
+
+		return $data;
+	}
+}

+ 16 - 0
tests/phpunit/tests/canonical/robots.php

@@ -0,0 +1,16 @@
+<?php
+
+/**
+ * @group canonical
+ * @group rewrite
+ * @group query
+ */
+class Tests_Canonical_Robots extends WP_Canonical_UnitTestCase {
+
+	public function test_remove_trailing_slashes_for_robots_requests() {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( '/robots.txt', '/robots.txt' );
+		$this->assertCanonical( '/robots.txt/', '/robots.txt' );
+	}
+
+}

+ 114 - 0
tests/phpunit/tests/canonical/sitemaps.php

@@ -0,0 +1,114 @@
+<?php
+
+/**
+ * @group canonical
+ * @group rewrite
+ * @group query
+ * @group sitemaps
+ */
+class Tests_Canonical_Sitemaps extends WP_Canonical_UnitTestCase {
+
+	public function setUp() {
+		parent::setUp();
+		$wp_sitemaps = new WP_Sitemaps();
+		$wp_sitemaps->init();
+	}
+
+	public function test_remove_trailing_slashes_for_sitemap_index_requests() {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( '/wp-sitemap.xml', '/wp-sitemap.xml' );
+		$this->assertCanonical( '/wp-sitemap.xml/', '/wp-sitemap.xml' );
+	}
+
+	public function test_remove_trailing_slashes_for_sitemap_index_stylesheet_requests() {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( '/wp-sitemap-index.xsl', '/wp-sitemap-index.xsl' );
+		$this->assertCanonical( '/wp-sitemap-index.xsl/', '/wp-sitemap-index.xsl' );
+	}
+
+	public function test_remove_trailing_slashes_for_sitemap_requests() {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( '/wp-sitemap-posts-post-1.xml', '/wp-sitemap-posts-post-1.xml' );
+		$this->assertCanonical( '/wp-sitemap-posts-post-1.xml/', '/wp-sitemap-posts-post-1.xml' );
+		$this->assertCanonical( '/wp-sitemap-users-1.xml', '/wp-sitemap-users-1.xml' );
+		$this->assertCanonical( '/wp-sitemap-users-1.xml/', '/wp-sitemap-users-1.xml' );
+	}
+
+	public function test_remove_trailing_slashes_for_sitemap_stylesheet_requests() {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( '/wp-sitemap.xsl', '/wp-sitemap.xsl' );
+		$this->assertCanonical( '/wp-sitemap.xsl/', '/wp-sitemap.xsl' );
+	}
+
+	/**
+	 * Ensure sitemaps redirects work as expected with pretty permalinks.
+	 *
+	 * @dataProvider data_sitemaps_canonical_pretty_redirects
+	 * @ticket 50910
+	 */
+	public function test_sitemaps_canonical_pretty_redirects( $test_url, $expected ) {
+		$this->set_permalink_structure( '/%postname%/' );
+		$this->assertCanonical( $test_url, $expected, 50910 );
+	}
+
+	/**
+	 * Data provider for test_sitemaps_canonical_pretty_redirects.
+	 *
+	 * @return array[] {
+	 *     Data to test with.
+	 *
+	 *     @type string $0 The test URL.
+	 *     @type string $1 The expected canonical URL.
+	 * }
+	 */
+	public function data_sitemaps_canonical_pretty_redirects() {
+		return array(
+			// Ugly/incorrect versions redirect correctly.
+			array( '/?sitemap=index', '/wp-sitemap.xml' ),
+			array( '/wp-sitemap.xml/', '/wp-sitemap.xml' ),
+			array( '/?sitemap=posts&sitemap-subtype=post', '/wp-sitemap-posts-post-1.xml' ),
+			array( '/?sitemap=posts&sitemap-subtype=post&paged=2', '/wp-sitemap-posts-post-2.xml' ),
+			array( '/?sitemap=taxonomies&sitemap-subtype=category', '/wp-sitemap-taxonomies-category-1.xml' ),
+			array( '/?sitemap=taxonomies&sitemap-subtype=category&paged=2', '/wp-sitemap-taxonomies-category-2.xml' ),
+
+			// Pretty versions don't redirect incorrectly.
+			array( '/wp-sitemap.xml', '/wp-sitemap.xml' ),
+			array( '/wp-sitemap-posts-post-1.xml', '/wp-sitemap-posts-post-1.xml' ),
+			array( '/wp-sitemap-posts-post-2.xml', '/wp-sitemap-posts-post-2.xml' ),
+			array( '/wp-sitemap-taxonomies-category-1.xml', '/wp-sitemap-taxonomies-category-1.xml' ),
+			array( '/wp-sitemap-taxonomies-category-2.xml', '/wp-sitemap-taxonomies-category-2.xml' ),
+		);
+	}
+
+	/**
+	 * Ensure sitemaps redirects work as expected with ugly permalinks.
+	 *
+	 * @dataProvider data_sitemaps_canonical_ugly_redirects
+	 * @ticket 50910
+	 */
+	public function test_sitemaps_canonical_ugly_redirects( $test_url, $expected ) {
+		$this->set_permalink_structure( '' );
+		$this->assertCanonical( $test_url, $expected, 50910 );
+	}
+
+	/**
+	 * Data provider for test_sitemaps_canonical_ugly_redirects.
+	 *
+	 * @return array[] {
+	 *     Data to test with.
+	 *
+	 *     @type string $0 The test URL.
+	 *     @type string $1 The expected canonical URL.
+	 * }
+	 */
+	public function data_sitemaps_canonical_ugly_redirects() {
+		return array(
+			// Ugly permalinks remain ugly.
+			array( '/?sitemap=index', '/?sitemap=index' ),
+			array( '/?sitemap=posts&sitemap-subtype=post', '/?sitemap=posts&sitemap-subtype=post' ),
+			array( '/?sitemap=posts&sitemap-subtype=post&paged=2', '/?sitemap=posts&sitemap-subtype=post&paged=2' ),
+			array( '/?sitemap=taxonomies&sitemap-subtype=category', '/?sitemap=taxonomies&sitemap-subtype=category' ),
+			array( '/?sitemap=taxonomies&sitemap-subtype=category&paged=2', '/?sitemap=taxonomies&sitemap-subtype=category&paged=2' ),
+		);
+	}
+}

+ 245 - 0
tests/phpunit/tests/category.php

@@ -0,0 +1,245 @@
+<?php
+/**
+ * Validate Category API
+ *
+ * Notes:
+ * cat_is_ancestor_of is validated under test\term\term_is_ancestor_of
+ *
+ * @group category.php
+ */
+class Tests_Category extends WP_UnitTestCase {
+
+	function tearDown() {
+		_unregister_taxonomy( 'test_tax_cat' );
+		parent::tearDown();
+	}
+
+	/**
+	 * Validate get_all_category_ids
+	 *
+	 * @expectedDeprecated get_all_category_ids
+	 */
+	function test_get_all_category_ids() {
+		// Ccreate categories.
+		self::factory()->category->create_many( 2 );
+
+		// Create new taxonomy to ensure not included.
+		register_taxonomy( 'test_tax_cat', 'post' );
+		wp_insert_term( 'test1', 'test_tax_cat' );
+
+		// Validate length is 1 + created due to uncategorized.
+		$cat_ids = get_all_category_ids();
+		$this->assertSame( 3, count( $cat_ids ) );
+	}
+
+	/**
+	 * Validate get_category_by_slug function
+	 */
+	function test_get_category_by_slug() {
+
+		// Create test categories.
+		$testcat  = self::factory()->category->create_and_get(
+			array(
+				'slug' => 'testcat',
+				'name' => 'Test Category 1',
+			)
+		);
+		$testcat2 = self::factory()->category->create_and_get(
+			array(
+				'slug' => 'testcat2',
+				'name' => 'Test Category 2',
+			)
+		);
+
+		// Validate category is returned by slug.
+		$ret_testcat = get_category_by_slug( 'testcat' );
+		$this->assertSame( $testcat->term_id, $ret_testcat->term_id );
+		$ret_testcat = get_category_by_slug( 'TeStCaT' );
+		$this->assertSame( $testcat->term_id, $ret_testcat->term_id );
+
+		// Validate unknown category returns false.
+		$this->assertFalse( get_category_by_slug( 'testcat3' ) );
+
+	}
+
+	/**
+	 * Validate _make_cat_compat function
+	 */
+	function test__make_cat_compat() {
+
+		// Create test categories and array representations.
+		$testcat_array            = array(
+			'slug'        => 'testmcc',
+			'name'        => 'Test MCC',
+			'description' => 'Category Test',
+		);
+		$testcat                  = self::factory()->category->create_and_get( $testcat_array );
+		$testcat_array['term_id'] = $testcat->term_id;
+
+		$testcat2_array            = array(
+			'slug'        => 'testmcc',
+			'name'        => 'Test MCC',
+			'description' => 'Category Test',
+			'parent'      => $testcat->term_id,
+		);
+		$testcat2                  = self::factory()->category->create_and_get( $testcat2_array );
+		$testcat2_array['term_id'] = $testcat2->term_id;
+
+		// Unset properties to enable validation of object.
+		unset( $testcat->cat_ID );
+		unset( $testcat->category_count );
+		unset( $testcat->category_description );
+		unset( $testcat->cat_name );
+		unset( $testcat->category_nicename );
+		unset( $testcat->category_parent );
+
+		unset( $testcat2->cat_ID );
+		unset( $testcat2->category_count );
+		unset( $testcat2->category_description );
+		unset( $testcat2->cat_name );
+		unset( $testcat2->category_nicename );
+		unset( $testcat2->category_parent );
+
+		// Make compatible.
+		_make_cat_compat( $testcat );
+		_make_cat_compat( $testcat2 );
+		_make_cat_compat( $testcat_array );
+		_make_cat_compat( $testcat2_array );
+
+		// Validate compatibility object.
+		$this->assertSame( $testcat->cat_ID, $testcat->term_id );
+		$this->assertSame( $testcat->category_count, $testcat->count );
+		$this->assertSame( $testcat->category_description, $testcat->description );
+		$this->assertSame( $testcat->cat_name, $testcat->name );
+		$this->assertSame( $testcat->category_nicename, $testcat->slug );
+		$this->assertSame( $testcat->category_parent, $testcat->parent );
+
+		// Validate compatibility object with parent.
+		$this->assertSame( $testcat->cat_ID, $testcat->term_id );
+		$this->assertSame( $testcat->category_count, $testcat->count );
+		$this->assertSame( $testcat->category_description, $testcat->description );
+		$this->assertSame( $testcat->cat_name, $testcat->name );
+		$this->assertSame( $testcat->category_nicename, $testcat->slug );
+		$this->assertSame( $testcat->category_parent, $testcat->parent );
+
+		// Validate compatibility array.
+		$this->assertSame( $testcat_array['cat_ID'], $testcat_array['term_id'] );
+		$this->assertSame( $testcat_array['category_count'], $testcat_array['count'] );
+		$this->assertSame( $testcat_array['category_description'], $testcat_array['description'] );
+		$this->assertSame( $testcat_array['cat_name'], $testcat_array['name'] );
+		$this->assertSame( $testcat_array['category_nicename'], $testcat_array['slug'] );
+		$this->assertSame( $testcat_array['category_parent'], $testcat_array['parent'] );
+
+		// Validate compatibility array with parent.
+		$this->assertSame( $testcat_array['cat_ID'], $testcat_array['term_id'] );
+		$this->assertSame( $testcat_array['category_count'], $testcat_array['count'] );
+		$this->assertSame( $testcat_array['category_description'], $testcat_array['description'] );
+		$this->assertSame( $testcat_array['cat_name'], $testcat_array['name'] );
+		$this->assertSame( $testcat_array['category_nicename'], $testcat_array['slug'] );
+		$this->assertSame( $testcat_array['category_parent'], $testcat_array['parent'] );
+	}
+
+	/**
+	 * Validate get_cat_name function
+	 */
+	function test_get_cat_name() {
+
+		// Create test category.
+		$testcat = self::factory()->category->create_and_get(
+			array(
+				'slug' => 'testcat',
+				'name' => 'Test Category 1',
+			)
+		);
+
+		// Validate.
+		$this->assertSame( $testcat->name, get_cat_name( $testcat->term_id ) );
+		$this->assertSame( '', get_cat_name( -1 ) );
+		$this->assertSame( '', get_cat_name( $testcat->term_id + 100 ) );
+
+	}
+
+	/**
+	 * Validate get_cat_name function
+	 */
+	function test_get_cat_ID() {
+
+		// Create test category.
+		$testcat = self::factory()->category->create_and_get(
+			array(
+				'slug' => 'testcat',
+				'name' => 'Test Category 1',
+			)
+		);
+
+		// Validate.
+		$this->assertSame( $testcat->term_id, get_cat_ID( $testcat->name ) );
+		$this->assertSame( 0, get_cat_ID( 'NO CAT' ) );
+		$this->assertSame( 0, get_cat_ID( 12 ) );
+
+	}
+
+	/**
+	 * Validate get_category_by_path function
+	 */
+	function test_get_category_by_path() {
+
+		// Create test categories.
+		$root_id           = self::factory()->category->create(
+			array(
+				'slug' => 'root',
+			)
+		);
+		$root_cat_id       = self::factory()->category->create(
+			array(
+				'slug'   => 'cat',
+				'parent' => $root_id,
+			)
+		);
+		$root_cat_cat_id   = self::factory()->category->create(
+			array(
+				'slug'   => 'cat', // Note this is modified on create.
+				'parent' => $root_cat_id,
+			)
+		);
+		$root_path_id      = self::factory()->category->create(
+			array(
+				'slug'   => 'path',
+				'parent' => $root_id,
+			)
+		);
+		$root_path_cat_id  = self::factory()->category->create(
+			array(
+				'slug'   => 'cat', // Note this is modified on create.
+				'parent' => $root_path_id,
+			)
+		);
+		$root_level_id     = self::factory()->category->create(
+			array(
+				'slug'   => 'level-1',
+				'parent' => $root_id,
+			)
+		);
+		$root_level_cat_id = self::factory()->category->create(
+			array(
+				'slug'   => 'cat', // Note this is modified on create.
+				'parent' => $root_level_id,
+			)
+		);
+
+		// Validate full match.
+		$ret_cat = get_category_by_path( '/root/level-1', true );
+		$this->assertSame( $root_level_id, $ret_cat->term_id );
+		$this->assertNull( get_category_by_path( 'level-1', true ) );
+		$this->assertNull( get_category_by_path( 'nocat/nocat/', true ) );
+
+		// Validate partial match.
+		$ret_cat = get_category_by_path( 'level-1', false );
+		$this->assertSame( $root_level_id, $ret_cat->term_id );
+		$ret_cat = get_category_by_path( 'root/cat/level-1', false );
+		$this->assertSame( $root_level_id, $ret_cat->term_id );
+		$ret_cat = get_category_by_path( 'root$2Fcat%20%2Flevel-1', false );
+		$this->assertSame( $root_level_id, $ret_cat->term_id );
+		$this->assertNull( get_category_by_path( 'nocat/nocat/', false ) );
+	}
+}

+ 86 - 0
tests/phpunit/tests/category/categoryDescription.php

@@ -0,0 +1,86 @@
+<?php
+
+/**
+ * @group taxonomy
+ * @covers ::category_description
+ */
+class Tests_Category_CategoryDescription extends WP_UnitTestCase {
+	public function test_success_query_by_id() {
+		$description = 'Foo';
+		$c           = self::factory()->category->create(
+			array(
+				'description' => $description,
+			)
+		);
+
+		$found    = category_description( $c );
+		$expected = apply_filters( 'term_description', $description );
+
+		$this->assertSame( $expected, $found );
+	}
+
+	public function test_success_query_by_object() {
+		$description = 'Foo';
+		$c           = self::factory()->category->create(
+			array(
+				'description' => $description,
+				'slug'        => 'bar',
+			)
+		);
+
+		$category = get_term( $c );
+
+		$found    = category_description( $c );
+		$expected = apply_filters( 'term_description', $description );
+
+		$this->assertSame( $expected, $found );
+	}
+
+	/**
+	 * @ticket 42605
+	 * @ticket 42771
+	 */
+	public function test_should_return_description_for_term_from_another_taxonomy_on_primed_cache() {
+		register_taxonomy( 'wptests_tax', 'post' );
+
+		$description = 'Foo';
+
+		$t = self::factory()->term->create(
+			array(
+				'taxonomy'    => 'wptests_tax',
+				'description' => $description,
+			)
+		);
+
+		$term = get_term( $t );
+
+		$found    = category_description( $t );
+		$expected = apply_filters( 'term_description', $description );
+
+		$this->assertSame( $expected, $found );
+	}
+
+	/**
+	 * @ticket 42605
+	 * @ticket 42771
+	 */
+	public function test_should_return_description_for_term_from_another_taxonomy_on_empty_cache() {
+		register_taxonomy( 'wptests_tax', 'post' );
+
+		$description = 'Foo';
+
+		$t = self::factory()->term->create(
+			array(
+				'taxonomy'    => 'wptests_tax',
+				'description' => $description,
+			)
+		);
+
+		clean_term_cache( $t );
+
+		$found    = category_description( $t );
+		$expected = apply_filters( 'term_description', $description );
+
+		$this->assertSame( $expected, $found );
+	}
+}

+ 15 - 0
tests/phpunit/tests/category/getCategories.php

@@ -0,0 +1,15 @@
+<?php
+
+/**
+ * @group taxonomy
+ * @group category.php
+ */
+class Tests_Category_GetCategories extends WP_UnitTestCase {
+	/**
+	 * @ticket 36227
+	 */
+	public function test_wp_error_should_return_an_empty_array() {
+		$found = get_categories( array( 'taxonomy' => 'foo' ) );
+		$this->assertSame( array(), $found );
+	}
+}

Some files were not shown because too many files changed in this diff