class MediaTest

Tests Drupal\ckeditor5\Plugin\CKEditor5Plugin\Media.

@internal

Attributes

#[CoversClass(\Drupal\ckeditor5\Plugin\CKEditor5Plugin\Media::class)] #[Group('ckeditor5')] #[Group('#slow')] #[RunTestsInSeparateProcesses]

Hierarchy

Expanded class hierarchy of MediaTest

File

core/modules/ckeditor5/tests/src/FunctionalJavascript/MediaTest.php, line 31

Namespace

Drupal\Tests\ckeditor5\FunctionalJavascript
View source
class MediaTest extends MediaTestBase {
  
  /**
   * Tests the drupal-media tag.
   */
  public function testDrupalMedia() : void {
    $this->testConversion();
    $this->testOnlyDrupalMediaTagProcessed();
    $this->testEditableCaption();
    $this->testAlignment();
    $this->testAlt();
    $this->testMediaSplitList();
  }
  
  /**
   * Tests that `<drupal-media>` is converted into a block element.
   */
  protected function testConversion() : void {
    // Wrap the `<drupal-media>` markup in a `<p>`.
    $original_value = $this->host->body->value;
    $this->host->body->value = '<p>foo' . $original_value . '</p>';
    $this->host
      ->save();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    $assert_session = $this->assertSession();
    $assert_session->waitForElementVisible('css', 'img[src*="image-test.png"]', 1000);
    $editor_html = $this->getEditorDataAsHtmlString();
    // Observe that `<drupal-media>` was moved into its own block element.
    $this->assertEquals('<p>foo</p>' . $original_value, str_replace('&nbsp;', '', $editor_html));
  }
  
  /**
   * Tests that only <drupal-media> tags are processed.
   *
   * @see \Drupal\Tests\media\Kernel\MediaEmbedFilterTest::testOnlyDrupalMediaTagProcessed()
   */
  protected function testOnlyDrupalMediaTagProcessed() : void {
    $original_value = $this->host->body->value;
    $this->host->body->value = str_replace('drupal-media', 'p', $original_value);
    $this->host
      ->save();
    // Assert that `<p data-* …>` is not upcast into a CKEditor Widget.
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    $assert_session = $this->assertSession();
    $this->assertEmpty($assert_session->waitForElementVisible('css', 'img[src*="image-test.png"]', 1000));
    $assert_session->elementNotExists('css', '.ck-widget.drupal-media');
    $this->host->body->value = $original_value;
    $this->host
      ->save();
    // Assert that `<drupal-media data-* …>` is upcast into a CKEditor Widget.
    $this->getSession()
      ->reload();
    $this->waitForEditor();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', 'img[src*="image-test.png"]'));
    $assert_session->elementExists('css', '.ck-widget.drupal-media');
  }
  
  /**
   * Tests adding media to a list does not split the list.
   */
  protected function testMediaSplitList() : void {
    $assert_session = $this->assertSession();
    $editor = Editor::load('test_format');
    $settings = $editor->getSettings();
    // Add lists to the editor.
    $settings['plugins']['ckeditor5_list'] = [
      'properties' => [
        'reversed' => FALSE,
        'startIndex' => FALSE,
        'styles' => FALSE,
      ],
      'multiBlock' => TRUE,
    ];
    $settings['toolbar']['items'] = array_merge($settings['toolbar']['items'], [
      'bulletedList',
      'numberedList',
    ]);
    $editor->setSettings($settings);
    $editor->save();
    // Add lists to the filter.
    $filter_format = $editor->getFilterFormat();
    $filter_format->setFilterConfig('filter_html', [
      'status' => TRUE,
      'settings' => [
        'allowed_html' => '<p> <br> <strong> <em> <a href> <drupal-media data-entity-type data-entity-uuid data-align data-caption alt data-view-mode> <ol> <ul> <li>',
      ],
    ]);
    $filter_format->save();
    $this->assertSame([], array_map(function (ConstraintViolationInterface $v) {
      return (string) $v->getMessage();
    }, iterator_to_array(CKEditor5::validatePair(Editor::load('test_format'), FilterFormat::load('test_format')))));
    // Wrap the media with a list item.
    $original_value = $this->host->body->value;
    $this->host->body->value = '<ol><li>' . $original_value . '</li></ol>';
    $this->host
      ->save();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->assertNotEmpty($upcasted_media = $assert_session->waitForElementVisible('css', '.ck-widget.drupal-media'));
    // Confirm the media is wrapped by the list item on the editing view.
    $assert_session->elementExists('css', 'li > .drupal-media');
    // Confirm the media is not adjacent to the list on the editing view.
    $assert_session->elementNotExists('css', 'ol + .drupal-media');
    $editor_dom = new \DOMXPath($this->getEditorDataAsDom());
    // Confirm drupal-media is wrapped by the list item.
    $this->assertNotEmpty($editor_dom->query('//li/drupal-media'));
    // Confirm the media is not adjacent to the list.
    $this->assertEmpty($editor_dom->query('//ol/following-sibling::drupal-media'));
  }
  
