You are here

function FileTranslatorTest::testXLIFF in Translation Management Tool 8

Tests import and export for the XLIFF format.

File

translators/tmgmt_file/tests/src/Functional/FileTranslatorTest.php, line 287

Class

FileTranslatorTest
Tests for the file translator.

Namespace

Drupal\Tests\tmgmt_file\Functional

Code

function testXLIFF() {
  $translator = Translator::load('file');
  $translator
    ->setSetting('export_format', 'xlf')
    ->setSetting('format_configuration', [
    'target' => 'source',
  ])
    ->save();

  // Set multiple data items for the source.
  \Drupal::state()
    ->set('tmgmt.test_source_data', array(
    'dummy' => array(
      'deep_nesting' => array(
        '#text' => file_get_contents(drupal_get_path('module', 'tmgmt') . '/tests/testing_html/sample.html') . ' @id.',
        '#label' => 'Label of deep nested item @id',
      ),
      '#label' => 'Dummy item',
    ),
    'another_item' => array(
      '#text' => 'Text of another item @id.',
      '#label' => 'Label of another item @id.',
      '#max_length' => '100',
    ),
  ));
  $job = $this
    ->createJob();
  $job->translator = $translator
    ->id();
  $first_item = $job
    ->addItem('test_source', 'test', '1');

  // Keep the first item data for later use.
  $first_item_data = \Drupal::service('tmgmt.data')
    ->flatten($first_item
    ->getData());
  $job
    ->addItem('test_source', 'test', '2');
  $job
    ->requestTranslation();
  $messages = $job
    ->getMessages();
  $message = reset($messages);
  $variables = $message->variables;
  $download_url = $variables->{'@link'};
  $this
    ->assertFalse((bool) strpos('< a', $download_url));
  $xliff = file_get_contents($download_url);
  $dom = new \DOMDocument();
  $dom
    ->loadXML($xliff);
  $this
    ->assertTrue($dom
    ->schemaValidate(drupal_get_path('module', 'tmgmt_file') . '/xliff-core-1.2-strict.xsd'));

  // Build a list of expected note labels.
  $expected_notes = [
    '1][dummy][deep_nesting' => 'Dummy item > Label of deep nested item @id',
    '1][another_item' => 'Label of another item @id.',
    '2][dummy][deep_nesting' => 'Dummy item > Label of deep nested item @id',
    '2][another_item' => 'Label of another item @id.',
  ];

  // "Translate" items.
  $xml = simplexml_import_dom($dom);
  $translated_text = array();
  foreach ($xml->file->body
    ->children() as $group) {
    foreach ($group
      ->children() as $transunit) {
      if ($transunit
        ->getName() == 'trans-unit') {

        // The target should contain the source data.
        $this
          ->assertEqual($transunit->target, $transunit->source);

        // Assert that notes contain parent and non-parent labels.
        $this
          ->assertEqual($expected_notes[(string) $transunit['id']], (string) $transunit->note);
        $transunit->target = $xml->file['target-language'] . '_' . (string) $transunit->source;

        // Store the text to allow assertions later on.
        $translated_text[(string) $group['id']][(string) $transunit['id']] = (string) $transunit->target;

        // Check that the character limit is in the target.
        $attributes = $transunit
          ->attributes();
        if ($transunit
          ->attributes()['id'] == '1][another_item') {
          $this
            ->assertEquals('100', $attributes['maxwidth']);
          $this
            ->assertEquals('char', $attributes['size-unit']);
        }
        if ($transunit
          ->attributes()['id'] == '1][dummy][deep_nesting') {
          $this
            ->assertFalse(isset($attributes['maxwidth']));
          $this
            ->assertFalse(isset($attributes['size-unit']));
        }
      }
    }
  }

  // Change the job id to a non-existing one and try to import it.
  $wrong_xml = clone $xml;
  $wrong_xml->file->header->{'phase-group'}->phase['job-id'] = 500;
  $wrong_file = 'public://tmgmt_file/wrong_file.xlf';
  $wrong_xml
    ->asXML($wrong_file);
  $edit = array(
    'files[file]' => $wrong_file,
  );
  $this
    ->drupalPostForm($job
    ->toUrl(), $edit, t('Import'));
  $this
    ->assertText(t('Failed to validate file, import aborted.'));

  // Change the job id to a wrong one and try to import it.
  $wrong_xml = clone $xml;
  $second_job = $this
    ->createJob();
  $second_job->translator = $translator
    ->id();

  // We need to add the elements count value into settings, otherwise the
  // validation will fail on integrity check.
  $xliff_validation = array(
    1 => 0,
    2 => 0,
  );
  $second_job->settings->xliff_validation = $xliff_validation;
  $second_job
    ->save();
  $wrong_xml->file->header->{'phase-group'}->phase['job-id'] = $second_job
    ->id();
  $wrong_file = 'public://tmgmt_file/wrong_file.xlf';
  $wrong_xml
    ->asXML($wrong_file);
  $edit = array(
    'files[file]' => $wrong_file,
  );
  $this
    ->drupalPostForm($job
    ->toUrl(), $edit, t('Import'));
  $this
    ->assertRaw(t('The imported file job id @file_id does not match the job id @job_id.', array(
    '@file_id' => $second_job
      ->id(),
    '@job_id' => $job
      ->id(),
  )));
  $translated_file = 'public://tmgmt_file/translated file.xlf';
  $xml
    ->asXML($translated_file);

  // Import the file and accept translation for the "dummy" item.
  $edit = array(
    'files[file]' => $translated_file,
  );
  $this
    ->drupalPostForm($job
    ->toUrl(), $edit, t('Import'));
  $this
    ->assertText(t('The translation of @job_item to German is finished and can now be reviewed.', [
    '@job_item' => $first_item
      ->label(),
  ]));
  $this
    ->clickLink(t('Review'));
  $this
    ->getSession()
    ->getPage()
    ->pressButton('reviewed-dummy|deep_nesting');

  // Update the translation for "another" item and import.
  $xml->file->body->group[0]->{'trans-unit'}[1]->target = $xml->file->body->group[0]->{'trans-unit'}[1]->target . ' updated';
  $xml
    ->asXML($translated_file);
  $edit = array(
    'files[file]' => $translated_file,
  );
  $this
    ->drupalPostForm($job
    ->toUrl(), $edit, t('Import'));

  // At this point we must have the "dummy" item accepted and intact. The
  // "another" item must have updated translation.
  $this
    ->assertText('Review');
  $this
    ->drupalGet($first_item
    ->toUrl());
  $this
    ->assertFieldByName('dummy|deep_nesting[translation]', 'de_' . $first_item_data['dummy][deep_nesting']['#text']);
  $this
    ->assertFieldByName('another_item[translation]', 'de_' . $first_item_data['another_item']['#text'] . ' updated');

  // Now finish the import/save as completed process doing another extra
  // import. The extra import will test that a duplicate import of the same
  // file does not break the process.
  $this
    ->importFile($translated_file, $translated_text, $job);
  $this
    ->assertNoText(t('Import translated file'));

  // Create a job, assign to the file translator and delete before attaching
  // a file.
  $other_job = $this
    ->createJob();
  $other_job->translator = $translator
    ->id();
  $other_job
    ->save();
  $other_job
    ->delete();

  // Make sure the file of the other job still exists.
  $response = \Drupal::httpClient()
    ->get($download_url);
  $this
    ->assertEqual(200, $response
    ->getStatusCode());

  // Delete the job and then make sure that the file has been deleted.
  $job
    ->delete();
  try {
    $response = \Drupal::httpClient()
      ->get($download_url);
    $this
      ->fail('Expected exception not thrown.');
  } catch (RequestException $e) {
    $this
      ->assertEqual(404, $e
      ->getResponse()
      ->getStatusCode());
  }
}