REST API: Introduce baby API to the world.

Baby API was born at 2.8KLOC on October 8th at 2:30 UTC. API has lots
of growing to do, so wish it the best of luck.

Thanks to everyone who helped along the way:

Props rmccue, rachelbaker, danielbachhuber, joehoyle, drewapicture,
adamsilverstein, netweb, tlovett1, shelob9, kadamwhite, pento,
westonruter, nikv, tobych, redsweater, alecuf, pollyplummer, hurtige,
bpetty, oso96_2000, ericlewis, wonderboymusic, joshkadis, mordauk,
jdgrimes, johnbillion, jeremyfelt, thiago-negri, jdolan, pkevan,
iseulde, thenbrent, maxcutler, kwight, markoheijnen, phh, natewr,
jjeaton, shprink, mattheu, quasel, jmusal, codebykat, hubdotcom,
tapsboy, QWp6t, pushred, jaredcobb, justinsainton, japh, matrixik,
jorbin, frozzare, codfish, michael-arestad, kellbot, ironpaperweight,
simonlampen, alisspers, eliorivero, davidbhayes, JohnDittmar, dimadin,
traversal, cmmarslender, Toddses, kokarn, welcher, and ericpedia.

Fixes #33982.


git-svn-id: https://develop.svn.wordpress.org/trunk@34928 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Ryan McCue
2015-10-08 02:30:18 +00:00
parent 374b39d6ba
commit b39211475d
14 changed files with 4522 additions and 0 deletions

View File