  /**
   * Tests that arbitrary attributes are allowed via GHS.
   */
  public function testMediaArbitraryHtml() : void {
    $assert_session = $this->assertSession();
    $editor = Editor::load('test_format');
    $settings = $editor->getSettings();
    // Allow the data-foo attribute in drupal-media via GHS. Also, add support
    // for div's with data-foo attribute to ensure that drupal-media elements
    // can be wrapped with other block elements.
    $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = [
      '<drupal-media data-foo>',
      '<div data-bar>',
    ];
    $editor->setSettings($settings);
    $editor->save();
    $filter_format = $editor->getFilterFormat();
    $filter_format->setFilterConfig('filter_html', [
      'status' => TRUE,
      'settings' => [
        'allowed_html' => '<p> <br> <strong> <em> <a href> <drupal-media data-entity-type data-entity-uuid data-align data-caption alt data-foo data-view-mode> <div data-bar>',
      ],
    ]);
    $filter_format->save();
    $this->assertSame([], array_map(function (ConstraintViolationInterface $v) {
      return (string) $v->getMessage();
    }, iterator_to_array(CKEditor5::validatePair(Editor::load('test_format'), FilterFormat::load('test_format')))));
    // Add data-foo use to an existing drupal-media tag.
    $original_value = $this->host->body->value;
    $this->host->body->value = '<div data-bar="baz">' . str_replace('drupal-media', 'drupal-media data-foo="bar" ', $original_value) . '</div>';
    $this->host
      ->save();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    // Confirm data-foo is present in the drupal-media preview.
    $this->assertNotEmpty($upcasted_media = $assert_session->waitForElementVisible('css', '.ck-widget.drupal-media'));
    $this->assertFalse($upcasted_media->hasAttribute('data-foo'));
    $this->assertNotEmpty($preview = $assert_session->waitForElementVisible('css', '.ck-widget.drupal-media > [data-drupal-media-preview="ready"] > .media', 30000));
    $this->assertEquals('bar', $preview->getAttribute('data-foo'));
    // Confirm that the media is wrapped by the div on the editing view.
    $assert_session->elementExists('css', 'div[data-bar="baz"] > .drupal-media');
    // Confirm data-foo is not stripped from source.
    $this->assertSourceAttributeSame('data-foo', 'bar');
    // Confirm that drupal-media is wrapped by the div.
    $editor_dom = new \DOMXPath($this->getEditorDataAsDom());
    $this->assertNotEmpty($editor_dom->query('//div[@data-bar="baz"]/drupal-media'));
  }
  
  /**
   * Tests caption editing in the CKEditor widget.
   */
  protected function testEditableCaption() : void {
    $page = $this->getSession()
      ->getPage();
    $assert_session = $this->assertSession();
    // Test that setting caption to blank string doesn't break 'Edit media'
    // button.
    $original_value = $this->host->body->value;
    $this->host->body->value = str_replace('data-caption="baz"', 'data-caption=""', $original_value);
    $this->host
      ->save();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    $assert_session->elementExists('css', '[data-drupal-media-preview][aria-label="Screaming hairy armadillo"]');
    $assert_session->elementContains('css', 'figcaption', '');
    $assert_session->elementAttributeContains('css', 'figcaption', 'data-placeholder', 'Enter media caption');
    // Test if you leave the caption blank, but change another attribute,
    // such as the alt text, the editable caption is still there and the edit
    // button still exists.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Click the "Override media image alternative text" button.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    // Fill in the alt field and submit.
    $alt_override_input->setValue('Gold star for robot boy.');
    $this->getBalloonButton('Save')
      ->click();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.drupal-media img[alt*="Gold star for robot boy."]'));
    $this->assertEquals('', $assert_session->waitForElement('css', '.drupal-media figcaption')
      ->getText());
    $assert_session->elementAttributeContains('css', '.drupal-media figcaption', 'data-placeholder', 'Enter media caption');
    // Restore caption in saved body value.
    $original_value = $this->host->body->value;
    $this->host->body->value = str_replace('data-caption=""', 'data-caption="baz"', $original_value);
    $this->host
      ->save();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    $this->assertNotEmpty($figcaption = $assert_session->waitForElement('css', '.drupal-media figcaption'));
    $this->assertSame('baz', $figcaption->getHtml());
    // Ensure that the media contextual toolbar is visible when figcaption is
    // selected.
    $this->selectTextInsideElement('.drupal-media figcaption');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $expected_buttons = [
      'Toggle caption off',
      'Link media',
      'Override media image alternative text',
      // Check only one of the element style buttons since that is sufficient
      // for confirming that element style buttons are visible in the toolbar.
'Break text',
    ];
    foreach ($expected_buttons as $expected_button) {
      $this->assertNotEmpty($this->getBalloonButton($expected_button));
    }
    // Ensure that caption can be toggled off from the toolbar.
    $this->getBalloonButton('Toggle caption off')
      ->click();
    $assert_session->assertNoElementAfterWait('css', 'figcaption');
    // Ensure that caption can be toggled on from the toolbar.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->getBalloonButton('Toggle caption on')
      ->click();
    $this->assertNotEmpty($figcaption = $assert_session->waitForElementVisible('css', '.drupal-media figcaption'));
    // Ensure that the media contextual toolbar is visible after toggling
    // caption on.
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Type into the widget's caption element.
    $this->selectTextInsideElement('.drupal-media figcaption');
    $figcaption->setValue('Llamas are the most awesome ever');
    $editor_dom = $this->getEditorDataAsDom();
    $this->assertEquals('Llamas are the most awesome ever', $editor_dom->getElementsByTagName('drupal-media')
      ->item(0)
      ->getAttribute('data-caption'));
    // Ensure that the caption can be changed to bold.
    $this->assertNotEmpty($figcaption = $assert_session->waitForElement('css', '.drupal-media figcaption'));
    $this->selectTextInsideElement('.drupal-media figcaption');
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption.ck-editor__nested-editable'));
    $this->pressEditorButton('Bold');
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption > strong'));
    $this->assertEquals('<strong>Llamas are the most awesome ever</strong>', $figcaption->getHtml());
    $editor_dom = $this->getEditorDataAsDom();
    $this->assertEquals('<strong>Llamas are the most awesome ever</strong>', $editor_dom->getElementsByTagName('drupal-media')
      ->item(0)
      ->getAttribute('data-caption'));
    // Ensure that bold can be removed from the caption.
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption > strong'));
    $this->selectTextInsideElement('.drupal-media figcaption > strong');
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption.ck-editor__nested-editable'));
    $this->pressEditorButton('Bold');
    $this->assertTrue($assert_session->waitForElementRemoved('css', '.drupal-media figcaption > strong'));
    $this->assertNotEmpty($figcaption = $assert_session->waitForElement('css', '.drupal-media figcaption'));
    $this->assertEquals('Llamas are the most awesome ever', $figcaption->getHtml());
    $editor_dom = $this->getEditorDataAsDom();
    $this->assertEquals('Llamas are the most awesome ever', $editor_dom->getElementsByTagName('drupal-media')
      ->item(0)
      ->getAttribute('data-caption'));
    // Ensure that caption can contain elements such as <br>.
    $this->pressEditorButton('Source');
    $source_text_area = $assert_session->waitForElement('css', '.ck-source-editing-area textarea');
    $source_text = $source_text_area->getValue();
    $source_text_area->setValue(str_replace('data-caption="Llamas are the most awesome ever"', 'data-caption="Llamas are the most<br>awesome ever"', $source_text));
    // Click source again to make source inactive.
    $this->pressEditorButton('Source');
    // Check that the source mode is toggled off.
    $assert_session->elementNotExists('css', '.ck-source-editing-area textarea');
    // Put back the caption as it was before.
    $this->pressEditorButton('Source');
    $source_text_area = $assert_session->waitForElement('css', '.ck-source-editing-area textarea');
    $source_text = $source_text_area->getValue();
    $source_text_area->setValue(str_replace('data-caption="Llamas are the most&lt;br&gt;awesome ever"', 'data-caption="Llamas are the most awesome ever"', $source_text));
    // Click source again to make source inactive.
    $this->pressEditorButton('Source');
    // Check that the source mode is toggled off.
    $assert_session->elementNotExists('css', '.ck-source-editing-area textarea');
    // Ensure that caption can be linked.
    $this->assertNotEmpty($figcaption = $assert_session->waitForElement('css', '.drupal-media figcaption'));
    $figcaption->click();
    $this->selectTextInsideElement('.drupal-media figcaption');
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption.ck-editor__nested-editable'));
    $this->pressEditorButton('Link');
    $this->assertVisibleBalloon('.ck-link-form');
    $link_input = $page->find('css', '.ck-balloon-panel .ck-link-form input[type=text][inputmode=url]');
    $link_input->setValue('https://example.com');
    $page->find('css', '.ck-balloon-panel .ck-link-form button[type=submit]')
      ->click();
    $this->assertNotEmpty($assert_session->waitForElement('css', '.drupal-media figcaption > a'));
    $this->assertEquals('<a class="ck-link_selected" href="https://example.com">Llamas are the most awesome ever</a>', $figcaption->getHtml());
    $editor_dom = $this->getEditorDataAsDom();
    $this->assertEquals('<a href="https://example.com">Llamas are the most awesome ever</a>', $editor_dom->getElementsByTagName('drupal-media')
      ->item(0)
      ->getAttribute('data-caption'));
  }
  
