function ExceptionHandlingTest::testExceptionEscaping

Same name in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Routing/ExceptionHandlingTest.php \Drupal\KernelTests\Core\Routing\ExceptionHandlingTest::testExceptionEscaping()
  2. 10 core/tests/Drupal/KernelTests/Core/Routing/ExceptionHandlingTest.php \Drupal\KernelTests\Core\Routing\ExceptionHandlingTest::testExceptionEscaping()
  3. 11.x core/tests/Drupal/KernelTests/Core/Routing/ExceptionHandlingTest.php \Drupal\KernelTests\Core\Routing\ExceptionHandlingTest::testExceptionEscaping()

Tests exception message escaping.

File

core/tests/Drupal/KernelTests/Core/Routing/ExceptionHandlingTest.php, line 173

Class

ExceptionHandlingTest
Tests the exception handling for various cases.

Namespace

Drupal\KernelTests\Core\Routing

Code

public function testExceptionEscaping() {
    // Enable verbose error logging.
    $this->config('system.logging')
        ->set('error_level', ERROR_REPORTING_DISPLAY_VERBOSE)
        ->save();
    // Using \Drupal\Component\Render\FormattableMarkup.
    $request = Request::create('/router_test/test24');
    $request->setFormat('html', [
        'text/html',
    ]);
    
    /** @var \Symfony\Component\HttpKernel\HttpKernelInterface $kernel */
    $kernel = \Drupal::getContainer()->get('http_kernel');
    $response = $kernel->handle($request)
        ->prepare($request);
    $this->assertEquals(Response::HTTP_INTERNAL_SERVER_ERROR, $response->getStatusCode());
    $this->assertEquals('text/html; charset=UTF-8', $response->headers
        ->get('Content-type'));
    // Test message is properly escaped, and that the unescaped string is not
    // output at all.
    $this->setRawContent($response->getContent());
    $this->assertRaw(Html::escape('Escaped content: <p> <br> <h3>'));
    $this->assertNoRaw('<p> <br> <h3>');
    $string = '<script>alert(123);</script>';
    $request = Request::create('/router_test/test2?_format=json' . urlencode($string), 'GET');
    $kernel = \Drupal::getContainer()->get('http_kernel');
    $response = $kernel->handle($request)
        ->prepare($request);
    // As the Content-type is text/plain the fact that the raw string is
    // contained in the output would not matter, but because it is output by the
    // final exception subscriber, it is printed as partial HTML, and hence
    // escaped.
    $this->assertEquals('text/plain; charset=UTF-8', $response->headers
        ->get('Content-type'));
    $this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.<br><br><em class="placeholder">Symfony\\Component\\HttpKernel\\Exception\\NotAcceptableHttpException</em>: Not acceptable format: json&lt;script&gt;alert(123);&lt;/script&gt; in <em class="placeholder">', $response->getContent());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.