@@ -90,11 +90,13 @@ require_once ABSPATH . '/wp-settings.php';
_delete_all_posts();
require dirname( __FILE__ ) . '/testcase.php';
require dirname( __FILE__ ) . '/testcase-rest-api.php';
require dirname( __FILE__ ) . '/testcase-xmlrpc.php';
require dirname( __FILE__ ) . '/testcase-ajax.php';
require dirname( __FILE__ ) . '/testcase-canonical.php';
require dirname( __FILE__ ) . '/exceptions.php';
require dirname( __FILE__ ) . '/utils.php';
require dirname( __FILE__ ) . '/spy-rest-server.php';
/**
* A child class of the PHP test runner.

View File

@@ -0,0 +1,23 @@
<?php
class Spy_REST_Server extends WP_REST_Server {
/**
* Get 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 );
}
}

View File

@@ -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->assertInstanceOf( 'WP_Error', $response );
$this->assertEquals( $code, $response->get_error_code() );
if ( null !== $status ) {
$data = $response->get_error_data();
$this->assertArrayHasKey( 'status', $data );
$this->assertEquals( $status, $data['status'] );
}
}
}

View File

@@ -0,0 +1,255 @@
<?php
/**
* REST API functions.
*
* @package WordPress
* @subpackage REST API
*/
require_once ABSPATH . 'wp-admin/includes/admin.php';
require_once ABSPATH . WPINC . '/rest-api.php';
/**
* @group restapi
*/
class Tests_REST_API extends WP_UnitTestCase {
public function setUp() {
// Override the normal server with our spying server.
$GLOBALS['wp_rest_server'] = new Spy_REST_Server();
parent::setup();
}
/**
* The plugin should be installed and activated.
*/
function test_rest_api_activated() {
$this->assertTrue( class_exists( 'WP_REST_Server' ) );
}
/**
* The rest_api_init hook should have been registered with init, and should
* have a default priority of 10.
*/
function test_init_action_added() {
$this->assertEquals( 10, has_action( 'init', 'rest_api_init' ) );
}
/**
* Check that a single route is canonicalized.
*
* Ensures that single and multiple routes are handled correctly.
*/
public function test_route_canonicalized() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
) );
// Check the route was registered correctly.
$endpoints = $GLOBALS['wp_rest_server']->get_raw_endpoint_data();
$this->assertArrayHasKey( '/test-ns/test', $endpoints );
// Check the route was wrapped in an array.
$endpoint = $endpoints['/test-ns/test'];
$this->assertArrayNotHasKey( 'callback', $endpoint );
$this->assertArrayHasKey( 'namespace', $endpoint );
$this->assertEquals( 'test-ns', $endpoint['namespace'] );
// Grab the filtered data.
$filtered_endpoints = $GLOBALS['wp_rest_server']->get_routes();
$this->assertArrayHasKey( '/test-ns/test', $filtered_endpoints );
$endpoint = $filtered_endpoints['/test-ns/test'];
$this->assertCount( 1, $endpoint );
$this->assertArrayHasKey( 'callback', $endpoint[0] );
$this->assertArrayHasKey( 'methods', $endpoint[0] );
$this->assertArrayHasKey( 'args', $endpoint[0] );
}
/**
* Check that a single route is canonicalized.
*
* Ensures that single and multiple routes are handled correctly.
*/
public function test_route_canonicalized_multiple() {
register_rest_route( 'test-ns', '/test', array(
array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
),
array(
'methods' => array( 'POST' ),
'callback' => '__return_null',
),
) );
// Check the route was registered correctly.
$endpoints = $GLOBALS['wp_rest_server']->get_raw_endpoint_data();
$this->assertArrayHasKey( '/test-ns/test', $endpoints );
// Check the route was wrapped in an array.
$endpoint = $endpoints['/test-ns/test'];
$this->assertArrayNotHasKey( 'callback', $endpoint );
$this->assertArrayHasKey( 'namespace', $endpoint );
$this->assertEquals( 'test-ns', $endpoint['namespace'] );
$filtered_endpoints = $GLOBALS['wp_rest_server']->get_routes();
$endpoint = $filtered_endpoints['/test-ns/test'];
$this->assertCount( 2, $endpoint );
// Check for both methods.
foreach ( array( 0, 1 ) as $key ) {
$this->assertArrayHasKey( 'callback', $endpoint[ $key ] );
$this->assertArrayHasKey( 'methods', $endpoint[ $key ] );
$this->assertArrayHasKey( 'args', $endpoint[ $key ] );
}
}
/**
* Check that routes are merged by default.
*/
public function test_route_merge() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
) );
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'POST' ),
'callback' => '__return_null',
) );
// Check both routes exist.
$endpoints = $GLOBALS['wp_rest_server']->get_routes();
$endpoint = $endpoints['/test-ns/test'];
$this->assertCount( 2, $endpoint );
}
/**
* Check that we can override routes.
*/
public function test_route_override() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
'should_exist' => false,
) );
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'POST' ),
'callback' => '__return_null',
'should_exist' => true,
), true );
// Check we only have one route.
$endpoints = $GLOBALS['wp_rest_server']->get_routes();
$endpoint = $endpoints['/test-ns/test'];
$this->assertCount( 1, $endpoint );
// Check it's the right one.
$this->assertArrayHasKey( 'should_exist', $endpoint[0] );
$this->assertTrue( $endpoint[0]['should_exist'] );
}
/**
* The rest_route query variable should be registered.
*/
function test_rest_route_query_var() {
rest_api_init();
$this->assertTrue( in_array( 'rest_route', $GLOBALS['wp']->public_query_vars ) );
}
public function test_route_method() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
) );
$routes = $GLOBALS['wp_rest_server']->get_routes();
$this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true ) );
}
/**
* The 'methods' arg should accept a single value as well as array.
*/
public function test_route_method_string() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
) );
$routes = $GLOBALS['wp_rest_server']->get_routes();
$this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true ) );
}
/**
* The 'methods' arg should accept a single value as well as array.
*/
public function test_route_method_array() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET', 'POST' ),
'callback' => '__return_null',
) );
$routes = $GLOBALS['wp_rest_server']->get_routes();
$this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true, 'POST' => true ) );
}
/**
* The 'methods' arg should a comma seperated string.
*/
public function test_route_method_comma_seperated() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET,POST',
'callback' => '__return_null',
) );
$routes = $GLOBALS['wp_rest_server']->get_routes();
$this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true, 'POST' => true ) );
}
public function test_options_request() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET,POST',
'callback' => '__return_null',
) );
$request = new WP_REST_Request( 'OPTIONS', '/test-ns/test' );
$response = rest_handle_options_request( null, $GLOBALS['wp_rest_server'], $request );
$headers = $response->get_headers();
$this->assertArrayHasKey( 'Accept', $headers );
$this->assertEquals( 'GET, POST', $headers['Accept'] );
}
/**
* Ensure that the OPTIONS handler doesn't kick in for non-OPTIONS requests.
*/
public function test_options_request_not_options() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET,POST',
'callback' => '__return_true',
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test' );
$response = rest_handle_options_request( null, $GLOBALS['wp_rest_server'], $request );
$this->assertNull( $response );
}
/**
* The get_rest_url function should return a URL consistently terminated with a "/",
* whether the blog is configured with pretty permalink support or not.
*/
public function test_rest_url_generation() {
// In pretty permalinks case, we expect a path of wp-json/ with no query.
update_option( 'permalink_structure', '/%year%/%monthnum%/%day%/%postname%/' );
$this->assertEquals( 'http://' . WP_TESTS_DOMAIN . '/wp-json/', get_rest_url() );
update_option( 'permalink_structure', '' );
// In non-pretty case, we get a query string to invoke the rest router.
$this->assertEquals( 'http://' . WP_TESTS_DOMAIN . '/?rest_route=/', get_rest_url() );
}
}