  /**
   * Tests that the image media source's alt_field being disabled is respected.
   *
   * @see \Drupal\Tests\ckeditor5\Functional\MediaEntityMetadataApiTest::testApi()
   */
  public function testAltDisabled() : void {
    // Disable the alt field for image media.
    FieldConfig::loadByName('media', 'image', 'field_media_image')->setSetting('alt_field', FALSE)
      ->save();
    $assert_session = $this->assertSession();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    // Test that by default no alt attribute is present on the drupal-media
    // element.
    $this->assertSourceAttributeSame('alt', NULL);
    // Test that the preview shows the alt value from the media field's
    // alt text.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img[alt*="default alt"]'));
    // Test that clicking the media widget triggers a CKEditor balloon panel
    // with a single button to override the alt text.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Assert that no "Override media image alternative text" button is visible.
    $override_alt_button = $this->getBalloonButton('Override media image alternative text');
    $this->assertFalse($override_alt_button->isVisible());
  }
  
  /**
   * Tests the CKEditor 5 media plugin can override image media's alt attribute.
   */
  protected function testAlt() : void {
    $page = $this->getSession()
      ->getPage();
    $assert_session = $this->assertSession();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    // Test that by default no alt attribute is present on the drupal-media
    // element.
    $this->assertSourceAttributeSame('alt', NULL);
    // Test that the preview shows the alt value from the media field's
    // alt text.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img[alt*="default alt"]'));
    // Test that clicking the media widget triggers a CKEditor balloon panel
    // with a single button to override the alt text.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Click the "Override media image alternative text" button.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    // Assert that the default alt text is visible in the UI.
    $assert_session->elementTextEquals('css', '.ck-media-alternative-text-form .ck-labeled-field-view__status', 'Leave blank to use the default alternative text: "default alt".');
    // Assert that the value is currently empty.
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    $this->assertSame('', $alt_override_input->getValue());
    // Fill in the alt field and submit.
    // cSpell:disable-next-line
    $who_is_zartan = 'Zartan is the leader of the Dreadnoks.';
    $alt_override_input->setValue($who_is_zartan);
    $this->getBalloonButton('Save')
      ->click();
    // Assert that the img within the media embed within the CKEditor contains
    // the overridden alt text set in the dialog.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img[alt*="' . $who_is_zartan . '"]'));
    // Ensure that the Drupal Media widget doesn't have alt attribute.
    // @see https://www.drupal.org/project/drupal/issues/3248440
    $assert_session->elementNotExists('css', '.ck-widget.drupal-media[alt]');
    // Test `aria-label` attribute appears on the widget wrapper.
    $assert_session->elementExists('css', '.ck-widget.drupal-media [aria-label="Screaming hairy armadillo"]');
    // Test that the downcast drupal-media element now has the alt attribute
    // entered in the balloon.
    $this->assertSourceAttributeSame('alt', $who_is_zartan);
    // The alt field should now display the override instead of the default.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    $this->assertSame($who_is_zartan, $alt_override_input->getValue());
    // Assert that the default alt text is still visible in the UI.
    $assert_session->elementTextEquals('css', '.ck-media-alternative-text-form .ck-labeled-field-view__status', 'Leave blank to use the default alternative text: "default alt".');
    // Test the process again with a different alt text to make sure it works
    // the second time around.
    $cobra_commander_bio = 'The supreme leader of the terrorist organization Cobra';
    // Set the alt field to the new alt text.
    $alt_override_input->setValue($cobra_commander_bio);
    $this->getBalloonButton('Save')
      ->click();
    // Assert that the img within the media embed preview inside CKEditor 5
    // contains the overridden alt text set in the balloon.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img[alt*="' . $cobra_commander_bio . '"]'));
    // Test that the downcast drupal-media element now has the alt attribute
    // entered in the dialog.
    $this->assertSourceAttributeSame('alt', $cobra_commander_bio);
    // The default value of the alt field should now display the override
    // instead of the value on the media image field.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    $this->assertSame($cobra_commander_bio, $alt_override_input->getValue());
    // Test that setting alt value to two double quotes will signal to the
    // MediaEmbed filter to unset the attribute on the media image field.
    // We intentionally add a space after the two double quotes to test that the
    // string is trimmed to two quotes.
    $alt_override_input->setValue('"" ');
    $this->getBalloonButton('Save')
      ->click();
    // Verify that the two double quote empty alt indicator ('""') set in
    // the alt text form balloon has successfully resulted in a media image
    // field with the alt attribute present but without a value.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '[data-media-embed-test-view-mode] img[alt=""]'));
    // Test that the downcast drupal-media element's alt attribute now has the
    // empty string indicator.
    $this->assertSourceAttributeSame('alt', '""');
    // Test that setting alt to back to an empty string within the balloon will
    // restore the default alt value saved in to the media image field of the
    // media item.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    // The 'decorative image' toggle is enabled because the alt was set to `""`.
    // Set the toggle to "off" to override the alt text value.
    $page->pressButton('Decorative image');
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    $alt_override_input->setValue('');
    $this->getBalloonButton('Save')
      ->click();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img[alt*="default alt"]'));
    // Test that the downcast drupal-media element no longer has an alt
    // attribute.
    $this->assertSourceAttributeSame('alt', NULL);
  }
  
