You are here

class FileTranslatorTest in Translation Management Tool 8

Tests for the file translator.

@group tmgmt

Hierarchy

Expanded class hierarchy of FileTranslatorTest

File

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

Namespace

Drupal\Tests\tmgmt_file\Functional
View source
class FileTranslatorTest extends TMGMTTestBase {

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

  /**
   * {@inheritdoc}
   */
  function setUp() : void {
    parent::setUp();
    $this
      ->loginAsAdmin();
    $this
      ->addLanguage('de');
  }

  /**
   * Test the content processing for XLIFF export and import.
   */
  public function testXLIFFTextProcessing() {
    $translator = $this
      ->createTranslator([
      'plugin' => 'file',
      'settings' => [
        'export_format' => 'xlf',
        'xliff_processing' => TRUE,
        'format_configuration' => [
          'target' => '',
        ],
      ],
    ]);

    // Get the source text.
    $source_text = trim(file_get_contents(drupal_get_path('module', 'tmgmt') . '/tests/testing_html/sample.html'));

    // Create the reader instance, it will be used through the tests.
    $reader = new \XMLReader();
    $xliff_elements = array(
      'bpt',
      'ept',
      'ph',
      'x',
      '#text',
      '#cdata-section',
      'content',
    );

    // ==== First test the whole cycle ==== //
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_html_source', 'test', '1');

    // Simulate an existing public://tmmgt_file directory that is not writable.
    mkdir('public://tmgmt_file', 0555);

    // Requesting translation will mask the html.
    $job
      ->requestTranslation();
    $content = $this
      ->getTransUnitsContent($job);

    // Test that the exported trans unit contains only xliff elements.
    $reader
      ->XML('<content>' . $content[0]['source'] . '</content>');
    while ($reader
      ->read()) {
      if (!in_array($reader->name, $xliff_elements)) {
        $this
          ->fail(t('The source contains unexpected element %element', array(
          '%element' => $reader->name,
        )));
      }
    }
    $reader
      ->XML('<content>' . $content[0]['target'] . '</content>');
    while ($reader
      ->read()) {
      if (!in_array($reader->name, $xliff_elements)) {
        $this
          ->fail(t('The target contains unexpected element %element', array(
          '%element' => $reader->name,
        )));
      }
    }

    // Import the file, make sure all the html has been revealed and no xliff
    // elements are present in the job translation.
    $messages = $job
      ->getMessages();
    $message = reset($messages);
    $translated_file = 'public://tmgmt_file/translated.xlf';
    $this
      ->createTranslationFile($message->variables->{'@link'}, 'one paragraph', 'one translated paragraph', $translated_file);
    $edit = array(
      'files[file]' => $translated_file,
    );
    $this
      ->drupalPostForm($job
      ->toUrl(), $edit, t('Import'));

    // Reset caches and reload job.
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job')
      ->resetCache();
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job_item')
      ->resetCache();
    $job = Job::load($job
      ->id());

    // Do the comparison of the translation text and the source. It must be the
    // same as there was no change done to the translation.
    $item_data = $job
      ->getData(array(
      1,
      'dummy',
      'deep_nesting',
    ));
    $this
      ->assertEqual(trim($item_data[1]['#translation']['#text']), str_replace('one paragraph', 'one translated paragraph', $source_text));
    $job_items = $job
      ->getItems();
    $job_item = array_shift($job_items);

    // Job item must be in review.
    $this
      ->assertTrue($job_item
      ->isNeedsReview());
    $this
      ->assertIntegrityCheck($job, FALSE);

    // ==== Test integrity check ==== //
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_html_source', 'test', '1');
    $job
      ->requestTranslation();
    $messages = $job
      ->getMessages();
    $message = reset($messages);

    // Get the xml content and remove the element representing <br />. This will
    // result in different element counts in the source and target and should
    // trigger an error and not import the translation.
    $translated_file = 'public://tmgmt_file/translated.xlf';
    $this
      ->createTranslationFile($message->variables->{'@link'}, '<x id="tjiid2-4" ctype="lb"/>', '', $translated_file);
    $edit = array(
      'files[file]' => $translated_file,
    );
    $this
      ->drupalPostForm($job
      ->toUrl(), $edit, t('Import'));
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job')
      ->resetCache();
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job_item')
      ->resetCache();
    $job = Job::load($job
      ->id());
    $this
      ->assertIntegrityCheck($job);

    // Set the XLIFF processing to FALSE and test it results in the source
    // text not being XLIFF processed.
    $translator
      ->setSetting('xliff_processing', FALSE);
    $translator
      ->save();
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_html_source', 'test', '1');
    $job
      ->requestTranslation();
    $targets = $this
      ->getTransUnitsContent($job);
    $this
      ->assertEqual(trim(html_entity_decode($targets['0']['source'])), $source_text);
  }

