class CommentInterfaceTest

Hierarchy

Expanded class hierarchy of CommentInterfaceTest

File

drupal/modules/comment/comment.test, line 263
Tests for comment.module.

View source
class CommentInterfaceTest extends CommentHelperCase {
  public static function getInfo() {
    return array(
      'name' => 'Comment interface',
      'description' => 'Test comment user interfaces.',
      'group' => 'Comment',
    );
  }

  /**
   * Test comment interface.
   */
  function testCommentInterface() {
    $langcode = LANGUAGE_NONE;

    // Set comments to have subject and preview disabled.
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentPreview(DRUPAL_DISABLED);
    $this
      ->setCommentForm(TRUE);
    $this
      ->setCommentSubject(FALSE);
    $this
      ->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
    $this
      ->drupalLogout();

    // Post comment #1 without subject or preview.
    $this
      ->drupalLogin($this->web_user);
    $comment_text = $this
      ->randomName();
    $comment = $this
      ->postComment($this->node, $comment_text);
    $comment_loaded = comment_load($comment->id);
    $this
      ->assertTrue($this
      ->commentExists($comment), 'Comment found.');

    // Set comments to have subject and preview to required.
    $this
      ->drupalLogout();
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentSubject(TRUE);
    $this
      ->setCommentPreview(DRUPAL_REQUIRED);
    $this
      ->drupalLogout();

    // Create comment #2 that allows subject and requires preview.
    $this
      ->drupalLogin($this->web_user);
    $subject_text = $this
      ->randomName();
    $comment_text = $this
      ->randomName();
    $comment = $this
      ->postComment($this->node, $comment_text, $subject_text, TRUE);
    $comment_loaded = comment_load($comment->id);
    $this
      ->assertTrue($this
      ->commentExists($comment), 'Comment found.');

    // Check comment display.
    $this
      ->drupalGet('node/' . $this->node->nid . '/' . $comment->id);
    $this
      ->assertText($subject_text, 'Individual comment subject found.');
    $this
      ->assertText($comment_text, 'Individual comment body found.');

    // Set comments to have subject and preview to optional.
    $this
      ->drupalLogout();
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentSubject(TRUE);
    $this
      ->setCommentPreview(DRUPAL_OPTIONAL);

    // Test changing the comment author to "Anonymous".
    $this
      ->drupalGet('comment/' . $comment->id . '/edit');
    $comment = $this
      ->postComment(NULL, $comment->comment, $comment->subject, array(
      'name' => '',
    ));
    $comment_loaded = comment_load($comment->id);
    $this
      ->assertTrue(empty($comment_loaded->name) && $comment_loaded->uid == 0, 'Comment author successfully changed to anonymous.');

    // Test changing the comment author to an unverified user.
    $random_name = $this
      ->randomName();
    $this
      ->drupalGet('comment/' . $comment->id . '/edit');
    $comment = $this
      ->postComment(NULL, $comment->comment, $comment->subject, array(
      'name' => $random_name,
    ));
    $this
      ->drupalGet('node/' . $this->node->nid);
    $this
      ->assertText($random_name . ' (' . t('not verified') . ')', 'Comment author successfully changed to an unverified user.');

    // Test changing the comment author to a verified user.
    $this
      ->drupalGet('comment/' . $comment->id . '/edit');
    $comment = $this
      ->postComment(NULL, $comment->comment, $comment->subject, array(
      'name' => $this->web_user->name,
    ));
    $comment_loaded = comment_load($comment->id);
    $this
      ->assertTrue($comment_loaded->name == $this->web_user->name && $comment_loaded->uid == $this->web_user->uid, 'Comment author successfully changed to a registered user.');
    $this
      ->drupalLogout();

    // Reply to comment #2 creating comment #3 with optional preview and no
    // subject though field enabled.
    $this
      ->drupalLogin($this->web_user);
    $this
      ->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
    $this
      ->assertText($subject_text, 'Individual comment-reply subject found.');
    $this
      ->assertText($comment_text, 'Individual comment-reply body found.');
    $reply = $this
      ->postComment(NULL, $this
      ->randomName(), '', TRUE);
    $reply_loaded = comment_load($reply->id);
    $this
      ->assertTrue($this
      ->commentExists($reply, TRUE), 'Reply found.');
    $this
      ->assertEqual($comment->id, $reply_loaded->pid, 'Pid of a reply to a comment is set correctly.');
    $this
      ->assertEqual(rtrim($comment_loaded->thread, '/') . '.00/', $reply_loaded->thread, 'Thread of reply grows correctly.');

    // Second reply to comment #3 creating comment #4.
    $this
      ->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
    $this
      ->assertText($subject_text, 'Individual comment-reply subject found.');
    $this
      ->assertText($comment_text, 'Individual comment-reply body found.');
    $reply = $this
      ->postComment(NULL, $this
      ->randomName(), $this
      ->randomName(), TRUE);
    $reply_loaded = comment_load($reply->id);
    $this
      ->assertTrue($this
      ->commentExists($reply, TRUE), 'Second reply found.');
    $this
      ->assertEqual(rtrim($comment_loaded->thread, '/') . '.01/', $reply_loaded->thread, 'Thread of second reply grows correctly.');

    // Edit reply.
    $this
      ->drupalGet('comment/' . $reply->id . '/edit');
    $reply = $this
      ->postComment(NULL, $this
      ->randomName(), $this
      ->randomName(), TRUE);
    $this
      ->assertTrue($this
      ->commentExists($reply, TRUE), 'Modified reply found.');

    // Correct link count
    $this
      ->drupalGet('node');
    $this
      ->assertRaw('4 comments', 'Link to the 4 comments exist.');

    // Confirm a new comment is posted to the correct page.
    $this
      ->setCommentsPerPage(2);
    $comment_new_page = $this
      ->postComment($this->node, $this
      ->randomName(), $this
      ->randomName(), TRUE);
    $this
      ->assertTrue($this
      ->commentExists($comment_new_page), 'Page one exists. %s');
    $this
      ->drupalGet('node/' . $this->node->nid, array(
      'query' => array(
        'page' => 1,
      ),
    ));
    $this
      ->assertTrue($this
      ->commentExists($reply, TRUE), 'Page two exists. %s');
    $this
      ->setCommentsPerPage(50);

    // Attempt to post to node with comments disabled.
    $this->node = $this
      ->drupalCreateNode(array(
      'type' => 'article',
      'promote' => 1,
      'comment' => COMMENT_NODE_HIDDEN,
    ));
    $this
      ->assertTrue($this->node, 'Article node created.');
    $this
      ->drupalGet('comment/reply/' . $this->node->nid);
    $this
      ->assertText('This discussion is closed', 'Posting to node with comments disabled');
    $this
      ->assertNoField('edit-comment', 'Comment body field found.');

    // Attempt to post to node with read-only comments.
    $this->node = $this
      ->drupalCreateNode(array(
      'type' => 'article',
      'promote' => 1,
      'comment' => COMMENT_NODE_CLOSED,
    ));
    $this
      ->assertTrue($this->node, 'Article node created.');
    $this
      ->drupalGet('comment/reply/' . $this->node->nid);
    $this
      ->assertText('This discussion is closed', 'Posting to node with comments read-only');
    $this
      ->assertNoField('edit-comment', 'Comment body field found.');

    // Attempt to post to node with comments enabled (check field names etc).
    $this->node = $this
      ->drupalCreateNode(array(
      'type' => 'article',
      'promote' => 1,
      'comment' => COMMENT_NODE_OPEN,
    ));
    $this
      ->assertTrue($this->node, 'Article node created.');
    $this
      ->drupalGet('comment/reply/' . $this->node->nid);
    $this
      ->assertNoText('This discussion is closed', 'Posting to node with comments enabled');
    $this
      ->assertField('edit-comment-body-' . $langcode . '-0-value', 'Comment body field found.');

    // Delete comment and make sure that reply is also removed.
    $this
      ->drupalLogout();
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->deleteComment($comment);
    $this
      ->deleteComment($comment_new_page);
    $this
      ->drupalGet('node/' . $this->node->nid);
    $this
      ->assertFalse($this
      ->commentExists($comment), 'Comment not found.');
    $this
      ->assertFalse($this
      ->commentExists($reply, TRUE), 'Reply not found.');

    // Enabled comment form on node page.
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentForm(TRUE);
    $this
      ->drupalLogout();

    // Submit comment through node form.
    $this
      ->drupalLogin($this->web_user);
    $this
      ->drupalGet('node/' . $this->node->nid);
    $form_comment = $this
      ->postComment(NULL, $this
      ->randomName(), $this
      ->randomName(), TRUE);
    $this
      ->assertTrue($this
      ->commentExists($form_comment), 'Form comment found.');

    // Disable comment form on node page.
    $this
      ->drupalLogout();
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentForm(FALSE);
  }