  /**
   * Tests the CKEditor 5 media plugin loads the translated alt attribute.
   */
  public function testTranslationAlt() : void {
    \Drupal::service('module_installer')->install([
      'language',
      'content_translation',
    ]);
    $this->resetAll();
    ConfigurableLanguage::createFromLangcode('fr')->save();
    ContentLanguageSettings::loadByEntityTypeBundle('media', 'image')->setDefaultLangcode('en')
      ->setLanguageAlterable(TRUE)
      ->save();
    $media = Media::create([
      'bundle' => 'image',
      'name' => 'Screaming hairy armadillo',
      'field_media_image' => [
        [
          'target_id' => 1,
          'alt' => 'default alt',
          'title' => 'default title',
        ],
      ],
    ]);
    $media->save();
    $media_fr = $media->addTranslation('fr');
    $media_fr->name = "Tatou poilu hurlant";
    $media_fr->field_media_image
      ->setValue([
      [
        'target_id' => '1',
        'alt' => "texte alternatif par défaut",
        'title' => "titre alternatif par défaut",
      ],
    ]);
    $media_fr->save();
    ContentLanguageSettings::loadByEntityTypeBundle('node', 'blog')->setDefaultLangcode('en')
      ->setLanguageAlterable(TRUE)
      ->save();
    $host = $this->createNode([
      'type' => 'blog',
      'title' => 'Animals with strange names',
      'body' => [
        'value' => '<drupal-media data-caption="baz" data-entity-type="media" data-entity-uuid="' . $media->uuid() . '"></drupal-media>',
        'format' => 'test_format',
      ],
    ]);
    $host->save();
    $translation = $host->addTranslation('fr');
    // cSpell:disable-next-line
    $translation->title = 'Animaux avec des noms étranges';
    $translation->body->value = $host->body->value;
    $translation->body->format = $host->body->format;
    $translation->save();
    Role::load(RoleInterface::AUTHENTICATED_ID)->grantPermission('translate any entity')
      ->save();
    $page = $this->getSession()
      ->getPage();
    $assert_session = $this->assertSession();
    $this->drupalGet('/fr/node/' . $host->id() . '/edit');
    $this->waitForEditor();
    // Test that the default alt attribute displays without an override.
    // cSpell:disable-next-line
    $this->assertNotEmpty($assert_session->waitForElementVisible('xpath', '//img[contains(@alt, "texte alternatif par défaut")]'));
    // Test `aria-label` attribute appears on the preview wrapper.
    // cSpell:disable-next-line
    $assert_session->elementExists('css', '[data-drupal-media-preview][aria-label="Tatou poilu hurlant"]');
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Click the "Override media image alternative text" button.
    $this->getBalloonButton('Override media image alternative text')
      ->click();
    $this->assertVisibleBalloon('.ck-media-alternative-text-form');
    // Assert that the default alt on the UI is the default alt text from the
    // media entity.
    // cSpell:disable-next-line
    $assert_session->elementTextEquals('css', '.ck-media-alternative-text-form .ck-labeled-field-view__status', 'Leave blank to use the default alternative text: "texte alternatif par défaut".');
    // Fill in the alt field in the balloon form.
    // cSpell:disable-next-line
    $qui_est_zartan = 'Zartan est le chef des Dreadnoks.';
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-media-alternative-text-form input[type=text]');
    $alt_override_input->setValue($qui_est_zartan);
    $this->getBalloonButton('Save')
      ->click();
    // Assert that the img within the media embed within CKEditor 5 contains
    // the overridden alt text set in CKEditor 5.
    $this->assertNotEmpty($assert_session->waitForElementVisible('xpath', '//img[contains(@alt, "' . $qui_est_zartan . '")]'));
    $this->getSession()
      ->switchToIFrame();
    $page->pressButton('Save');
    $assert_session->elementExists('xpath', '//img[contains(@alt, "' . $qui_est_zartan . '")]');
  }
  