  /**
   * Test the CDATA option for XLIFF export and import.
   */
  function testXLIFFCDATA() {
    $translator = $this
      ->createTranslator([
      'plugin' => 'file',
      'settings' => [
        'export_format' => 'xlf',
        'xliff_cdata' => TRUE,
      ],
    ]);

    // Get the source text.
    $source_text = trim(file_get_contents(drupal_get_path('module', 'tmgmt') . '/tests/testing_html/sample.html'));

    // Create a new job.
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_html_source', 'test', '1');
    $job
      ->requestTranslation();
    $messages = $job
      ->getMessages();
    $message = reset($messages);

    // Get XLIFF content.
    $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'));

    // "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 be empty.
          $this
            ->assertEqual($transunit->target, '');

          // Update translations using CDATA.
          $node = dom_import_simplexml($transunit->target);
          $owner = $node->ownerDocument;
          $node
            ->appendChild($owner
            ->createCDATASection($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;
        }
      }
    }
    $translated_file = 'public://tmgmt_file/translated file.xlf';
    $xml
      ->asXML($translated_file);

    // Import the file and check translation for the "dummy" item.
    $edit = array(
      'files[file]' => $translated_file,
    );
    $this
      ->drupalPostForm($job
      ->toUrl(), $edit, t('Import'));

