8f339a839dcdfa283050249f7fc05c69c2536053
[yaffs-website] / web / core / tests / Drupal / Tests / Core / EventSubscriber / ExceptionJsonSubscriberTest.php
1 <?php
2
3 namespace Drupal\Tests\Core\EventSubscriber;
4
5 use Drupal\Core\Cache\CacheableJsonResponse;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\EventSubscriber\ExceptionJsonSubscriber;
8 use Drupal\Core\Http\Exception\CacheableMethodNotAllowedHttpException;
9 use Drupal\Tests\UnitTestCase;
10 use Symfony\Component\HttpFoundation\JsonResponse;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
13 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
14 use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
15 use Symfony\Component\HttpKernel\HttpKernelInterface;
16
17 /**
18  * @coversDefaultClass \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber
19  * @group EventSubscriber
20  */
21 class ExceptionJsonSubscriberTest extends UnitTestCase {
22
23   /**
24    * @covers ::on4xx
25    * @dataProvider providerTestOn4xx
26    */
27   public function testOn4xx(HttpExceptionInterface $exception, $expected_response_class) {
28     $kernel = $this->prophesize(HttpKernelInterface::class);
29     $request = Request::create('/test');
30     $event = new GetResponseForExceptionEvent($kernel->reveal(), $request, 'GET', $exception);
31     $subscriber = new ExceptionJsonSubscriber();
32     $subscriber->on4xx($event);
33     $response = $event->getResponse();
34
35     $this->assertInstanceOf($expected_response_class, $response);
36     $this->assertEquals('{"message":"test message"}', $response->getContent());
37     $this->assertEquals(405, $response->getStatusCode());
38     $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
39     $this->assertEquals('application/json', $response->headers->get('Content-Type'));
40   }
41
42   public function providerTestOn4xx() {
43     return [
44       'uncacheable exception' => [
45         new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message'),
46         JsonResponse::class
47       ],
48       'cacheable exception' => [
49         new CacheableMethodNotAllowedHttpException((new CacheableMetadata())->setCacheContexts(['route']), ['POST', 'PUT'], 'test message'),
50         CacheableJsonResponse::class
51       ],
52     ];
53   }
54
55 }