  /**
   * Tests alignment integration.
   *
   * Tests that alignment is reflected onto the CKEditor Widget wrapper, that
   * the media style toolbar allows altering the alignment and that the changes
   * are reflected on the widget and downcast drupal-media tag.
   */
  protected function testAlignment() : void {
    $assert_session = $this->assertSession();
    $page = $this->getSession()
      ->getPage();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    // Ensure that by default the "Break text" alignment option is selected.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->assertTrue($this->getBalloonButton('Break text')
      ->hasClass('ck-on'));
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertFalse($drupal_media_element->hasAttribute('data-align'));
    $this->getBalloonButton('Align center and break text')
      ->click();
    // Assert the alignment class exists after editing downcast.
    $this->assertNotEmpty($assert_session->waitForElement('css', '.ck-widget.drupal-media.drupal-media-style-align-center'));
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertEquals('center', $drupal_media_element->getAttribute('data-align'));
    $page->pressButton('Save');
    // Check that the 'content has been updated' message status appears to
    // confirm we left the editor.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.messages.messages--status'));
    // Check that the class is correct in the front end.
    $assert_session->elementExists('css', 'figure.align-center');
    // Go back to the editor to check that the alignment class still exists.
    $edit_url = $this->getSession()
      ->getCurrentURL() . '/edit';
    $this->drupalGet($edit_url);
    $this->waitForEditor();
    $assert_session->elementExists('css', '.ck-widget.drupal-media.drupal-media-style-align-center');
    // Ensure that "Centered media" alignment option is selected.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->assertTrue($this->getBalloonButton('Align center and break text')
      ->hasClass('ck-on'));
    $this->getBalloonButton('Break text')
      ->click();
    $this->assertTrue($assert_session->waitForElementRemoved('css', '.ck-widget.drupal-media.drupal-media-style-align-center'));
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertFalse($drupal_media_element->hasAttribute('data-align'));
  }
  
  /**
   * Ensures that Drupal Media Styles can be displayed in a dropdown.
   */
  public function testDrupalMediaStyleInDropdown() : void {
    \Drupal::service('module_installer')->install([
      'ckeditor5_drupalelementstyle_test',
    ]);
    $this->resetAll();
    $assert_session = $this->assertSession();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    // Ensure that by default the "Break text" alignment option is selected and
    // that the split button title is displayed.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->assertNotEmpty(($split_button = $this->getBalloonButton('Test title: Break text'))
      ->hasClass('ck-on'));
    // Ensure that the split button can be opened.
    $split_button->click();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-dropdown__panel-visible'));
    // Ensure that a button inside the split button can be clicked.
    $this->assertNotEmpty($align_button = $this->getBalloonButton('Align center and break text'));
    $align_button->click();
    // Ensure that the "Align center and break text" option is selected and the
    // split button title is displayed.
    $this->assertNotEmpty($assert_session->waitForElement('css', '.ck-widget.drupal-media.drupal-media-style-align-center'));
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertEquals('center', $drupal_media_element->getAttribute('data-align'));
    $this->assertNotEmpty($this->getBalloonButton('Test title: Align center and break text')
      ->hasClass('ck-on'));
  }
  
  /**
   * Tests Drupal Media Style with a CSS class.
   */
  public function testDrupalMediaStyleWithClass() : void {
    $editor = Editor::load('test_format');
    $editor->setSettings([
      'toolbar' => [
        'items' => [
          'heading',
          'sourceEditing',
          'simpleBox',
        ],
      ],
      'plugins' => [
        'ckeditor5_heading' => [
          'enabled_headings' => [
            'heading1',
          ],
        ],
        'ckeditor5_sourceEditing' => [
          'allowed_tags' => [
            '<div>',
            '<section>',
          ],
        ],
        'media_media' => [
          'allow_view_mode_override' => TRUE,
        ],
      ],
    ]);
    $filter_format = $editor->getFilterFormat();
    $filter_format->setFilterConfig('filter_html', [
      'status' => TRUE,
      'settings' => [
        'allowed_html' => '<p> <br> <h1 class> <div class> <section class> <drupal-media data-entity-type data-entity-uuid data-align data-caption data-view-mode alt class="layercake-side">',
      ],
    ]);
    $filter_format->save();
    $editor->save();
    $this->assertSame([], array_map(function (ConstraintViolationInterface $v) {
      return (string) $v->getMessage();
    }, iterator_to_array(CKEditor5::validatePair(Editor::load('test_format'), FilterFormat::load('test_format')))));
    $assert_session = $this->assertSession();
    $page = $this->getSession()
      ->getPage();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    $page->pressButton('Source');
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    // Add `layercake-side` class which is used in `ckeditor5_test_layercake`,
    // as well as an arbitrary class to compare behavior between these.
    $drupal_media_element->setAttribute('class', 'layercake-side arbitrary-class');
    $textarea = $page->find('css', '.ck-source-editing-area > textarea');
    $textarea->setValue($editor_dom->C14N());
    $page->pressButton('Source');
    // Ensure that the `layercake-side` class is retained.
    $this->assertNotEmpty($assert_session->waitForElement('css', '.ck-widget.drupal-media.layercake-side'));
    // Ensure that the `arbitrary-class` class is removed.
    $assert_session->elementNotExists('css', '.ck-widget.drupal-media.arbitrary-class');
    $page->pressButton('Save');
    // Check that the 'content has been updated' message status appears to
    // confirm we left the editor.
    $assert_session->waitForElementVisible('css', 'messages messages--status');
    // Ensure that the class is correct in the front end.
    $assert_session->elementExists('css', 'figure.layercake-side');
    $assert_session->elementNotExists('css', 'figure.arbitrary-class');
  }
  
  /**
   * Tests view mode integration.
   *
   * Tests that view mode is reflected onto the CKEditor 5 Widget wrapper, that
   * the media style toolbar allows changing the view mode and that the changes
   * are reflected on the widget and downcast drupal-media tag.
   */
  public function testViewMode(bool $with_alignment) : void {
    EntityViewMode::create([
      'id' => 'media.view_mode_3',
      'targetEntityType' => 'media',
      'status' => TRUE,
      'enabled' => TRUE,
      'label' => 'View Mode 3',
    ])->save();
    EntityViewMode::create([
      'id' => 'media.view_mode_4',
      'targetEntityType' => 'media',
      'status' => TRUE,
      'enabled' => TRUE,
      'label' => 'View Mode 4',
    ])->save();
    // Enable view mode 1, 2, 4 for Image.
    EntityViewDisplay::create([
      'id' => 'media.image.view_mode_4',
      'targetEntityType' => 'media',
      'status' => TRUE,
      'bundle' => 'image',
      'mode' => 'view_mode_4',
    ])->save();
    $filter_format = FilterFormat::load('test_format');
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
          '22222' => '22222',
          'view_mode_3' => 'view_mode_3',
        ],
      ],
    ])
      ->save();
    if (!$with_alignment) {
      $filter_format->filters('filter_align')
        ->setConfiguration(array_merge($filter_format->filters('filter_align')
        ->getConfiguration(), [
        'status' => FALSE,
      ]));
    }
    // Test that view mode dependencies are returned from the MediaEmbed
    // filter's ::getDependencies() method.
    $expected_config_dependencies = [
      'core.entity_view_mode.media.view_mode_1',
      'core.entity_view_mode.media.22222',
      'core.entity_view_mode.media.view_mode_3',
    ];
    $dependencies = $filter_format->getDependencies();
    $this->assertArrayHasKey('config', $dependencies);
    $this->assertEqualsCanonicalizing($expected_config_dependencies, $dependencies['config']);
    $assert_session = $this->assertSession();
    $page = $this->getSession()
      ->getPage();
    $this->drupalGet($this->host
      ->toUrl('edit-form'));
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Check that there is no data-view-mode set after embedding media.
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertFalse($drupal_media_element->hasAttribute('data-view-mode'));
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->getBalloonButton('View Mode 1')
      ->click();
    // Set view mode.
    $this->getBalloonButton('View Mode 2 has Numeric ID')
      ->click();
    $editor_dom = $this->getEditorDataAsDom();
    // Check that “data-view-mode” exists inside source editing.
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertEquals('22222', $drupal_media_element->getAttribute('data-view-mode'));
    // Check that toolbar matches current view mode.
    $dropdown_button = $page->find('css', 'button.ck-dropdown__button > span.ck-button__label');
    $this->assertEquals('View Mode 2 has Numeric ID', $dropdown_button->getText());
    // Enter source mode.
    $this->pressEditorButton('Source');
    // Leave source mode to force CKEditor 5 to upcast again to check data
    // persistence.
    $this->pressEditorButton('Source');
    $this->click('.ck-widget.drupal-media');
    $dropdown_button = $page->find('css', 'button.ck-dropdown__button > span.ck-button__label');
    // Check that view mode 2 persisted.
    $this->assertEquals('View Mode 2 has Numeric ID', $dropdown_button->getText());
    // Check that selecting a caption that is the child of a drupal-media will
    // inherit the drupalElementStyle of its parent element.
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->getBalloonButton('Toggle caption off')
      ->click();
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    // Select the caption by toggling it on.
    $this->getBalloonButton('Toggle caption on')
      ->click();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.drupal-media figcaption'));
    // Ensure that the media contextual toolbar is visible after toggling
    // caption on.
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $dropdown_button = $page->find('css', 'button.ck-dropdown__button > span.ck-button__label');
    $this->assertEquals('View Mode 2 has Numeric ID', $dropdown_button->getText());
    // Remove the current view mode by setting it to Default.
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->getBalloonButton('View Mode 2 has Numeric ID')
      ->click();
    // Unset view mode.
    $this->getBalloonButton('View Mode 1')
      ->click();
    $this->waitForEditor();
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    // Test that setting the view mode back to the default removes the
    // `data-view-mode` attribute.
    $this->assertFalse($drupal_media_element->hasAttribute('data-view-mode'));
    $this->assertNotEmpty($assert_session->waitForElement('css', 'article.media--view-mode-view-mode-1'));
    // Check that the toolbar status matches "no view mode".
    $dropdown_button = $page->find('css', 'button.ck-dropdown__button > span.ck-button__label');
    $this->assertEquals('View Mode 1', $dropdown_button->getText());
    // Test that setting the allowed_view_modes option to only one option hides
    // the field (it requires more than one option).
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
        ],
      ],
    ])
      ->save();
    // Test that the dependencies change when the allowed_view_modes change.
    $dependencies = $filter_format->getDependencies();
    $this->assertArrayHasKey('config', $dependencies);
    $this->assertSame([
      'core.entity_view_mode.media.view_mode_1',
    ], $dependencies['config']);
    // Reload page to get new configuration.
    $this->getSession()
      ->reload();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    $this->click('.ck-widget.drupal-media');
    // Check that view mode dropdown is gone because there is only one option.
    $this->assertEmpty($assert_session->waitForElementVisible('css', '.ck.ck-dropdown', 1000));
    $editor_dom = $this->getEditorDataAsDom();
    $drupal_media_element = $editor_dom->getElementsByTagName('drupal-media')
      ->item(0);
    $this->assertFalse($drupal_media_element->hasAttribute('data-view-mode'));
    $this->assertNotEmpty($assert_session->waitForElement('css', 'article.media--view-mode-view-mode-1'));
    // Test that setting allowed_view_modes back to two items restores the
    // field.
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
          '22222' => '22222',
        ],
      ],
    ])
      ->save();
    // Test that the dependencies change when the allowed_view_modes change.
    $expected_config_dependencies = [
      'core.entity_view_mode.media.view_mode_1',
      'core.entity_view_mode.media.22222',
    ];
    $dependencies = $filter_format->getDependencies();
    $this->assertArrayHasKey('config', $dependencies);
    $this->assertEqualsCanonicalizing($expected_config_dependencies, $dependencies['config']);
    // Reload page to get new configuration.
    $this->getSession()
      ->reload();
    $this->waitForEditor();
    // Test that changing the view mode with an empty editable caption
    // preserves the empty editable caption when the preview reloads.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.drupal-media figcaption'));
    $original_value = $this->host->body->value;
    $this->host->body->value = str_replace('data-caption="baz"', '', $original_value);
    $this->host
      ->save();
    $this->getSession()
      ->reload();
    $this->waitForEditor();
    $this->assertNotEmpty($assert_session->waitForElement('css', 'article.media--view-mode-view-mode-1'));
    $this->assertEmpty($assert_session->waitForElementVisible('css', '.drupal-media figcaption'));
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->getBalloonButton('View Mode 1')
      ->click();
    $this->getBalloonButton('View Mode 2 has Numeric ID')
      ->click();
    $assert_session->waitForElement('css', 'article.media--view-mode-_2222');
    $this->assertEmpty($assert_session->waitForElementVisible('css', '.drupal-media figcaption'));
    // Test that a media with no view modes configured will be
    // set to the default view mode.
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [],
      ],
    ])
      ->save();
    $dependencies = $filter_format->getDependencies();
    $this->assertArrayHasKey('config', $dependencies);
    $this->assertSame([
      'core.entity_view_mode.media.view_mode_1',
    ], $dependencies['config']);
    $this->host->body->value = '<drupal-media data-caption="armadillo" data-entity-type="media" data-entity-uuid="' . $this->mediaFile
      ->uuid() . '"></drupal-media>';
    $this->host
      ->save();
    // Reload page to get new configuration.
    $this->getSession()
      ->reload();
    $this->waitForEditor();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', 'article.media--view-mode-view-mode-1'));
    // Test that having a default_view_mode that is not an allowed_view_mode
    // will still be added to the editor.
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          '22222' => '22222',
          'view_mode_4' => 'view_mode_4',
        ],
      ],
    ])
      ->save();
    // Test that the dependencies change when the allowed_view_modes change.
    $expected_config_dependencies = [
      'core.entity_view_mode.media.22222',
      'core.entity_view_mode.media.view_mode_1',
      'core.entity_view_mode.media.view_mode_4',
    ];
    $dependencies = $filter_format->getDependencies();
    $this->assertArrayHasKey('config', $dependencies);
    $this->assertEqualsCanonicalizing($expected_config_dependencies, $dependencies['config']);
    $this->host->body->value = '<drupal-media data-entity-type="media" data-entity-uuid="' . $this->media
      ->uuid() . '" data-caption="baz"></drupal-media>';
    $this->host
      ->save();
    // Reload page to get new configuration.
    $this->getSession()
      ->reload();
    $this->waitForEditor();
    // Wait for the media preview to load.
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-widget.drupal-media img'));
    $this->click('.ck-widget.drupal-media');
    $this->assertVisibleBalloon('[aria-label="Drupal Media toolbar"]');
    $this->assertNotEmpty($dropdown = $this->getBalloonButton('View Mode 1'));
    $dropdown->click();
    // Check that all three view modes exist including the default view mode
    // that was not originally included in the allowed_view_modes.
    $this->assertNotEmpty($this->getBalloonButton('View Mode 1'));
    $this->assertNotEmpty($this->getBalloonButton('View Mode 2 has Numeric ID'));
    $this->assertNotEmpty($this->getBalloonButton('View Mode 4'));
  }
  
  /**
   * For testing view modes in different scenarios.
   */
  public static function providerTestViewMode() : array {
    return [
      'with alignment' => [
        TRUE,
      ],
      'without alignment' => [
        FALSE,
      ],
    ];
  }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Member alias Overriden Title Overrides
