Tests: Add a helper method for for creating named data providers in WP_UnitTestCase_Base.

This introduces a new test helper function which allows for turning a single-level array containing text strings into a data provider with named data sets, where the value of the data set will also be used as the name of the data set.

The function contains safeguards to ensure that it is only used with data compatible with this principle and will throw generic PHP exceptions when the data is incompatible. These type of exceptions will be displayed before the tests even start running and will stop the test run when they occur.

While generally speaking, all test cases ''should'' extend the base `WP_UnitTestCase_Base` class, this is still made a `public static` method to allow for a test, which by exception directly extends the PHPUnit base `TestCase` or the `PHPUnit_Adapter_TestCase`, to also be able to use this method.

Typical usage of this method:
{{{
public function data_provider_for_test_name() {
	$array = array(
		'value1',
		'value2',
	);

	return $this->text_array_to_dataprovider( $array );
}
}}}
The returned result will look like:
{{{
array(
	'value1' => array( 'value1' ),
	'value2' => array( 'value2' ),
)
}}}

Props jrf, hellofromTonya, adamsilverstein.
See #55652.

git-svn-id: https://develop.svn.wordpress.org/trunk@53521 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2022-06-18 21:28:39 +00:00
parent 0fa05bacca
commit 044f702a1c

View File

@ -877,6 +877,56 @@ abstract class WP_UnitTestCase_Base extends PHPUnit_Adapter_TestCase {
}
}
/**
* Helper function to convert a single-level array containing text strings to a named data provider.
*
* The value of the data set will also be used as the name of the data set.
*
* Typical usage of this method:
*
* public function data_provider_for_test_name() {
* $array = array(
* 'value1',
* 'value2',
* );
*
* return $this->text_array_to_dataprovider( $array );
* }
*
* The returned result will look like:
*
* array(
* 'value1' => array( 'value1' ),
* 'value2' => array( 'value2' ),
* )
*
* @since 6.1.0
*
* @param array $input Input array.
* @return array Array which is usable as a test data provider with named data sets.
*/
public static function text_array_to_dataprovider( $input ) {
$data = array();
foreach ( $input as $value ) {
if ( ! is_string( $value ) ) {
throw new Exception(
'All values in the input array should be text strings. Fix the input data.'
);
}
if ( isset( $data[ $value ] ) ) {
throw new Exception(
"Attempting to add a duplicate data set for value $value to the data provider. Fix the input data."
);
}
$data[ $value ] = array( $value );
}
return $data;
}
/**
* Sets the global state to as if a given URL has been requested.
*