LocaleImportFunctionalTest.php 19 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php

/**
 * @file
 * Definition of Drupal\locale\Tests\LocaleImportFunctionalTest.
 */

namespace Drupal\locale\Tests;

use Drupal\simpletest\WebTestBase;

/**
 * Functional tests for the import of translation files.
 */
class LocaleImportFunctionalTest extends WebTestBase {
16 17 18 19 20 21 22 23

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('locale', 'dblog');

24 25 26 27 28 29 30 31 32 33 34 35 36 37
  public static function getInfo() {
    return array(
      'name' => 'Translation import',
      'description' => 'Tests the import of locale files.',
      'group' => 'Locale',
    );
  }

  /**
   * A user able to create languages and import translations.
   */
  protected $admin_user = NULL;

  function setUp() {
38
    parent::setUp();
39

40 41 42
    // Copy test po files to the translations directory.
    file_unmanaged_copy(drupal_get_path('module', 'locale') . '/tests/test.de.po', 'translations://', FILE_EXISTS_REPLACE);
    file_unmanaged_copy(drupal_get_path('module', 'locale') . '/tests/test.xx.po', 'translations://', FILE_EXISTS_REPLACE);
43 44 45 46 47 48 49 50 51 52 53 54 55

    $this->admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Test import of standalone .po files.
   */
  function testStandalonePoFile() {
    // Try importing a .po file.
    $this->importPoFile($this->getPoFile(), array(
      'langcode' => 'fr',
    ));
56
    \Drupal::config('locale.settings');
57
    // The import should automatically create the corresponding language.
58
    $this->assertRaw(t('The language %language has been created.', array('%language' => 'French')), 'The language has been automatically created.');
59 60

    // The import should have created 8 strings.
61
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 8, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
62 63

    // This import should have saved plural forms to have 2 variants.
64
    $locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: array();
65
    $this->assert($locale_plurals['fr']['plurals'] == 2, 'Plural number initialized.');
66 67

    // Ensure we were redirected correctly.
68
    $this->assertEqual($this->getUrl(), url('admin/config/regional/translate', array('absolute' => TRUE)), 'Correct page redirection.');
69 70 71 72 73 74 75 76


    // Try importing a .po file with invalid tags.
    $this->importPoFile($this->getBadPoFile(), array(
      'langcode' => 'fr',
    ));

    // The import should have created 1 string and rejected 2.
77
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
78 79

    $skip_message = format_plural(2, 'One translation string was skipped because of disallowed or malformed HTML. <a href="@url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. <a href="@url">See the log</a> for details.', array('@url' => url('admin/reports/dblog')));
80
    $this->assertRaw($skip_message, 'Unsafe strings were skipped.');
81

82 83 84 85 86 87
    // Try importing a zero byte sized .po file.
    $this->importPoFile($this->getEmptyPoFile(), array(
      'langcode' => 'fr',
    ));

    // The import should have created 0 string and rejected 0.
88
    $this->assertRaw(t('One translation file could not be imported. <a href="@url">See the log</a> for details.', array('@url' => url('admin/reports/dblog'))), 'The empty translation file was successfully imported.');
89 90 91

    // Try importing a .po file which doesn't exist.
    $name = $this->randomName(16);
92
    $this->drupalPostForm('admin/config/regional/translate/import', array(
93 94 95
      'langcode' => 'fr',
      'files[file]' => $name,
    ), t('Import'));
96 97
    $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/import', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertText(t('File to import not found.'), 'File to import not found message.');
98 99 100 101 102 103 104 105 106


    // Try importing a .po file with overriding strings, and ensure existing
    // strings are kept.
    $this->importPoFile($this->getOverwritePoFile(), array(
      'langcode' => 'fr',
    ));

    // The import should have created 1 string.
107
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
108 109 110
    // Ensure string wasn't overwritten.
    $search = array(
      'string' => 'Montag',
111
      'langcode' => 'fr',
112 113
      'translation' => 'translated',
    );
114
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
115
    $this->assertText(t('No strings available.'), 'String not overwritten by imported string.');
116 117

    // This import should not have changed number of plural forms.
118
    $locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: array();
119
    $this->assert($locale_plurals['fr']['plurals'] == 2, 'Plural numbers untouched.');
120 121 122 123 124 125 126 127 128

    // Try importing a .po file with overriding strings, and ensure existing
    // strings are overwritten.
    $this->importPoFile($this->getOverwritePoFile(), array(
      'langcode' => 'fr',
      'overwrite_options[not_customized]' => TRUE,
    ));

    // The import should have updated 2 strings.
129
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 2, '%delete' => 0)), 'The translation file was successfully imported.');
130 131 132
    // Ensure string was overwritten.
    $search = array(
      'string' => 'Montag',
133
      'langcode' => 'fr',
134 135
      'translation' => 'translated',
    );
136
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
137
    $this->assertNoText(t('No strings available.'), 'String overwritten by imported string.');
138
    // This import should have changed number of plural forms.
139
    $locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: array();