  /**
   * Tests new comment marker.
   */
  public function testCommentNewCommentsIndicator() {

    // Test if the right links are displayed when no comment is present for the
    // node.
    $this
      ->drupalLogin($this->admin_user);
    $this->node = $this
      ->drupalCreateNode(array(
      'type' => 'article',
      'promote' => 1,
      'comment' => COMMENT_NODE_OPEN,
    ));
    $this
      ->drupalGet('node');
    $this
      ->assertNoLink(t('@count comments', array(
      '@count' => 0,
    )));
    $this
      ->assertNoLink(t('@count new comments', array(
      '@count' => 0,
    )));
    $this
      ->assertLink(t('Read more'));
    $count = $this
      ->xpath('//div[@id=:id]/div[@class=:class]/ul/li', array(
      ':id' => 'node-' . $this->node->nid,
      ':class' => 'link-wrapper',
    ));
    $this
      ->assertTrue(count($count) == 1, 'One child found');

    // Create a new comment. This helper function may be run with different
    // comment settings so use comment_save() to avoid complex setup.
    $comment = (object) array(
      'cid' => NULL,
      'nid' => $this->node->nid,
      'node_type' => $this->node->type,
      'pid' => 0,
      'uid' => $this->loggedInUser->uid,
      'status' => COMMENT_PUBLISHED,
      'subject' => $this
        ->randomName(),
      'hostname' => ip_address(),
      'language' => LANGUAGE_NONE,
      'comment_body' => array(
        LANGUAGE_NONE => array(
          $this
            ->randomName(),
        ),
      ),
    );
    comment_save($comment);
    $this
      ->drupalLogout();

    // Log in with 'web user' and check comment links.
    $this
      ->drupalLogin($this->web_user);
    $this
      ->drupalGet('node');
    $this
      ->assertLink(t('1 new comment'));
    $this
      ->clickLink(t('1 new comment'));
    $this
      ->assertRaw('<a id="new"></a>', 'Found "new" marker.');
    $this
      ->assertTrue($this
      ->xpath('//a[@id=:new]/following-sibling::a[1][@id=:comment_id]', array(
      ':new' => 'new',
      ':comment_id' => 'comment-1',
    )), 'The "new" anchor is positioned at the right comment.');

    // Test if "new comment" link is correctly removed.
    $this
      ->drupalGet('node');
    $this
      ->assertLink(t('1 comment'));
    $this
      ->assertLink(t('Read more'));
    $this
      ->assertNoLink(t('1 new comment'));
    $this
      ->assertNoLink(t('@count new comments', array(
      '@count' => 0,
    )));
    $count = $this
      ->xpath('//div[@id=:id]/div[@class=:class]/ul/li', array(
      ':id' => 'node-' . $this->node->nid,
      ':class' => 'link-wrapper',
    ));
    $this
      ->assertTrue(count($count) == 2, print_r($count, TRUE));
  }

