You are here

public function RequestHandlerTest::testHandle in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/rest/tests/src/Kernel/RequestHandlerTest.php \Drupal\Tests\rest\Kernel\RequestHandlerTest::testHandle()
  2. 10 core/modules/rest/tests/src/Kernel/RequestHandlerTest.php \Drupal\Tests\rest\Kernel\RequestHandlerTest::testHandle()

@covers ::handle

File

core/modules/rest/tests/src/Kernel/RequestHandlerTest.php, line 55

Class

RequestHandlerTest
Test REST RequestHandler controller logic.

Namespace

Drupal\Tests\rest\Kernel

Code

public function testHandle() {
  $request = new Request([], [], [], [], [], [
    'CONTENT_TYPE' => 'application/json',
  ], Json::encode([
    'this is an array',
  ]));
  $route_match = new RouteMatch('test', (new Route('/rest/test', [
    '_rest_resource_config' => 'restplugin',
    'example' => '',
  ], [
    '_format' => 'json',
  ]))
    ->setMethods([
    'GET',
  ]));
  $resource = $this
    ->prophesize(StubRequestHandlerResourcePlugin::class);
  $resource
    ->get('', $request)
    ->shouldBeCalled();
  $resource
    ->getPluginDefinition()
    ->willReturn([])
    ->shouldBeCalled();

  // Setup the configuration.
  $config = $this
    ->prophesize(RestResourceConfigInterface::class);
  $config
    ->getResourcePlugin()
    ->willReturn($resource
    ->reveal());
  $config
    ->getCacheContexts()
    ->willReturn([]);
  $config
    ->getCacheTags()
    ->willReturn([]);
  $config
    ->getCacheMaxAge()
    ->willReturn(12);

  // Response returns NULL this time because response from plugin is not
  // a ResourceResponse so it is passed through directly.
  $response = $this->requestHandler
    ->handle($route_match, $request, $config
    ->reveal());
  $this
    ->assertEquals(NULL, $response);

  // Response will return a ResourceResponse this time.
  $response = new ResourceResponse([]);
  $resource
    ->get(NULL, $request)
    ->willReturn($response);
  $handler_response = $this->requestHandler
    ->handle($route_match, $request, $config
    ->reveal());
  $this
    ->assertEquals($response, $handler_response);

  // We will call the patch method this time.
  $route_match = new RouteMatch('test', (new Route('/rest/test', [
    '_rest_resource_config' => 'restplugin',
    'example_original' => '',
  ], [
    '_content_type_format' => 'json',
  ]))
    ->setMethods([
    'PATCH',
  ]));
  $request
    ->setMethod('PATCH');
  $response = new ResourceResponse([]);
  $resource
    ->patch([
    'this is an array',
  ], $request)
    ->shouldBeCalledTimes(1)
    ->willReturn($response);
  $handler_response = $this->requestHandler
    ->handle($route_match, $request, $config
    ->reveal());
  $this
    ->assertEquals($response, $handler_response);
}