140
    $this->assert($locale_plurals['fr']['plurals'] == 3, 'Plural numbers changed.');
141 142 143 144 145 146 147 148

    // Importing a .po file and mark its strings as customized strings.
    $this->importPoFile($this->getCustomPoFile(), array(
      'langcode' => 'fr',
      'customized' => TRUE,
    ));

    // The import should have created 6 strings.
149
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 6, '%update' => 0, '%delete' => 0)), 'The customized translation file was successfully imported.');
150 151 152 153

    // The database should now contain 6 customized strings (two imported
    // strings are not translated).
    $count = db_query('SELECT lid FROM {locales_target} WHERE customized = :custom', array(':custom' => 1))->rowCount();
154
    $this->assertEqual($count, 6, 'Customized translations successfully imported.');
155 156 157 158 159 160 161 162 163 164

    // Try importing a .po file with overriding strings, and ensure existing
    // customized strings are kept.
    $this->importPoFile($this->getCustomOverwritePoFile(), array(
      'langcode' => 'fr',
      'overwrite_options[not_customized]' => TRUE,
      'overwrite_options[customized]' => FALSE,
    ));

    // The import should have created 1 string.
165
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The customized translation file was successfully imported.');
166 167 168
    // Ensure string wasn't overwritten.
    $search = array(
      'string' => 'januari',
169
      'langcode' => 'fr',
170 171
      'translation' => 'translated',
    );
172
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
173
    $this->assertText(t('No strings available.'), 'Customized string not overwritten by imported string.');
174 175 176 177 178 179 180 181 182 183

    // Try importing a .po file with overriding strings, and ensure existing
    // customized strings are overwritten.
    $this->importPoFile($this->getCustomOverwritePoFile(), array(
      'langcode' => 'fr',
      'overwrite_options[not_customized]' => FALSE,
      'overwrite_options[customized]' => TRUE,
    ));

    // The import should have updated 2 strings.
184
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 2, '%delete' => 0)), 'The customized translation file was successfully imported.');
185 186 187
    // Ensure string was overwritten.
    $search = array(
      'string' => 'januari',
188
      'langcode' => 'fr',
189 190
      'translation' => 'translated',
    );
191
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
192
    $this->assertNoText(t('No strings available.'), 'Customized string overwritten by imported string.');
193 194 195 196 197 198 199 200 201 202 203 204

  }

  /**
   * Test msgctxt context support.
   */
  function testLanguageContext() {
    // Try importing a .po file.
    $this->importPoFile($this->getPoFileWithContext(), array(
      'langcode' => 'hr',
    ));

205 206
    $this->assertIdentical(t('May', array(), array('langcode' => 'hr', 'context' => 'Long month name')), 'Svibanj', 'Long month name context is working.');
    $this->assertIdentical(t('May', array(), array('langcode' => 'hr')), 'Svi.', 'Default context is working.');
207 208 209 210 211 212 213 214 215 216 217 218 219
  }

  /**
   * Test empty msgstr at end of .po file see #611786.
   */
  function testEmptyMsgstr() {
    $langcode = 'hu';

    // Try importing a .po file.
    $this->importPoFile($this->getPoFileWithMsgstr(), array(
      'langcode' => $langcode,
    ));

220 221
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
    $this->assertIdentical(t('Operations', array(), array('langcode' => $langcode)), 'Műveletek', 'String imported and translated.');
222 223 224 225 226 227

    // Try importing a .po file.
    $this->importPoFile($this->getPoFileWithEmptyMsgstr(), array(
      'langcode' => $langcode,
      'overwrite_options[not_customized]' => TRUE,
    ));
228
    $this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 0, '%delete' => 1)), 'The translation file was successfully imported.');
229

230 231 232
    $str = "Operations";
    $search = array(
      'string' => $str,
233 234
      'langcode' => $langcode,
      'translation' => 'untranslated',
235
    );
236
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
237
    $this->assertText($str, 'Search found the string as untranslated.');
238 239
  }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  /**
   * Tests .po file import with configuration translation.
   */
  function testConfigPoFile() {
    // Values for translations to assert. Config key, original string,
    // translation and config property name.
    $config_strings = array(
      'system.maintenance' => array(
        '@site is currently under maintenance. We should be back shortly. Thank you for your patience.',
        '@site karbantartás alatt áll. Rövidesen visszatérünk. Köszönjük a türelmet.',
        'message',
      ),
      'user.role.anonymous' => array(
        'Anonymous user',
        'Névtelen felhasználó',
        'label',
      ),
    );

    // Add custom language for testing.
    $langcode = 'xx';
    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => $langcode,
      'name' => $this->randomName(16),
      'direction' => '0',
    );
267
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
268 269 270 271

    // Check for the source strings we are going to translate. Adding the
    // custom language should have made the process to export configuration
    // strings to interface translation executed.
