You are here

public function LocaleTranslationUiTest::testStringValidation in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php \Drupal\Tests\locale\Functional\LocaleTranslationUiTest::testStringValidation()
  2. 10 core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php \Drupal\Tests\locale\Functional\LocaleTranslationUiTest::testStringValidation()

Tests the validation of the translation input.

File

core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php, line 293

Class

LocaleTranslationUiTest
Adds a new locale and translates its name. Checks the validation of translation strings and search results.

Namespace

Drupal\Tests\locale\Functional

Code

public function testStringValidation() {

  // User to add language and strings.
  $admin_user = $this
    ->drupalCreateUser([
    'administer languages',
    'access administration pages',
    'translate interface',
  ]);
  $this
    ->drupalLogin($admin_user);
  $langcode = 'xx';

  // The English name for the language. This will be translated.
  $name = $this
    ->randomMachineName(16);

  // These will be the invalid translations of $name.
  $key = $this
    ->randomMachineName(16);
  $bad_translations[$key] = "<script>alert('xss');</script>" . $key;
  $key = $this
    ->randomMachineName(16);
  $bad_translations[$key] = '<img SRC="javascript:alert(\'xss\');">' . $key;
  $key = $this
    ->randomMachineName(16);
  $bad_translations[$key] = '<<SCRIPT>alert("xss");//<</SCRIPT>' . $key;
  $key = $this
    ->randomMachineName(16);
  $bad_translations[$key] = "<BODY ONLOAD=alert('xss')>" . $key;

  // Add custom language.
  $edit = [
    'predefined_langcode' => 'custom',
    'langcode' => $langcode,
    'label' => $name,
    'direction' => LanguageInterface::DIRECTION_LTR,
  ];
  $this
    ->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));

  // Add string.
  t($name, [], [
    'langcode' => $langcode,
  ])
    ->render();

  // Reset locale cache.
  $search = [
    'string' => $name,
    'langcode' => $langcode,
    'translation' => 'all',
  ];
  $this
    ->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));

  // Find the edit path.
  $textarea = current($this
    ->xpath('//textarea'));
  $lid = $textarea
    ->getAttribute('name');
  foreach ($bad_translations as $translation) {
    $edit = [
      $lid => $translation,
    ];
    $this
      ->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    // Check for a form error on the textarea.
    $form_class = $this
      ->xpath('//form[@id="locale-translate-edit-form"]//textarea/@class');
    $this
      ->assertStringContainsString('error', $form_class[0]
      ->getText(), 'The string was rejected as unsafe.');
    $this
      ->assertNoText(t('The string has been saved.'), 'The string was not saved.');
  }
}