    // Reset caches and reload job.
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job')
      ->resetCache();
    \Drupal::entityTypeManager()
      ->getStorage('tmgmt_job_item')
      ->resetCache();
    $job = Job::load($job
      ->id());
    $item_data = $job
      ->getData(array(
      1,
      'dummy',
      'deep_nesting',
    ));
    $this
      ->assertEqual(trim($item_data[1]['#translation']['#text']), str_replace($source_text, $xml->file['target-language'] . '_' . $source_text, $source_text));
  }

  /**
   * Gets trans-unit content from the XLIFF file that has been exported for the
   * given job as last.
   */
  protected function getTransUnitsContent(JobInterface $job) {
    $messages = $job
      ->getMessages();
    $message = reset($messages);
    $download_url = $message->variables->{'@link'};
    $this
      ->assertFalse((bool) strpos('< a', $download_url));
    $xml_string = file_get_contents($download_url);
    $xml = simplexml_load_string($xml_string);

    // Register the xliff namespace, required for xpath.
    $xml
      ->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
    $reader = new \XMLReader();
    $data = array();
    $i = 0;
    foreach ($xml
      ->xpath('//xliff:trans-unit') as $unit) {
      $reader
        ->XML($unit->source
        ->asXML());
      $reader
        ->read();
      $data[$i]['source'] = $reader
        ->readInnerXML();
      $reader
        ->XML($unit->target
        ->asXML());
      $reader
        ->read();
      $data[$i]['target'] = $reader
        ->readInnerXML();
      $i++;
    }
    return $data;
  }

  /**
   * Tests export and import for the HTML format.
   */
  function testHTML() {
    $translator = Translator::load('file');
    $translator
      ->setSetting('export_format', 'html')
      ->save();
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_source', 'test', '1');
    $job
      ->addItem('test_source', 'test', '2');
    $job
      ->requestTranslation();
    $messages = $job
      ->getMessages();
    $message = reset($messages);
    $download_url = $message->variables->{'@link'};
    $this
      ->assertFalse((bool) strpos('< a', $download_url));

    // "Translate" items.
    $xml = simplexml_load_file($download_url);
    $translated_text = array();
    foreach ($xml->body
      ->children() as $group) {
      for ($i = 0; $i < $group
        ->count(); $i++) {

        // This does not actually override the whole object, just the content.
        $group->div[$i] = (string) $xml->head->meta[3]['content'] . '_' . (string) $group->div[$i];

        // Store the text to allow assertions later on.
        $translated_text[(string) $group['id']][(string) $group->div[$i]['id']] = (string) $group->div[$i];
      }
    }
    $translated_file = 'public://tmgmt_file/translated.html';
    $xml
      ->asXML($translated_file);
    $this
      ->importFile($translated_file, $translated_text, $job);
  }

  /**
   * Tests import and export for the XLIFF format.
   */
  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());
    }
  }

  /**
   * Tests storing files in the private file system.
   */
  function testPrivate() {

    // Create a translator using the private file system.
    // @todo: Test the configuration UI.
    $translator = $this
      ->createTranslator([
      'plugin' => 'file',
      'settings' => [
        'export_format' => 'xlf',
        'xliff_processing' => TRUE,
        'scheme' => 'private',
      ],
    ]);
    $job = $this
      ->createJob();
    $job->translator = $translator
      ->id();
    $job
      ->addItem('test_source', 'test', '1');
    $job
      ->addItem('test_source', 'test', '2');
    $job
      ->requestTranslation();
    $messages = $job
      ->getMessages();
    $message = reset($messages);
    $this
      ->drupalGet('admin/tmgmt/jobs');
    $this
      ->clickLink(t('Manage'));

    // Assert that the label field is only shown once in page.
    $this
      ->assertEqual(count($this
      ->xpath('//div[@id="tmgmt-ui-label"]')), 1);
    $download_url = $message->variables->{'@link'};
    $this
      ->assertFalse((bool) strpos('< a', $download_url));
    $this
      ->drupalGet($download_url);

    // Verify that the URL is served using the private file system and the
    // access checks work.
    $this
      ->assertNotEmpty(preg_match('|system/files|', $download_url));
    $this
      ->assertResponse(200);
    $this
      ->drupalLogout();

    // Verify that access is now protected.
    $this
      ->drupalGet($download_url);
    $this
      ->assertResponse(403);
  }
  protected function importFile($translated_file, $translated_text, JobInterface $job) {

    // To test the upload form functionality, navigate to the edit form.
    $edit = array(
      'files[file]' => $translated_file,
    );
    $this
      ->drupalPostForm($job
      ->toUrl(), $edit, t('Import'));

    // Make sure the translations have been imported correctly.
    $this
      ->assertNoRaw('title="In progress"');

    // @todo: Enable this assertion once new releases for views and entity
    // module are out.

    //$this->assertText(t('Needs review'));

    // Review both items.
    list($item1, $item2) = array_values($job
      ->getItems());
    $this
      ->drupalGet($item1
      ->toUrl());
    foreach ($translated_text[1] as $key => $value) {
      $this
        ->assertText(Html::escape($value));
    }
    foreach ($translated_text[2] as $key => $value) {
      $this
        ->assertNoText(Html::escape($value));
    }
    $this
      ->drupalPostForm(NULL, array(), t('Save as completed'));

    // Review both items.
    $this
      ->drupalGet($item2
      ->toUrl());
    foreach ($translated_text[1] as $key => $value) {
      $this
        ->assertNoText(Html::escape($value));
    }
    foreach ($translated_text[2] as $key => $value) {
      $this
        ->assertText(Html::escape($value));
    }
    $this
      ->drupalPostForm(NULL, array(), t('Save as completed'));

    // @todo: Enable this assertion once new releases for views and entity
    // module are out.

    //$this->assertText(t('Accepted'));
    $this
      ->assertText(t('Finished'));
    $this
      ->assertNoRaw('title="Needs review"');
  }

  /**
   * Creates a translated XLIFF file based on the replacement definition.
   *
   * @param string $source_file
   *   Source file name.
   * @param $search
   *   String to search in the source.
   * @param $replace
   *   String to replace it with in the target.
   * @param $translated_file
   *   Name of the file to write.
   */
  protected function createTranslationFile($source_file, $search, $replace, $translated_file) {
    $xml_string = file_get_contents($source_file);
    preg_match('/<source xml:lang="en">(.+)<\\/source>/s', $xml_string, $matches);
    $target = str_replace($search, $replace, $matches[1]);
    if ($replace) {
      $this
        ->assertTrue(strpos($target, $replace) !== FALSE, 'String replaced in translation');
    }
    $translated_xml_string = str_replace('<target xml:lang="de"/>', '<target xml:lang="de">' . $target . '</target>', $xml_string);
    file_put_contents($translated_file, $translated_xml_string);
  }

  /**
   * Asserts import integrity for a job.
   *
   * @param \Drupal\tmgmt\JobInterface $job
   *   The job to check.
   * @param bool $expected
   *   (optional) If an integrity failed message is expected or not, defaults
   *   to FALSE.
   */
  protected function assertIntegrityCheck(JobInterface $job, $expected = TRUE) {
    $integrity_check_failed = FALSE;

    /** @var \Drupal\tmgmt\MessageInterface $message */
    foreach ($job
      ->getMessages() as $message) {
      if ($message
        ->getMessage() == new TranslatableMarkup('Failed to validate semantic integrity of %key element. Please check also the HTML code of the element in the review process.', array(
        '%key' => 'dummy][deep_nesting',
      ))) {
        $integrity_check_failed = TRUE;
        break;
      }
    }

    // Check if the message was found or not, based on the expected argument.
    if ($expected) {
      $this
        ->assertTrue($integrity_check_failed, 'The validation of semantic integrity must fail.');
    }
    else {
      $this
        ->assertFalse($integrity_check_failed, 'The validation of semantic integrity must not fail.');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertHelperTrait::castSafeStrings protected static function Casts MarkupInterface objects into strings.
AssertLegacyTrait::assert protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::assertCacheTag protected function Asserts whether an expected cache tag was present in the last response.
AssertLegacyTrait::assertElementNotPresent protected function Asserts that the element with the given CSS selector is not present.
AssertLegacyTrait::assertElementPresent protected function Asserts that the element with the given CSS selector is present.
AssertLegacyTrait::assertEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertLegacyTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertLegacyTrait::assertFieldById protected function Asserts that a field exists with the given ID and value.
AssertLegacyTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertLegacyTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertLegacyTrait::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
AssertLegacyTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertLegacyTrait::assertHeader protected function Checks that current response header equals value.
AssertLegacyTrait::assertIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertSame() instead.
AssertLegacyTrait::assertIdenticalObject protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertLink protected function Passes if a link with the specified label is found.
AssertLegacyTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertLegacyTrait::assertNoCacheTag protected function Asserts whether an expected cache tag was absent in the last response.
AssertLegacyTrait::assertNoEscaped protected function Passes if the raw text is not found escaped on the loaded page.
AssertLegacyTrait::assertNoField protected function Asserts that a field does NOT exist with the given name or ID.
AssertLegacyTrait::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
AssertLegacyTrait::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
AssertLegacyTrait::assertNoFieldByXPath protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertLegacyTrait::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
AssertLegacyTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertLegacyTrait::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
AssertLegacyTrait::assertNoOption protected function Asserts that a select option does NOT exist in the current page.
AssertLegacyTrait::assertNoPattern protected function Triggers a pass if the Perl regex pattern is not found in the raw content.
AssertLegacyTrait::assertNoRaw protected function Passes if the raw text IS not found on the loaded page, fail otherwise. 1
AssertLegacyTrait::assertNotEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotEquals() instead.
AssertLegacyTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text. 1
AssertLegacyTrait::assertNotIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotSame() instead.
AssertLegacyTrait::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertLegacyTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertLegacyTrait::assertOptionByText protected function Asserts that a select option with the visible text exists.
AssertLegacyTrait::assertOptionSelected protected function Asserts that a select option in the current page is checked.
AssertLegacyTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertLegacyTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise. 1
AssertLegacyTrait::assertResponse protected function Asserts the page responds with the specified response code. 1
AssertLegacyTrait::assertText protected function Passes if the page (with HTML stripped) contains the text. 1
AssertLegacyTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertLegacyTrait::assertTitle protected function Pass if the page title is the given string.
AssertLegacyTrait::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertLegacyTrait::assertUrl protected function Passes if the internal browser's URL matches the given path.
AssertLegacyTrait::buildXPathQuery protected function Builds an XPath query.
AssertLegacyTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertLegacyTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertLegacyTrait::getRawContent protected function Gets the current raw content.
AssertLegacyTrait::pass protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::verbose protected function
BlockCreationTrait::placeBlock protected function Creates a block instance based on default settings. Aliased as: drupalPlaceBlock
BrowserHtmlDebugTrait::$htmlOutputBaseUrl protected property The Base URI to use for links to the output files.
BrowserHtmlDebugTrait::$htmlOutputClassName protected property Class name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounter protected property Counter for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounterStorage protected property Counter storage for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputDirectory protected property Directory name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputEnabled protected property HTML output output enabled.
BrowserHtmlDebugTrait::$htmlOutputFile protected property The file name to write the list of URLs to.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getHtmlOutputHeaders protected function Returns headers in HTML output format. 1
BrowserHtmlDebugTrait::htmlOutput protected function Logs a HTML output message in a text file.
BrowserHtmlDebugTrait::initBrowserOutputFile protected function Creates the directory to store browser output.
BrowserTestBase::$baseUrl protected property The base URL.
BrowserTestBase::$configImporter protected property The config importer that can be used in a test.
BrowserTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
BrowserTestBase::$databasePrefix protected property The database prefix of this test run.
BrowserTestBase::$mink protected property Mink session manager.
BrowserTestBase::$minkDefaultDriverArgs protected property
BrowserTestBase::$minkDefaultDriverClass protected property 1
BrowserTestBase::$originalContainer protected property The original container.
BrowserTestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks.
BrowserTestBase::$preserveGlobalState protected property
BrowserTestBase::$profile protected property The profile to install as a basis for testing. 39
BrowserTestBase::$root protected property The app root.
BrowserTestBase::$runTestInSeparateProcess protected property Browser tests are run in separate processes to prevent collisions between code that may be loaded by tests.
BrowserTestBase::$timeLimit protected property Time limit in seconds for the test.
BrowserTestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
BrowserTestBase::cleanupEnvironment protected function Clean up the Simpletest environment.
BrowserTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
BrowserTestBase::cssSelectToXpath protected function Translates a CSS expression to its XPath equivalent.
BrowserTestBase::drupalGetHeader protected function Gets the value of an HTTP response header.
BrowserTestBase::drupalGetHeaders Deprecated protected function Returns all response headers.
BrowserTestBase::filePreDeleteCallback public static function Ensures test files are deletable.
BrowserTestBase::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
BrowserTestBase::getDrupalSettings protected function Gets the JavaScript drupalSettings variable for the currently-loaded page. 1
BrowserTestBase::getHttpClient protected function Obtain the HTTP client for the system under test.
BrowserTestBase::getMinkDriverArgs protected function Get the Mink driver args from an environment variable, if it is set. Can be overridden in a derived class so it is possible to use a different value for a subset of tests, e.g. the JavaScript tests. 1
BrowserTestBase::getOptions protected function Helper function to get the options of select field.
BrowserTestBase::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received. Overrides BrowserHtmlDebugTrait::getResponseLogHandler
BrowserTestBase::getSession public function Returns Mink session.
BrowserTestBase::getSessionCookies protected function Get session cookies from current session.
BrowserTestBase::getTestMethodCaller protected function Retrieves the current calling line in the class under test. Overrides BrowserHtmlDebugTrait::getTestMethodCaller
BrowserTestBase::initFrontPage protected function Visits the front page when initializing Mink. 3
BrowserTestBase::initMink protected function Initializes Mink sessions. 1
BrowserTestBase::installDrupal public function Installs Drupal into the Simpletest site. 1
BrowserTestBase::registerSessions protected function Registers additional Mink sessions.
BrowserTestBase::tearDown protected function 3
BrowserTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for drupalPostForm().
BrowserTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
BrowserTestBase::__construct public function 1
BrowserTestBase::__sleep public function Prevents serializing any properties.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
ContentTypeCreationTrait::createContentType protected function Creates a custom content type based on default settings. Aliased as: drupalCreateContentType 1
FileTranslatorTest::$modules public static property Modules to enable. Overrides TMGMTTestBase::$modules
FileTranslatorTest::assertIntegrityCheck protected function Asserts import integrity for a job.
FileTranslatorTest::createTranslationFile protected function Creates a translated XLIFF file based on the replacement definition.
FileTranslatorTest::getTransUnitsContent protected function Gets trans-unit content from the XLIFF file that has been exported for the given job as last.
FileTranslatorTest::importFile protected function
FileTranslatorTest::setUp function Overrides DrupalWebTestCase::setUp() Overrides TMGMTTestBase::setUp
FileTranslatorTest::testHTML function Tests export and import for the HTML format.
FileTranslatorTest::testPrivate function Tests storing files in the private file system.
FileTranslatorTest::testXLIFF function Tests import and export for the XLIFF format.
FileTranslatorTest::testXLIFFCDATA function Test the CDATA option for XLIFF export and import.
FileTranslatorTest::testXLIFFTextProcessing public function Test the content processing for XLIFF export and import.
FunctionalTestSetupTrait::$apcuEnsureUniquePrefix protected property The flag to set 'apcu_ensure_unique_prefix' setting. 1
FunctionalTestSetupTrait::$classLoader protected property The class loader to use for installation and initialization of setup.
FunctionalTestSetupTrait::$configDirectories Deprecated protected property The config directories used in this test.
FunctionalTestSetupTrait::$rootUser protected property The "#1" admin user.
FunctionalTestSetupTrait::doInstall protected function Execute the non-interactive installer. 1
FunctionalTestSetupTrait::getDatabaseTypes protected function Returns all supported database driver installer objects.
FunctionalTestSetupTrait::initConfig protected function Initialize various configurations post-installation. 2
FunctionalTestSetupTrait::initKernel protected function Initializes the kernel after installation.
FunctionalTestSetupTrait::initSettings protected function Initialize settings created during install.
FunctionalTestSetupTrait::initUserSession protected function Initializes user 1 for the site to be installed.
FunctionalTestSetupTrait::installDefaultThemeFromClassProperty protected function Installs the default theme defined by `static::$defaultTheme` when needed.
FunctionalTestSetupTrait::installModulesFromClassProperty protected function Install modules defined by `static::$modules`. 1
FunctionalTestSetupTrait::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal. 9
FunctionalTestSetupTrait::prepareEnvironment protected function Prepares the current environment for running the test. 23
FunctionalTestSetupTrait::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
FunctionalTestSetupTrait::prepareSettings protected function Prepares site settings and services before installation. 2
FunctionalTestSetupTrait::rebuildAll protected function Resets and rebuilds the environment after setup.
FunctionalTestSetupTrait::rebuildContainer protected function Rebuilds \Drupal::getContainer().
FunctionalTestSetupTrait::resetAll protected function Resets all data structures after having enabled new modules.
FunctionalTestSetupTrait::setContainerParameter protected function Changes parameters in the services.yml file.
FunctionalTestSetupTrait::setupBaseUrl protected function Sets up the base URL based upon the environment variable.
FunctionalTestSetupTrait::writeSettings protected function Rewrites the settings.php file of the test site.
NodeCreationTrait::createNode protected function Creates a node based on default settings. Aliased as: drupalCreateNode
NodeCreationTrait::getNodeByTitle public function Get a node from the database based on its title. Aliased as: drupalGetNodeByTitle
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
RefreshVariablesTrait::refreshVariables protected function Refreshes in-memory configuration and state information. 3
SessionTestTrait::$sessionName protected property The name of the session cookie.
SessionTestTrait::generateSessionName protected function Generates a session cookie name.
SessionTestTrait::getSessionName protected function Returns the session name in use on the child site.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::checkModuleRequirements private function Checks missing module requirements.
TestRequirementsTrait::checkRequirements protected function Check module requirements for the Drupal use case. 1
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.
TestSetupTrait::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
TestSetupTrait::$container protected property The dependency injection container used in the test.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateFilesDirectory protected property The private file directory for the test environment.
TestSetupTrait::$publicFilesDirectory protected property The public file directory for the test environment.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 2
TestSetupTrait::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestSetupTrait::$testId protected property The test run ID.
TestSetupTrait::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestSetupTrait::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestSetupTrait::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestSetupTrait::prepareDatabasePrefix protected function Generates a database prefix for running tests. 2
TMGMTTestBase::$defaultTheme protected property The theme to install as the default for testing. Overrides BrowserTestBase::$defaultTheme
TMGMTTestBase::$default_translator protected property A default translator using the test translator.
TmgmtTestTrait::$admin_permissions protected property List of permissions used by loginAsAdmin().
TmgmtTestTrait::$admin_user protected property Drupal user object created by loginAsAdmin().
TmgmtTestTrait::$languageWeight protected property The language weight for new languages.
TmgmtTestTrait::$translator_permissions protected property List of permissions used by loginAsTranslator().
TmgmtTestTrait::$translator_user protected property Drupal user object created by loginAsTranslator().
TmgmtTestTrait::addLanguage function Sets the proper environment.
TmgmtTestTrait::assertJobItemLangCodes function Asserts job item language codes.
TmgmtTestTrait::assertTextByXpath protected function Asserts text in the page with an xpath expression.
TmgmtTestTrait::clickLinkWithImageTitle function Clicks on an image link with the provided title attribute.
TmgmtTestTrait::createJob function Creates, saves and returns a translation job.
TmgmtTestTrait::createTranslator function Creates, saves and returns a translator.
TmgmtTestTrait::loginAsAdmin function Will create a user with admin permissions and log it in.
TmgmtTestTrait::loginAsTranslator function Will create a user with translator permissions and log it in.
UiHelperTrait::$loggedInUser protected property The current user logged in using the Mink controlled browser.
UiHelperTrait::$maximumMetaRefreshCount protected property The number of meta refresh redirects to follow, or NULL if unlimited.
UiHelperTrait::$metaRefreshCount protected property The number of meta refresh redirects followed during ::drupalGet().
UiHelperTrait::assertSession public function Returns WebAssert object. 1
UiHelperTrait::buildUrl protected function Builds an a absolute URL from a system path or a URL object.
UiHelperTrait::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
UiHelperTrait::click protected function Clicks the element with the given CSS selector.
UiHelperTrait::clickLink protected function Follows a link by complete name.
UiHelperTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
UiHelperTrait::drupalGet protected function Retrieves a Drupal path or an absolute path. 3
UiHelperTrait::drupalLogin protected function Logs in a user using the Mink controlled browser.
UiHelperTrait::drupalLogout protected function Logs a user out of the Mink controlled browser and confirms.
UiHelperTrait::drupalPostForm protected function Executes a form submission.
UiHelperTrait::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
UiHelperTrait::getAbsoluteUrl protected function Takes a path and returns an absolute path.
UiHelperTrait::getTextContent protected function Retrieves the plain-text content from the current page.
UiHelperTrait::getUrl protected function Get the current URL from the browser.
UiHelperTrait::prepareRequest protected function Prepare for a request to testing site. 1
UiHelperTrait::submitForm protected function Fills and submits a form.
UserCreationTrait::checkPermissions protected function Checks whether a given list of permission names is valid.
UserCreationTrait::createAdminRole protected function Creates an administrative role.
UserCreationTrait::createRole protected function Creates a role with specified permissions. Aliased as: drupalCreateRole
UserCreationTrait::createUser protected function Create a user with a given set of permissions. Aliased as: drupalCreateUser
UserCreationTrait::grantPermissions protected function Grant permissions to a user role.
UserCreationTrait::setCurrentUser protected function Switch the current logged in user.
UserCreationTrait::setUpCurrentUser protected function Creates a random user account and sets it as current user.
XdebugRequestTrait::extractCookiesFromRequest protected function Adds xdebug cookies, from request setup.