  /**
   * Tests CSS classes on comments.
   */
  function testCommentClasses() {

    // Create all permutations for comments, users, and nodes.
    $parameters = array(
      'node_uid' => array(
        0,
        $this->web_user->uid,
      ),
      'comment_uid' => array(
        0,
        $this->web_user->uid,
        $this->admin_user->uid,
      ),
      'comment_status' => array(
        COMMENT_PUBLISHED,
        COMMENT_NOT_PUBLISHED,
      ),
      'user' => array(
        'anonymous',
        'authenticated',
        'admin',
      ),
    );
    $permutations = $this
      ->generatePermutations($parameters);
    foreach ($permutations as $case) {

      // Create a new node.
      $node = $this
        ->drupalCreateNode(array(
        'type' => 'article',
        'uid' => $case['node_uid'],
      ));

      // Add a comment.
      $comment = (object) array(
        'cid' => NULL,
        'nid' => $node->nid,
        'pid' => 0,
        'uid' => $case['comment_uid'],
        'status' => $case['comment_status'],
        'subject' => $this
          ->randomName(),
        'language' => LANGUAGE_NONE,
        'comment_body' => array(
          LANGUAGE_NONE => array(
            $this
              ->randomName(),
          ),
        ),
      );
      comment_save($comment);

      // Adjust the current/viewing user.
      switch ($case['user']) {
        case 'anonymous':
          $this
            ->drupalLogout();
          $case['user_uid'] = 0;
          break;
        case 'authenticated':
          $this
            ->drupalLogin($this->web_user);
          $case['user_uid'] = $this->web_user->uid;
          break;
        case 'admin':
          $this
            ->drupalLogin($this->admin_user);
          $case['user_uid'] = $this->admin_user->uid;
          break;
      }

      // Request the node with the comment.
      $this
        ->drupalGet('node/' . $node->nid);

      // Verify classes if the comment is visible for the current user.
      if ($case['comment_status'] == COMMENT_PUBLISHED || $case['user'] == 'admin') {

        // Verify the comment-by-anonymous class.
        $comments = $this
          ->xpath('//*[contains(@class, "comment-by-anonymous")]');
        if ($case['comment_uid'] == 0) {
          $this
            ->assertTrue(count($comments) == 1, 'comment-by-anonymous class found.');
        }
        else {
          $this
            ->assertFalse(count($comments), 'comment-by-anonymous class not found.');
        }

        // Verify the comment-by-node-author class.
        $comments = $this
          ->xpath('//*[contains(@class, "comment-by-node-author")]');
        if ($case['comment_uid'] > 0 && $case['comment_uid'] == $case['node_uid']) {
          $this
            ->assertTrue(count($comments) == 1, 'comment-by-node-author class found.');
        }
        else {
          $this
            ->assertFalse(count($comments), 'comment-by-node-author class not found.');
        }

        // Verify the comment-by-viewer class.
        $comments = $this
          ->xpath('//*[contains(@class, "comment-by-viewer")]');
        if ($case['comment_uid'] > 0 && $case['comment_uid'] == $case['user_uid']) {
          $this
            ->assertTrue(count($comments) == 1, 'comment-by-viewer class found.');
        }
        else {
          $this
            ->assertFalse(count($comments), 'comment-by-viewer class not found.');
        }
      }

      // Verify the comment-unpublished class.
      $comments = $this
        ->xpath('//*[contains(@class, "comment-unpublished")]');
      if ($case['comment_status'] == COMMENT_NOT_PUBLISHED && $case['user'] == 'admin') {
        $this
          ->assertTrue(count($comments) == 1, 'comment-unpublished class found.');
      }
      else {
        $this
          ->assertFalse(count($comments), 'comment-unpublished class not found.');
      }

      // Verify the comment-new class.
      if ($case['comment_status'] == COMMENT_PUBLISHED || $case['user'] == 'admin') {
        $comments = $this
          ->xpath('//*[contains(@class, "comment-new")]');
        if ($case['user'] != 'anonymous') {
          $this
            ->assertTrue(count($comments) == 1, 'comment-new class found.');

          // Request the node again. The comment-new class should disappear.
          $this
            ->drupalGet('node/' . $node->nid);
          $comments = $this
            ->xpath('//*[contains(@class, "comment-new")]');
          $this
            ->assertFalse(count($comments), 'comment-new class not found.');
        }
        else {
          $this
            ->assertFalse(count($comments), 'comment-new class not found.');
        }
      }
    }
  }

