You are here

class ForumTest in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/forum/tests/src/Functional/ForumTest.php \Drupal\Tests\forum\Functional\ForumTest

Tests for forum.module.

Create, view, edit, delete, and change forum entries and verify its consistency in the database.

@group forum

Hierarchy

Expanded class hierarchy of ForumTest

File

core/modules/forum/tests/src/Functional/ForumTest.php, line 22

Namespace

Drupal\Tests\forum\Functional
View source
class ForumTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  protected static $modules = [
    'taxonomy',
    'comment',
    'forum',
    'node',
    'block',
    'menu_ui',
    'help',
  ];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'classy';

  /**
   * A user with various administrative privileges.
   */
  protected $adminUser;

  /**
   * A user that can create forum topics and edit its own topics.
   */
  protected $editOwnTopicsUser;

  /**
   * A user that can create, edit, and delete forum topics.
   */
  protected $editAnyTopicsUser;

  /**
   * A user with no special privileges.
   */
  protected $webUser;

  /**
   * An administrative user who can bypass comment approval.
   */
  protected $postCommentUser;

  /**
   * An array representing a forum container.
   */
  protected $forumContainer;

  /**
   * An array representing a forum.
   */
  protected $forum;

  /**
   * An array representing a root forum.
   */
  protected $rootForum;

  /**
   * An array of forum topic node IDs.
   */
  protected $nids;

  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    $this
      ->drupalPlaceBlock('system_breadcrumb_block');
    $this
      ->drupalPlaceBlock('page_title_block');

    // Create users.
    $this->adminUser = $this
      ->drupalCreateUser([
      'access administration pages',
      'administer modules',
      'administer blocks',
      'administer forums',
      'administer menu',
      'administer taxonomy',
      'create forum content',
      'access comments',
    ]);
    $this->editAnyTopicsUser = $this
      ->drupalCreateUser([
      'access administration pages',
      'create forum content',
      'edit any forum content',
      'delete any forum content',
    ]);
    $this->editOwnTopicsUser = $this
      ->drupalCreateUser([
      'create forum content',
      'edit own forum content',
      'delete own forum content',
    ]);
    $this->webUser = $this
      ->drupalCreateUser();
    $this->postCommentUser = $this
      ->drupalCreateUser([
      'administer content types',
      'create forum content',
      'post comments',
      'skip comment approval',
      'access comments',
    ]);
    $this
      ->drupalPlaceBlock('help_block', [
      'region' => 'help',
    ]);
    $this
      ->drupalPlaceBlock('local_actions_block');
  }

  /**
   * Tests forum functionality through the admin and user interfaces.
   */
  public function testForum() {

    // Check that the basic forum install creates a default forum topic
    $this
      ->drupalGet('/forum');

    // Look for the "General discussion" default forum
    $this
      ->assertSession()
      ->linkExists('General discussion');
    $this
      ->assertSession()
      ->linkByHrefExists('/forum/1');

    // Check the presence of expected cache tags.
    $this
      ->assertSession()
      ->responseHeaderContains('X-Drupal-Cache-Tags', 'config:forum.settings');
    $this
      ->drupalGet(Url::fromRoute('forum.page', [
      'taxonomy_term' => 1,
    ]));
    $this
      ->assertSession()
      ->responseHeaderContains('X-Drupal-Cache-Tags', 'config:forum.settings');

    // Do the admin tests.
    $this
      ->doAdminTests($this->adminUser);

    // Check display order.
    $display = EntityViewDisplay::load('node.forum.default');
    $body = $display
      ->getComponent('body');
    $comment = $display
      ->getComponent('comment_forum');
    $taxonomy = $display
      ->getComponent('taxonomy_forums');

    // Assert field order is body » taxonomy » comments.
    $this
      ->assertLessThan($body['weight'], $taxonomy['weight']);
    $this
      ->assertLessThan($comment['weight'], $body['weight']);

    // Check form order.
    $display = EntityFormDisplay::load('node.forum.default');
    $body = $display
      ->getComponent('body');
    $comment = $display
      ->getComponent('comment_forum');
    $taxonomy = $display
      ->getComponent('taxonomy_forums');

    // Assert category comes before body in order.
    $this
      ->assertLessThan($body['weight'], $taxonomy['weight']);
    $this
      ->generateForumTopics();

    // Log in an unprivileged user to view the forum topics and generate an
    // active forum topics list.
    $this
      ->drupalLogin($this->webUser);

    // Verify that this user is shown a message that they may not post content.
    $this
      ->drupalGet('forum/' . $this->forum['tid']);
    $this
      ->assertSession()
      ->pageTextContains('You are not allowed to post new content in the forum');

    // Log in, and do basic tests for a user with permission to edit any forum
    // content.
    $this
      ->doBasicTests($this->editAnyTopicsUser, TRUE);

    // Create a forum node authored by this user.
    $any_topics_user_node = $this
      ->createForumTopic($this->forum, FALSE);

    // Log in, and do basic tests for a user with permission to edit only its
    // own forum content.
    $this
      ->doBasicTests($this->editOwnTopicsUser, FALSE);

    // Create a forum node authored by this user.
    $own_topics_user_node = $this
      ->createForumTopic($this->forum, FALSE);

    // Verify that this user cannot edit forum content authored by another user.
    $this
      ->verifyForums($any_topics_user_node, FALSE, 403);

    // Verify that this user is shown a local task to add new forum content.
    $this
      ->drupalGet('forum');
    $this
      ->assertSession()
      ->linkExists('Add new Forum topic');
    $this
      ->drupalGet('forum/' . $this->forum['tid']);
    $this
      ->assertSession()
      ->linkExists('Add new Forum topic');

    // Log in a user with permission to edit any forum content.
    $this
      ->drupalLogin($this->editAnyTopicsUser);

    // Verify that this user can edit forum content authored by another user.
    $this
      ->verifyForums($own_topics_user_node, TRUE);

    // Verify the topic and post counts on the forum page.
    $this
      ->drupalGet('forum');

    // Verify row for testing forum.
    $forum_arg = [
      ':forum' => 'forum-list-' . $this->forum['tid'],
    ];

    // Topics cell contains number of topics and number of unread topics.
    $xpath = $this
      ->assertSession()
      ->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__topics"]', $forum_arg);
    $topics = $this
      ->xpath($xpath);
    $topics = trim($topics[0]
      ->getText());

    // The extracted text contains the number of topics (6) and new posts
    // (also 6) in this table cell.
    $this
      ->assertEquals('6 6 new posts in forum ' . $this->forum['name'], $topics, 'Number of topics found.');

    // Verify the number of unread topics.
    $elements = $this
      ->xpath('//tr[@id=:forum]//td[@class="forum__topics"]//a', $forum_arg);
    $this
      ->assertStringStartsWith('6 new posts', $elements[0]
      ->getText(), 'Number of unread topics found.');

    // Verify that the forum name is in the unread topics text.
    $elements = $this
      ->xpath('//tr[@id=:forum]//em[@class="placeholder"]', $forum_arg);
    $this
      ->assertStringContainsString($this->forum['name'], $elements[0]
      ->getText(), 'Forum name found in unread topics text.');

    // Verify total number of posts in forum.
    $elements = $this
      ->xpath('//tr[@id=:forum]//td[@class="forum__posts"]', $forum_arg);
    $this
      ->assertEquals('6', $elements[0]
      ->getText(), 'Number of posts found.');

    // Test loading multiple forum nodes on the front page.
    $this
      ->drupalLogin($this
      ->drupalCreateUser([
      'administer content types',
      'create forum content',
      'post comments',
    ]));
    $this
      ->drupalGet('admin/structure/types/manage/forum');
    $this
      ->submitForm([
      'options[promote]' => 'promote',
    ], 'Save content type');
    $this
      ->createForumTopic($this->forum, FALSE);
    $this
      ->createForumTopic($this->forum, FALSE);
    $this
      ->drupalGet('node');

    // Test adding a comment to a forum topic.
    $node = $this
      ->createForumTopic($this->forum, FALSE);
    $edit = [];
    $edit['comment_body[0][value]'] = $this
      ->randomMachineName();
    $this
      ->drupalGet('node/' . $node
      ->id());
    $this
      ->submitForm($edit, 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);

    // Test editing a forum topic that has a comment.
    $this
      ->drupalLogin($this->editAnyTopicsUser);
    $this
      ->drupalGet('forum/' . $this->forum['tid']);
    $this
      ->drupalGet('node/' . $node
      ->id() . '/edit');
    $this
      ->submitForm([], 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);

    // Test the root forum page title change.
    $this
      ->drupalGet('forum');
    $this
      ->assertSession()
      ->responseHeaderContains('X-Drupal-Cache-Tags', 'config:taxonomy.vocabulary.' . $this->forum['vid']);
    $this
      ->assertSession()
      ->titleEquals('Forums | Drupal');
    $vocabulary = Vocabulary::load($this->forum['vid']);
    $vocabulary
      ->set('name', 'Discussions');
    $vocabulary
      ->save();
    $this
      ->drupalGet('forum');
    $this
      ->assertSession()
      ->titleEquals('Discussions | Drupal');

    // Test anonymous action link.
    $this
      ->drupalLogout();
    $this
      ->drupalGet('forum/' . $this->forum['tid']);
    $this
      ->assertSession()
      ->linkExists('Log in to post new content in the forum.');
  }

  /**
   * Tests that forum nodes can't be added without a parent.
   *
   * Verifies that forum nodes are not created without choosing "forum" from the
   * select list.
   */
  public function testAddOrphanTopic() {

    // Must remove forum topics to test creating orphan topics.
    $vid = $this
      ->config('forum.settings')
      ->get('vocabulary');
    $tids = \Drupal::entityQuery('taxonomy_term')
      ->accessCheck(FALSE)
      ->condition('vid', $vid)
      ->execute();
    $term_storage = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term');
    $terms = $term_storage
      ->loadMultiple($tids);
    $term_storage
      ->delete($terms);

    // Create an orphan forum item.
    $edit = [];
    $edit['title[0][value]'] = $this
      ->randomMachineName(10);
    $edit['body[0][value]'] = $this
      ->randomMachineName(120);
    $this
      ->drupalLogin($this->adminUser);
    $this
      ->drupalGet('node/add/forum');
    $this
      ->submitForm($edit, 'Save');
    $nid_count = $this->container
      ->get('entity_type.manager')
      ->getStorage('node')
      ->getQuery()
      ->accessCheck(FALSE)
      ->count()
      ->execute();
    $this
      ->assertEquals(0, $nid_count, 'A forum node was not created when missing a forum vocabulary.');

    // Reset the defaults for future tests.
    \Drupal::service('module_installer')
      ->install([
      'forum',
    ]);
  }

  /**
   * Runs admin tests on the admin user.
   *
   * @param object $user
   *   The logged-in user.
   */
  private function doAdminTests($user) {

    // Log in the user.
    $this
      ->drupalLogin($user);

    // Add forum to the Tools menu.
    $edit = [];
    $this
      ->drupalGet('admin/structure/menu/manage/tools');
    $this
      ->submitForm($edit, 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);

    // Edit forum taxonomy.
    // Restoration of the settings fails and causes subsequent tests to fail.
    $this
      ->editForumVocabulary();

    // Create forum container.
    $this->forumContainer = $this
      ->createForum('container');

    // Verify "edit container" link exists and functions correctly.
    $this
      ->drupalGet('admin/structure/forum');

    // Verify help text is shown.
    $this
      ->assertSession()
      ->pageTextContains('Forums contain forum topics. Use containers to group related forums');

    // Verify action links are there.
    $this
      ->assertSession()
      ->linkExists('Add forum');
    $this
      ->assertSession()
      ->linkExists('Add container');
    $this
      ->clickLink('edit container');
    $this
      ->assertSession()
      ->pageTextContains('Edit container');

    // Create forum inside the forum container.
    $this->forum = $this
      ->createForum('forum', $this->forumContainer['tid']);

    // Verify the "edit forum" link exists and functions correctly.
    $this
      ->drupalGet('admin/structure/forum');
    $this
      ->clickLink('edit forum');
    $this
      ->assertSession()
      ->pageTextContains('Edit forum');

    // Navigate back to forum structure page.
    $this
      ->drupalGet('admin/structure/forum');

    // Create second forum in container, destined to be deleted below.
    $delete_forum = $this
      ->createForum('forum', $this->forumContainer['tid']);

    // Save forum overview.
    $this
      ->drupalGet('admin/structure/forum/');
    $this
      ->submitForm([], 'Save');
    $this
      ->assertSession()
      ->pageTextContains('The configuration options have been saved.');

    // Delete this second forum.
    $this
      ->deleteForum($delete_forum['tid']);

    // Create forum at the top (root) level.
    $this->rootForum = $this
      ->createForum('forum');

    // Test vocabulary form alterations.
    $this
      ->drupalGet('admin/structure/taxonomy/manage/forums');
    $this
      ->assertSession()
      ->buttonExists('Save');
    $this
      ->assertSession()
      ->buttonNotExists('Delete');

    // Test term edit form alterations.
    $this
      ->drupalGet('taxonomy/term/' . $this->forumContainer['tid'] . '/edit');

    // Test parent field been hidden by forum module.
    $this
      ->assertSession()
      ->fieldNotExists('parent[]');

    // Create a default vocabulary named "Tags".
    $description = 'Use tags to group articles on similar topics into categories.';
    $help = 'Enter a comma-separated list of words to describe your content.';
    $vocabulary = Vocabulary::create([
      'name' => 'Tags',
      'description' => $description,
      'vid' => 'tags',
      'langcode' => \Drupal::languageManager()
        ->getDefaultLanguage()
        ->getId(),
      'help' => $help,
    ]);
    $vocabulary
      ->save();

    // Test tags vocabulary form is not affected.
    $this
      ->drupalGet('admin/structure/taxonomy/manage/tags');
    $this
      ->assertSession()
      ->buttonExists('Save');
    $this
      ->assertSession()
      ->linkExists('Delete');

    // Test tags vocabulary term form is not affected.
    $this
      ->drupalGet('admin/structure/taxonomy/manage/tags/add');
    $this
      ->assertSession()
      ->fieldExists('parent[]');

    // Test relations widget exists.
    $relations_widget = $this
      ->xpath("//details[@id='edit-relations']");
    $this
      ->assertTrue(isset($relations_widget[0]), 'Relations widget element found.');
  }

  /**
   * Edits the forum taxonomy.
   */
  public function editForumVocabulary() {

    // Backup forum taxonomy.
    $vid = $this
      ->config('forum.settings')
      ->get('vocabulary');
    $original_vocabulary = Vocabulary::load($vid);

    // Generate a random name and description.
    $edit = [
      'name' => $this
        ->randomMachineName(10),
      'description' => $this
        ->randomMachineName(100),
    ];

    // Edit the vocabulary.
    $this
      ->drupalGet('admin/structure/taxonomy/manage/' . $original_vocabulary
      ->id());
    $this
      ->submitForm($edit, 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);
    $this
      ->assertSession()
      ->pageTextContains("Updated vocabulary {$edit['name']}.");

    // Grab the newly edited vocabulary.
    $current_vocabulary = Vocabulary::load($vid);

    // Make sure we actually edited the vocabulary properly.
    $this
      ->assertEquals($edit['name'], $current_vocabulary
      ->label(), 'The name was updated');
    $this
      ->assertEquals($edit['description'], $current_vocabulary
      ->getDescription(), 'The description was updated');

    // Restore the original vocabulary's name and description.
    $current_vocabulary
      ->set('name', $original_vocabulary
      ->label());
    $current_vocabulary
      ->set('description', $original_vocabulary
      ->getDescription());
    $current_vocabulary
      ->save();

    // Reload vocabulary to make sure changes are saved.
    $current_vocabulary = Vocabulary::load($vid);
    $this
      ->assertEquals($original_vocabulary
      ->label(), $current_vocabulary
      ->label(), 'The original vocabulary settings were restored');
  }

  /**
   * Creates a forum container or a forum.
   *
   * @param string $type
   *   The forum type (forum container or forum).
   * @param int $parent
   *   The forum parent. This defaults to 0, indicating a root forum.
   *
   * @return \Drupal\Core\Database\StatementInterface
   *   The created taxonomy term data.
   */
  public function createForum($type, $parent = 0) {

    // Generate a random name/description.
    $name = $this
      ->randomMachineName(10);
    $description = $this
      ->randomMachineName(100);
    $edit = [
      'name[0][value]' => $name,
      'description[0][value]' => $description,
      'parent[0]' => $parent,
      'weight' => '0',
    ];

    // Create forum.
    $this
      ->drupalGet('admin/structure/forum/add/' . $type);
    $this
      ->submitForm($edit, 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);
    $type = $type == 'container' ? 'forum container' : 'forum';
    $this
      ->assertSession()
      ->pageTextContains('Created new ' . $type . ' ' . $name . '.');

    // Verify that the creation message contains a link to a term.
    $this
      ->assertSession()
      ->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "term/")]');

    /** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_term_storage */
    $taxonomy_term_storage = $this->container
      ->get('entity_type.manager')
      ->getStorage('taxonomy_term');

    // Verify forum.
    $term = $taxonomy_term_storage
      ->loadByProperties([
      'vid' => $this
        ->config('forum.settings')
        ->get('vocabulary'),
      'name' => $name,
      'description__value' => $description,
    ]);
    $term = array_shift($term);
    $this
      ->assertTrue(!empty($term), 'The ' . $type . ' exists in the database');

    // Verify forum hierarchy.
    $tid = $term
      ->id();
    $parent_tid = $taxonomy_term_storage
      ->loadParents($tid);
    $parent_tid = empty($parent_tid) ? 0 : array_shift($parent_tid)
      ->id();
    $this
      ->assertSame($parent, $parent_tid, 'The ' . $type . ' is linked to its container');
    $forum = $taxonomy_term_storage
      ->load($tid);
    $this
      ->assertEquals($type == 'forum container', (bool) $forum->forum_container->value);
    return [
      'tid' => $tid,
      'name' => $term
        ->getName(),
      'vid' => $term
        ->bundle(),
    ];
  }

  /**
   * Deletes a forum.
   *
   * @param int $tid
   *   The forum ID.
   */
  public function deleteForum($tid) {

    // Delete the forum.
    $this
      ->drupalGet('admin/structure/forum/edit/forum/' . $tid);
    $this
      ->clickLink('Delete');
    $this
      ->assertSession()
      ->pageTextContains('Are you sure you want to delete the forum');
    $this
      ->assertSession()
      ->pageTextNotContains('Add forum');
    $this
      ->assertSession()
      ->pageTextNotContains('Add forum container');
    $this
      ->submitForm([], 'Delete');

    // Assert that the forum no longer exists.
    $this
      ->drupalGet('forum/' . $tid);
    $this
      ->assertSession()
      ->statusCodeEquals(404);
  }

  /**
   * Runs basic tests on the indicated user.
   *
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The logged in user.
   * @param bool $admin
   *   User has 'access administration pages' privilege.
   */
  private function doBasicTests($user, $admin) {

    // Log in the user.
    $this
      ->drupalLogin($user);

    // Attempt to create forum topic under a container.
    $this
      ->createForumTopic($this->forumContainer, TRUE);

    // Create forum node.
    $node = $this
      ->createForumTopic($this->forum, FALSE);

    // Verify the user has access to all the forum nodes.
    $this
      ->verifyForums($node, $admin);
  }

  /**
   * Tests a forum with a new post displays properly.
   */
  public function testForumWithNewPost() {

    // Log in as the first user.
    $this
      ->drupalLogin($this->adminUser);

    // Create a forum container.
    $this->forumContainer = $this
      ->createForum('container');

    // Create a forum.
    $this->forum = $this
      ->createForum('forum');

    // Create a topic.
    $node = $this
      ->createForumTopic($this->forum, FALSE);

    // Log in as a second user.
    $this
      ->drupalLogin($this->postCommentUser);

    // Post a reply to the topic.
    $edit = [];
    $edit['subject[0][value]'] = $this
      ->randomMachineName();
    $edit['comment_body[0][value]'] = $this
      ->randomMachineName();
    $this
      ->drupalGet('node/' . $node
      ->id());
    $this
      ->submitForm($edit, 'Save');
    $this
      ->assertSession()
      ->statusCodeEquals(200);

    // Test adding a new comment.
    $this
      ->clickLink('Add new comment');
    $this
      ->assertSession()
      ->statusCodeEquals(200);
    $this
      ->assertSession()
      ->fieldExists('comment_body[0][value]');

    // Log in as the first user.
    $this
      ->drupalLogin($this->adminUser);

    // Check that forum renders properly.
    $this
      ->drupalGet("forum/{$this->forum['tid']}");
    $this
      ->assertSession()
      ->statusCodeEquals(200);

    // Verify there is no unintentional HTML tag escaping.
    $this
      ->assertSession()
      ->assertNoEscaped('<');
  }

  /**
   * Creates a forum topic.
   *
   * @param array $forum
   *   A forum array.
   * @param bool $container
   *   TRUE if $forum is a container; FALSE otherwise.
   *
   * @return object|null
   *   The created topic node or NULL if the forum is a container.
   */
  public function createForumTopic($forum, $container = FALSE) {

    // Generate a random subject/body.
    $title = $this
      ->randomMachineName(20);
    $body = $this
      ->randomMachineName(200);
    $edit = [
      'title[0][value]' => $title,
      'body[0][value]' => $body,
    ];
    $tid = $forum['tid'];

    // Create the forum topic, preselecting the forum ID via a URL parameter.
    $this
      ->drupalGet('node/add/forum', [
      'query' => [
        'forum_id' => $tid,
      ],
    ]);
    $this
      ->submitForm($edit, 'Save');
    $type = t('Forum topic');
    if ($container) {
      $this
        ->assertSession()
        ->pageTextNotContains("{$type} {$title} has been created.");
      $this
        ->assertSession()
        ->pageTextContains("The item {$forum['name']} is a forum container, not a forum.");
      return;
    }
    else {
      $this
        ->assertSession()
        ->pageTextContains($type . ' ' . $title . ' has been created.');
      $this
        ->assertSession()
        ->pageTextNotContains("The item {$forum['name']} is a forum container, not a forum.");

      // Verify that the creation message contains a link to a node.
      $this
        ->assertSession()
        ->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "node/")]');
    }

    // Retrieve node object, ensure that the topic was created and in the proper forum.
    $node = $this
      ->drupalGetNodeByTitle($title);
    $this
      ->assertNotNull($node, new FormattableMarkup('Node @title was loaded', [
      '@title' => $title,
    ]));
    $this
      ->assertEquals($tid, $node->taxonomy_forums->target_id, 'Saved forum topic was in the expected forum');

    // View forum topic.
    $this
      ->drupalGet('node/' . $node
      ->id());
    $this
      ->assertSession()
      ->pageTextContains($title);
    $this
      ->assertSession()
      ->pageTextContains($body);
    return $node;
  }

  /**
   * Verifies that the logged in user has access to a forum node.
   *
   * @param \Drupal\Core\Entity\EntityInterface $node
   *   The node being checked.
   * @param bool $admin
   *   Boolean to indicate whether the user can 'access administration pages'.
   * @param int $response
   *   The expected HTTP response code.
   */
  private function verifyForums(EntityInterface $node, $admin, $response = 200) {
    $response2 = $admin ? 200 : 403;

    // View forum help node.
    $this
      ->drupalGet('admin/help/forum');
    $this
      ->assertSession()
      ->statusCodeEquals($response2);
    if ($response2 == 200) {
      $this
        ->assertSession()
        ->titleEquals('Forum | Drupal');
      $this
        ->assertSession()
        ->pageTextContains('Forum');
    }

    // View forum container page.
    $this
      ->verifyForumView($this->forumContainer);

    // View forum page.
    $this
      ->verifyForumView($this->forum, $this->forumContainer);

    // View root forum page.
    $this
      ->verifyForumView($this->rootForum);

    // View forum node.
    $this
      ->drupalGet('node/' . $node
      ->id());
    $this
      ->assertSession()
      ->statusCodeEquals(200);
    $this
      ->assertSession()
      ->titleEquals($node
      ->label() . ' | Drupal');
    $breadcrumb_build = [
      Link::createFromRoute(t('Home'), '<front>'),
      Link::createFromRoute(t('Forums'), 'forum.index'),
      Link::createFromRoute($this->forumContainer['name'], 'forum.page', [
        'taxonomy_term' => $this->forumContainer['tid'],
      ]),
      Link::createFromRoute($this->forum['name'], 'forum.page', [
        'taxonomy_term' => $this->forum['tid'],
      ]),
    ];
    $breadcrumb = [
      '#theme' => 'breadcrumb',
      '#links' => $breadcrumb_build,
    ];
    $this
      ->assertSession()
      ->responseContains(\Drupal::service('renderer')
      ->renderRoot($breadcrumb));

    // View forum edit node.
    $this
      ->drupalGet('node/' . $node
      ->id() . '/edit');
    $this
      ->assertSession()
      ->statusCodeEquals($response);
    if ($response == 200) {
      $this
        ->assertSession()
        ->titleEquals('Edit Forum topic ' . $node
        ->label() . ' | Drupal');
    }
    if ($response == 200) {

      // Edit forum node (including moving it to another forum).
      $edit = [];
      $edit['title[0][value]'] = 'node/' . $node
        ->id();
      $edit['body[0][value]'] = $this
        ->randomMachineName(256);

      // Assume the topic is initially associated with $forum.
      $edit['taxonomy_forums'] = $this->rootForum['tid'];
      $edit['shadow'] = TRUE;
      $this
        ->drupalGet('node/' . $node
        ->id() . '/edit');
      $this
        ->submitForm($edit, 'Save');
      $this
        ->assertSession()
        ->pageTextContains('Forum topic ' . $edit['title[0][value]'] . ' has been updated.');

      // Verify topic was moved to a different forum.
      $forum_tid = $this->container
        ->get('database')
        ->select('forum', 'f')
        ->fields('f', [
        'tid',
      ])
        ->condition('nid', $node
        ->id())
        ->condition('vid', $node
        ->getRevisionId())
        ->execute()
        ->fetchField();
      $this
        ->assertSame($this->rootForum['tid'], $forum_tid, 'The forum topic is linked to a different forum');

      // Delete forum node.
      $this
        ->drupalGet('node/' . $node
        ->id() . '/delete');
      $this
        ->submitForm([], 'Delete');
      $this
        ->assertSession()
        ->statusCodeEquals($response);
      $this
        ->assertSession()
        ->pageTextContains("Forum topic {$edit['title[0][value]']} has been deleted.");
    }
  }

  /**
   * Verifies the display of a forum page.
   *
   * @param array $forum
   *   A row from the taxonomy_term_data table in an array.
   * @param array $parent
   *   (optional) An array representing the forum's parent.
   */
  private function verifyForumView($forum, $parent = NULL) {

    // View forum page.
    $this
      ->drupalGet('forum/' . $forum['tid']);
    $this
      ->assertSession()
      ->statusCodeEquals(200);
    $this
      ->assertSession()
      ->titleEquals($forum['name'] . ' | Drupal');
    $breadcrumb_build = [
      Link::createFromRoute(t('Home'), '<front>'),
      Link::createFromRoute(t('Forums'), 'forum.index'),
    ];
    if (isset($parent)) {
      $breadcrumb_build[] = Link::createFromRoute($parent['name'], 'forum.page', [
        'taxonomy_term' => $parent['tid'],
      ]);
    }
    $breadcrumb = [
      '#theme' => 'breadcrumb',
      '#links' => $breadcrumb_build,
    ];
    $this
      ->assertSession()
      ->responseContains(\Drupal::service('renderer')
      ->renderRoot($breadcrumb));
  }

  /**
   * Generates forum topics.
   */
  private function generateForumTopics() {
    $this->nids = [];
    for ($i = 0; $i < 5; $i++) {
      $node = $this
        ->createForumTopic($this->forum, FALSE);
      $this->nids[] = $node
        ->id();
    }
  }

  /**
   * Evaluate whether "Add new Forum topic" button is present or not.
   */
  public function testForumTopicButton() {
    $this
      ->drupalLogin($this->adminUser);

    // Validate that link doesn't exist on the forum container page.
    $forum_container = $this
      ->createForum('container');
    $this
      ->drupalGet('forum/' . $forum_container['tid']);
    $this
      ->assertSession()
      ->linkNotExists('Add new Forum topic');

    // Validate that link exists on forum page.
    $forum = $this
      ->createForum('forum');
    $this
      ->drupalGet('forum/' . $forum['tid']);
    $this
      ->assertSession()
      ->linkExists('Add new Forum topic');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertLegacyTrait::assert Deprecated protected function
AssertLegacyTrait::assertCacheTag Deprecated protected function Asserts whether an expected cache tag was present in the last response.
AssertLegacyTrait::assertElementNotPresent Deprecated protected function Asserts that the element with the given CSS selector is not present.
AssertLegacyTrait::assertElementPresent Deprecated protected function Asserts that the element with the given CSS selector is present.
AssertLegacyTrait::assertEqual Deprecated protected function
AssertLegacyTrait::assertEscaped Deprecated protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertLegacyTrait::assertField Deprecated protected function Asserts that a field exists with the given name or ID.
AssertLegacyTrait::assertFieldById Deprecated protected function Asserts that a field exists with the given ID and value.
AssertLegacyTrait::assertFieldByName Deprecated protected function Asserts that a field exists with the given name and value.
AssertLegacyTrait::assertFieldByXPath Deprecated protected function Asserts that a field exists in the current page by the given XPath.
AssertLegacyTrait::assertFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is checked.
AssertLegacyTrait::assertFieldsByValue Deprecated protected function Asserts that a field exists in the current page with a given Xpath result.
AssertLegacyTrait::assertHeader Deprecated protected function Checks that current response header equals value.
AssertLegacyTrait::assertIdentical Deprecated protected function
AssertLegacyTrait::assertIdenticalObject Deprecated protected function
AssertLegacyTrait::assertLink Deprecated protected function Passes if a link with the specified label is found.
AssertLegacyTrait::assertLinkByHref Deprecated protected function Passes if a link containing a given href (part) is found.
AssertLegacyTrait::assertNoCacheTag Deprecated protected function Asserts whether an expected cache tag was absent in the last response.
AssertLegacyTrait::assertNoEscaped Deprecated protected function Passes if the raw text is not found escaped on the loaded page.
AssertLegacyTrait::assertNoField Deprecated protected function Asserts that a field does NOT exist with the given name or ID.
AssertLegacyTrait::assertNoFieldById Deprecated protected function Asserts that a field does not exist with the given ID and value.
AssertLegacyTrait::assertNoFieldByName Deprecated protected function Asserts that a field does not exist with the given name and value.
AssertLegacyTrait::assertNoFieldByXPath Deprecated protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertLegacyTrait::assertNoFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is not checked.
AssertLegacyTrait::assertNoLink Deprecated protected function Passes if a link with the specified label is not found.
AssertLegacyTrait::assertNoLinkByHref Deprecated protected function Passes if a link containing a given href (part) is not found.
AssertLegacyTrait::assertNoOption Deprecated protected function Asserts that a select option does NOT exist in the current page.
AssertLegacyTrait::assertNoPattern Deprecated protected function Triggers a pass if the Perl regex pattern is not found in the raw content.
AssertLegacyTrait::assertNoRaw Deprecated protected function Passes if the raw text IS not found on the loaded page, fail otherwise.
AssertLegacyTrait::assertNotEqual Deprecated protected function
AssertLegacyTrait::assertNoText Deprecated protected function Passes if the page (with HTML stripped) does not contains the text.
AssertLegacyTrait::assertNotIdentical Deprecated protected function
AssertLegacyTrait::assertNoUniqueText Deprecated protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertLegacyTrait::assertOption Deprecated protected function Asserts that a select option in the current page exists.
AssertLegacyTrait::assertOptionByText Deprecated protected function Asserts that a select option with the visible text exists.
AssertLegacyTrait::assertOptionSelected Deprecated protected function Asserts that a select option in the current page is checked.
AssertLegacyTrait::assertPattern Deprecated protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertLegacyTrait::assertRaw Deprecated protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertLegacyTrait::assertResponse Deprecated protected function Asserts the page responds with the specified response code.
AssertLegacyTrait::assertText Deprecated protected function Passes if the page (with HTML stripped) contains the text.
AssertLegacyTrait::assertTextHelper Deprecated protected function Helper for assertText and assertNoText.
AssertLegacyTrait::assertTitle Deprecated protected function Pass if the page title is the given string.
AssertLegacyTrait::assertUniqueText Deprecated protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertLegacyTrait::assertUrl Deprecated protected function Passes if the internal browser's URL matches the given path.
AssertLegacyTrait::buildXPathQuery Deprecated protected function Builds an XPath query.
AssertLegacyTrait::constructFieldXpath Deprecated protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertLegacyTrait::getAllOptions Deprecated protected function Get all option elements, including nested options, in a select.
AssertLegacyTrait::getRawContent Deprecated protected function Gets the current raw content.
AssertLegacyTrait::pass Deprecated protected function
AssertLegacyTrait::verbose Deprecated 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::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::$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 Mink default driver params.
BrowserTestBase::$minkDefaultDriverClass protected property Mink class for the default driver to use. 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::drupalGetHeader Deprecated protected function Gets the value of an HTTP response header.
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::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::setUpAppRoot protected function Sets up the root application path.
BrowserTestBase::setUpBeforeClass public static function 1
BrowserTestBase::tearDown protected function 3
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::__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
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
ForumTest::$adminUser protected property A user with various administrative privileges.
ForumTest::$defaultTheme protected property The theme to install as the default for testing. Overrides BrowserTestBase::$defaultTheme
ForumTest::$editAnyTopicsUser protected property A user that can create, edit, and delete forum topics.
ForumTest::$editOwnTopicsUser protected property A user that can create forum topics and edit its own topics.
ForumTest::$forum protected property An array representing a forum.
ForumTest::$forumContainer protected property An array representing a forum container.
ForumTest::$modules protected static property Modules to enable. Overrides BrowserTestBase::$modules
ForumTest::$nids protected property An array of forum topic node IDs.
ForumTest::$postCommentUser protected property An administrative user who can bypass comment approval.
ForumTest::$rootForum protected property An array representing a root forum.
ForumTest::$webUser protected property A user with no special privileges.
ForumTest::createForum public function Creates a forum container or a forum.
ForumTest::createForumTopic public function Creates a forum topic.
ForumTest::deleteForum public function Deletes a forum.
ForumTest::doAdminTests private function Runs admin tests on the admin user.
ForumTest::doBasicTests private function Runs basic tests on the indicated user.
ForumTest::editForumVocabulary public function Edits the forum taxonomy.
ForumTest::generateForumTopics private function Generates forum topics.
ForumTest::setUp protected function Overrides BrowserTestBase::setUp
ForumTest::testAddOrphanTopic public function Tests that forum nodes can't be added without a parent.
ForumTest::testForum public function Tests forum functionality through the admin and user interfaces.
ForumTest::testForumTopicButton public function Evaluate whether "Add new Forum topic" button is present or not.
ForumTest::testForumWithNewPost public function Tests a forum with a new post displays properly.
ForumTest::verifyForums private function Verifies that the logged in user has access to a forum node.
ForumTest::verifyForumView private function Verifies the display of a forum page.
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::$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. 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.
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. 20
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. 1
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
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
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. 1
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. 1
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. 1
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 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. 2
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 Deprecated 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::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
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.