View File

@@ -0,0 +1,394 @@
<?php
/**
* Unit tests covering WP_REST_Request functionality.
*
* @package WordPress
* @subpackage REST API
*/
/**
* @group restapi
*/
class Tests_REST_Request extends WP_UnitTestCase {
public function setUp() {
$this->request = new WP_REST_Request();
}
public function test_header() {
$value = 'application/x-wp-example';
$this->request->set_header( 'Content-Type', $value );
$this->assertEquals( $value, $this->request->get_header( 'Content-Type' ) );
}
public function test_header_missing() {
$this->assertNull( $this->request->get_header( 'missing' ) );
$this->assertNull( $this->request->get_header_as_array( 'missing' ) );
}
public function test_header_multiple() {
$value1 = 'application/x-wp-example-1';
$value2 = 'application/x-wp-example-2';
$this->request->add_header( 'Accept', $value1 );
$this->request->add_header( 'Accept', $value2 );
$this->assertEquals( $value1 . ',' . $value2, $this->request->get_header( 'Accept' ) );
$this->assertEquals( array( $value1, $value2 ), $this->request->get_header_as_array( 'Accept' ) );
}
public static function header_provider() {
return array(
array( 'Test', 'test' ),
array( 'TEST', 'test' ),
array( 'Test-Header', 'test_header' ),
array( 'test-header', 'test_header' ),
array( 'Test_Header', 'test_header' ),
array( 'test_header', 'test_header' ),
);
}
/**
* @dataProvider header_provider
* @param string $original Original header key.
* @param string $expected Expected canonicalized version.
*/
public function test_header_canonicalization( $original, $expected ) {
$this->assertEquals( $expected, $this->request->canonicalize_header_name( $original ) );
}
public static function content_type_provider() {
return array(
// Check basic parsing.
array( 'application/x-wp-example', 'application/x-wp-example', 'application', 'x-wp-example', '' ),
array( 'application/x-wp-example; charset=utf-8', 'application/x-wp-example', 'application', 'x-wp-example', 'charset=utf-8' ),
// Check case insensitivity.
array( 'APPLICATION/x-WP-Example', 'application/x-wp-example', 'application', 'x-wp-example', '' ),
);
}
/**
* @dataProvider content_type_provider
*
* @param string $header Header value.
* @param string $value Full type value.
* @param string $type Main type (application, text, etc).
* @param string $subtype Subtype (json, etc).
* @param string $parameters Parameters (charset=utf-8, etc).
*/
public function test_content_type_parsing( $header, $value, $type, $subtype, $parameters ) {
// Check we start with nothing.
$this->assertEmpty( $this->request->get_content_type() );
$this->request->set_header( 'Content-Type', $header );
$parsed = $this->request->get_content_type();
$this->assertEquals( $value, $parsed['value'] );
$this->assertEquals( $type, $parsed['type'] );
$this->assertEquals( $subtype, $parsed['subtype'] );
$this->assertEquals( $parameters, $parsed['parameters'] );
}
protected function request_with_parameters() {
$this->request->set_url_params( array(
'source' => 'url',
'has_url_params' => true,
) );
$this->request->set_query_params( array(
'source' => 'query',
'has_query_params' => true,
) );
$this->request->set_body_params( array(
'source' => 'body',
'has_body_params' => true,
) );
$json_data = wp_json_encode( array(
'source' => 'json',
'has_json_params' => true,
) );
$this->request->set_body( $json_data );
$this->request->set_default_params( array(
'source' => 'defaults',
'has_default_params' => true,
) );
}
public function test_parameter_order() {
$this->request_with_parameters();
$this->request->set_method( 'GET' );
// Check that query takes precedence.
$this->assertEquals( 'query', $this->request->get_param( 'source' ) );
// Check that the correct arguments are parsed (and that falling through
// the stack works).
$this->assertTrue( $this->request->get_param( 'has_url_params' ) );
$this->assertTrue( $this->request->get_param( 'has_query_params' ) );
$this->assertTrue( $this->request->get_param( 'has_default_params' ) );
// POST and JSON parameters shouldn't be parsed.
$this->assertEmpty( $this->request->get_param( 'has_body_params' ) );
$this->assertEmpty( $this->request->get_param( 'has_json_params' ) );
}
public function test_parameter_order_post() {
$this->request_with_parameters();
$this->request->set_method( 'POST' );
$this->request->set_header( 'Content-Type', 'application/x-www-form-urlencoded' );
$this->request->set_attributes( array( 'accept_json' => true ) );
// Check that POST takes precedence.
$this->assertEquals( 'body', $this->request->get_param( 'source' ) );
// Check that the correct arguments are parsed (and that falling through
// the stack works).
$this->assertTrue( $this->request->get_param( 'has_url_params' ) );
$this->assertTrue( $this->request->get_param( 'has_query_params' ) );
$this->assertTrue( $this->request->get_param( 'has_body_params' ) );
$this->assertTrue( $this->request->get_param( 'has_default_params' ) );
// JSON shouldn't be parsed.
$this->assertEmpty( $this->request->get_param( 'has_json_params' ) );
}
public function test_parameter_order_json() {
$this->request_with_parameters();
$this->request->set_method( 'POST' );
$this->request->set_header( 'Content-Type', 'application/json' );
$this->request->set_attributes( array( 'accept_json' => true ) );
// Check that JSON takes precedence.
$this->assertEquals( 'json', $this->request->get_param( 'source' ) );
// Check that the correct arguments are parsed (and that falling through
// the stack works).
$this->assertTrue( $this->request->get_param( 'has_url_params' ) );
$this->assertTrue( $this->request->get_param( 'has_query_params' ) );
$this->assertTrue( $this->request->get_param( 'has_body_params' ) );
$this->assertTrue( $this->request->get_param( 'has_json_params' ) );
$this->assertTrue( $this->request->get_param( 'has_default_params' ) );
}
public function test_parameter_order_json_invalid() {
$this->request_with_parameters();
$this->request->set_method( 'POST' );
$this->request->set_header( 'Content-Type', 'application/json' );
$this->request->set_attributes( array( 'accept_json' => true ) );
// Use invalid JSON data.
$this->request->set_body( '{ this is not json }' );
// Check that JSON is ignored.
$this->assertEquals( 'body', $this->request->get_param( 'source' ) );
// Check that the correct arguments are parsed (and that falling through
// the stack works).
$this->assertTrue( $this->request->get_param( 'has_url_params' ) );
$this->assertTrue( $this->request->get_param( 'has_query_params' ) );
$this->assertTrue( $this->request->get_param( 'has_body_params' ) );
$this->assertTrue( $this->request->get_param( 'has_default_params' ) );
// JSON should be ignored.
$this->assertEmpty( $this->request->get_param( 'has_json_params' ) );
}
/**
* PUT requests don't get $_POST automatically parsed, so ensure that
* WP_REST_Request does it for us.
*/
public function test_parameters_for_put() {
$data = array(
'foo' => 'bar',
'alot' => array(
'of' => 'parameters',
),
'list' => array(
'of',
'cool',
'stuff',
),
);
$this->request->set_method( 'PUT' );
$this->request->set_body_params( array() );
$this->request->set_body( http_build_query( $data ) );
foreach ( $data as $key => $expected_value ) {
$this->assertEquals( $expected_value, $this->request->get_param( $key ) );
}
}
public function test_parameters_for_json_put() {
$data = array(
'foo' => 'bar',
'alot' => array(
'of' => 'parameters',
),
'list' => array(
'of',
'cool',
'stuff',
),
);
$this->request->set_method( 'PUT' );
$this->request->add_header( 'content-type', 'application/json' );
$this->request->set_body( wp_json_encode( $data ) );
foreach ( $data as $key => $expected_value ) {
$this->assertEquals( $expected_value, $this->request->get_param( $key ) );
}
}
public function test_parameters_for_json_post() {
$data = array(
'foo' => 'bar',
'alot' => array(
'of' => 'parameters',
),
'list' => array(
'of',
'cool',
'stuff',
),
);
$this->request->set_method( 'POST' );
$this->request->add_header( 'content-type', 'application/json' );
$this->request->set_body( wp_json_encode( $data ) );
foreach ( $data as $key => $expected_value ) {
$this->assertEquals( $expected_value, $this->request->get_param( $key ) );
}
}
public function test_parameter_merging() {
$this->request_with_parameters();
$this->request->set_method( 'POST' );
$expected = array(
'source' => 'body',
'has_url_params' => true,
'has_query_params' => true,
'has_body_params' => true,
'has_default_params' => true,
);
$this->assertEquals( $expected, $this->request->get_params() );
}
public function test_sanitize_params() {
$this->request->set_url_params( array(
'someinteger' => '123',
'somestring' => 'hello',
));
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'sanitize_callback' => 'absint',
),
'somestring' => array(
'sanitize_callback' => 'absint',
),
),
) );
$this->request->sanitize_params();
$this->assertEquals( 123, $this->request->get_param( 'someinteger' ) );
$this->assertEquals( 0, $this->request->get_param( 'somestring' ) );
}
public function test_has_valid_params_required_flag() {
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'required' => true,
),
),
) );
$valid = $this->request->has_valid_params();
$this->assertWPError( $valid );
$this->assertEquals( 'rest_missing_callback_param', $valid->get_error_code() );
}
public function test_has_valid_params_required_flag_multiple() {
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'required' => true,
),
'someotherinteger' => array(
'required' => true,
),
),
));
$valid = $this->request->has_valid_params();
$this->assertWPError( $valid );
$this->assertEquals( 'rest_missing_callback_param', $valid->get_error_code() );
$data = $valid->get_error_data( 'rest_missing_callback_param' );
$this->assertTrue( in_array( 'someinteger', $data['params'] ) );
$this->assertTrue( in_array( 'someotherinteger', $data['params'] ) );
}
public function test_has_valid_params_validate_callback() {
$this->request->set_url_params( array(
'someinteger' => '123',
));
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'validate_callback' => '__return_false',
),
),
));
$valid = $this->request->has_valid_params();
$this->assertWPError( $valid );
$this->assertEquals( 'rest_invalid_param', $valid->get_error_code() );
}
public function test_has_multiple_invalid_params_validate_callback() {
$this->request->set_url_params( array(
'someinteger' => '123',
'someotherinteger' => '123',
));
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'validate_callback' => '__return_false',
),
'someotherinteger' => array(
'validate_callback' => '__return_false',
),
),
));
$valid = $this->request->has_valid_params();
$this->assertWPError( $valid );
$this->assertEquals( 'rest_invalid_param', $valid->get_error_code() );
$data = $valid->get_error_data( 'rest_invalid_param' );
$this->assertArrayHasKey( 'someinteger', $data['params'] );
$this->assertArrayHasKey( 'someotherinteger', $data['params'] );
}
}

