Tests: Add a $message parameter for a custom assertion in WP_Test_REST_TestCase.

All assertions in PHPUnit have a `$message` parameter. Setting this parameter allows to distinguish which assertion is failing when a test runs multiple assertions, making debugging of the tests easier.

This optional parameter is now added for `WP_Test_REST_TestCase::assertErrorResponse()`.

Follow-up to [34928], [51478].

Props mykolashlyakhtun, antonvlasenko, swissspidy, SergeyBiryukov.
Fixes #60426.

git-svn-id: https://develop.svn.wordpress.org/trunk@58039 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2024-04-23 18:55:26 +00:00
parent 68baba5c9f
commit 25b9f8b156

View File

@ -1,19 +1,31 @@
<?php <?php
abstract class WP_Test_REST_TestCase extends WP_UnitTestCase { abstract class WP_Test_REST_TestCase extends WP_UnitTestCase {
protected function assertErrorResponse( $code, $response, $status = null ) {
/**
* Asserts that the REST API response has the specified error.
*
* @since 4.4.0
* @since 6.6.0 Added the `$message` parameter.
*
* @param string|int $code Expected error code.
* @param WP_REST_Response|WP_Error $response REST API response.
* @param int $status Optional. Status code.
* @param string $message Optional. Message to display when the assertion fails.
*/
protected function assertErrorResponse( $code, $response, $status = null, $message = '' ) {
if ( $response instanceof WP_REST_Response ) { if ( $response instanceof WP_REST_Response ) {
$response = $response->as_error(); $response = $response->as_error();
} }
$this->assertWPError( $response ); $this->assertWPError( $response, $message );
$this->assertSame( $code, $response->get_error_code() ); $this->assertSame( $code, $response->get_error_code(), $message );
if ( null !== $status ) { if ( null !== $status ) {
$data = $response->get_error_data(); $data = $response->get_error_data();
$this->assertArrayHasKey( 'status', $data ); $this->assertArrayHasKey( 'status', $data, $message );
$this->assertSame( $status, $data['status'] ); $this->assertSame( $status, $data['status'], $message );
} }
} }
} }