  /**
   * Tests the node comment statistics.
   */
  function testCommentNodeCommentStatistics() {
    $langcode = LANGUAGE_NONE;

    // Set comments to have subject and preview disabled.
    $this
      ->drupalLogin($this->admin_user);
    $this
      ->setCommentPreview(DRUPAL_DISABLED);
    $this
      ->setCommentForm(TRUE);
    $this
      ->setCommentSubject(FALSE);
    $this
      ->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
    $this
      ->drupalLogout();

    // Creates a second user to post comments.
    $this->web_user2 = $this
      ->drupalCreateUser(array(
      'access comments',
      'post comments',
      'create article content',
      'edit own comments',
    ));

    // Checks the initial values of node comment statistics with no comment.
    $node = node_load($this->node->nid);
    $this
      ->assertEqual($node->last_comment_timestamp, $this->node->created, 'The initial value of node last_comment_timestamp is the node created date.');
    $this
      ->assertEqual($node->last_comment_name, NULL, 'The initial value of node last_comment_name is NULL.');
    $this
      ->assertEqual($node->last_comment_uid, $this->web_user->uid, 'The initial value of node last_comment_uid is the node uid.');
    $this
      ->assertEqual($node->comment_count, 0, 'The initial value of node comment_count is zero.');

    // Post comment #1 as web_user2.
    $this
      ->drupalLogin($this->web_user2);
    $comment_text = $this
      ->randomName();
    $comment = $this
      ->postComment($this->node, $comment_text);
    $comment_loaded = comment_load($comment->id);

    // Checks the new values of node comment statistics with comment #1.
    // The node needs to be reloaded with a node_load_multiple cache reset.
    $node = node_load($this->node->nid, NULL, TRUE);
    $this
      ->assertEqual($node->last_comment_name, NULL, 'The value of node last_comment_name is NULL.');
    $this
      ->assertEqual($node->last_comment_uid, $this->web_user2->uid, 'The value of node last_comment_uid is the comment #1 uid.');
    $this
      ->assertEqual($node->comment_count, 1, 'The value of node comment_count is 1.');

    // Prepare for anonymous comment submission (comment approval enabled).
    variable_set('user_register', USER_REGISTER_VISITORS);
    $this
      ->drupalLogin($this->admin_user);
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access comments' => TRUE,
      'post comments' => TRUE,
      'skip comment approval' => FALSE,
    ));

    // Ensure that the poster can leave some contact info.
    $this
      ->setCommentAnonymous('1');
    $this
      ->drupalLogout();

    // Post comment #2 as anonymous (comment approval enabled).
    $this
      ->drupalGet('comment/reply/' . $this->node->nid);
    $anonymous_comment = $this
      ->postComment($this->node, $this
      ->randomName(), '', TRUE);
    $comment_unpublished_loaded = comment_load($anonymous_comment->id);

    // Checks the new values of node comment statistics with comment #2 and
    // ensure they haven't changed since the comment has not been moderated.
    // The node needs to be reloaded with a node_load_multiple cache reset.
    $node = node_load($this->node->nid, NULL, TRUE);
    $this
      ->assertEqual($node->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.');
    $this
      ->assertEqual($node->last_comment_uid, $this->web_user2->uid, 'The value of node last_comment_uid is still the comment #1 uid.');
    $this
      ->assertEqual($node->comment_count, 1, 'The value of node comment_count is still 1.');

    // Prepare for anonymous comment submission (no approval required).
    $this
      ->drupalLogin($this->admin_user);
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access comments' => TRUE,
      'post comments' => TRUE,
      'skip comment approval' => TRUE,
    ));
    $this
      ->drupalLogout();

    // Post comment #3 as anonymous.
    $this
      ->drupalGet('comment/reply/' . $this->node->nid);
    $anonymous_comment = $this
      ->postComment($this->node, $this
      ->randomName(), '', array(
      'name' => $this
        ->randomName(),
    ));
    $comment_loaded = comment_load($anonymous_comment->id);

    // Checks the new values of node comment statistics with comment #3.
    // The node needs to be reloaded with a node_load_multiple cache reset.
    $node = node_load($this->node->nid, NULL, TRUE);
    $this
      ->assertEqual($node->last_comment_name, $comment_loaded->name, 'The value of node last_comment_name is the name of the anonymous user.');
    $this
      ->assertEqual($node->last_comment_uid, 0, 'The value of node last_comment_uid is zero.');
    $this
      ->assertEqual($node->comment_count, 2, 'The value of node comment_count is 2.');
  }

  /**
   * Tests comment links.
   *
   * The output of comment links depends on various environment conditions:
   * - Various Comment module configuration settings, user registration
   *   settings, and user access permissions.
   * - Whether the user is authenticated or not, and whether any comments exist.
   *
   * To account for all possible cases, this test creates permutations of all
   * possible conditions and tests the expected appearance of comment links in
   * each environment.
   */
  function testCommentLinks() {

    // Bartik theme alters comment links, so use a different theme.
    theme_enable(array(
      'garland',
    ));
    variable_set('theme_default', 'garland');

    // Remove additional user permissions from $this->web_user added by setUp(),
    // since this test is limited to anonymous and authenticated roles only.
    user_role_delete(key($this->web_user->roles));

    // Matrix of possible environmental conditions and configuration settings.
    // See setEnvironment() for details.
    $conditions = array(
      'authenticated' => array(
        FALSE,
        TRUE,
      ),
      'comment count' => array(
        FALSE,
        TRUE,
      ),
      'access comments' => array(
        0,
        1,
      ),
      'post comments' => array(
        0,
        1,
      ),
      'form' => array(
        COMMENT_FORM_BELOW,
        COMMENT_FORM_SEPARATE_PAGE,
      ),
      // USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL is irrelevant for this
      // test; there is only a difference between open and closed registration.
      'user_register' => array(
        USER_REGISTER_VISITORS,
        USER_REGISTER_ADMINISTRATORS_ONLY,
      ),
    );
    $environments = $this
      ->generatePermutations($conditions);
    foreach ($environments as $info) {
      $this
        ->assertCommentLinks($info);
    }
  }

  /**
   * Re-configures the environment, module settings, and user permissions.
   *
   * @param $info
   *   An associative array describing the environment to setup:
   *   - Environment conditions:
   *     - authenticated: Boolean whether to test with $this->web_user or
   *       anonymous.
   *     - comment count: Boolean whether to test with a new/unread comment on
   *       $this->node or no comments.
   *   - Configuration settings:
   *     - form: COMMENT_FORM_BELOW or COMMENT_FORM_SEPARATE_PAGE.
   *     - user_register: USER_REGISTER_ADMINISTRATORS_ONLY or
   *       USER_REGISTER_VISITORS.
   *     - contact: COMMENT_ANONYMOUS_MAY_CONTACT or
   *       COMMENT_ANONYMOUS_MAYNOT_CONTACT.
   *     - comments: COMMENT_NODE_OPEN, COMMENT_NODE_CLOSED, or
   *       COMMENT_NODE_HIDDEN.
   *   - User permissions:
   *     These are granted or revoked for the user, according to the
   *     'authenticated' flag above. Pass 0 or 1 as parameter values. See
   *     user_role_change_permissions().
   *     - access comments
   *     - post comments
   *     - skip comment approval
   *     - edit own comments
   */
  function setEnvironment(array $info) {
    static $current;

    // Apply defaults to initial environment.
    if (!isset($current)) {
      $current = array(
        'authenticated' => FALSE,
        'comment count' => FALSE,
        'form' => COMMENT_FORM_BELOW,
        'user_register' => USER_REGISTER_VISITORS,
        'contact' => COMMENT_ANONYMOUS_MAY_CONTACT,
        'comments' => COMMENT_NODE_OPEN,
        'access comments' => 0,
        'post comments' => 0,
        // Enabled by default, because it's irrelevant for this test.
        'skip comment approval' => 1,
        'edit own comments' => 0,
      );
    }

    // Complete new environment with current environment.
    $info = array_merge($current, $info);

    // Change environment conditions.
    if ($current['authenticated'] != $info['authenticated']) {
      if ($this->loggedInUser) {
        $this
          ->drupalLogout();
      }
      else {
        $this
          ->drupalLogin($this->web_user);
      }
    }
    if ($current['comment count'] != $info['comment count']) {
      if ($info['comment count']) {

        // Create a comment via CRUD API functionality, since
        // $this->postComment() relies on actual user permissions.
        $comment = (object) array(
          'cid' => NULL,
          'nid' => $this->node->nid,
          'node_type' => $this->node->type,
          'pid' => 0,
          'uid' => 0,
          'status' => COMMENT_PUBLISHED,
          'subject' => $this
            ->randomName(),
          'hostname' => ip_address(),
          'language' => LANGUAGE_NONE,
          'comment_body' => array(
            LANGUAGE_NONE => array(
              $this
                ->randomName(),
            ),
          ),
        );
        comment_save($comment);
        $this->comment = $comment;

        // comment_num_new() relies on node_last_viewed(), so ensure that no one
        // has seen the node of this comment.
        db_delete('history')
          ->condition('nid', $this->node->nid)
          ->execute();
      }
      else {
        $cids = db_query("SELECT cid FROM {comment}")
          ->fetchCol();
        comment_delete_multiple($cids);
        unset($this->comment);
      }
    }

    // Change comment settings.
    variable_set('comment_form_location_' . $this->node->type, $info['form']);
    variable_set('comment_anonymous_' . $this->node->type, $info['contact']);
    if ($this->node->comment != $info['comments']) {
      $this->node->comment = $info['comments'];
      node_save($this->node);
    }

    // Change user settings.
    variable_set('user_register', $info['user_register']);

    // Change user permissions.
    $rid = $this->loggedInUser ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
    $perms = array_intersect_key($info, array(
      'access comments' => 1,
      'post comments' => 1,
      'skip comment approval' => 1,
      'edit own comments' => 1,
    ));
    user_role_change_permissions($rid, $perms);

    // Output verbose debugging information.
    // @see DrupalTestCase::error()
    $t_form = array(
      COMMENT_FORM_BELOW => 'below',
      COMMENT_FORM_SEPARATE_PAGE => 'separate page',
    );
    $t_contact = array(
      COMMENT_ANONYMOUS_MAY_CONTACT => 'optional',
      COMMENT_ANONYMOUS_MAYNOT_CONTACT => 'disabled',
      COMMENT_ANONYMOUS_MUST_CONTACT => 'required',
    );
    $t_comments = array(
      COMMENT_NODE_OPEN => 'open',
      COMMENT_NODE_CLOSED => 'closed',
      COMMENT_NODE_HIDDEN => 'hidden',
    );
    $verbose = $info;
    $verbose['form'] = $t_form[$info['form']];
    $verbose['contact'] = $t_contact[$info['contact']];
    $verbose['comments'] = $t_comments[$info['comments']];
    $message = t('Changed environment:<pre>@verbose</pre>', array(
      '@verbose' => var_export($verbose, TRUE),
    ));
    $this
      ->assert('debug', $message, 'Debug');

    // Update current environment.
    $current = $info;
    return $info;
  }

  /**
   * Asserts that comment links appear according to the passed environment setup.
   *
   * @param $info
   *   An associative array describing the environment to pass to
   *   setEnvironment().
   */
  function assertCommentLinks(array $info) {
    $info = $this
      ->setEnvironment($info);
    $nid = $this->node->nid;
    foreach (array(
      '',
      "node/{$nid}",
    ) as $path) {
      $this
        ->drupalGet($path);

      // User is allowed to view comments.
      if ($info['access comments']) {
        if ($path == '') {

          // In teaser view, a link containing the comment count is always
          // expected.
          if ($info['comment count']) {
            $this
              ->assertLink(t('1 comment'));

            // For logged in users, a link containing the amount of new/unread
            // comments is expected.
            // See important note about comment_num_new() below.
            if ($this->loggedInUser && isset($this->comment) && !isset($this->comment->seen)) {
              $this
                ->assertLink(t('1 new comment'));
              $this->comment->seen = TRUE;
            }
          }
        }
      }
      else {
        $this
          ->assertNoLink(t('1 comment'));
        $this
          ->assertNoLink(t('1 new comment'));
      }

      // comment_num_new() is based on node views, so comments are marked as
      // read when a node is viewed, regardless of whether we have access to
      // comments.
      if ($path == "node/{$nid}" && $this->loggedInUser && isset($this->comment)) {
        $this->comment->seen = TRUE;
      }

      // User is not allowed to post comments.
      if (!$info['post comments']) {
        $this
          ->assertNoLink('Add new comment');

        // Anonymous users should see a note to log in or register in case
        // authenticated users are allowed to post comments.
        // @see theme_comment_post_forbidden()
        if (!$this->loggedInUser) {
          if (user_access('post comments', $this->web_user)) {

            // The note depends on whether users are actually able to register.
            if ($info['user_register']) {
              $this
                ->assertText('Log in or register to post comments');
            }
            else {
              $this
                ->assertText('Log in to post comments');
            }
          }
          else {
            $this
              ->assertNoText('Log in or register to post comments');
            $this
              ->assertNoText('Log in to post comments');
          }
        }
      }
      else {
        $this
          ->assertNoText('Log in or register to post comments');

        // "Add new comment" is always expected, except when there are no
        // comments or if the user cannot see them.
        if ($path == "node/{$nid}" && $info['form'] == COMMENT_FORM_BELOW && (!$info['comment count'] || !$info['access comments'])) {
          $this
            ->assertNoLink('Add new comment');
        }
        else {
          $this
            ->assertLink('Add new comment');
        }

        // Also verify that the comment form appears according to the configured
        // location.
        if ($path == "node/{$nid}") {
          $elements = $this
            ->xpath('//form[@id=:id]', array(
            ':id' => 'comment-form',
          ));
          if ($info['form'] == COMMENT_FORM_BELOW) {
            $this
              ->assertTrue(count($elements), 'Comment form found below.');
          }
          else {
            $this
              ->assertFalse(count($elements), 'Comment form not found below.');
          }
        }
      }
    }
  }

}