BlockCreationTrait::placeBlock protected function Creates a block instance based on default settings. Aliased as: drupalPlaceBlock
BodyFieldCreationTrait::createBodyField protected function Creates a field of an body field storage on the specified bundle.
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 enabled.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received.
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::$mink protected property Mink session manager.
BrowserTestBase::$minkDefaultDriverArgs protected property Mink default driver params.
BrowserTestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks.
BrowserTestBase::$profile protected property The profile to install as a basis for testing. 42
BrowserTestBase::$timeLimit protected property Time limit in seconds for the test.
BrowserTestBase::cleanupEnvironment protected function Clean up the test environment.
BrowserTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
BrowserTestBase::filePreDeleteCallback public static function Ensures test files are deletable.
BrowserTestBase::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
BrowserTestBase::getHttpClient protected function Obtain the HTTP client for the system under test.
BrowserTestBase::getOptions Deprecated protected function Helper function to get the options of select field.
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::installDrupal public function Installs Drupal into the test site. 2
BrowserTestBase::registerSessions protected function Registers additional Mink sessions.
BrowserTestBase::setDebugDumpHandler public static function Registers the dumper CLI handler when the DebugDump extension is enabled.
BrowserTestBase::setUpAppRoot protected function Sets up the root application path.
BrowserTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for submitForm().
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.
CKEditor5TestTrait::assertBalloonClosed protected function Asserts that the active balloon is closed.
CKEditor5TestTrait::assertEditorButtonDisabled protected function Asserts a CKEditor button is disabled.
CKEditor5TestTrait::assertEditorButtonEnabled protected function Asserts a CKEditor button is enabled.
CKEditor5TestTrait::assertVisibleBalloon protected function Asserts a particular balloon is visible.
CKEditor5TestTrait::getBalloonButton protected function Gets a button from the currently visible balloon.
CKEditor5TestTrait::getEditorButton protected function Waits for a CKEditor button and returns it when available and visible.
CKEditor5TestTrait::getEditorDataAsDom protected function Gets CKEditor 5 instance data as a PHP DOMDocument.
CKEditor5TestTrait::getEditorDataAsHtmlString protected function Gets CKEditor 5 instance data as a HTML string.
CKEditor5TestTrait::pressEditorButton protected function Clicks a CKEditor button.
CKEditor5TestTrait::selectTextInsideElement protected function Selects text inside an element.
CKEditor5TestTrait::waitForEditor protected function Waits for CKEditor to initialize.
CKEditor5ValidationTestTrait::assertExpectedCkeditor5Violations protected function Asserts CKEditor5 validation errors match an expected array of strings.
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
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
FunctionalTestSetupTrait::$apcuEnsureUniquePrefix protected property The flag to set &#039;apcu_ensure_unique_prefix&#039; setting. 1
FunctionalTestSetupTrait::$classLoader protected property The class loader to use for installation and initialization of setup.
FunctionalTestSetupTrait::$rootUser protected property The &quot;#1&quot; admin user.
FunctionalTestSetupTrait::$usesSuperUserAccessPolicy protected property Set to TRUE to make user 1 a super user.
FunctionalTestSetupTrait::doInstall protected function Execute the non-interactive installer. 1
FunctionalTestSetupTrait::initConfig protected function Initialize various configurations post-installation. 1
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. 1
FunctionalTestSetupTrait::installParameters protected function Returns the parameters that will be used when the test installs Drupal. 8
FunctionalTestSetupTrait::prepareEnvironment protected function Prepares the current environment for running the test. 29
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. 5
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. 1
MediaTest::providerTestViewMode public static function For testing view modes in different scenarios.
MediaTest::testAlignment protected function Tests alignment integration.
MediaTest::testAlt protected function Tests the CKEditor 5 media plugin can override image media&#039;s alt attribute.
MediaTest::testAltDisabled public function Tests that the image media source&#039;s alt_field being disabled is respected.
MediaTest::testConversion protected function Tests that `&lt;drupal-media&gt;` is converted into a block element.
MediaTest::testDrupalMedia public function Tests the drupal-media tag.
MediaTest::testDrupalMediaStyleInDropdown public function Ensures that Drupal Media Styles can be displayed in a dropdown.
MediaTest::testDrupalMediaStyleWithClass public function Tests Drupal Media Style with a CSS class.
MediaTest::testEditableCaption protected function Tests caption editing in the CKEditor widget.
MediaTest::testMediaArbitraryHtml public function Tests that arbitrary attributes are allowed via GHS.
MediaTest::testMediaSplitList protected function Tests adding media to a list does not split the list.
MediaTest::testOnlyDrupalMediaTagProcessed protected function Tests that only &lt;drupal-media&gt; tags are processed.
MediaTest::testTranslationAlt public function Tests the CKEditor 5 media plugin loads the translated alt attribute.
MediaTest::testViewMode public function Tests view mode integration.
MediaTestBase::$adminUser protected property The user to use during testing.
MediaTestBase::$defaultTheme protected property The theme to install as the default for testing. Overrides BrowserTestBase::$defaultTheme
MediaTestBase::$host protected property A host entity with a body field to embed media in.
MediaTestBase::$media protected property The sample Media entity to embed.
MediaTestBase::$mediaFile protected property The second sample Media entity to embed used in one of the tests.
MediaTestBase::$modules protected static property Modules to install. Overrides BrowserTestBase::$modules
MediaTestBase::assertSourceAttributeSame protected function Verifies value of an attribute on the downcast &lt;drupal-media&gt; element.
MediaTestBase::getLastPreviewRequestTransferSize protected function Gets the transfer size of the last preview request.
MediaTestBase::setUp protected function Overrides BrowserTestBase::setUp
MediaTypeCreationTrait::createMediaType protected function Create a media type for a source plugin.
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
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.
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.
RefreshVariablesTrait::refreshVariables protected function Refreshes in-memory configuration and state information. 2
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.
TestFileCreationTrait::$generatedTestFiles protected property Whether the files were copied to the test files directory.
TestFileCreationTrait::compareFiles protected function Compares two files based on size and file name.
TestFileCreationTrait::generateFile protected static function Generates a test file.
TestFileCreationTrait::getTestFiles protected function Gets a list of files that can be used in tests.
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. 4
TestSetupTrait::$databasePrefix protected property The database prefix of this test run.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateContainer private property Stores the container in case it is set before available with \Drupal.
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::$root protected property The app root.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 4
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::prepareDatabasePrefix protected function Generates a database prefix for running tests. 1
TestSetupTrait::__get public function Implements the magic method for getting object properties.
TestSetupTrait::__set public function Implements the magic method for setting object properties.
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::$useOneTimeLoginLinks protected property Use one-time login links instead of submitting the login form. 3
UiHelperTrait::buildUrl protected function Builds an 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::cssSelectToXpath protected function Translates a CSS expression to its XPath equivalent.
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::drupalResetSession protected function Resets the current active session back to Anonymous session.
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::isTestUsingGuzzleClient protected function Determines if test is using DrupalTestBrowser.
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 1
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.
WebDriverTestBase::$disableCssAnimations protected property Disables CSS animations in tests for more reliable testing.
WebDriverTestBase::$failOnJavascriptConsoleErrors protected property Determines if a test should fail on JavaScript console errors. 2
WebDriverTestBase::$minkDefaultDriverClass protected property Mink class for the default driver to use. Overrides BrowserTestBase::$minkDefaultDriverClass
WebDriverTestBase::assertJsCondition protected function Waits for the given time or until the given JS condition becomes TRUE.
WebDriverTestBase::assertSession public function Returns WebAssert object. Overrides UiHelperTrait::assertSession
WebDriverTestBase::createScreenshot protected function Creates a screenshot.
WebDriverTestBase::failOnJavaScriptErrors protected function Triggers a test failure if a JavaScript error was encountered.
WebDriverTestBase::getDrupalSettings protected function Gets the current Drupal javascript settings and parses into an array. Overrides BrowserTestBase::getDrupalSettings
WebDriverTestBase::getHtmlOutputHeaders protected function Returns headers in HTML output format. Overrides BrowserHtmlDebugTrait::getHtmlOutputHeaders
WebDriverTestBase::getMinkDriverArgs protected function Gets the Mink driver args from an environment variable. Overrides BrowserTestBase::getMinkDriverArgs 1
WebDriverTestBase::initFrontPage protected function Visits the front page when initializing Mink. Overrides BrowserTestBase::initFrontPage
WebDriverTestBase::initMink protected function Initializes Mink sessions. Overrides BrowserTestBase::initMink
WebDriverTestBase::installModulesFromClassProperty protected function Install modules defined by `static::$modules`. Overrides FunctionalTestSetupTrait::installModulesFromClassProperty 1
WebDriverTestBase::tearDown protected function Overrides BrowserTestBase::tearDown 1
XdebugRequestTrait::extractCookiesFromRequest protected function Adds xdebug cookies, from request setup.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.