XssUnitTest.php 2.29 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\system\Tests\Common\XssUnitTest.
6 7 8 9
 */

namespace Drupal\system\Tests\Common;

10
use Drupal\Component\Utility\UrlHelper;
11
use Drupal\simpletest\KernelTestBase;
12 13

/**
14 15 16 17
 * Confirm that \Drupal\Component\Utility\Xss::filter() and check_url() work
 * correctly, including invalid multi-byte sequences.
 *
 * @group Common
18
 */
19
class XssUnitTest extends KernelTestBase {
20 21 22 23 24 25

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = array('filter', 'system');
27

28 29
  protected function setUp() {
    parent::setUp();
30
    $this->installConfig(array('system'));
31 32
  }

33
  /**
34
   * Tests t() functionality.
35
   */
36 37 38 39 40 41 42 43 44
  function testT() {
    $text = t('Simple text');
    $this->assertEqual($text, 'Simple text', 't leaves simple text alone.');
    $text = t('Escaped text: @value', array('@value' => '<script>'));
    $this->assertEqual($text, 'Escaped text: &lt;script&gt;', 't replaces and escapes string.');
    $text = t('Placeholder text: %value', array('%value' => '<script>'));
    $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', 't replaces, escapes and themes string.');
    $text = t('Verbatim text: !value', array('!value' => '<script>'));
    $this->assertEqual($text, 'Verbatim text: <script>', 't replaces verbatim string as-is.');
45 46 47
  }

  /**
48
   * Checks that harmful protocols are stripped.
49 50 51
   */
  function testBadProtocolStripping() {
    // Ensure that check_url() strips out harmful protocols, and encodes for
52 53
    // HTML.
    // Ensure \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() can
54
    // be used to return a plain-text string stripped of harmful protocols.
55 56 57
    $url = 'javascript:http://www.example.com/?x=1&y=2';
    $expected_plain = 'http://www.example.com/?x=1&y=2';
    $expected_html = 'http://www.example.com/?x=1&amp;y=2';
58
    $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
59 60 61
    $this->assertIdentical(UrlHelper::filterBadProtocol($url), $expected_html, '\Drupal\Component\Utility\UrlHelper::filterBadProtocol() filters a URL and encodes it for HTML.');
    $this->assertIdentical(UrlHelper::stripDangerousProtocols($url), $expected_plain, '\Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() filters a URL and returns plain text.');

62 63
  }
}