272
    $locale_storage = $this->container->get('locale.storage');
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    foreach ($config_strings as $config_string) {
      $string = $locale_storage->findString(array('source' => $config_string[0], 'context' => '', 'type' => 'configuration'));
      $this->assertTrue($string, 'Configuration strings have been created upon installation.');
    }

    // Import a .po file to translate.
    $this->importPoFile($this->getPoFileWithConfig(), array(
      'langcode' => $langcode,
    ));

    // Translations got recorded in the interface translation system.
    foreach ($config_strings as $config_string) {
      $search = array(
        'string' => $config_string[0],
        'langcode' => $langcode,
        'translation' => 'all',
      );
290
      $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
291 292 293 294 295 296 297 298 299 300 301 302 303 304
      $this->assertText($config_string[1], format_string('Translation of @string found.', array('@string' => $config_string[0])));
    }

    $locale_config = $this->container->get('locale.config.typed');
    // Translations got recorded in the config system.
    foreach ($config_strings as $config_key => $config_string) {
      $wrapper = $locale_config->get($config_key);
      $translation = $wrapper->getTranslation($langcode);
      $properties = $translation->getProperties();
      $this->assertEqual(count($properties), 1, 'Got the right number of properties with strict translation');
      $this->assertEqual($properties[$config_string[2]]->getValue(), $config_string[1]);
    }
  }

305 306 307 308 309 310 311 312 313 314 315 316
  /**
   * Helper function: import a standalone .po file in a given language.
   *
   * @param $contents
   *   Contents of the .po file to import.
   * @param $options
   *   Additional options to pass to the translation import form.
   */
  function importPoFile($contents, array $options = array()) {
    $name = tempnam('temporary://', "po_") . '.po';
    file_put_contents($name, $contents);
    $options['files[file]'] = $name;
317
    $this->drupalPostForm('admin/config/regional/translate/import', $options, t('Import'));
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    drupal_unlink($name);
  }

  /**
   * Helper function that returns a proper .po file.
   */
  function getPoFile() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "One sheep"
msgid_plural "@count sheep"
msgstr[0] "un mouton"
msgstr[1] "@count moutons"

msgid "Monday"
msgstr "lundi"

msgid "Tuesday"
msgstr "mardi"

msgid "Wednesday"
msgstr "mercredi"

msgid "Thursday"
msgstr "jeudi"

msgid "Friday"
msgstr "vendredi"

msgid "Saturday"
msgstr "samedi"

msgid "Sunday"
msgstr "dimanche"
EOF;
  }

362 363 364 365 366 367 368
  /**
   * Helper function that returns a empty .po file.
   */
  function getEmptyPoFile() {
    return '';
  }

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  /**
   * Helper function that returns a bad .po file.
   */
  function getBadPoFile() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "Save configuration"
msgstr "Enregistrer la configuration"

msgid "edit"
msgstr "modifier<img SRC="javascript:alert(\'xss\');">"

msgid "delete"
msgstr "supprimer<script>alert('xss');</script>"

EOF;
  }

  /**
   * Helper function that returns a proper .po file for testing.
   */
  function getOverwritePoFile() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\\n"

msgid "Monday"
msgstr "Montag"

msgid "Day"
msgstr "Jour"
EOF;
  }

  /**
   * Helper function that returns a .po file which strings will be marked
   * as customized.
   */
  function getCustomPoFile() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "One dog"
msgid_plural "@count dogs"
msgstr[0] "un chien"
msgstr[1] "@count chiens"

msgid "January"
msgstr "janvier"

msgid "February"
msgstr "février"

msgid "March"
msgstr "mars"

msgid "April"
msgstr "avril"

msgid "June"
msgstr "juin"
EOF;
  }

  /**
   * Helper function that returns a .po file for testing customized strings.
   */
  function getCustomOverwritePoFile() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "January"
msgstr "januari"

msgid "February"
msgstr "februari"

msgid "July"
msgstr "juillet"
EOF;
  }

  /**
   * Helper function that returns a .po file with context.
   */
  function getPoFileWithContext() {
    // Croatian (code hr) is one the the languages that have a different
    // form for the full name and the abbreviated name for the month May.
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\\n"

msgctxt "Long month name"
msgid "May"
msgstr "Svibanj"

msgid "May"
msgstr "Svi."
EOF;
  }

  /**
   * Helper function that returns a .po file with an empty last item.
   */
  function getPoFileWithEmptyMsgstr() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "Operations"
msgstr ""

EOF;
  }
517

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  /**
   * Helper function that returns a .po file with an empty last item.
   */
  function getPoFileWithMsgstr() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "Operations"
msgstr "Műveletek"

msgid "Will not appear in Drupal core, so we can ensure the test passes"
msgstr ""

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
EOF;
  }

  /**
   * Helper function that returns a .po file with configuration translations.
   */
  function getPoFileWithConfig() {
    return <<< EOF
msgid ""
msgstr ""
"Project-Id-Version: Drupal 8\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\\n"

msgid "@site is currently under maintenance. We should be back shortly. Thank you for your patience."
msgstr "@site karbantartás alatt áll. Rövidesen visszatérünk. Köszönjük a türelmet."

msgid "Anonymous user"
msgstr "Névtelen felhasználó"

559 560 561 562
EOF;
  }

}