View File

@@ -0,0 +1,582 @@
<?php
/**
* Unit tests covering WP_REST_Server functionality.
*
* @package WordPress
* @subpackage REST API
*/
/**
* @group restapi
*/
class Tests_REST_Server extends WP_Test_REST_TestCase {
public function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new Spy_REST_Server();
do_action( 'rest_api_init', $this->server );
}
public function test_envelope() {
$data = array(
'amount of arbitrary data' => 'alot',
);
$status = 987;
$headers = array(
'Arbitrary-Header' => 'value',
'Multiple' => 'maybe, yes',
);
$response = new WP_REST_Response( $data, $status );
$response->header( 'Arbitrary-Header', 'value' );
// Check header concatenation as well.
$response->header( 'Multiple', 'maybe' );
$response->header( 'Multiple', 'yes', false );
$envelope_response = $this->server->envelope_response( $response, false );
// The envelope should still be a response, but with defaults.
$this->assertInstanceOf( 'WP_REST_Response', $envelope_response );
$this->assertEquals( 200, $envelope_response->get_status() );
$this->assertEmpty( $envelope_response->get_headers() );
$this->assertEmpty( $envelope_response->get_links() );
$enveloped = $envelope_response->get_data();
$this->assertEquals( $data, $enveloped['body'] );
$this->assertEquals( $status, $enveloped['status'] );
$this->assertEquals( $headers, $enveloped['headers'] );
}
public function test_default_param() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
'args' => array(
'foo' => array(
'default' => 'bar',
),
),
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 'bar', $request['foo'] );
}
public function test_default_param_is_overridden() {
register_rest_route( 'test-ns', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
'args' => array(
'foo' => array(
'default' => 'bar',
),
),
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test' );
$request->set_query_params( array( 'foo' => 123 ) );
$response = $this->server->dispatch( $request );
$this->assertEquals( '123', $request['foo'] );
}
public function test_optional_param() {
register_rest_route( 'optional', '/test', array(
'methods' => array( 'GET' ),
'callback' => '__return_null',
'args' => array(
'foo' => array(),
),
) );
$request = new WP_REST_Request( 'GET', '/optional/test' );
$request->set_query_params( array() );
$response = $this->server->dispatch( $request );
$this->assertInstanceOf( 'WP_REST_Response', $response );
$this->assertEquals( 200, $response->get_status() );
$this->assertArrayNotHasKey( 'foo', (array) $request );
}
/**
* Pass a capability which the user does not have, this should
* result in a 403 error.
*/
function test_rest_route_capability_authorization_fails() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
'should_exist' => false,
'permission_callback' => array( $this, 'permission_denied' ),
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test', array() );
$result = $this->server->dispatch( $request );
$this->assertEquals( 403, $result->get_status() );
}
/**
* An editor should be able to get access to an route with the
* edit_posts capability.
*/
function test_rest_route_capability_authorization() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
'should_exist' => false,
'permission_callback' => '__return_true',
) );
$editor = $this->factory->user->create( array( 'role' => 'editor' ) );
$request = new WP_REST_Request( 'GET', '/test-ns/test', array() );
wp_set_current_user( $editor );
$result = $this->server->dispatch( $request );
$this->assertEquals( 200, $result->get_status() );
}
/**
* An "Allow" HTTP header should be sent with a request
* for all available methods on that route.
*/
function test_allow_header_sent() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
'should_exist' => false,
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test', array() );
$result = $this->server->dispatch( $request );
$result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request );
$this->assertFalse( $result->get_status() !== 200 );
$sent_headers = $result->get_headers();
$this->assertEquals( $sent_headers['Allow'], 'GET' );
}
/**
* The "Allow" HTTP header should include all available
* methods that can be sent to a route.
*/
function test_allow_header_sent_with_multiple_methods() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
'should_exist' => false,
) );
register_rest_route( 'test-ns', '/test', array(
'methods' => 'POST',
'callback' => '__return_null',
'should_exist' => false,
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test', array() );
$result = $this->server->dispatch( $request );
$this->assertFalse( $result->get_status() !== 200 );
$result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request );
$sent_headers = $result->get_headers();
$this->assertEquals( $sent_headers['Allow'], 'GET, POST' );
}
/**
* The "Allow" HTTP header should NOT include other methods
* which the user does not have access to.
*/
function test_allow_header_send_only_permitted_methods() {
register_rest_route( 'test-ns', '/test', array(
'methods' => 'GET',
'callback' => '__return_null',
'should_exist' => false,
'permission_callback' => array( $this, 'permission_denied' ),
) );
register_rest_route( 'test-ns', '/test', array(
'methods' => 'POST',
'callback' => '__return_null',
'should_exist' => false,
) );
$request = new WP_REST_Request( 'GET', '/test-ns/test', array() );
$result = $this->server->dispatch( $request );
$result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request );
$this->assertEquals( $result->get_status(), 403 );
$sent_headers = $result->get_headers();
$this->assertEquals( $sent_headers['Allow'], 'POST' );
}
public function permission_denied() {
return new WP_Error( 'forbidden', 'You are not allowed to do this', array( 'status' => 403 ) );
}
public function test_error_to_response() {
$code = 'wp-api-test-error';
$message = 'Test error message for the API';
$error = new WP_Error( $code, $message );
$response = $this->server->error_to_response( $error );
$this->assertInstanceOf( 'WP_REST_Response', $response );
// Make sure we default to a 500 error.
$this->assertEquals( 500, $response->get_status() );
$data = $response->get_data();
$this->assertCount( 1, $data );
$this->assertEquals( $code, $data[0]['code'] );
$this->assertEquals( $message, $data[0]['message'] );
}
public function test_error_to_response_with_status() {
$code = 'wp-api-test-error';
$message = 'Test error message for the API';
$error = new WP_Error( $code, $message, array( 'status' => 400 ) );
$response = $this->server->error_to_response( $error );
$this->assertInstanceOf( 'WP_REST_Response', $response );
$this->assertEquals( 400, $response->get_status() );
$data = $response->get_data();
$this->assertCount( 1, $data );
$this->assertEquals( $code, $data[0]['code'] );
$this->assertEquals( $message, $data[0]['message'] );
}
public function test_rest_error() {
$data = array(
array(
'code' => 'wp-api-test-error',
'message' => 'Message text',
),
);
$expected = wp_json_encode( $data );
$response = $this->server->json_error( 'wp-api-test-error', 'Message text' );
$this->assertEquals( $expected, $response );
}
public function test_json_error_with_status() {
$stub = $this->getMockBuilder( 'Spy_REST_Server' )
->setMethods( array( 'set_status' ) )
->getMock();
$stub->expects( $this->once() )
->method( 'set_status' )
->with( $this->equalTo( 400 ) );
$data = array(
array(
'code' => 'wp-api-test-error',
'message' => 'Message text',
),
);
$expected = wp_json_encode( $data );
$response = $stub->json_error( 'wp-api-test-error', 'Message text', 400 );
$this->assertEquals( $expected, $response );
}
public function test_response_to_data_links() {
$response = new WP_REST_Response();
$response->add_link( 'self', 'http://example.com/' );
$response->add_link( 'alternate', 'http://example.org/', array( 'type' => 'application/xml' ) );
$data = $this->server->response_to_data( $response, false );
$this->assertArrayHasKey( '_links', $data );
$self = array(
'href' => 'http://example.com/',
);
$this->assertEquals( $self, $data['_links']['self'][0] );
$alternate = array(
'href' => 'http://example.org/',
'type' => 'application/xml',
);
$this->assertEquals( $alternate, $data['_links']['alternate'][0] );
}
public function test_link_embedding() {
// Register our testing route.
$this->server->register_route( 'test', '/test/embeddable', array(
'methods' => 'GET',
'callback' => array( $this, 'embedded_response_callback' ),
) );
$response = new WP_REST_Response();
// External links should be ignored.
$response->add_link( 'alternate', 'http://not-api.example.com/', array( 'embeddable' => true ) );
// All others should be embedded.
$response->add_link( 'alternate', rest_url( '/test/embeddable' ), array( 'embeddable' => true ) );
$data = $this->server->response_to_data( $response, true );
$this->assertArrayHasKey( '_embedded', $data );
$alternate = $data['_embedded']['alternate'];
$this->assertCount( 2, $alternate );
$this->assertEmpty( $alternate[0] );
$this->assertInternalType( 'array', $alternate[1] );
$this->assertArrayNotHasKey( 'code', $alternate[1] );
$this->assertTrue( $alternate[1]['hello'] );
// Ensure the context is set to embed when requesting.
$this->assertEquals( 'embed', $alternate[1]['parameters']['context'] );
}
/**
* @depends test_link_embedding
*/
public function test_link_embedding_self() {
// Register our testing route.
$this->server->register_route( 'test', '/test/embeddable', array(
'methods' => 'GET',
'callback' => array( $this, 'embedded_response_callback' ),
) );
$response = new WP_REST_Response();
// 'self' should be ignored.
$response->add_link( 'self', rest_url( '/test/notembeddable' ), array( 'embeddable' => true ) );
$data = $this->server->response_to_data( $response, true );
$this->assertArrayNotHasKey( '_embedded', $data );
}
/**
* @depends test_link_embedding
*/
public function test_link_embedding_params() {
// Register our testing route.
$this->server->register_route( 'test', '/test/embeddable', array(
'methods' => 'GET',
'callback' => array( $this, 'embedded_response_callback' ),
) );
$response = new WP_REST_Response();
$response->add_link( 'alternate', rest_url( '/test/embeddable?parsed_params=yes' ), array( 'embeddable' => true ) );
$data = $this->server->response_to_data( $response, true );
$this->assertArrayHasKey( '_embedded', $data );
$this->assertArrayHasKey( 'alternate', $data['_embedded'] );
$data = $data['_embedded']['alternate'][0];
$this->assertEquals( 'yes', $data['parameters']['parsed_params'] );
}
/**
* @depends test_link_embedding_params
*/
public function test_link_embedding_error() {
// Register our testing route.
$this->server->register_route( 'test', '/test/embeddable', array(
'methods' => 'GET',
'callback' => array( $this, 'embedded_response_callback' ),
) );
$response = new WP_REST_Response();
$response->add_link( 'up', rest_url( '/test/embeddable?error=1' ), array( 'embeddable' => true ) );
$data = $this->server->response_to_data( $response, true );
$this->assertArrayHasKey( '_embedded', $data );
$this->assertArrayHasKey( 'up', $data['_embedded'] );
// Check that errors are embedded correctly.
$up = $data['_embedded']['up'];
$this->assertCount( 1, $up );
$up_data = $up[0];
$this->assertEquals( 'wp-api-test-error', $up_data[0]['code'] );
$this->assertEquals( 'Test message', $up_data[0]['message'] );
$this->assertEquals( 403, $up_data[0]['data']['status'] );
}
/**
* Ensure embedding is a no-op without links in the data.
*/
public function test_link_embedding_without_links() {
$data = array(
'untouched' => 'data',
);
$result = $this->server->embed_links( $data );
$this->assertArrayNotHasKey( '_links', $data );
$this->assertArrayNotHasKey( '_embedded', $data );
$this->assertEquals( 'data', $data['untouched'] );
}
public function embedded_response_callback( $request ) {
$params = $request->get_params();
if ( isset( $params['error'] ) ) {
return new WP_Error( 'wp-api-test-error', 'Test message', array( 'status' => 403 ) );
}
$data = array(
'hello' => true,
'parameters' => $params,
);
return $data;
}
public function test_removing_links() {
$response = new WP_REST_Response();
$response->add_link( 'self', 'http://example.com/' );
$response->add_link( 'alternate', 'http://example.org/', array( 'type' => 'application/xml' ) );
$response->remove_link( 'self' );
$data = $this->server->response_to_data( $response, false );
$this->assertArrayHasKey( '_links', $data );
$this->assertArrayNotHasKey( 'self', $data['_links'] );
$alternate = array(
'href' => 'http://example.org/',
'type' => 'application/xml',
);
$this->assertEquals( $alternate, $data['_links']['alternate'][0] );
}
public function test_removing_links_for_href() {
$response = new WP_REST_Response();
$response->add_link( 'self', 'http://example.com/' );
$response->add_link( 'self', 'https://example.com/' );
$response->remove_link( 'self', 'https://example.com/' );
$data = $this->server->response_to_data( $response, false );
$this->assertArrayHasKey( '_links', $data );
$this->assertArrayHasKey( 'self', $data['_links'] );
$self_not_filtered = array(
'href' => 'http://example.com/',
);
$this->assertEquals( $self_not_filtered, $data['_links']['self'][0] );
}
public function test_get_index() {
$server = new WP_REST_Server();
$server->register_route( 'test/example', '/test/example/some-route', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => '__return_true',
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => '__return_true',
),
) );
$request = new WP_REST_Request( 'GET', '/' );
$index = $server->dispatch( $request );
$data = $index->get_data();
$this->assertArrayHasKey( 'name', $data );
$this->assertArrayHasKey( 'description', $data );
$this->assertArrayHasKey( 'url', $data );
$this->assertArrayHasKey( 'namespaces', $data );
$this->assertArrayHasKey( 'authentication', $data );
$this->assertArrayHasKey( 'routes', $data );
// Check namespace data.
$this->assertContains( 'test/example', $data['namespaces'] );
// Check the route.
$this->assertArrayHasKey( '/test/example/some-route', $data['routes'] );
$route = $data['routes']['/test/example/some-route'];
$this->assertEquals( 'test/example', $route['namespace'] );
$this->assertArrayHasKey( 'methods', $route );
$this->assertContains( 'GET', $route['methods'] );
$this->assertContains( 'DELETE', $route['methods'] );
$this->assertArrayHasKey( '_links', $route );
}
public function test_get_namespace_index() {
$server = new WP_REST_Server();
$server->register_route( 'test/example', '/test/example/some-route', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => '__return_true',
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => '__return_true',
),
) );
$server->register_route( 'test/another', '/test/another/route', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => '__return_false',
),
) );
$request = new WP_REST_Request();
$request->set_param( 'namespace', 'test/example' );
$index = rest_ensure_response( $server->get_namespace_index( $request ) );
$data = $index->get_data();
// Check top-level.
$this->assertEquals( 'test/example', $data['namespace'] );
$this->assertArrayHasKey( 'routes', $data );
// Check we have the route we expect...
$this->assertArrayHasKey( '/test/example/some-route', $data['routes'] );
// ...and none we don't.
$this->assertArrayNotHasKey( '/test/another/route', $data['routes'] );
}
public function test_get_namespaces() {
$server = new WP_REST_Server();
$server->register_route( 'test/example', '/test/example/some-route', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => '__return_true',
),
) );
$server->register_route( 'test/another', '/test/another/route', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => '__return_false',
),
) );
$namespaces = $server->get_namespaces();
$this->assertContains( 'test/example', $namespaces );
$this->assertContains( 'test/another', $namespaces );
}
}