Members

Namesort ascending Modifiers Type Description Overrides
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
CommentInterfaceTest::testCommentNodeCommentStatistics function Tests the node comment statistics.
CommentInterfaceTest::testCommentNewCommentsIndicator public function Tests new comment marker.
CommentInterfaceTest::testCommentLinks function Tests comment links.
CommentInterfaceTest::testCommentInterface function Test comment interface.
CommentInterfaceTest::testCommentClasses function Tests CSS classes on comments.
CommentInterfaceTest::setEnvironment function Re-configures the environment, module settings, and user permissions.
CommentInterfaceTest::getInfo public static function
CommentInterfaceTest::assertCommentLinks function Asserts that comment links appear according to the passed environment setup.
CommentHelperCase::setUp function Sets up a Drupal site for running functional and integration tests. Overrides DrupalWebTestCase::setUp 3
CommentHelperCase::setCommentSubject function Set comment subject setting.
CommentHelperCase::setCommentsPerPage function Set the default number of comments per page.
CommentHelperCase::setCommentSettings function Set comment setting for article content type.
CommentHelperCase::setCommentPreview function Set comment preview setting.
CommentHelperCase::setCommentForm function Set comment form location setting.
CommentHelperCase::setCommentAnonymous function Set comment anonymous level setting.
CommentHelperCase::postComment function Post comment.
CommentHelperCase::performCommentOperation function Perform the specified operation on the specified comment.
CommentHelperCase::getUnapprovedComment function Get the comment ID for an unapproved comment.
CommentHelperCase::deleteComment function Delete comment.
CommentHelperCase::commentExists function Checks current page for specified comment.
CommentHelperCase::commentContactInfoAvailable function Check for contact info.
CommentHelperCase::$web_user protected property
CommentHelperCase::$node protected property
CommentHelperCase::$admin_user protected property