3 namespace Drupal\config_translation\Tests;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\SafeMarkup;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Language\Language;
10 use Drupal\Core\Language\LanguageInterface;
11 use Drupal\field\Entity\FieldConfig;
12 use Drupal\field\Entity\FieldStorageConfig;
13 use Drupal\filter\Entity\FilterFormat;
14 use Drupal\language\Entity\ConfigurableLanguage;
15 use Drupal\node\Entity\NodeType;
16 use Drupal\simpletest\WebTestBase;
19 * Translate settings and entities to various languages.
21 * @group config_translation
23 class ConfigTranslationUiTest extends WebTestBase {
30 public static $modules = [
33 'config_translation_test',
48 * Languages to enable.
52 protected $langcodes = ['fr', 'ta'];
55 * Administrator user for tests.
57 * @var \Drupal\user\UserInterface
62 * Translator user for tests.
64 * @var \Drupal\user\UserInterface
66 protected $translatorUser;
69 * String translation storage object.
71 * @var \Drupal\locale\StringStorageInterface
73 protected $localeStorage;
75 protected function setUp() {
77 $translator_permissions = [
78 'translate configuration',
81 /** @var \Drupal\filter\FilterFormatInterface $filter_test_format */
82 $filter_test_format = FilterFormat::load('filter_test');
83 /** @var \Drupal\filter\FilterFormatInterface $filtered_html_format */
84 $filtered_html_format = FilterFormat::load('filtered_html');
85 /** @var \Drupal\filter\FilterFormatInterface $full_html_format */
86 $full_html_format = FilterFormat::load('full_html');
88 $admin_permissions = array_merge(
89 $translator_permissions,
91 'administer languages',
92 'administer site configuration',
94 'administer contact forms',
96 $filtered_html_format->getPermissionName(),
97 $full_html_format->getPermissionName(),
98 $filter_test_format->getPermissionName(),
99 'access site-wide contact form',
100 'access contextual links',
102 'administer account settings',
104 'bypass node access',
105 'administer content types',
106 'translate interface',
109 // Create and log in user.
110 $this->translatorUser = $this->drupalCreateUser($translator_permissions);
111 $this->adminUser = $this->drupalCreateUser($admin_permissions);
114 foreach ($this->langcodes as $langcode) {
115 ConfigurableLanguage::createFromLangcode($langcode)->save();
117 $this->localeStorage = $this->container->get('locale.storage');
118 $this->drupalPlaceBlock('local_tasks_block');
119 $this->drupalPlaceBlock('page_title_block');
123 * Tests the site information translation interface.
125 public function testSiteInformationTranslationUi() {
126 $this->drupalLogin($this->adminUser);
128 $site_name = 'Name of the site for testing configuration translation';
129 $site_slogan = 'Site slogan for testing configuration translation';
130 $site_name_label = 'Site name';
131 $fr_site_name = 'Nom du site pour tester la configuration traduction';
132 $fr_site_slogan = 'Slogan du site pour tester la traduction de configuration';
133 $fr_site_name_label = 'Libellé du champ "Nom du site"';
134 $translation_base_url = 'admin/config/system/site-information/translate';
136 // Set site name and slogan for default language.
137 $this->setSiteInformation($site_name, $site_slogan);
139 $this->drupalGet('admin/config/system/site-information');
140 // Check translation tab exist.
141 $this->assertLinkByHref($translation_base_url);
143 $this->drupalGet($translation_base_url);
145 // Check that the 'Edit' link in the source language links back to the
147 $this->clickLink(t('Edit'));
148 // Also check that saving the form leads back to the translation overview.
149 $this->drupalPostForm(NULL, [], t('Save configuration'));
150 $this->assertUrl($translation_base_url);
152 // Check 'Add' link of French to visit add page.
153 $this->assertLinkByHref("$translation_base_url/fr/add");
154 $this->clickLink(t('Add'));
156 // Make sure original text is present on this page.
157 $this->assertRaw($site_name);
158 $this->assertRaw($site_slogan);
160 // Update site name and slogan for French.
162 'translation[config_names][system.site][name]' => $fr_site_name,
163 'translation[config_names][system.site][slogan]' => $fr_site_slogan,
166 $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
167 $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
169 // Check for edit, delete links (and no 'add' link) for French language.
170 $this->assertNoLinkByHref("$translation_base_url/fr/add");
171 $this->assertLinkByHref("$translation_base_url/fr/edit");
172 $this->assertLinkByHref("$translation_base_url/fr/delete");
174 // Check translation saved proper.
175 $this->drupalGet("$translation_base_url/fr/edit");
176 $this->assertFieldByName('translation[config_names][system.site][name]', $fr_site_name);
177 $this->assertFieldByName('translation[config_names][system.site][slogan]', $fr_site_slogan);
179 // Place branding block with site name and slogan into header region.
180 $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
182 // Check French translation of site name and slogan are in place.
183 $this->drupalGet('fr');
184 $this->assertRaw($fr_site_name);
185 $this->assertRaw($fr_site_slogan);
187 // Visit French site to ensure base language string present as source.
188 $this->drupalGet("fr/$translation_base_url/fr/edit");
189 $this->assertText($site_name);
190 $this->assertText($site_slogan);
192 // Translate 'Site name' label in French.
194 'string' => $site_name_label,
196 'translation' => 'untranslated',
198 $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
200 $textarea = current($this->xpath('//textarea'));
201 $lid = (string) $textarea[0]['name'];
203 $lid => $fr_site_name_label,
205 $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
207 // Ensure that the label is in French (and not in English).
208 $this->drupalGet("fr/$translation_base_url/fr/edit");
209 $this->assertText($fr_site_name_label);
210 $this->assertNoText($site_name_label);
212 // Ensure that the label is also in French (and not in English)
213 // when editing another language with the interface in French.
214 $this->drupalGet("fr/$translation_base_url/ta/edit");
215 $this->assertText($fr_site_name_label);
216 $this->assertNoText($site_name_label);
218 // Ensure that the label is not translated when the interface is in English.
219 $this->drupalGet("$translation_base_url/fr/edit");
220 $this->assertText($site_name_label);
221 $this->assertNoText($fr_site_name_label);
225 * Tests the site information translation interface.
227 public function testSourceValueDuplicateSave() {
228 $this->drupalLogin($this->adminUser);
230 $site_name = 'Site name for testing configuration translation';
231 $site_slogan = 'Site slogan for testing configuration translation';
232 $translation_base_url = 'admin/config/system/site-information/translate';
233 $this->setSiteInformation($site_name, $site_slogan);
235 $this->drupalGet($translation_base_url);
237 // Case 1: Update new value for site slogan and site name.
239 'translation[config_names][system.site][name]' => 'FR ' . $site_name,
240 'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
242 // First time, no overrides, so just Add link.
243 $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
245 // Read overridden file from active config.
246 $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
248 // Expect both name and slogan in language specific file.
250 'name' => 'FR ' . $site_name,
251 'slogan' => 'FR ' . $site_slogan,
253 $this->assertEqual($expected, $override->get());
255 // Case 2: Update new value for site slogan and default value for site name.
256 $this->drupalGet("$translation_base_url/fr/edit");
257 // Assert that the language configuration does not leak outside of the
258 // translation form into the actual site name and slogan.
259 $this->assertNoText('FR ' . $site_name);
260 $this->assertNoText('FR ' . $site_slogan);
262 'translation[config_names][system.site][name]' => $site_name,
263 'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
265 $this->drupalPostForm(NULL, $edit, t('Save translation'));
266 $this->assertRaw(t('Successfully updated @language translation.', ['@language' => 'French']));
267 $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
269 // Expect only slogan in language specific file.
270 $expected = 'FR ' . $site_slogan;
271 $this->assertEqual($expected, $override->get('slogan'));
273 // Case 3: Keep default value for site name and slogan.
274 $this->drupalGet("$translation_base_url/fr/edit");
275 $this->assertNoText('FR ' . $site_slogan);
277 'translation[config_names][system.site][name]' => $site_name,
278 'translation[config_names][system.site][slogan]' => $site_slogan,
280 $this->drupalPostForm(NULL, $edit, t('Save translation'));
281 $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
283 // Expect no language specific file.
284 $this->assertTrue($override->isNew());
286 // Check configuration page with translator user. Should have no access.
287 $this->drupalLogout();
288 $this->drupalLogin($this->translatorUser);
289 $this->drupalGet('admin/config/system/site-information');
290 $this->assertResponse(403);
292 // While translator can access the translation page, the edit link is not
293 // present due to lack of permissions.
294 $this->drupalGet($translation_base_url);
295 $this->assertNoLink(t('Edit'));
297 // Check 'Add' link for French.
298 $this->assertLinkByHref("$translation_base_url/fr/add");
302 * Tests the contact form translation.
304 public function testContactConfigEntityTranslation() {
305 $this->drupalLogin($this->adminUser);
307 $this->drupalGet('admin/structure/contact');
309 // Check for default contact form configuration entity from Contact module.
310 $this->assertLinkByHref('admin/structure/contact/manage/feedback');
312 // Save default language configuration.
313 $label = 'Send your feedback';
316 'recipients' => 'sales@example.com,support@example.com',
317 'reply' => 'Thank you for your mail',
319 $this->drupalPostForm('admin/structure/contact/manage/feedback', $edit, t('Save'));
321 // Ensure translation link is present.
322 $translation_base_url = 'admin/structure/contact/manage/feedback/translate';
323 $this->assertLinkByHref($translation_base_url);
325 // Make sure translate tab is present.
326 $this->drupalGet('admin/structure/contact/manage/feedback');
327 $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
329 // Visit the form to confirm the changes.
330 $this->drupalGet('contact/feedback');
331 $this->assertText($label);
333 foreach ($this->langcodes as $langcode) {
334 $this->drupalGet($translation_base_url);
335 $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
337 // 'Add' link should be present for $langcode translation.
338 $translation_page_url = "$translation_base_url/$langcode/add";
339 $this->assertLinkByHref($translation_page_url);
341 // Make sure original text is present on this page.
342 $this->drupalGet($translation_page_url);
343 $this->assertText($label);
345 // Update translatable fields.
347 'translation[config_names][contact.form.feedback][label]' => 'Website feedback - ' . $langcode,
348 'translation[config_names][contact.form.feedback][reply]' => 'Thank you for your mail - ' . $langcode,
351 // Save language specific version of form.
352 $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
354 // Expect translated values in language specific file.
355 $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
357 'label' => 'Website feedback - ' . $langcode,
358 'reply' => 'Thank you for your mail - ' . $langcode,
360 $this->assertEqual($expected, $override->get());
362 // Check for edit, delete links (and no 'add' link) for $langcode.
363 $this->assertNoLinkByHref("$translation_base_url/$langcode/add");
364 $this->assertLinkByHref("$translation_base_url/$langcode/edit");
365 $this->assertLinkByHref("$translation_base_url/$langcode/delete");
367 // Visit language specific version of form to check label.
368 $this->drupalGet($langcode . '/contact/feedback');
369 $this->assertText('Website feedback - ' . $langcode);
373 'subject[0][value]' => 'Test subject',
374 'message[0][value]' => 'Test message',
376 $this->drupalPostForm(NULL, $edit, t('Send message'));
379 // Now that all language translations are present, check translation and
380 // original text all appear in any translated page on the translation
382 foreach ($this->langcodes as $langcode) {
383 $langcode_prefixes = array_merge([''], $this->langcodes);
384 foreach ($langcode_prefixes as $langcode_prefix) {
385 $this->drupalGet(ltrim("$langcode_prefix/$translation_base_url/$langcode/edit", '/'));
386 $this->assertFieldByName('translation[config_names][contact.form.feedback][label]', 'Website feedback - ' . $langcode);
387 $this->assertText($label);
391 // We get all emails so no need to check inside the loop.
392 $captured_emails = $this->drupalGetMails();
394 // Check language specific auto reply text in email body.
395 foreach ($captured_emails as $email) {
396 if ($email['id'] == 'contact_page_autoreply') {
397 // Trim because we get an added newline for the body.
398 $this->assertEqual(trim($email['body']), 'Thank you for your mail - ' . $email['langcode']);
402 // Test that delete links work and operations perform properly.
403 foreach ($this->langcodes as $langcode) {
404 $replacements = ['%label' => t('@label @entity_type', ['@label' => $label, '@entity_type' => Unicode::strtolower(t('Contact form'))]), '@language' => \Drupal::languageManager()->getLanguage($langcode)->getName()];
406 $this->drupalGet("$translation_base_url/$langcode/delete");
407 $this->assertRaw(t('Are you sure you want to delete the @language translation of %label?', $replacements));
408 // Assert link back to list page to cancel delete is present.
409 $this->assertLinkByHref($translation_base_url);
411 $this->drupalPostForm(NULL, [], t('Delete'));
412 $this->assertRaw(t('@language translation of %label was deleted', $replacements));
413 $this->assertLinkByHref("$translation_base_url/$langcode/add");
414 $this->assertNoLinkByHref("translation_base_url/$langcode/edit");
415 $this->assertNoLinkByHref("$translation_base_url/$langcode/delete");
417 // Expect no language specific file present anymore.
418 $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
419 $this->assertTrue($override->isNew());
422 // Check configuration page with translator user. Should have no access.
423 $this->drupalLogout();
424 $this->drupalLogin($this->translatorUser);
425 $this->drupalGet('admin/structure/contact/manage/feedback');
426 $this->assertResponse(403);
428 // While translator can access the translation page, the edit link is not
429 // present due to lack of permissions.
430 $this->drupalGet($translation_base_url);
431 $this->assertNoLink(t('Edit'));
433 // Check 'Add' link for French.
434 $this->assertLinkByHref("$translation_base_url/fr/add");
438 * Tests date format translation.
440 public function testDateFormatTranslation() {
441 $this->drupalLogin($this->adminUser);
443 $this->drupalGet('admin/config/regional/date-time');
445 // Check for medium format.
446 $this->assertLinkByHref('admin/config/regional/date-time/formats/manage/medium');
448 // Save default language configuration for a new format.
450 'label' => 'Custom medium date',
451 'id' => 'custom_medium',
452 'date_format_pattern' => 'Y. m. d. H:i',
454 $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
456 // Test translating a default shipped format and our custom format.
458 'medium' => 'Default medium date',
459 'custom_medium' => 'Custom medium date',
461 foreach ($formats as $id => $label) {
462 $translation_base_url = 'admin/config/regional/date-time/formats/manage/' . $id . '/translate';
464 $this->drupalGet($translation_base_url);
466 // 'Add' link should be present for French translation.
467 $translation_page_url = "$translation_base_url/fr/add";
468 $this->assertLinkByHref($translation_page_url);
470 // Make sure original text is present on this page.
471 $this->drupalGet($translation_page_url);
472 $this->assertText($label);
474 // Make sure that the date library is added.
475 $this->assertRaw('core/modules/system/js/system.date.js');
477 // Update translatable fields.
479 'translation[config_names][core.date_format.' . $id . '][label]' => $id . ' - FR',
480 'translation[config_names][core.date_format.' . $id . '][pattern]' => 'D',
483 // Save language specific version of form.
484 $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
486 // Get translation and check we've got the right value.
487 $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'core.date_format.' . $id);
489 'label' => $id . ' - FR',
492 $this->assertEqual($expected, $override->get());
494 // Formatting the date 8 / 27 / 1985 @ 13:37 EST with pattern D should
496 $formatted_date = format_date(494015820, $id, NULL, 'America/New_York', 'fr');
497 $this->assertEqual($formatted_date, 'Tue', 'Got the right formatted date using the date format translation pattern.');
502 * Tests the account settings translation interface.
504 * This is the only special case so far where we have multiple configuration
505 * names involved building up one configuration translation form. Test that
506 * the translations are saved for all configuration names properly.
508 public function testAccountSettingsConfigurationTranslation() {
509 $this->drupalLogin($this->adminUser);
511 $this->drupalGet('admin/config/people/accounts');
512 $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
514 $this->drupalGet('admin/config/people/accounts/translate');
515 $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
516 $this->assertLinkByHref('admin/config/people/accounts/translate/fr/add');
518 // Update account settings fields for French.
520 'translation[config_names][user.settings][anonymous]' => 'Anonyme',
521 'translation[config_names][user.mail][status_blocked][subject]' => 'Testing, your account is blocked.',
522 'translation[config_names][user.mail][status_blocked][body]' => 'Testing account blocked body.',
525 $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation'));
527 // Make sure the changes are saved and loaded back properly.
528 $this->drupalGet('admin/config/people/accounts/translate/fr/edit');
529 foreach ($edit as $key => $value) {
530 // Check the translations appear in the right field type as well.
531 $xpath = '//' . (strpos($key, '[body]') ? 'textarea' : 'input') . '[@name="' . $key . '"]';
532 $this->assertFieldByXPath($xpath, $value);
534 // Check that labels for email settings appear.
535 $this->assertText(t('Account cancellation confirmation'));
536 $this->assertText(t('Password recovery'));
540 * Tests source and target language edge cases.
542 public function testSourceAndTargetLanguage() {
543 $this->drupalLogin($this->adminUser);
545 // Loading translation page for not-specified language (und)
546 // should return 403.
547 $this->drupalGet('admin/config/system/site-information/translate/und/add');
548 $this->assertResponse(403);
550 // Check the source language doesn't have 'Add' or 'Delete' link and
551 // make sure source language edit goes to original configuration page
552 // not the translation specific edit page.
553 $this->drupalGet('admin/config/system/site-information/translate');
554 $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/edit');
555 $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/add');
556 $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/delete');
557 $this->assertLinkByHref('admin/config/system/site-information');
559 // Translation addition to source language should return 403.
560 $this->drupalGet('admin/config/system/site-information/translate/en/add');
561 $this->assertResponse(403);
563 // Translation editing in source language should return 403.
564 $this->drupalGet('admin/config/system/site-information/translate/en/edit');
565 $this->assertResponse(403);
567 // Translation deletion in source language should return 403.
568 $this->drupalGet('admin/config/system/site-information/translate/en/delete');
569 $this->assertResponse(403);
571 // Set default language of site information to not-specified language (und).
572 $this->config('system.site')
573 ->set('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED)
576 // Make sure translation tab does not exist on the configuration page.
577 $this->drupalGet('admin/config/system/site-information');
578 $this->assertNoLinkByHref('admin/config/system/site-information/translate');
580 // If source language is not specified, translation page should be 403.
581 $this->drupalGet('admin/config/system/site-information/translate');
582 $this->assertResponse(403);
586 * Tests the views translation interface.
588 public function testViewsTranslationUI() {
589 $this->drupalLogin($this->adminUser);
591 // Assert contextual link related to views.
592 $ids = ['entity.view.edit_form:view=frontpage:location=page&name=frontpage&display_id=page_1'];
593 $response = $this->renderContextualLinks($ids, 'node');
594 $this->assertResponse(200);
595 $json = Json::decode($response);
596 $this->assertTrue(strpos($json[$ids[0]], 'Translate view'), 'Translate view contextual link added.');
598 $description = 'All content promoted to the front page.';
599 $human_readable_name = 'Frontpage';
600 $display_settings_master = 'Master';
601 $display_options_master = '(Empty)';
602 $translation_base_url = 'admin/structure/views/view/frontpage/translate';
604 $this->drupalGet($translation_base_url);
606 // Check 'Add' link of French to visit add page.
607 $this->assertLinkByHref("$translation_base_url/fr/add");
608 $this->clickLink(t('Add'));
610 // Make sure original text is present on this page.
611 $this->assertRaw($description);
612 $this->assertRaw($human_readable_name);
614 // Update Views Fields for French.
616 'translation[config_names][views.view.frontpage][description]' => $description . " FR",
617 'translation[config_names][views.view.frontpage][label]' => $human_readable_name . " FR",
618 'translation[config_names][views.view.frontpage][display][default][display_title]' => $display_settings_master . " FR",
619 'translation[config_names][views.view.frontpage][display][default][display_options][title]' => $display_options_master . " FR",
621 $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
622 $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
624 // Check for edit, delete links (and no 'add' link) for French language.
625 $this->assertNoLinkByHref("$translation_base_url/fr/add");
626 $this->assertLinkByHref("$translation_base_url/fr/edit");
627 $this->assertLinkByHref("$translation_base_url/fr/delete");
629 // Check translation saved proper.
630 $this->drupalGet("$translation_base_url/fr/edit");
631 $this->assertFieldByName('translation[config_names][views.view.frontpage][description]', $description . " FR");
632 $this->assertFieldByName('translation[config_names][views.view.frontpage][label]', $human_readable_name . " FR");
633 $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_title]', $display_settings_master . " FR");
634 $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_options][title]', $display_options_master . " FR");
638 * Test the number of source elements for plural strings in config translation forms.
640 public function testPluralConfigStringsSourceElements() {
641 $this->drupalLogin($this->adminUser);
643 // Languages to test, with various number of plural forms.
645 'vi' => ['plurals' => 1, 'expected' => [TRUE, FALSE, FALSE, FALSE]],
646 'fr' => ['plurals' => 2, 'expected' => [TRUE, TRUE, FALSE, FALSE]],
647 'sl' => ['plurals' => 4, 'expected' => [TRUE, TRUE, TRUE, TRUE]],
650 foreach ($languages as $langcode => $data) {
651 // Import a .po file to add a new language with a given number of plural forms
652 $name = \Drupal::service('file_system')->tempnam('temporary://', $langcode . '_') . '.po';
653 file_put_contents($name, $this->getPoFile($data['plurals']));
654 $this->drupalPostForm('admin/config/regional/translate/import', [
655 'langcode' => $langcode,
656 'files[file]' => $name,
659 // Change the config langcode of the 'files' view.
660 $config = \Drupal::service('config.factory')->getEditable('views.view.files');
661 $config->set('langcode', $langcode);
664 // Go to the translation page of the 'files' view.
665 $translation_url = 'admin/structure/views/view/files/translate/en/add';
666 $this->drupalGet($translation_url);
668 // Check if the expected number of source elements are present.
669 foreach ($data['expected'] as $index => $expected) {
671 $this->assertRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
674 $this->assertNoRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
681 * Test translation of plural strings with multiple plural forms in config.
683 public function testPluralConfigStrings() {
684 $this->drupalLogin($this->adminUser);
686 // First import a .po file with multiple plural forms.
687 // This will also automatically add the 'sl' language.
688 $name = \Drupal::service('file_system')->tempnam('temporary://', "sl_") . '.po';
689 file_put_contents($name, $this->getPoFile(4));
690 $this->drupalPostForm('admin/config/regional/translate/import', [
692 'files[file]' => $name,
695 // Translate the files view, as this one uses numeric formatters.
696 $description = 'Singular form';
697 $field_value = '1 place';
698 $field_value_plural = '@count places';
699 $translation_url = 'admin/structure/views/view/files/translate/sl/add';
700 $this->drupalGet($translation_url);
702 // Make sure original text is present on this page, in addition to 2 new
704 $this->assertRaw($description);
705 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', $field_value);
706 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', $field_value_plural);
707 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', '');
708 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', '');
710 // Then make sure it also works.
712 'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]' => $field_value . ' SL',
713 'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]' => $field_value_plural . ' 1 SL',
714 'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]' => $field_value_plural . ' 2 SL',
715 'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]' => $field_value_plural . ' 3 SL',
717 $this->drupalPostForm($translation_url, $edit, t('Save translation'));
719 // Make sure the values have changed.
720 $this->drupalGet($translation_url);
721 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', "$field_value SL");
722 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', "$field_value_plural 1 SL");
723 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', "$field_value_plural 2 SL");
724 $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', "$field_value_plural 3 SL");
728 * Tests the translation of field and field storage configuration.
730 public function testFieldConfigTranslation() {
731 // Add a test field which has a translatable field setting and a
732 // translatable field storage setting.
733 $field_name = strtolower($this->randomMachineName());
734 $field_storage = FieldStorageConfig::create([
735 'field_name' => $field_name,
736 'entity_type' => 'entity_test',
737 'type' => 'test_field',
740 $translatable_storage_setting = $this->randomString();
741 $field_storage->setSetting('translatable_storage_setting', $translatable_storage_setting);
742 $field_storage->save();
744 $bundle = strtolower($this->randomMachineName());
745 entity_test_create_bundle($bundle);
746 $field = FieldConfig::create([
747 'field_name' => $field_name,
748 'entity_type' => 'entity_test',
752 $translatable_field_setting = $this->randomString();
753 $field->setSetting('translatable_field_setting', $translatable_field_setting);
756 $this->drupalLogin($this->translatorUser);
758 $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
759 $this->clickLink('Add');
761 $this->assertText('Translatable field setting');
762 $this->assertEscaped($translatable_field_setting);
763 $this->assertText('Translatable storage setting');
764 $this->assertEscaped($translatable_storage_setting);
768 * Tests the translation of a boolean field settings.
770 public function testBooleanFieldConfigTranslation() {
771 // Add a test boolean field.
772 $field_name = strtolower($this->randomMachineName());
773 FieldStorageConfig::create([
774 'field_name' => $field_name,
775 'entity_type' => 'entity_test',
779 $bundle = strtolower($this->randomMachineName());
780 entity_test_create_bundle($bundle);
781 $field = FieldConfig::create([
782 'field_name' => $field_name,
783 'entity_type' => 'entity_test',
787 $on_label = 'On label (with <em>HTML</em> & things)';
788 $field->setSetting('on_label', $on_label);
789 $off_label = 'Off label (with <em>HTML</em> & things)';
790 $field->setSetting('off_label', $off_label);
793 $this->drupalLogin($this->translatorUser);
795 $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
796 $this->clickLink('Add');
798 // Checks the text of details summary element that surrounds the translation
800 $this->assertText(Html::escape(strip_tags($on_label)) . ' Boolean settings');
802 // Checks that the correct on and off labels appear on the form.
803 $this->assertEscaped($on_label);
804 $this->assertEscaped($off_label);
808 * Test translation storage in locale storage.
810 public function testLocaleDBStorage() {
811 // Enable import of translations. By default this is disabled for automated
813 $this->config('locale.settings')
814 ->set('translation.import_enabled', TRUE)
817 $this->drupalLogin($this->adminUser);
820 $name = $this->randomMachineName(16);
822 'predefined_langcode' => 'custom',
823 'langcode' => $langcode,
825 'direction' => Language::DIRECTION_LTR,
827 $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
829 // Make sure there is no translation stored in locale storage before edit.
830 $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
831 $this->assertTrue(empty($translation));
833 // Add custom translation.
835 'translation[config_names][user.settings][anonymous]' => 'Anonyme',
837 $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation'));
839 // Make sure translation stored in locale storage after saved language
840 // specific configuration translation.
841 $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
842 $this->assertEqual('Anonyme', $translation->getString());
844 // revert custom translations to base translation.
846 'translation[config_names][user.settings][anonymous]' => 'Anonymous',
848 $this->drupalPostForm('admin/config/people/accounts/translate/fr/edit', $edit, t('Save translation'));
850 // Make sure there is no translation stored in locale storage after revert.
851 $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
852 $this->assertEqual('Anonymous', $translation->getString());
856 * Tests the single language existing.
858 public function testSingleLanguageUI() {
859 $this->drupalLogin($this->adminUser);
861 // Delete French language
862 $this->drupalPostForm('admin/config/regional/language/delete/fr', [], t('Delete'));
863 $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'French', '%langcode' => 'fr']));
865 // Change default language to Tamil.
867 'site_default_language' => 'ta',
869 $this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));
870 $this->assertRaw(t('Configuration saved.'));
872 // Delete English language
873 $this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
874 $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'English', '%langcode' => 'en']));
876 // Visit account setting translation page, this should not
877 // throw any notices.
878 $this->drupalGet('admin/config/people/accounts/translate');
879 $this->assertResponse(200);
883 * Tests the config_translation_info_alter() hook.
885 public function testAlterInfo() {
886 $this->drupalLogin($this->adminUser);
888 $this->container->get('state')->set('config_translation_test_config_translation_info_alter', TRUE);
889 $this->container->get('plugin.manager.config_translation.mapper')->clearCachedDefinitions();
891 // Check out if the translation page has the altered in settings.
892 $this->drupalGet('admin/config/system/site-information/translate/fr/add');
893 $this->assertText(t('Feed channel'));
894 $this->assertText(t('Feed description'));
896 // Check if the translation page does not have the altered out settings.
897 $this->drupalGet('admin/config/people/accounts/translate/fr/add');
898 $this->assertText(t('Name'));
899 $this->assertNoText(t('Account cancellation confirmation'));
900 $this->assertNoText(t('Password recovery'));
904 * Tests the sequence data type translation.
906 public function testSequenceTranslation() {
907 $this->drupalLogin($this->adminUser);
908 /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
909 $config_factory = $this->container->get('config.factory');
916 $actual = $config_factory
917 ->getEditable('config_translation_test.content')
919 $this->assertEqual($expected, $actual);
922 'translation[config_names][config_translation_test.content][content][value]' => '<p><strong>Hello World</strong> - FR</p>',
923 'translation[config_names][config_translation_test.content][animals][0]' => 'kitten - FR',
924 'translation[config_names][config_translation_test.content][animals][1]' => 'llama - FR',
925 'translation[config_names][config_translation_test.content][animals][2]' => 'elephant - FR',
927 $this->drupalPostForm('admin/config/media/file-system/translate/fr/add', $edit, t('Save translation'));
929 $this->container->get('language.config_factory_override')
930 ->setLanguage(new Language(['id' => 'fr']));
937 $actual = $config_factory
938 ->get('config_translation_test.content')
940 $this->assertEqual($expected, $actual);
944 * Test text_format translation.
946 public function testTextFormatTranslation() {
947 $this->drupalLogin($this->adminUser);
948 /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
949 $config_factory = $this->container->get('config.factory');
952 'value' => '<p><strong>Hello World</strong></p>',
953 'format' => 'plain_text',
955 $actual = $config_factory
956 ->get('config_translation_test.content')
957 ->getOriginal('content', FALSE);
958 $this->assertEqual($expected, $actual);
960 $translation_base_url = 'admin/config/media/file-system/translate';
961 $this->drupalGet($translation_base_url);
963 // 'Add' link should be present for French translation.
964 $translation_page_url = "$translation_base_url/fr/add";
965 $this->assertLinkByHref($translation_page_url);
967 $this->drupalGet($translation_page_url);
969 // Assert that changing the text format is not possible, even for an
971 $this->assertNoFieldByName('translation[config_names][config_translation_test.content][content][format]');
973 // Update translatable fields.
975 'translation[config_names][config_translation_test.content][content][value]' => '<p><strong>Hello World</strong> - FR</p>',
978 // Save language specific version of form.
979 $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
981 // Get translation and check we've got the right value.
983 'value' => '<p><strong>Hello World</strong> - FR</p>',
984 'format' => 'plain_text',
986 $this->container->get('language.config_factory_override')
987 ->setLanguage(new Language(['id' => 'fr']));
988 $actual = $config_factory
989 ->get('config_translation_test.content')
991 $this->assertEqual($expected, $actual);
993 // Change the text format of the source configuration and verify that the
994 // text format of the translation does not change because that could lead to
995 // security vulnerabilities.
997 ->getEditable('config_translation_test.content')
998 ->set('content.format', 'full_html')
1001 $actual = $config_factory
1002 ->get('config_translation_test.content')
1004 // The translation should not have changed, so re-use $expected.
1005 $this->assertEqual($expected, $actual);
1007 // Because the text is now in a text format that the translator does not
1008 // have access to, the translator should not be able to translate it.
1009 $translation_page_url = "$translation_base_url/fr/edit";
1010 $this->drupalLogin($this->translatorUser);
1011 $this->drupalGet($translation_page_url);
1012 $this->assertDisabledTextarea('edit-translation-config-names-config-translation-testcontent-content-value');
1013 $this->drupalPostForm(NULL, [], t('Save translation'));
1014 // Check that submitting the form did not update the text format of the
1016 $actual = $config_factory
1017 ->get('config_translation_test.content')
1019 $this->assertEqual($expected, $actual);
1021 // The administrator must explicitly change the text format.
1022 $this->drupalLogin($this->adminUser);
1024 'translation[config_names][config_translation_test.content][content][format]' => 'full_html',
1026 $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
1028 'value' => '<p><strong>Hello World</strong> - FR</p>',
1029 'format' => 'full_html',
1031 $actual = $config_factory
1032 ->get('config_translation_test.content')
1034 $this->assertEqual($expected, $actual);
1038 * Tests field translation for node fields.
1040 public function testNodeFieldTranslation() {
1041 NodeType::create(['type' => 'article', 'name' => 'Article'])->save();
1043 $field_name = 'translatable_field';
1044 $field_storage = FieldStorageConfig::create([
1045 'field_name' => $field_name,
1046 'entity_type' => 'node',
1050 $field_storage->setSetting('translatable_storage_setting', 'translatable_storage_setting');
1051 $field_storage->save();
1052 $field = FieldConfig::create([
1053 'field_name' => $field_name,
1054 'entity_type' => 'node',
1055 'bundle' => 'article',
1059 $this->drupalLogin($this->translatorUser);
1061 $this->drupalGet("/entity_test/structure/article/fields/node.article.$field_name/translate");
1062 $this->clickLink('Add');
1065 'translation[config_names][field.field.node.article.translatable_field][description]' => 'FR Help text.',
1066 'translation[config_names][field.field.node.article.translatable_field][label]' => 'FR label',
1068 $this->drupalPostForm(NULL, $form_values, 'Save translation');
1069 $this->assertText('Successfully saved French translation.');
1071 // Check that the translations are saved.
1072 $this->clickLink('Add');
1073 $this->assertRaw('FR label');
1077 * Gets translation from locale storage.
1079 * @param $config_name
1080 * Configuration object.
1082 * Translation configuration field key.
1084 * String language code to load translation.
1086 * @return bool|mixed
1087 * Returns translation if exists, FALSE otherwise.
1089 protected function getTranslation($config_name, $key, $langcode) {
1090 $settings_locations = $this->localeStorage->getLocations(['type' => 'configuration', 'name' => $config_name]);
1091 $this->assertTrue(!empty($settings_locations), format_string('Configuration locations found for %config_name.', ['%config_name' => $config_name]));
1093 if (!empty($settings_locations)) {
1094 $source = $this->container->get('config.factory')->get($config_name)->get($key);
1095 $source_string = $this->localeStorage->findString(['source' => $source, 'type' => 'configuration']);
1096 $this->assertTrue(!empty($source_string), format_string('Found string for %config_name.%key.', ['%config_name' => $config_name, '%key' => $key]));
1098 if (!empty($source_string)) {
1100 'lid' => $source_string->lid,
1101 'language' => $langcode,
1103 $translations = $this->localeStorage->getTranslations($conditions + ['translated' => TRUE]);
1104 return reset($translations);
1111 * Sets site name and slogan for default language, helps in tests.
1113 * @param string $site_name
1114 * @param string $site_slogan
1116 protected function setSiteInformation($site_name, $site_slogan) {
1118 'site_name' => $site_name,
1119 'site_slogan' => $site_slogan,
1121 $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
1122 $this->assertRaw(t('The configuration options have been saved.'));
1126 * Get server-rendered contextual links for the given contextual link ids.
1129 * An array of contextual link ids.
1130 * @param string $current_path
1131 * The Drupal path for the page for which the contextual links are rendered.
1134 * The response body.
1136 protected function renderContextualLinks($ids, $current_path) {
1138 for ($i = 0; $i < count($ids); $i++) {
1139 $post['ids[' . $i . ']'] = $ids[$i];
1141 return $this->drupalPostWithFormat('contextual/render', 'json', $post, ['query' => ['destination' => $current_path]]);
1145 * Asserts that a textarea with a given ID has been disabled from editing.
1148 * The HTML ID of the textarea.
1151 * TRUE if the assertion passed; FALSE otherwise.
1153 protected function assertDisabledTextarea($id) {
1154 $textarea = $this->xpath('//textarea[@id=:id and contains(@disabled, "disabled")]', [
1157 $textarea = reset($textarea);
1158 $passed = $this->assertTrue($textarea instanceof \SimpleXMLElement, SafeMarkup::format('Disabled field @id exists.', [
1161 $expected = 'This field has been disabled because you do not have sufficient permissions to edit it.';
1162 $passed = $passed && $this->assertEqual((string) $textarea, $expected, SafeMarkup::format('Disabled textarea @id hides text in an inaccessible text format.', [
1165 // Make sure the text format select is not shown.
1166 $select_id = str_replace('value', 'format--2', $id);
1167 $select = $this->xpath('//select[@id=:id]', [':id' => $select_id]);
1168 return $passed && $this->assertFalse($select, SafeMarkup::format('Field @id does not exist.', [
1174 * Helper function that returns a .po file with a given number of plural forms.
1176 public function getPoFile($plurals) {
1179 $po_file[1] = <<< EOF
1182 "Project-Id-Version: Drupal 8\\n"
1183 "MIME-Version: 1.0\\n"
1184 "Content-Type: text/plain; charset=UTF-8\\n"
1185 "Content-Transfer-Encoding: 8bit\\n"
1186 "Plural-Forms: nplurals=1; plural=0;\\n"
1189 $po_file[2] = <<< EOF
1192 "Project-Id-Version: Drupal 8\\n"
1193 "MIME-Version: 1.0\\n"
1194 "Content-Type: text/plain; charset=UTF-8\\n"
1195 "Content-Transfer-Encoding: 8bit\\n"
1196 "Plural-Forms: nplurals=2; plural=(n>1);\\n"
1199 $po_file[4] = <<< EOF
1202 "Project-Id-Version: Drupal 8\\n"
1203 "MIME-Version: 1.0\\n"
1204 "Content-Type: text/plain; charset=UTF-8\\n"
1205 "Content-Transfer-Encoding: 8bit\\n"
1206 "Plural-Forms: nplurals=4; plural=(((n%100)==1)?(0):(((n%100)==2)?(1):((((n%100)==3)||((n%100)==4))?(2):3)));\\n"
1209 return $po_file[$plurals];